@devries-cameron20 / t3code-1 / commits / cfb1f12541
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(mobile): one shared upload per attachment, and new threads keep their project (#37682)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Nov 16, 2026 at 12:15 UTC cfb1f125412d40a78979c2e8056556266ede19da
18 files changed +1267 -934
apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
+7 -11
@@ -431,15 +431,16 @@ export function NewTaskDraftScreen(props: {
431 if (appliedInitialProjectKeyRef.current === directProjectKey) {
432 return;
433 }
434 + // setProject creates the draft, so it also runs when the fallback already shows this project.
435 + const showsDirectProject =
436 + flow.draftKey !== null &&
437 + selectedProject?.environmentId === directProject.environmentId &&
438 + selectedProject.id === directProject.id;
439 if (props.initialProjectRef?.branch) {
435 - if (
436 - selectedProject?.environmentId !== directProject.environmentId ||
437 - selectedProject.id !== directProject.id
438 - ) {
440 + if (!showsDirectProject || !flow.draftKey) {
441 setProject(directProject);
442 return;
443 }
442 - if (!flow.draftKey) return;
444 // Checkout completed before mount; local mode reuses it while worktree mode would create another.
445 updateComposerDraftSettings(flow.draftKey, {
446 workspaceSelection: {
@@ -451,12 +452,7 @@ export function NewTaskDraftScreen(props: {
452 });
453 }
454 appliedInitialProjectKeyRef.current = directProjectKey;
454 - if (
455 - selectedProject?.environmentId === directProject.environmentId &&
456 - selectedProject.id === directProject.id
457 - ) {
458 - return;
459 - }
455 + if (showsDirectProject) return;
456 setProject(directProject);
457 return;
458 }
apps/mobile/src/features/threads/new-task-flow-provider.test.tsx
+23 -4
@@ -14,7 +14,7 @@ import * as Layer from "effect/Layer";
14 import * as Queue from "effect/Queue";
15 import * as Stream from "effect/Stream";
16 import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
17 -import { act, useLayoutEffect } from "react";
17 +import { act, useEffect, useLayoutEffect } from "react";
18 import { createRoot } from "react-dom/client";
19 import { expect, it, vi } from "vite-plus/test";
20 import type { ComposerDraft } from "../../state/use-composer-drafts";
@@ -213,11 +213,16 @@ function setup() {
213 mocks.writeSettings.mockImplementation(write);
214 mocks.writeText.mockImplementation((key, text) => write(key, { text }));
215 let current: ReturnType<typeof useNewTaskFlow>;
216 - function Probe() {
216 + function Probe(props: { readonly pickOnMount?: EnvironmentProject }) {
217 const value = useNewTaskFlow();
218 useLayoutEffect(() => {
219 current = value;
220 });
221 + // Mirrors the draft screen applying its route project on mount, before the provider's effects run.
222 + useEffect(() => {
223 + if (props.pickOnMount) value.setProject(props.pickOnMount);
224 + // oxlint-disable-next-line react/exhaustive-effect-dependencies -- picks once on mount; setProject changes every render
225 + }, []);
226 return null;
227 }
228 const root = createRoot(document.createElement("div"));
@@ -245,16 +250,20 @@ function setup() {
250 get current() {
251 return current;
252 },
248 - async render(active: boolean) {
253 + async render(active: boolean, pickOnMount?: EnvironmentProject) {
254 await act(async () =>
255 root.render(
256 <RegistryContext.Provider value={registry}>
257 <NewTaskFlowProvider active={active} flowKey="test-flow">
253 - <Probe />
258 + <Probe pickOnMount={pickOnMount} />
259 </NewTaskFlowProvider>
260 </RegistryContext.Provider>,
261 ),
262 );
263 + // The draft screen applies a project whenever it shows without a draft.
264 + if (active && current.draftKey === null) {
265 + await act(async () => current.setProject(projects[0]!));
266 + }
267 },
268 async emit(cwd: string, branch: string, isRepo = true) {
269 await act(async () => emitters.get(cwd)!(branch, isRepo));
@@ -270,6 +279,16 @@ function setup() {
279 };
280 }
281
282 +it("keeps the draft on a project the screen picks as it mounts", async () => {
283 + using screen = setup();
284 + await screen.render(true, screen.projects[2]);
285 + expect(screen.current.selectedProject).toEqual(screen.projects[2]);
286 + expect(screen.snapshot(screen.current.draftKey).project).toEqual({
287 + environmentId: "two",
288 + projectId: "b",
289 + });
290 +});
291 +
292 it("owns a status stream only while the draft is active, retaining draft choices on reopen", async () => {
293 using screen = setup();
294 await screen.render(false);
apps/mobile/src/features/threads/new-task-flow-provider.tsx
+17 -23
@@ -2,7 +2,7 @@ import { ActiveNewTaskContext } from "../../state/active-new-task";
2 import { resolveNewThreadModelSelection } from "@t3tools/shared/usageLimits";
3 import { useNowMinuteMs } from "../../lib/clock";
4 import * as Dialog from "../../components/ui/Dialog";
5 -import React, { useEffect, useRef, useState } from "react";
5 +import React, { useRef, useState } from "react";
6
7 import type {
8 EnvironmentId,
@@ -304,11 +304,23 @@ export function NewTaskFlowProvider(
304 // binding outlives the draft's project stamp (submit clears it).
305 const updateFlow = (patch: Partial<NewTaskFlowState>) =>
306 updateNewTaskFlowState(flowKey, { ...readFlow(), ...patch });
307 + // A draft's project stamp is the selection: picking a project writes it, and uploads and
308 + // the send read it, so the screen cannot show one project while the draft holds another.
309 + const draftStamp = useComposerDraft(activeDraftKey).project;
310 + const stampedProject =
311 + draftStamp === undefined
312 + ? undefined
313 + : projects.find(
314 + (project) =>
315 + project.environmentId === draftStamp.environmentId &&
316 + project.id === draftStamp.projectId,
317 + );
318 const selectedEnvironmentId =
308 - selectedEnvironmentIdOverride !== null &&
319 + stampedProject?.environmentId ??
320 + (selectedEnvironmentIdOverride !== null &&
321 projects.some((project) => project.environmentId === selectedEnvironmentIdOverride)
322 ? selectedEnvironmentIdOverride
311 - : (projects[0]?.environmentId ?? null);
323 + : (projects[0]?.environmentId ?? null));
324 const projectsForEnvironment = pipe(
325 projects,
326 Arr.filter((project) => project.environmentId === selectedEnvironmentId),
@@ -319,7 +331,8 @@ export function NewTaskFlowProvider(
331 const selectedProject =
332 routeDraftResolution.kind === "pending"
333 ? null
322 - : (projectsForEnvironment.find(
334 + : (stampedProject ??
335 + projectsForEnvironment.find(
336 (project) => scopedProjectKey(project.environmentId, project.id) === selectedProjectKey,
337 ) ??
338 projectsForEnvironment[0] ??
@@ -333,25 +346,6 @@ export function NewTaskFlowProvider(
346 const serverConfigs = useServerConfigs();
347 const { connectedEnvironments } = useRemoteConnectionStatus();
348 const selectedProjectDraftKey = selectedProject ? activeDraftKey : null;
336 - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- creates the persistent draft in the new-task flow store once a project is selected, before the composer mounts
337 - useEffect(() => {
338 - // A route that names a draft binds that draft, or returns to the picker.
339 - if (
340 - props.active === false ||
341 - props.routeDraftId !== undefined ||
342 - activeDraftKey !== null ||
343 - selectedProject === null
344 - ) {
345 - return;
346 - }
347 - // Creates the persistent draft once the project selection is ready; the key must exist before the composer mounts.
348 - updateNewTaskFlowState(flowKey, {
349 - draftKey: createNewTaskDraft({
350 - environmentId: selectedProject.environmentId,
351 - projectId: selectedProject.id,
352 - }),
353 - });
354 - }, [activeDraftKey, flowKey, selectedProject, props.active, props.routeDraftId]);
349 const activePendingKey =
350 props.active === false
351 ? null
apps/mobile/src/lib/attachmentUpload.test.ts
+542 -469
@@ -1,6 +1,7 @@
1 import { EnvironmentId, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES } from "@t3tools/contracts";
2 import * as Option from "effect/Option";
3 -import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
3 +import { describe, expect, it } from "@effect/vitest";
4 +import { beforeEach, vi } from "vite-plus/test";
5
6 const mocks = vi.hoisted(() => ({
7 canOperate: true,
@@ -89,11 +90,51 @@ vi.mock("expo-file-system", () => ({
90 UploadType: { BINARY_CONTENT: 0 },
91 }));
92
93 +import * as Effect from "effect/Effect";
94 +import * as Exit from "effect/Exit";
95 +import * as Fiber from "effect/Fiber";
96 +import { uploadError } from "./composerAttachmentUploadQueue";
97 import {
93 - prepareTurnAttachments,
98 + prepareTurnAttachments as prepareWithUploads,
99 releasePendingAttachmentUploads,
100 + uploadComposerAttachment,
101 withUploadedMobileAttachmentReferences,
102 } from "./attachmentUpload";
103 +
104 +/** Uploads each attachment directly, as the shared registry does for one holder. */
105 +function prepare(
106 + input: Omit<Parameters<typeof prepareWithUploads>[0], "uploadAttachment"> & {
107 + readonly onUploadProgress?: (attachmentId: string, progress: number) => void;
108 + },
109 +) {
110 + return prepareWithUploads({
111 + ...input,
112 + // An interrupted send waits for its transfer to settle, as the shared registry does.
113 + uploadAttachment: (attachment) =>
114 + Effect.suspend(() => {
115 + const controller = new AbortController();
116 + const upload = uploadComposerAttachment(
117 + input.environmentId,
118 + attachment,
119 + controller.signal,
120 + input.onUploadProgress
121 + ? (progress) => input.onUploadProgress?.(attachment.id, progress)
122 + : undefined,
123 + );
124 + return Effect.tryPromise({ try: () => upload, catch: uploadError }).pipe(
125 + Effect.onInterrupt(() =>
126 + Effect.promise(() => {
127 + controller.abort();
128 + return upload.then(
129 + () => undefined,
130 + () => undefined,
131 + );
132 + }),
133 + ),
134 + );
135 + }),
136 + });
137 +}
138 import type { DraftComposerAttachment } from "./composerImages";
139
140 const environmentId = EnvironmentId.make("environment-1");
@@ -176,68 +217,80 @@ describe("prepareTurnAttachments", () => {
217 mocks.upload.mockResolvedValue({ status: 204, body: "", headers: {} });
218 });
219
179 - it("does not mint or transfer attachments without task operation access", async () => {
180 - mocks.canOperate = false;
181 - await expect(
182 - prepareTurnAttachments({
183 - environmentId,
184 - attachments: [fileBackedImage],
185 - supportsImageUploads: true,
186 - }),
187 - ).rejects.toThrow("cannot upload attachments");
188 - expect(mocks.runAtomCommand).not.toHaveBeenCalled();
189 - expect(mocks.upload).not.toHaveBeenCalled();
190 - });
191 -
192 - it("rechecks access after a signed URL is minted before sending any bytes", async () => {
193 - mocks.runAtomCommand.mockImplementationOnce(async () => {
220 + it.effect("does not mint or transfer attachments without task operation access", () =>
221 + Effect.gen(function* () {
222 mocks.canOperate = false;
195 - return {
196 - _tag: "Success",
197 - value: {
198 - attachmentId: MINTED_ID,
199 - relativeUrl: "/api/attachments/upload/signed",
200 - expiresAt: 1,
201 - },
202 - };
203 - });
204 - const warning = vi.spyOn(console, "warn").mockImplementation(() => {});
205 - try {
206 - await expect(
207 - prepareTurnAttachments({
208 - environmentId,
209 - attachments: [fileBackedImage],
210 - supportsImageUploads: true,
211 - }),
212 - ).rejects.toThrow("cannot upload attachments");
223 + expect(
224 + (yield* Effect.flip(
225 + prepare({
226 + environmentId,
227 + attachments: [fileBackedImage],
228 + supportsImageUploads: true,
229 + }),
230 + )).message,
231 + ).toContain("cannot upload attachments");
232 + expect(mocks.runAtomCommand).not.toHaveBeenCalled();
233 expect(mocks.upload).not.toHaveBeenCalled();
214 - expect(mocks.runAtomCommand).toHaveBeenCalledTimes(1);
215 - } finally {
216 - warning.mockRestore();
217 - }
218 - });
234 + }),
235 + );
236
220 - it("does not replace an expired upload when access was revoked during verification", async () => {
221 - mocks.executeAtomQuery.mockImplementationOnce(async () => {
222 - mocks.canOperate = false;
223 - return { _tag: "Failure", error: { _tag: "AssetAttachmentNotFoundError" } };
224 - });
225 - await expect(
226 - prepareTurnAttachments({
227 - environmentId,
228 - attachments: [
229 - {
230 - ...fileBackedImage,
231 - uploadedAttachmentId: MINTED_ID,
232 - uploadEnvironmentId: environmentId,
237 + it.effect("rechecks access after a signed URL is minted before sending any bytes", () =>
238 + Effect.gen(function* () {
239 + mocks.runAtomCommand.mockImplementationOnce(async () => {
240 + mocks.canOperate = false;
241 + return {
242 + _tag: "Success",
243 + value: {
244 + attachmentId: MINTED_ID,
245 + relativeUrl: "/api/attachments/upload/signed",
246 + expiresAt: 1,
247 },
234 - ],
235 - supportsImageUploads: true,
236 - }),
237 - ).rejects.toThrow("cannot upload attachments");
238 - expect(mocks.runAtomCommand).not.toHaveBeenCalled();
239 - expect(mocks.upload).not.toHaveBeenCalled();
240 - });
248 + };
249 + });
250 + const warning = vi.spyOn(console, "warn").mockImplementation(() => {});
251 + try {
252 + expect(
253 + (yield* Effect.flip(
254 + prepare({
255 + environmentId,
256 + attachments: [fileBackedImage],
257 + supportsImageUploads: true,
258 + }),
259 + )).message,
260 + ).toContain("cannot upload attachments");
261 + expect(mocks.upload).not.toHaveBeenCalled();
262 + expect(mocks.runAtomCommand).toHaveBeenCalledTimes(1);
263 + } finally {
264 + warning.mockRestore();
265 + }
266 + }),
267 + );
268 +
269 + it.effect("does not replace an expired upload when access was revoked during verification", () =>
270 + Effect.gen(function* () {
271 + mocks.executeAtomQuery.mockImplementationOnce(async () => {
272 + mocks.canOperate = false;
273 + return { _tag: "Failure", error: { _tag: "AssetAttachmentNotFoundError" } };
274 + });
275 + expect(
276 + (yield* Effect.flip(
277 + prepare({
278 + environmentId,
279 + attachments: [
280 + {
281 + ...fileBackedImage,
282 + uploadedAttachmentId: MINTED_ID,
283 + uploadEnvironmentId: environmentId,
284 + },
285 + ],
286 + supportsImageUploads: true,
287 + }),
288 + )).message,
289 + ).toContain("cannot upload attachments");
290 + expect(mocks.runAtomCommand).not.toHaveBeenCalled();
291 + expect(mocks.upload).not.toHaveBeenCalled();
292 + }),
293 + );
294
295 it("rechecks deletion permission before retrying a failed cleanup", async () => {
296 mocks.runAtomCommand.mockImplementationOnce(async () => {
@@ -250,256 +303,272 @@ describe("prepareTurnAttachments", () => {
303 expect(mocks.runAtomCommand).toHaveBeenCalledTimes(1);
304 });
305
253 - it("inlines a file-backed image lazily when the server lacks image uploads", async () => {
254 - const prepared = await prepareTurnAttachments({
255 - environmentId,
256 - attachments: [fileBackedImage],
257 - });
306 + it.effect("inlines a file-backed image lazily when the server lacks image uploads", () =>
307 + Effect.gen(function* () {
308 + const prepared = yield* prepare({
309 + environmentId,
310 + attachments: [fileBackedImage],
311 + });
312
259 - expect(prepared.status).toBe("ready");
260 - if (prepared.status !== "ready") return;
261 - expect(prepared.attachments).toEqual([
262 - {
263 - type: "image",
264 - name: "photo.png",
265 - mimeType: "image/png",
266 - sizeBytes: 3,
267 - dataUrl: "data:image/png;base64,YWJj",
268 - },
269 - ]);
270 - expect(mocks.readBase64).toHaveBeenCalledExactlyOnceWith(fileBackedImage.fileUri);
271 - expect(mocks.upload).not.toHaveBeenCalled();
272 - });
313 + expect(prepared.status).toBe("ready");
314 + if (prepared.status !== "ready") return;
315 + expect(prepared.attachments).toEqual([
316 + {
317 + type: "image",
318 + name: "photo.png",
319 + mimeType: "image/png",
320 + sizeBytes: 3,
321 + dataUrl: "data:image/png;base64,YWJj",
322 + },
323 + ]);
324 + expect(mocks.readBase64).toHaveBeenCalledExactlyOnceWith(fileBackedImage.fileUri);
325 + expect(mocks.upload).not.toHaveBeenCalled();
326 + }),
327 + );
328
329 // regression: #9713 read file-backed image drafts before enabling them
275 - it("reads restored images from the current iOS document container for legacy sends", async () => {
276 - const fileName = "33333333-3333-4333-8333-333333333333-photo.png";
277 - mocks.documentUri =
278 - "file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents";
279 - const oldUri = `file:///var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/${fileName}`;
280 - const prepared = await prepareTurnAttachments({
281 - environmentId,
282 - attachments: [{ ...fileBackedImage, fileUri: oldUri, previewUri: oldUri }],
283 - });
284 - expect(prepared.status).toBe("ready");
285 - expect(mocks.readBase64).toHaveBeenCalledExactlyOnceWith(
286 - `${mocks.documentUri}/t3-composer-attachments/${fileName}`,
287 - );
288 - });
330 + it.effect("reads restored images from the current iOS document container for legacy sends", () =>
331 + Effect.gen(function* () {
332 + const fileName = "33333333-3333-4333-8333-333333333333-photo.png";
333 + mocks.documentUri =
334 + "file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents";
335 + const oldUri = `file:///var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/${fileName}`;
336 + const prepared = yield* prepare({
337 + environmentId,
338 + attachments: [{ ...fileBackedImage, fileUri: oldUri, previewUri: oldUri }],
339 + });
340 + expect(prepared.status).toBe("ready");
341 + expect(mocks.readBase64).toHaveBeenCalledExactlyOnceWith(
342 + `${mocks.documentUri}/t3-composer-attachments/${fileName}`,
343 + );
344 + }),
345 + );
346
347 // regression: #9713 read file-backed image drafts before enabling them
291 - it("rejects a legacy image without inline bytes or a file", async () => {
292 - const { fileUri: _, ...missingImage } = fileBackedImage;
293 - await expect(
294 - prepareTurnAttachments({ environmentId, attachments: [missingImage] }),
295 - ).rejects.toThrow("'photo.png' is no longer available. Attach the image again.");
296 - });
348 + it.effect("rejects a legacy image without inline bytes or a file", () =>
349 + Effect.gen(function* () {
350 + const { fileUri: _, ...missingImage } = fileBackedImage;
351 + expect(
352 + (yield* Effect.flip(prepare({ environmentId, attachments: [missingImage] }))).message,
353 + ).toContain("'photo.png' is no longer available. Attach the image again.");
354 + }),
355 + );
356
298 - it.each(["resolve", "reject"] as const)(
357 + it.effect.each(["resolve", "reject"] as const)(
358 "abandons a canceled legacy image read that later %ss",
300 - async (outcome) => {
301 - const readStarted = Promise.withResolvers<void>();
302 - const read = Promise.withResolvers<string>();
303 - const controller = new AbortController();
304 - mocks.readBase64.mockImplementation(() => {
305 - readStarted.resolve();
306 - return read.promise;
307 - });
308 - const preparing = prepareTurnAttachments({
359 + (outcome) =>
360 + Effect.gen(function* () {
361 + const readStarted = Promise.withResolvers<void>();
362 + const read = Promise.withResolvers<string>();
363 + mocks.readBase64.mockImplementation(() => {
364 + readStarted.resolve();
365 + return read.promise;
366 + });
367 + const preparing = yield* Effect.forkChild(
368 + prepare({ environmentId, attachments: [fileBackedImage] }),
369 + );
370 + yield* Effect.promise(() => readStarted.promise);
371 + yield* Fiber.interrupt(preparing);
372 + if (outcome === "resolve") read.resolve("YWJj");
373 + else read.reject(new Error("Native read failed after cancellation"));
374 +
375 + expect(Exit.hasInterrupts(yield* Fiber.await(preparing))).toBe(true);
376 + }),
377 + );
378 +
379 + // regression: #9713 read file-backed image drafts before enabling them
380 + it.effect("uploads a file-backed image from its owned copy without staging base64", () =>
381 + Effect.gen(function* () {
382 + mocks.upload.mockImplementation(
383 + async (
384 + _uri: string,
385 + _url: string,
386 + options: { onProgress?: (event: { bytesSent: unknown; totalBytes: unknown }) => void },
387 + ) => {
388 + // expo-modules-jsi delivers native Int64 progress counts as BigInt.
389 + options.onProgress?.({ bytesSent: BigInt(1), totalBytes: BigInt(4) });
390 + return { status: 204, body: "", headers: {} };
391 + },
392 + );
393 + const progress: Array<number> = [];
394 + const prepared = yield* prepare({
395 environmentId,
396 attachments: [fileBackedImage],
311 - signal: controller.signal,
397 + supportsImageUploads: true,
398 + onUploadProgress: (_, value) => progress.push(value),
399 });
313 - await readStarted.promise;
314 - controller.abort();
315 - if (outcome === "resolve") read.resolve("YWJj");
316 - else read.reject(new Error("Native read failed after cancellation"));
400
318 - await expect(preparing).resolves.toEqual({ status: "abandoned" });
319 - },
401 + expect(progress).toEqual([0.25]);
402 +
403 + expect(mocks.upload).toHaveBeenCalledWith(
404 + fileBackedImage.fileUri,
405 + "https://environment.example/api/attachments/upload/signed",
406 + expect.objectContaining({ headers: { "Content-Type": "image/png" } }),
407 + );
408 + expect(mocks.readBase64).not.toHaveBeenCalled();
409 + expect(mocks.writeFile).not.toHaveBeenCalled();
410 + expect(mocks.deleteFile).not.toHaveBeenCalled();
411 + expect(prepared.status).toBe("ready");
412 + if (prepared.status !== "ready") return;
413 + expect(prepared.attachments).toEqual([
414 + {
415 + type: "image",
416 + id: MINTED_ID,
417 + name: "photo.png",
418 + mimeType: "image/png",
419 + sizeBytes: 3,
420 + },
421 + ]);
422 + }),
423 );
424
322 - // regression: #9713 read file-backed image drafts before enabling them
323 - it("uploads a file-backed image from its owned copy without staging base64", async () => {
324 - mocks.upload.mockImplementation(
325 - async (
326 - _uri: string,
327 - _url: string,
328 - options: { onProgress?: (event: { bytesSent: unknown; totalBytes: unknown }) => void },
329 - ) => {
330 - // expo-modules-jsi delivers native Int64 progress counts as BigInt.
331 - options.onProgress?.({ bytesSent: BigInt(1), totalBytes: BigInt(4) });
332 - return { status: 204, body: "", headers: {} };
333 - },
334 - );
335 - const progress: Array<number> = [];
336 - const prepared = await prepareTurnAttachments({
337 - environmentId,
338 - attachments: [fileBackedImage],
339 - supportsImageUploads: true,
340 - onUploadProgress: (_, value) => progress.push(value),
341 - });
342 -
343 - expect(progress).toEqual([0.25]);
425 + it.effect("sends a document-picked picture with the mime it was uploaded under", () =>
426 + Effect.gen(function* () {
427 + const prepared = yield* prepare({
428 + environmentId,
429 + attachments: [documentPickedImage],
430 + });
431
345 - expect(mocks.upload).toHaveBeenCalledWith(
346 - fileBackedImage.fileUri,
347 - "https://environment.example/api/attachments/upload/signed",
348 - expect.objectContaining({ headers: { "Content-Type": "image/png" } }),
349 - );
350 - expect(mocks.readBase64).not.toHaveBeenCalled();
351 - expect(mocks.writeFile).not.toHaveBeenCalled();
352 - expect(mocks.deleteFile).not.toHaveBeenCalled();
353 - expect(prepared.status).toBe("ready");
354 - if (prepared.status !== "ready") return;
355 - expect(prepared.attachments).toEqual([
356 - {
432 + expect(mocks.upload).toHaveBeenCalledWith(
433 + "file:///documents/photo.png",
434 + "https://environment.example/api/attachments/upload/signed",
435 + expect.objectContaining({ headers: { "Content-Type": "image/png" } }),
436 + );
437 + expect(prepared.status).toBe("ready");
438 + if (prepared.status !== "ready") return;
439 + expect(prepared.attachments[0]).toEqual({
440 type: "image",
441 id: MINTED_ID,
442 name: "photo.png",
443 mimeType: "image/png",
444 sizeBytes: 3,
362 - },
363 - ]);
364 - });
365 -
366 - it("sends a document-picked picture with the mime it was uploaded under", async () => {
367 - const prepared = await prepareTurnAttachments({
368 - environmentId,
369 - attachments: [documentPickedImage],
370 - });
445 + });
446 + }),
447 + );
448
372 - expect(mocks.upload).toHaveBeenCalledWith(
373 - "file:///documents/photo.png",
374 - "https://environment.example/api/attachments/upload/signed",
375 - expect.objectContaining({ headers: { "Content-Type": "image/png" } }),
376 - );
377 - expect(prepared.status).toBe("ready");
378 - if (prepared.status !== "ready") return;
379 - expect(prepared.attachments[0]).toEqual({
380 - type: "image",
381 - id: MINTED_ID,
382 - name: "photo.png",
383 - mimeType: "image/png",
384 - sizeBytes: 3,
385 - });
386 - });
449 + it.effect("uploads an oversized document-picked image as a file", () =>
450 + Effect.gen(function* () {
451 + const largeImage = {
452 + ...documentPickedImage,
453 + mimeType: "image/png",
454 + sizeBytes: PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1,
455 + };
456 + const prepared = yield* prepare({ environmentId, attachments: [largeImage] });
457
388 - it("uploads an oversized document-picked image as a file", async () => {
389 - const largeImage = {
390 - ...documentPickedImage,
391 - mimeType: "image/png",
392 - sizeBytes: PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1,
393 - };
394 - const prepared = await prepareTurnAttachments({ environmentId, attachments: [largeImage] });
395 -
396 - expect(mocks.runAtomCommand).toHaveBeenCalledWith(
397 - expect.anything(),
398 - mocks.createUploadUrl,
399 - expect.objectContaining({
400 - input: {
458 + expect(mocks.runAtomCommand).toHaveBeenCalledWith(
459 + expect.anything(),
460 + mocks.createUploadUrl,
461 + expect.objectContaining({
462 + input: {
463 + type: "file",
464 + name: largeImage.name,
465 + mimeType: "image/png",
466 + sizeBytes: largeImage.sizeBytes,
467 + },
468 + }),
469 + expect.anything(),
470 + );
471 + expect(prepared.status).toBe("ready");
472 + if (prepared.status !== "ready") return;
473 + expect(prepared.attachments).toEqual([
474 + {
475 type: "file",
476 + id: MINTED_ID,
477 name: largeImage.name,
478 mimeType: "image/png",
479 sizeBytes: largeImage.sizeBytes,
480 },
406 - }),
407 - expect.anything(),
408 - );
409 - expect(prepared.status).toBe("ready");
410 - if (prepared.status !== "ready") return;
411 - expect(prepared.attachments).toEqual([
412 - {
413 - type: "file",
414 - id: MINTED_ID,
415 - name: largeImage.name,
416 - mimeType: "image/png",
417 - sizeBytes: largeImage.sizeBytes,
418 - },
419 - ]);
420 - expect(mocks.readBase64).not.toHaveBeenCalled();
421 - });
481 + ]);
482 + expect(mocks.readBase64).not.toHaveBeenCalled();
483 + }),
484 + );
485
423 - it("uploads generic file bytes directly and keeps mixed attachment order", async () => {
424 - const pastedFile = {
425 - ...file,
426 - source: { _tag: "pasted-text" as const },
427 - };
428 - const prepared = await prepareTurnAttachments({
429 - environmentId,
430 - attachments: [pastedFile, image],
431 - });
486 + it.effect("uploads generic file bytes directly and keeps mixed attachment order", () =>
487 + Effect.gen(function* () {
488 + const pastedFile = {
489 + ...file,
490 + source: { _tag: "pasted-text" as const },
491 + };
492 + const prepared = yield* prepare({
493 + environmentId,
494 + attachments: [pastedFile, image],
495 + });
496
433 - expect(mocks.upload).toHaveBeenCalledWith(
434 - "file:///documents/report.pdf",
435 - "https://environment.example/api/attachments/upload/signed",
436 - expect.objectContaining({
437 - httpMethod: "POST",
438 - uploadType: 0,
439 - headers: { "Content-Type": "application/pdf" },
440 - }),
441 - );
442 - expect(prepared.status).toBe("ready");
443 - if (prepared.status !== "ready") return;
444 - expect(prepared.attachments[0]).toEqual({
445 - type: "file",
446 - id: MINTED_ID,
447 - name: "report.pdf",
448 - mimeType: "application/pdf",
449 - sizeBytes: 42,
450 - source: { _tag: "pasted-text" },
451 - });
452 - expect(prepared.attachments[1]?.type).toBe("image");
453 - expect(prepared.pendingAttachmentIds).toEqual([MINTED_ID]);
454 - expect(prepared.draftAttachments[0]).toEqual({
455 - ...pastedFile,
456 - uploadedAttachmentId: MINTED_ID,
457 - uploadEnvironmentId: environmentId,
458 - });
459 - });
497 + expect(mocks.upload).toHaveBeenCalledWith(
498 + "file:///documents/report.pdf",
499 + "https://environment.example/api/attachments/upload/signed",
500 + expect.objectContaining({
501 + httpMethod: "POST",
502 + uploadType: 0,
503 + headers: { "Content-Type": "application/pdf" },
504 + }),
505 + );
506 + expect(prepared.status).toBe("ready");
507 + if (prepared.status !== "ready") return;
508 + expect(prepared.attachments[0]).toEqual({
509 + type: "file",
510 + id: MINTED_ID,
511 + name: "report.pdf",
512 + mimeType: "application/pdf",
513 + sizeBytes: 42,
514 + source: { _tag: "pasted-text" },
515 + });
516 + expect(prepared.attachments[1]?.type).toBe("image");
517 + expect(prepared.pendingAttachmentIds).toEqual([MINTED_ID]);
518 + expect(prepared.draftAttachments[0]).toEqual({
519 + ...pastedFile,
520 + uploadedAttachmentId: MINTED_ID,
521 + uploadEnvironmentId: environmentId,
522 + });
523 + }),
524 + );
525
461 - it("uses the current connection when an environment reconnects during URL creation", async () => {
462 - mocks.readAtom
463 - .mockReturnValueOnce(Option.some({ httpBaseUrl: "https://old-environment.example/" }))
464 - .mockReturnValueOnce(Option.some({ httpBaseUrl: "https://new-environment.example/" }));
526 + it.effect("uses the current connection when an environment reconnects during URL creation", () =>
527 + Effect.gen(function* () {
528 + mocks.readAtom
529 + .mockReturnValueOnce(Option.some({ httpBaseUrl: "https://old-environment.example/" }))
530 + .mockReturnValueOnce(Option.some({ httpBaseUrl: "https://new-environment.example/" }));
531
466 - await prepareTurnAttachments({ environmentId, attachments: [file] });
532 + yield* prepare({ environmentId, attachments: [file] });
533
468 - expect(mocks.upload).toHaveBeenCalledWith(
469 - file.fileUri,
470 - "https://new-environment.example/api/attachments/upload/signed",
471 - expect.anything(),
472 - );
473 - });
534 + expect(mocks.upload).toHaveBeenCalledWith(
535 + file.fileUri,
536 + "https://new-environment.example/api/attachments/upload/signed",
537 + expect.anything(),
538 + );
539 + }),
540 + );
541
475 - it("uploads a restored draft file from the current iOS document container", async () => {
476 - const fileName = "33333333-3333-4333-8333-333333333333-report%20%23.pdf";
477 - const restoredFile = {
478 - ...file,
479 - fileUri: `file:///private/var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/${fileName}`,
480 - };
481 - mocks.documentUri =
482 - "file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents";
483 - const currentUri = `${mocks.documentUri}/t3-composer-attachments/${fileName}`;
484 - mocks.upload.mockImplementation(async (uri: string) => {
485 - if (uri !== currentUri) {
486 - throw new Error("File does not exist in the previous application container.");
487 - }
488 - return { status: 204, body: "", headers: {} };
489 - });
542 + it.effect("uploads a restored draft file from the current iOS document container", () =>
543 + Effect.gen(function* () {
544 + const fileName = "33333333-3333-4333-8333-333333333333-report%20%23.pdf";
545 + const restoredFile = {
546 + ...file,
547 + fileUri: `file:///private/var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/${fileName}`,
548 + };
549 + mocks.documentUri =
550 + "file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents";
551 + const currentUri = `${mocks.documentUri}/t3-composer-attachments/${fileName}`;
552 + mocks.upload.mockImplementation(async (uri: string) => {
553 + if (uri !== currentUri) {
554 + throw new Error("File does not exist in the previous application container.");
555 + }
556 + return { status: 204, body: "", headers: {} };
557 + });
558
491 - const prepared = await prepareTurnAttachments({
492 - environmentId,
493 - attachments: [restoredFile],
494 - });
559 + const prepared = yield* prepare({
560 + environmentId,
561 + attachments: [restoredFile],
562 + });
563
496 - expect(prepared.status).toBe("ready");
497 - expect(mocks.upload).toHaveBeenCalledWith(
498 - currentUri,
499 - "https://environment.example/api/attachments/upload/signed",
500 - expect.anything(),
501 - );
502 - });
564 + expect(prepared.status).toBe("ready");
565 + expect(mocks.upload).toHaveBeenCalledWith(
566 + currentUri,
567 + "https://environment.example/api/attachments/upload/signed",
568 + expect.anything(),
569 + );
570 + }),
571 + );
572
573 it("adds uploaded file references to durable drafts without changing images", () => {
574 expect(
@@ -533,215 +602,219 @@ describe("prepareTurnAttachments", () => {
602 ]);
603 });
604
536 - it("reuses a pending file upload from a previous outbox attempt", async () => {
537 - const previouslyUploaded = {
538 - ...file,
539 - uploadedAttachmentId: "pending-existing-pdf",
540 - uploadEnvironmentId: environmentId,
541 - };
542 -
543 - const prepared = await prepareTurnAttachments({
544 - environmentId,
545 - attachments: [previouslyUploaded, image],
546 - });
605 + it.effect("reuses a pending file upload from a previous outbox attempt", () =>
606 + Effect.gen(function* () {
607 + const previouslyUploaded = {
608 + ...file,
609 + uploadedAttachmentId: "pending-existing-pdf",
610 + uploadEnvironmentId: environmentId,
611 + };
612
548 - expect(prepared.status).toBe("ready");
549 - if (prepared.status !== "ready") return;
550 - expect(prepared.attachments).toEqual([
551 - {
552 - type: "file",
553 - id: "pending-existing-pdf",
554 - name: "report.pdf",
555 - mimeType: "application/pdf",
556 - sizeBytes: 42,
557 - },
558 - {
559 - type: "image",
560 - name: "screenshot.png",
561 - mimeType: "image/png",
562 - sizeBytes: 3,
563 - dataUrl: "data:image/png;base64,YWJj",
564 - },
565 - ]);
566 - expect(prepared.pendingAttachmentIds).toEqual(["pending-existing-pdf"]);
567 - expect(mocks.upload).not.toHaveBeenCalled();
568 - expect(mocks.runAtomCommand).not.toHaveBeenCalled();
569 - });
613 + const prepared = yield* prepare({
614 + environmentId,
615 + attachments: [previouslyUploaded, image],
616 + });
617
571 - it("uploads a file again when its saved pending upload has expired", async () => {
572 - mocks.executeAtomQuery.mockResolvedValueOnce({
573 - _tag: "Failure",
574 - error: { _tag: "AssetAttachmentNotFoundError" },
575 - });
576 - const previouslyUploaded = {
577 - ...file,
578 - uploadedAttachmentId: "pending-expired-pdf",
579 - uploadEnvironmentId: environmentId,
580 - };
581 -
582 - const prepared = await prepareTurnAttachments({
583 - environmentId,
584 - attachments: [previouslyUploaded],
585 - });
618 + expect(prepared.status).toBe("ready");
619 + if (prepared.status !== "ready") return;
620 + expect(prepared.attachments).toEqual([
621 + {
622 + type: "file",
623 + id: "pending-existing-pdf",
624 + name: "report.pdf",
625 + mimeType: "application/pdf",
626 + sizeBytes: 42,
627 + },
628 + {
629 + type: "image",
630 + name: "screenshot.png",
631 + mimeType: "image/png",
632 + sizeBytes: 3,
633 + dataUrl: "data:image/png;base64,YWJj",
634 + },
635 + ]);
636 + expect(prepared.pendingAttachmentIds).toEqual(["pending-existing-pdf"]);
637 + expect(mocks.upload).not.toHaveBeenCalled();
638 + expect(mocks.runAtomCommand).not.toHaveBeenCalled();
639 + }),
640 + );
641
587 - expect(mocks.upload).toHaveBeenCalledOnce();
588 - expect(prepared.status).toBe("ready");
589 - if (prepared.status !== "ready") return;
590 - expect(prepared.pendingAttachmentIds).toEqual([MINTED_ID]);
591 - });
642 + it.effect("uploads a file again when its saved pending upload has expired", () =>
643 + Effect.gen(function* () {
644 + mocks.executeAtomQuery.mockResolvedValueOnce({
645 + _tag: "Failure",
646 + error: { _tag: "AssetAttachmentNotFoundError" },
647 + });
648 + const previouslyUploaded = {
649 + ...file,
650 + uploadedAttachmentId: "pending-expired-pdf",
651 + uploadEnvironmentId: environmentId,
652 + };
653
593 - it("uploads image bytes over HTTP while retaining the durable offline image", async () => {
594 - const persisted = vi.fn(async () => "persisted" as const);
595 - const prepared = await prepareTurnAttachments({
596 - environmentId,
597 - attachments: [image],
598 - supportsImageUploads: true,
599 - persistUploadedReferences: persisted,
600 - });
601 - expect(mocks.writeFile).toHaveBeenCalledWith("file:///cache/t3-upload-uuid", "YWJj", {
602 - encoding: "base64",
603 - });
604 - expect(mocks.upload).toHaveBeenCalledWith(
605 - "file:///cache/t3-upload-uuid",
606 - "https://environment.example/api/attachments/upload/signed",
607 - expect.objectContaining({ headers: { "Content-Type": "image/png" } }),
608 - );
609 - expect(mocks.deleteFile).toHaveBeenCalledExactlyOnceWith("file:///cache/t3-upload-uuid");
610 - expect(prepared.status).toBe("ready");
611 - if (prepared.status !== "ready") return;
612 - expect(prepared.attachments).toEqual([
613 - {
614 - type: "image",
615 - id: MINTED_ID,
616 - name: image.name,
617 - mimeType: image.mimeType,
618 - sizeBytes: image.sizeBytes,
619 - },
620 - ]);
621 - expect(prepared.draftAttachments).toEqual([
622 - { ...image, uploadedAttachmentId: MINTED_ID, uploadEnvironmentId: environmentId },
623 - ]);
624 - expect(persisted).toHaveBeenCalledWith(prepared.draftAttachments);
625 - });
654 + const prepared = yield* prepare({
655 + environmentId,
656 + attachments: [previouslyUploaded],
657 + });
658
627 - it("reuses an uploaded image and reuploads its local bytes after server expiry", async () => {
628 - const saved = {
629 - ...image,
630 - uploadedAttachmentId: "saved-image",
631 - uploadEnvironmentId: environmentId,
632 - };
633 - const reused = await prepareTurnAttachments({
634 - environmentId,
635 - attachments: [saved],
636 - supportsImageUploads: true,
637 - });
638 - expect(reused.status === "ready" && reused.attachments[0]).toEqual({
639 - type: "image",
640 - id: "saved-image",
641 - name: image.name,
642 - mimeType: image.mimeType,
643 - sizeBytes: image.sizeBytes,
644 - });
645 - expect(mocks.upload).not.toHaveBeenCalled();
646 - mocks.executeAtomQuery.mockResolvedValueOnce({
647 - _tag: "Failure",
648 - error: { _tag: "AssetAttachmentNotFoundError" },
649 - });
650 - const restored = await prepareTurnAttachments({
651 - environmentId,
652 - attachments: [saved],
653 - supportsImageUploads: true,
654 - });
655 - expect(restored.status === "ready" && restored.draftAttachments[0]).toEqual({
656 - ...saved,
657 - uploadedAttachmentId: MINTED_ID,
658 - });
659 - expect(mocks.writeFile).toHaveBeenCalledWith("file:///cache/t3-upload-uuid", "YWJj", {
660 - encoding: "base64",
661 - });
662 - });
659 + expect(mocks.upload).toHaveBeenCalledOnce();
660 + expect(prepared.status).toBe("ready");
661 + if (prepared.status !== "ready") return;
662 + expect(prepared.pendingAttachmentIds).toEqual([MINTED_ID]);
663 + }),
664 + );
665
664 - it("does not reuse an image upload from another environment", async () => {
665 - const prepared = await prepareTurnAttachments({
666 - environmentId,
667 - attachments: [
666 + it.effect("uploads image bytes over HTTP while retaining the durable offline image", () =>
667 + Effect.gen(function* () {
668 + const persisted = vi.fn(() => Effect.succeed("persisted" as const));
669 + const prepared = yield* prepare({
670 + environmentId,
671 + attachments: [image],
672 + supportsImageUploads: true,
673 + persistUploadedReferences: persisted,
674 + });
675 + expect(mocks.writeFile).toHaveBeenCalledWith("file:///cache/t3-upload-uuid", "YWJj", {
676 + encoding: "base64",
677 + });
678 + expect(mocks.upload).toHaveBeenCalledWith(
679 + "file:///cache/t3-upload-uuid",
680 + "https://environment.example/api/attachments/upload/signed",
681 + expect.objectContaining({ headers: { "Content-Type": "image/png" } }),
682 + );
683 + expect(mocks.deleteFile).toHaveBeenCalledExactlyOnceWith("file:///cache/t3-upload-uuid");
684 + expect(prepared.status).toBe("ready");
685 + if (prepared.status !== "ready") return;
686 + expect(prepared.attachments).toEqual([
687 {
669 - ...image,
670 - uploadedAttachmentId: "other-image",
671 - uploadEnvironmentId: EnvironmentId.make("other"),
688 + type: "image",
689 + id: MINTED_ID,
690 + name: image.name,
691 + mimeType: image.mimeType,
692 + sizeBytes: image.sizeBytes,
693 },
673 - ],
674 - supportsImageUploads: true,
675 - });
676 - expect(mocks.executeAtomQuery).not.toHaveBeenCalled();
677 - expect(mocks.upload).toHaveBeenCalledOnce();
678 - expect(prepared.status === "ready" && prepared.draftAttachments[0]?.uploadEnvironmentId).toBe(
679 - environmentId,
680 - );
681 - });
694 + ]);
695 + expect(prepared.draftAttachments).toEqual([
696 + { ...image, uploadedAttachmentId: MINTED_ID, uploadEnvironmentId: environmentId },
697 + ]);
698 + expect(persisted).toHaveBeenCalledWith(prepared.draftAttachments);
699 + }),
700 + );
701
683 - it("aborts an active transfer without dropping local bytes or stamping a partial upload", async () => {
684 - const started = Promise.withResolvers<void>();
685 - const controller = new AbortController();
686 - const persist = vi.fn(async () => "persisted" as const);
687 - mocks.upload.mockImplementation(
688 - (_uri: string, _url: string, options: { signal: AbortSignal }) =>
689 - new Promise((_, reject) => {
690 - options.signal.addEventListener("abort", () => reject(new Error("cancelled")), {
691 - once: true,
692 - });
693 - started.resolve();
694 - }),
695 - );
696 - const preparing = prepareTurnAttachments({
697 - environmentId,
698 - attachments: [file],
699 - signal: controller.signal,
700 - persistUploadedReferences: persist,
701 - });
702 - await started.promise;
703 - controller.abort();
704 - expect(await preparing).toEqual({ status: "abandoned" });
705 - expect(persist).not.toHaveBeenCalled();
706 - expect(mocks.deleteFile).not.toHaveBeenCalled();
707 - expect(removeCallsFor(MINTED_ID)).toBe(1);
708 - });
702 + it.effect("reuses an uploaded image and reuploads its local bytes after server expiry", () =>
703 + Effect.gen(function* () {
704 + const saved = {
705 + ...image,
706 + uploadedAttachmentId: "saved-image",
707 + uploadEnvironmentId: environmentId,
708 + };
709 + const reused = yield* prepare({
710 + environmentId,
711 + attachments: [saved],
712 + supportsImageUploads: true,
713 + });
714 + expect(reused.status === "ready" && reused.attachments[0]).toEqual({
715 + type: "image",
716 + id: "saved-image",
717 + name: image.name,
718 + mimeType: image.mimeType,
719 + sizeBytes: image.sizeBytes,
720 + });
721 + expect(mocks.upload).not.toHaveBeenCalled();
722 + mocks.executeAtomQuery.mockResolvedValueOnce({
723 + _tag: "Failure",
724 + error: { _tag: "AssetAttachmentNotFoundError" },
725 + });
726 + const restored = yield* prepare({
727 + environmentId,
728 + attachments: [saved],
729 + supportsImageUploads: true,
730 + });
731 + expect(restored.status === "ready" && restored.draftAttachments[0]).toEqual({
732 + ...saved,
733 + uploadedAttachmentId: MINTED_ID,
734 + });
735 + expect(mocks.writeFile).toHaveBeenCalledWith("file:///cache/t3-upload-uuid", "YWJj", {
736 + encoding: "base64",
737 + });
738 + }),
739 + );
740
710 - it("removes pending uploads when the native HTTP request fails", async () => {
711 - mocks.upload.mockResolvedValue({ status: 500, body: "failed", headers: {} });
741 + it.effect("does not reuse an image upload from another environment", () =>
742 + Effect.gen(function* () {
743 + const prepared = yield* prepare({
744 + environmentId,
745 + attachments: [
746 + {
747 + ...image,
748 + uploadedAttachmentId: "other-image",
749 + uploadEnvironmentId: EnvironmentId.make("other"),
750 + },
751 + ],
752 + supportsImageUploads: true,
753 + });
754 + expect(mocks.executeAtomQuery).not.toHaveBeenCalled();
755 + expect(mocks.upload).toHaveBeenCalledOnce();
756 + expect(prepared.status === "ready" && prepared.draftAttachments[0]?.uploadEnvironmentId).toBe(
757 + environmentId,
758 + );
759 + }),
760 + );
761
713 - await expect(prepareTurnAttachments({ environmentId, attachments: [file] })).rejects.toThrow(
714 - "Upload failed for 'report.pdf' (500).",
715 - );
716 - expect(removeCallsFor(MINTED_ID)).toBe(1);
717 - });
762 + it.effect(
763 + "aborts an active transfer without dropping local bytes or stamping a partial upload",
764 + () =>
765 + Effect.gen(function* () {
766 + const started = Promise.withResolvers<void>();
767 + const persist = vi.fn(() => Effect.succeed("persisted" as const));
768 + mocks.upload.mockImplementation(
769 + (_uri: string, _url: string, options: { signal: AbortSignal }) =>
770 + new Promise((_, reject) => {
771 + options.signal.addEventListener("abort", () => reject(new Error("cancelled")), {
772 + once: true,
773 + });
774 + started.resolve();
775 + }),
776 + );
777 + const preparing = yield* Effect.forkChild(
778 + prepare({ environmentId, attachments: [file], persistUploadedReferences: persist }),
779 + );
780 + yield* Effect.promise(() => started.promise);
781 + yield* Fiber.interrupt(preparing);
782 + expect(Exit.hasInterrupts(yield* Fiber.await(preparing))).toBe(true);
783 + expect(persist).not.toHaveBeenCalled();
784 + expect(mocks.deleteFile).not.toHaveBeenCalled();
785 + expect(removeCallsFor(MINTED_ID)).toBe(1);
786 + }),
787 + );
788
719 - it("keeps a previously persisted upload when a later attachment fails", async () => {
720 - const previouslyUploaded = {
721 - ...file,
722 - id: "file-existing",
723 - uploadedAttachmentId: "pending-existing-pdf",
724 - uploadEnvironmentId: environmentId,
725 - };
726 - mocks.upload.mockResolvedValue({ status: 500, body: "failed", headers: {} });
789 + it.effect("removes pending uploads when the native HTTP request fails", () =>
790 + Effect.gen(function* () {
791 + mocks.upload.mockResolvedValue({ status: 500, body: "failed", headers: {} });
792
728 - await expect(
729 - prepareTurnAttachments({ environmentId, attachments: [previouslyUploaded, file] }),
730 - ).rejects.toThrow("Upload failed for 'report.pdf' (500).");
793 + expect(
794 + (yield* Effect.flip(prepare({ environmentId, attachments: [file] }))).message,
795 + ).toContain("Upload failed for 'report.pdf' (500).");
796 + expect(removeCallsFor(MINTED_ID)).toBe(1);
797 + }),
798 + );
799
732 - expect(removeCallsFor("pending-existing-pdf")).toBe(0);
733 - });
800 + it.effect("keeps a previously persisted upload when a later attachment fails", () =>
801 + Effect.gen(function* () {
802 + const previouslyUploaded = {
803 + ...file,
804 + id: "file-existing",
805 + uploadedAttachmentId: "pending-existing-pdf",
806 + uploadEnvironmentId: environmentId,
807 + };
808 + mocks.upload.mockResolvedValue({ status: 500, body: "failed", headers: {} });
809
735 - it("deletes the minted uploads when the owner abandons the send", async () => {
736 - const result = await prepareTurnAttachments({
737 - environmentId,
738 - attachments: [file],
739 - persistUploadedReferences: async () => "abandon",
740 - });
810 + expect(
811 + (yield* Effect.flip(prepare({ environmentId, attachments: [previouslyUploaded, file] })))
812 + .message,
813 + ).toContain("Upload failed for 'report.pdf' (500).");
814
742 - expect(result.status).toBe("abandoned");
743 - expect(removeCallsFor(MINTED_ID)).toBe(1);
744 - });
815 + expect(removeCallsFor("pending-existing-pdf")).toBe(0);
816 + }),
817 + );
818 });
819
820 describe("releasePendingAttachmentUploads", () => {
apps/mobile/src/lib/attachmentUpload.ts
+134 -141
@@ -15,6 +15,7 @@ import {
15 AuthOrchestrationOperateScope,
16 PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES,
17 } from "@t3tools/contracts";
18 +import * as Effect from "effect/Effect";
19 import * as Option from "effect/Option";
20
21 import { appAtomRegistry } from "../state/atom-registry";
@@ -31,6 +32,7 @@ import {
32 } from "./composerImages";
33 import { imageMimeType } from "@t3tools/shared/image";
34 import { uuidv4 } from "./uuid";
35 +import { type ComposerAttachmentUploadError, uploadError } from "./composerAttachmentUploadQueue";
36
37 export type UploadedMobileAttachment =
38 | UploadChatImageAttachment
@@ -248,159 +250,150 @@ async function uploadFileBytes(
250 }
251 }
252
251 -/** persistUploadedReferences runs only for new uploaded ids; save them to their owner so crash retries reuse bytes. */
252 -export async function prepareTurnAttachments(input: {
253 +function requireUploadAccess(environmentId: EnvironmentId): void {
254 + if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) {
255 + throw new Error("This connection cannot upload attachments.");
256 + }
257 +}
258 +
259 +/**
260 + * Uploads one attachment and resolves to its uploaded id, reusing an earlier upload the server
261 + * still has. An abort deletes the pending upload it created.
262 + */
263 +export async function uploadComposerAttachment(
264 + environmentId: EnvironmentId,
265 + attachment: DraftComposerAttachment,
266 + signal: AbortSignal,
267 + onProgress?: (progress: number) => void,
268 +): Promise<string> {
269 + requireUploadAccess(environmentId);
270 + if (
271 + attachment.uploadEnvironmentId === environmentId &&
272 + attachment.uploadedAttachmentId !== undefined
273 + ) {
274 + const verification = await verifyPersistedAttachmentUpload({
275 + registry: appAtomRegistry,
276 + createAssetUrl: assetEnvironment.createUrl,
277 + environmentId,
278 + attachmentId: attachment.uploadedAttachmentId,
279 + });
280 + if (verification.status === "failed") throw verification.error;
281 + if (verification.status === "verified") return attachment.uploadedAttachmentId;
282 + }
283 + if (signal.aborted) throw new Error("Upload cancelled.");
284 + requireUploadAccess(environmentId);
285 + if (
286 + Option.isNone(
287 + appAtomRegistry.get(environmentSession.preparedConnectionValueAtom(environmentId)),
288 + )
289 + ) {
290 + throw new Error("The environment is not connected.");
291 + }
292 + let minted: string | null = null;
293 + const result = await runAttachmentUploadCycle({
294 + registry: appAtomRegistry,
295 + createUploadUrl: attachmentEnvironment.createUploadUrl,
296 + remove: attachmentEnvironment.remove,
297 + environmentId,
298 + upload: attachmentUploadInput(attachment),
299 + // Resolve at transfer time; reconnects may change the base URL.
300 + resolveUploadUrl: (relativeUrl) => {
301 + requireUploadAccess(environmentId);
302 + const connection = appAtomRegistry.get(
303 + environmentSession.preparedConnectionValueAtom(environmentId),
304 + );
305 + return Option.isNone(connection)
306 + ? null
307 + : resolveAssetUrl(connection.value.httpBaseUrl, relativeUrl);
308 + },
309 + transport: (url) => ({
310 + done: uploadFileBytes(environmentId, attachment, url, signal, onProgress),
311 + abort: () => {},
312 + }),
313 + onMinted: (attachmentId) => {
314 + if (signal.aborted) return "cancel";
315 + minted = attachmentId;
316 + return "continue";
317 + },
318 + });
319 + if (result.status === "uploaded") return result.attachmentId;
320 + if (minted !== null) await releaseCreatedUploadsQuietly(environmentId, [minted]);
321 + throw result.status === "failed" && result.error !== undefined
322 + ? result.error
323 + : new Error(`Upload failed for '${attachment.name}'.`);
324 +}
325 +
326 +/**
327 + * Turns a message's attachments into wire references. `uploadAttachment` is the shared upload
328 + * registry, so a send joins an upload the composer already started; interrupting this stops
329 + * waiting without cancelling that shared upload. persistUploadedReferences runs only for new
330 + * uploaded ids; save them to their owner so crash retries reuse bytes.
331 + */
332 +export const prepareTurnAttachments = Effect.fn("prepareTurnAttachments")(function* (input: {
333 readonly environmentId: EnvironmentId;
334 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
335 readonly supportsImageUploads?: boolean;
256 - readonly signal?: AbortSignal;
257 - readonly onUploadProgress?: (attachmentId: string, progress: number) => void;
336 + readonly uploadAttachment: (
337 + attachment: DraftComposerAttachment,
338 + ) => Effect.Effect<string, ComposerAttachmentUploadError>;
339 readonly persistUploadedReferences?: (
340 draftAttachments: ReadonlyArray<DraftComposerAttachment>,
260 - ) => Promise<"persisted" | "abandon">;
261 -}): Promise<PrepareTurnAttachmentsResult> {
341 + ) => Effect.Effect<"persisted" | "abandon">;
342 +}) {
343 const { environmentId } = input;
263 - if (input.signal?.aborted) return { status: "abandoned" };
344 + const inlineImages = (attachments: ReadonlyArray<DraftComposerAttachment>) =>
345 + Effect.tryPromise({
346 + try: () =>
347 + toUploadChatImageAttachments(
348 + attachments.filter(
349 + (attachment): attachment is DraftComposerImageAttachment => attachment.type === "image",
350 + ),
351 + ),
352 + catch: uploadError,
353 + });
354 const files = input.attachments.filter((attachment) => attachment.type === "file");
265 - const ready = (
266 - attachments: ReadonlyArray<UploadedMobileAttachment>,
267 - pendingAttachmentIds: ReadonlyArray<string>,
268 - draftAttachments: ReadonlyArray<DraftComposerAttachment>,
269 - ): PreparedTurnAttachments => ({
270 - status: "ready",
271 - attachments,
272 - draftAttachments,
273 - pendingAttachmentIds,
274 - });
275 -
355 if (input.attachments.length === 0 || (files.length === 0 && !input.supportsImageUploads)) {
277 - try {
278 - const imageAttachments = await toUploadChatImageAttachments(
279 - input.attachments.filter((attachment) => attachment.type === "image"),
280 - );
281 - if (input.signal?.aborted) return { status: "abandoned" };
282 - return ready(imageAttachments, [], input.attachments);
283 - } catch (error) {
284 - if (input.signal?.aborted) return { status: "abandoned" };
285 - throw error;
286 - }
287 - }
288 -
289 - const requireUploadAccess = () => {
290 - if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) {
291 - throw new Error("This connection cannot upload attachments.");
292 - }
293 - };
294 - requireUploadAccess();
295 -
296 - const connection = appAtomRegistry.get(
297 - environmentSession.preparedConnectionValueAtom(environmentId),
298 - );
299 - if (Option.isNone(connection)) {
300 - throw new Error("The environment is not connected.");
356 + const imageAttachments = yield* inlineImages(input.attachments);
357 + return {
358 + status: "ready",
359 + attachments: imageAttachments,
360 + draftAttachments: input.attachments,
361 + pendingAttachmentIds: [],
362 + } satisfies PreparedTurnAttachments as PrepareTurnAttachmentsResult;
363 }
364
365 + yield* Effect.try({ try: () => requireUploadAccess(environmentId), catch: uploadError });
366 const uploadedAttachments: UploadedMobileAttachment[] = [];
367 const pendingAttachmentIds: string[] = [];
305 - const createdAttachmentIds: string[] = [];
306 - const controller = new AbortController();
307 - const abort = () => controller.abort();
308 - input.signal?.addEventListener("abort", abort, { once: true });
309 - try {
310 - for (const attachment of input.attachments) {
311 - if (controller.signal.aborted) throw new Error("Upload cancelled.");
312 - requireUploadAccess();
313 - if (attachment.type === "image" && !input.supportsImageUploads) {
314 - uploadedAttachments.push(...(await toUploadChatImageAttachments([attachment])));
315 - continue;
316 - }
317 -
318 - if (
319 - attachment.uploadEnvironmentId === environmentId &&
320 - attachment.uploadedAttachmentId !== undefined
321 - ) {
322 - const verification = await verifyPersistedAttachmentUpload({
323 - registry: appAtomRegistry,
324 - createAssetUrl: assetEnvironment.createUrl,
325 - environmentId,
326 - attachmentId: attachment.uploadedAttachmentId,
327 - });
328 - if (verification.status === "failed") {
329 - throw verification.error;
330 - }
331 - if (verification.status === "verified") {
332 - pendingAttachmentIds.push(attachment.uploadedAttachmentId);
333 - uploadedAttachments.push(uploadedReference(attachment, attachment.uploadedAttachmentId));
334 - continue;
335 - }
336 - }
337 -
338 - requireUploadAccess();
339 - const result = await runAttachmentUploadCycle({
340 - registry: appAtomRegistry,
341 - createUploadUrl: attachmentEnvironment.createUploadUrl,
342 - remove: attachmentEnvironment.remove,
343 - environmentId,
344 - upload: attachmentUploadInput(attachment),
345 - // Resolve at transfer time; reconnects may change the base URL.
346 - resolveUploadUrl: (relativeUrl) => {
347 - requireUploadAccess();
348 - const currentConnection = appAtomRegistry.get(
349 - environmentSession.preparedConnectionValueAtom(environmentId),
350 - );
351 - return Option.isNone(currentConnection)
352 - ? null
353 - : resolveAssetUrl(currentConnection.value.httpBaseUrl, relativeUrl);
354 - },
355 - transport: (url) => ({
356 - done: uploadFileBytes(
357 - environmentId,
358 - attachment,
359 - url,
360 - controller.signal,
361 - input.onUploadProgress
362 - ? (progress) => input.onUploadProgress?.(attachment.id, progress)
363 - : undefined,
364 - ),
365 - abort,
366 - }),
367 - onMinted: (attachmentId) => {
368 - if (controller.signal.aborted) return "cancel";
369 - pendingAttachmentIds.push(attachmentId);
370 - createdAttachmentIds.push(attachmentId);
371 - return "continue";
372 - },
373 - });
374 - if (result.status !== "uploaded") {
375 - throw result.status === "failed" && result.error !== undefined
376 - ? result.error
377 - : new Error(`Upload failed for '${attachment.name}'.`);
378 - }
379 - uploadedAttachments.push(uploadedReference(attachment, result.attachmentId));
368 + for (const attachment of input.attachments) {
369 + if (attachment.type === "image" && !input.supportsImageUploads) {
370 + uploadedAttachments.push(...(yield* inlineImages([attachment])));
371 + continue;
372 }
373 + const uploadedId = yield* input.uploadAttachment(attachment);
374 + pendingAttachmentIds.push(uploadedId);
375 + uploadedAttachments.push(uploadedReference(attachment, uploadedId));
376 + }
377
382 - if (controller.signal.aborted) throw new Error("Upload cancelled.");
383 -
384 - const draftAttachments = withUploadedMobileAttachmentReferences({
385 - environmentId,
386 - attachments: input.attachments,
387 - uploadedAttachments,
388 - });
389 - const referencesChanged = draftAttachments.some(
390 - (attachment, index) => attachment !== input.attachments[index],
391 - );
392 - if (referencesChanged && input.persistUploadedReferences) {
393 - if ((await input.persistUploadedReferences(draftAttachments)) === "abandon") {
394 - await releaseCreatedUploadsQuietly(environmentId, createdAttachmentIds);
395 - return { status: "abandoned" };
396 - }
397 - }
398 - return ready(uploadedAttachments, pendingAttachmentIds, draftAttachments);
399 - } catch (error) {
400 - await releaseCreatedUploadsQuietly(environmentId, createdAttachmentIds);
401 - if (controller.signal.aborted) return { status: "abandoned" };
402 - throw error;
403 - } finally {
404 - input.signal?.removeEventListener("abort", abort);
378 + const draftAttachments = withUploadedMobileAttachmentReferences({
379 + environmentId,
380 + attachments: input.attachments,
381 + uploadedAttachments,
382 + });
383 + const referencesChanged = draftAttachments.some(
384 + (attachment, index) => attachment !== input.attachments[index],
385 + );
386 + if (
387 + referencesChanged &&
388 + input.persistUploadedReferences &&
389 + (yield* input.persistUploadedReferences(draftAttachments)) === "abandon"
390 + ) {
391 + return { status: "abandoned" } as PrepareTurnAttachmentsResult;
392 }
406 -}
393 + return {
394 + status: "ready",
395 + attachments: uploadedAttachments,
396 + draftAttachments,
397 + pendingAttachmentIds,
398 + } satisfies PreparedTurnAttachments as PrepareTurnAttachmentsResult;
399 +});
apps/mobile/src/lib/composerAttachmentUploadQueue.test.ts
+56 -26
@@ -1,5 +1,8 @@
1 import { ApprovalRequestId, EnvironmentId, ThreadId } from "@t3tools/contracts";
2 -import { describe, expect, it, vi } from "vite-plus/test";
2 +import * as Effect from "effect/Effect";
3 +import * as Fiber from "effect/Fiber";
4 +import { describe, expect, it } from "@effect/vitest";
5 +import { vi } from "vite-plus/test";
6 import {
7 questionAttachmentDraftKey,
8 questionAttachmentDraftPrefix,
@@ -33,7 +36,7 @@ function request(id: string, environment = environmentId): ComposerAttachmentUpl
36
37 describe("composer attachment upload queue", () => {
38 it("bounds concurrency, deduplicates updates, and drains all attachments", async () => {
36 - const gates = new Map<string, ReturnType<typeof Promise.withResolvers<boolean>>>();
39 + const gates = new Map<string, ReturnType<typeof Promise.withResolvers<string>>>();
40 const fourthStarted = Promise.withResolvers<void>();
41 const firstThreeStarted = Promise.withResolvers<void>();
42 let active = 0;
@@ -41,7 +44,7 @@ describe("composer attachment upload queue", () => {
44 const upload = vi.fn(async (input: ComposerAttachmentUploadRequest) => {
45 active += 1;
46 maximum = Math.max(maximum, active);
44 - const gate = Promise.withResolvers<boolean>();
47 + const gate = Promise.withResolvers<string>();
48 gates.set(input.attachment.id, gate);
49 if (gates.size === 3) firstThreeStarted.resolve();
50 if (gates.size === 4) fourthStarted.resolve();
@@ -57,9 +60,9 @@ describe("composer attachment upload queue", () => {
60 queue.sync(requests);
61 await firstThreeStarted.promise;
62 expect(upload).toHaveBeenCalledTimes(3);
60 - gates.get("one")!.resolve(true);
63 + gates.get("one")!.resolve("uploaded");
64 await fourthStarted.promise;
62 - for (const gate of gates.values()) gate.resolve(true);
65 + for (const gate of gates.values()) gate.resolve("uploaded");
66 await queue.settled();
67 queue.sync(requests);
68 await queue.settled();
@@ -76,8 +79,8 @@ describe("composer attachment upload queue", () => {
79 async (_request: ComposerAttachmentUploadRequest, currentSignal: AbortSignal) => {
80 signal = currentSignal;
81 started.resolve();
79 - return new Promise<boolean>((resolve) =>
80 - currentSignal.addEventListener("abort", () => resolve(false), { once: true }),
82 + return new Promise<string>((resolve) =>
83 + currentSignal.addEventListener("abort", () => resolve("aborted"), { once: true }),
84 );
85 },
86 );
@@ -94,7 +97,7 @@ describe("composer attachment upload queue", () => {
97 await queue.settled();
98 expect(signal?.aborted).toBe(true);
99 expect(states).toEqual({});
97 - upload.mockResolvedValueOnce(true);
100 + upload.mockResolvedValueOnce("uploaded");
101 queue.sync([local]);
102 await queue.settled();
103 expect(upload.mock.calls[1]?.[0]).toBe(local);
@@ -107,7 +110,10 @@ describe("composer attachment upload queue", () => {
110
111 it("retries a failed attachment when the worker restores requests after reconnect", async () => {
112 let states: Readonly<Record<string, ComposerAttachmentUploadState>> = {};
110 - const upload = vi.fn().mockRejectedValueOnce(new Error("Disconnected")).mockResolvedValue(true);
113 + const upload = vi
114 + .fn()
115 + .mockRejectedValueOnce(new Error("Disconnected"))
116 + .mockResolvedValue("uploaded");
117 const queue = createComposerAttachmentUploadQueue({
118 upload,
119 onChange: (next) => {
@@ -131,7 +137,7 @@ describe("composer attachment upload queue", () => {
137 });
138
139 it("ignores a late completion after removal or environment switch", async () => {
134 - const gate = Promise.withResolvers<boolean>();
140 + const gate = Promise.withResolvers<string>();
141 const started = Promise.withResolvers<void>();
142 let states: Readonly<Record<string, ComposerAttachmentUploadState>> = {};
143 const upload = vi.fn(async () => {
@@ -146,10 +152,10 @@ describe("composer attachment upload queue", () => {
152 });
153 queue.sync([request("photo")]);
154 await started.promise;
149 - upload.mockResolvedValueOnce(true);
155 + upload.mockResolvedValueOnce("uploaded");
156 const other = EnvironmentId.make("environment-2");
157 queue.sync([request("photo", other)]);
152 - gate.resolve(true);
158 + gate.resolve("uploaded");
159 await queue.settled();
160 expect(states).toEqual({ [composerAttachmentUploadKey(other, "photo")]: { status: "ready" } });
161 queue.sync([]);
@@ -159,9 +165,9 @@ describe("composer attachment upload queue", () => {
165
166 it("restarts a re-added attachment after its aborted transfer finishes settling", async () => {
167 const firstStarted = Promise.withResolvers<void>();
162 - const firstSettled = Promise.withResolvers<boolean>();
168 + const firstSettled = Promise.withResolvers<string>();
169 const secondStarted = Promise.withResolvers<void>();
164 - const secondSettled = Promise.withResolvers<boolean>();
170 + const secondSettled = Promise.withResolvers<string>();
171 let states: Readonly<Record<string, ComposerAttachmentUploadState>> = {};
172 let firstSignal: AbortSignal | undefined;
173 const upload = vi.fn(async (_request: ComposerAttachmentUploadRequest, signal: AbortSignal) => {
@@ -186,10 +192,10 @@ describe("composer attachment upload queue", () => {
192 queue.sync([local]);
193 expect(firstSignal?.aborted).toBe(true);
194 expect(upload).toHaveBeenCalledOnce();
189 - firstSettled.resolve(false);
195 + firstSettled.resolve("aborted");
196 await secondStarted.promise;
197 expect(upload).toHaveBeenCalledTimes(2);
192 - secondSettled.resolve(true);
198 + secondSettled.resolve("uploaded");
199 await queue.settled();
200 expect(states[composerAttachmentUploadKey(environmentId, local.attachment.id)]).toEqual({
201 status: "ready",
@@ -205,7 +211,7 @@ describe("composer attachment upload queue", () => {
211 _request: ComposerAttachmentUploadRequest,
212 _signal: AbortSignal,
213 report: (value: number) => void,
208 - ): Promise<boolean> => {
214 + ): Promise<string> => {
215 report(0.12);
216 report(0.13);
217 report(1.1);
@@ -229,21 +235,45 @@ describe("composer attachment upload queue", () => {
235 reason: "Server unavailable",
236 });
237 expect(progress).toEqual([0, 0.1, 1]);
232 - upload.mockImplementationOnce(async () => true);
238 + upload.mockImplementationOnce(async () => "uploaded");
239 queue.retry(environmentId, "file");
240 await queue.settled();
241 expect(states[composerAttachmentUploadKey(environmentId, "file")]).toEqual({ status: "ready" });
242 queue.dispose();
243 });
244
239 - it("does not spin when an upload's draft was abandoned before persistence", async () => {
240 - const upload = vi.fn(async () => false);
241 - const queue = createComposerAttachmentUploadQueue({ upload, onChange: () => {} });
242 - queue.sync([request("discarded")]);
243 - await queue.settled();
244 - expect(upload).toHaveBeenCalledOnce();
245 - queue.dispose();
246 - });
245 + it.effect("joins a send to the running upload instead of uploading again", () =>
246 + Effect.gen(function* () {
247 + const gate = Promise.withResolvers<string>();
248 + const started = Promise.withResolvers<void>();
249 + const uploaded = vi.fn();
250 + const upload = vi.fn(async () => {
251 + started.resolve();
252 + return gate.promise;
253 + });
254 + let states: Readonly<Record<string, ComposerAttachmentUploadState>> = {};
255 + const queue = createComposerAttachmentUploadQueue({
256 + upload,
257 + onUploaded: uploaded,
258 + onChange: (next) => {
259 + states = next;
260 + },
261 + });
262 + const local = request("video");
263 + queue.sync([local]);
264 + yield* Effect.promise(() => started.promise);
265 + // Sending hands the attachment from the draft to the outbox, which uploads it too.
266 + const sent = yield* Effect.forkChild(queue.upload(local), { startImmediately: true });
267 + queue.sync([]);
268 + gate.resolve("uploaded-1");
269 + expect(yield* Fiber.join(sent)).toBe("uploaded-1");
270 + expect(upload).toHaveBeenCalledOnce();
271 + expect(uploaded).toHaveBeenCalledExactlyOnceWith(local, "uploaded-1");
272 + yield* Effect.promise(() => queue.settled());
273 + expect(states).toEqual({});
274 + queue.dispose();
275 + }),
276 + );
277 });
278
279 describe("draft upload scope and offline submission", () => {
apps/mobile/src/lib/composerAttachmentUploadQueue.ts
+153 -69
@@ -1,4 +1,13 @@
1 import { EnvironmentId, type ServerConfig } from "@t3tools/contracts";
2 +import * as Effect from "effect/Effect";
3 +import * as Equal from "effect/Equal";
4 +import * as Exit from "effect/Exit";
5 +import * as Fiber from "effect/Fiber";
6 +import * as Hash from "effect/Hash";
7 +import * as RcMap from "effect/RcMap";
8 +import * as Schema from "effect/Schema";
9 +import * as Scope from "effect/Scope";
10 +import * as Semaphore from "effect/Semaphore";
11 import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments";
12
13 import { parseLegacyNewTaskDraftKey } from "../state/new-task-draft-key";
@@ -129,22 +138,45 @@ export function queuedAttachmentsStillUploading(input: {
138 );
139 }
140
141 +/** Equal by environment and attachment id; the request rides along for the upload. */
142 +class UploadKey implements Equal.Equal {
143 + constructor(
144 + readonly id: string,
145 + readonly request: ComposerAttachmentUploadRequest | null,
146 + ) {}
147 + static of(request: ComposerAttachmentUploadRequest): UploadKey {
148 + return new UploadKey(
149 + composerAttachmentUploadKey(request.environmentId, request.attachment.id),
150 + request,
151 + );
152 + }
153 + [Equal.symbol](that: unknown): boolean {
154 + return that instanceof UploadKey && that.id === this.id;
155 + }
156 + [Hash.symbol](): number {
157 + return Hash.string(this.id);
158 + }
159 +}
160 +
161 +/**
162 + * Every upload of a composer attachment, shared by key: the composer holds the attachments it
163 + * shows or has queued, and a send joins the upload already running instead of starting another.
164 + * An upload is interrupted once nothing holds it.
165 + */
166 export function createComposerAttachmentUploadQueue(options: {
167 readonly upload: (
168 request: ComposerAttachmentUploadRequest,
169 signal: AbortSignal,
170 onProgress: (progress: number) => void,
137 - ) => Promise<boolean>;
171 + ) => Promise<string>;
172 + /** Saves a finished upload's id; the upload is ready once this succeeds. */
173 + readonly onUploaded?: (
174 + request: ComposerAttachmentUploadRequest,
175 + uploadedId: string,
176 + ) => Effect.Effect<void, ComposerAttachmentUploadError>;
177 readonly onChange: (states: Readonly<Record<string, ComposerAttachmentUploadState>>) => void;
178 }) {
140 - const jobs = new Map<
141 - string,
142 - { readonly controller: AbortController; readonly done: Promise<void> }
143 - >();
144 - let desired = new Map<string, ComposerAttachmentUploadRequest>();
179 let states: Readonly<Record<string, ComposerAttachmentUploadState>> = {};
146 - let disposed = false;
147 -
180 function setState(key: string, state: ComposerAttachmentUploadState | undefined) {
181 const previous = states[key];
182 if (
@@ -161,82 +193,134 @@ export function createComposerAttachmentUploadQueue(options: {
193 options.onChange(states);
194 }
195
164 - function pump() {
165 - if (disposed) return;
166 - for (const [key, request] of desired) {
167 - if (jobs.size >= 3) break;
168 - if (jobs.has(key) || states[key]?.status === "ready" || states[key]?.status === "failed")
169 - continue;
196 + const permits = Semaphore.makeUnsafe(3);
197 + const running = new Set<Fiber.Fiber<string, ComposerAttachmentUploadError>>();
198 + // The latest transfer per attachment: a re-added attachment waits for an aborted one to settle.
199 + const transfers = new Map<string, Fiber.Fiber<string, ComposerAttachmentUploadError>>();
200 +
201 + /** The native transfer; interrupting it aborts the request and waits for it to settle. */
202 + const nativeTransfer = (key: UploadKey) =>
203 + Effect.suspend(() => {
204 const controller = new AbortController();
171 - setState(key, { status: "uploading", progress: 0 });
172 - // Publish the job before starting async work, including synchronous test transports.
173 - const done = Promise.resolve()
174 - .then(() =>
175 - options.upload(request, controller.signal, (progress) => {
176 - if (controller.signal.aborted) return;
177 - setState(key, {
178 - status: "uploading",
179 - progress: Math.floor(Math.max(0, Math.min(1, progress)) * 20) / 20,
180 - });
181 - }),
182 - )
183 - .then((persisted) => {
184 - if (!controller.signal.aborted && desired.has(key)) {
185 - if (!persisted) desired.delete(key);
186 - setState(key, persisted ? { status: "ready" } : undefined);
187 - }
188 - })
189 - .catch((error: unknown) => {
190 - if (!controller.signal.aborted && desired.has(key)) {
191 - setState(key, {
192 - status: "failed",
193 - reason: error instanceof Error ? error.message : "Upload failed. Tap to retry.",
194 - });
195 - }
196 - })
197 - .finally(() => {
198 - jobs.delete(key);
199 - pump();
205 + if (states[key.id]?.status !== "uploading") {
206 + setState(key.id, { status: "uploading", progress: 0 });
207 + }
208 + const done = options.upload(key.request!, controller.signal, (progress) => {
209 + if (controller.signal.aborted) return;
210 + setState(key.id, {
211 + status: "uploading",
212 + progress: Math.floor(Math.max(0, Math.min(1, progress)) * 20) / 20,
213 });
201 - jobs.set(key, { controller, done });
214 + });
215 + return Effect.tryPromise({ try: () => done, catch: uploadError }).pipe(
216 + Effect.onInterrupt(() =>
217 + Effect.sync(() => controller.abort()).pipe(
218 + Effect.andThen(Effect.tryPromise({ try: () => done, catch: uploadError })),
219 + Effect.ignore,
220 + ),
221 + ),
222 + );
223 + });
224 +
225 + const transfer = (key: UploadKey, previous: Fiber.Fiber<string, unknown> | undefined) =>
226 + (previous === undefined ? Effect.void : Fiber.await(previous)).pipe(
227 + Effect.andThen(nativeTransfer(key).pipe(Semaphore.withPermits(permits, 1))),
228 + Effect.tap((uploadedId) => options.onUploaded?.(key.request!, uploadedId) ?? Effect.void),
229 + Effect.tap(() => Effect.sync(() => setState(key.id, { status: "ready" }))),
230 + Effect.tapError((error) =>
231 + Effect.sync(() => setState(key.id, { status: "failed", reason: error.message })),
232 + ),
233 + );
234 +
235 + const scope = Scope.makeUnsafe();
236 + const uploads = Effect.runSync(
237 + Scope.provide(scope)(
238 + RcMap.make({
239 + lookup: Effect.fn("ComposerAttachmentUploads.lookup")(function* (key: UploadKey) {
240 + setState(key.id, { status: "uploading", progress: 0 });
241 + yield* Effect.addFinalizer(() => Effect.sync(() => setState(key.id, undefined)));
242 + const fiber = yield* Effect.forkScoped(transfer(key, transfers.get(key.id)));
243 + transfers.set(key.id, fiber);
244 + running.add(fiber);
245 + fiber.addObserver(() => {
246 + running.delete(fiber);
247 + if (transfers.get(key.id) === fiber) transfers.delete(key.id);
248 + });
249 + return fiber;
250 + }),
251 + }),
252 + ),
253 + );
254 +
255 + const holders = new Map<string, Scope.Closeable>();
256 + let requested: ReadonlyArray<ComposerAttachmentUploadRequest> = [];
257 + let disposed = false;
258 + const release = (id: string) => {
259 + const holder = holders.get(id);
260 + if (!holder) return;
261 + holders.delete(id);
262 + Effect.runFork(Scope.close(holder, Exit.void));
263 + };
264 +
265 + /** Holds exactly these uploads; anything no longer requested and held nowhere else stops. */
266 + function sync(requests: ReadonlyArray<ComposerAttachmentUploadRequest>) {
267 + if (disposed) return;
268 + requested = requests;
269 + const keys = new Map(requests.map((request) => [UploadKey.of(request).id, request]));
270 + for (const id of holders.keys()) {
271 + if (!keys.has(id)) release(id);
272 + }
273 + for (const [id, request] of keys) {
274 + if (holders.has(id)) continue;
275 + const holder = Scope.makeUnsafe();
276 + holders.set(id, holder);
277 + Effect.runSync(Scope.provide(holder)(RcMap.get(uploads, UploadKey.of(request))));
278 }
279 }
280
281 return {
206 - sync(requests: ReadonlyArray<ComposerAttachmentUploadRequest>) {
207 - if (disposed) return;
208 - desired = new Map(
209 - requests.map((request) => [
210 - composerAttachmentUploadKey(request.environmentId, request.attachment.id),
211 - request,
212 - ]),
213 - );
214 - for (const [key, job] of jobs) {
215 - if (!desired.has(key)) job.controller.abort();
216 - }
217 - for (const key of Object.keys(states)) {
218 - if (!desired.has(key)) setState(key, undefined);
219 - }
220 - for (const key of desired.keys()) {
221 - if (!states[key]) setState(key, { status: "uploading", progress: 0 });
222 - }
223 - pump();
282 + sync,
283 + /** Uploads the attachment, joining its running upload when there is one. */
284 + upload(
285 + request: ComposerAttachmentUploadRequest,
286 + ): Effect.Effect<string, ComposerAttachmentUploadError> {
287 + return disposed
288 + ? Effect.fail(uploadError(new Error("Upload cancelled.")))
289 + : RcMap.get(uploads, UploadKey.of(request)).pipe(Effect.flatMap(Fiber.join), Effect.scoped);
290 },
291 retry(environmentId: EnvironmentId, attachmentId: string) {
226 - const key = composerAttachmentUploadKey(environmentId, attachmentId);
227 - if (states[key]?.status !== "failed") return;
228 - setState(key, undefined);
229 - pump();
292 + const id = composerAttachmentUploadKey(environmentId, attachmentId);
293 + if (states[id]?.status !== "failed") return;
294 + Effect.runSync(RcMap.invalidate(uploads, new UploadKey(id, null)));
295 + release(id);
296 + sync(requested);
297 },
298 async settled() {
232 - while (jobs.size > 0) await Promise.all([...jobs.values()].map((job) => job.done));
299 + while (running.size > 0) {
300 + await Effect.runPromise(Fiber.awaitAll([...running]));
301 + }
302 },
303 dispose() {
304 disposed = true;
236 - desired.clear();
237 - for (const job of jobs.values()) job.controller.abort();
305 + holders.clear();
306 + Effect.runFork(Scope.close(scope, Exit.void));
307 states = {};
308 options.onChange(states);
309 },
310 };
311 }
312 +
313 +export function uploadError(cause: unknown): ComposerAttachmentUploadError {
314 + if (isComposerAttachmentUploadError(cause)) return cause;
315 + return new ComposerAttachmentUploadError({
316 + message: cause instanceof Error ? cause.message : "Upload failed. Tap to retry.",
317 + cause,
318 + });
319 +}
320 +
321 +export class ComposerAttachmentUploadError extends Schema.TaggedError<ComposerAttachmentUploadError>()(
322 + "ComposerAttachmentUploadError",
323 + { message: Schema.String, cause: Schema.Defect() },
324 +) {}
325 +
326 +const isComposerAttachmentUploadError = Schema.is(ComposerAttachmentUploadError);
apps/mobile/src/state/composer-attachment-uploads.test.ts
+2 -1
@@ -369,7 +369,8 @@ it("keeps an unexpected draft flush error blocking Send", async () => {
369 expect(composerAttachmentUploadBlockReason(sendInput())).toBe(
370 "Retry or remove the failed attachment",
371 );
372 - expect(native.deleted).toEqual(["pending-1"]);
372 + // The server sweeps pending uploads nothing claims; a retry uploads again.
373 + expect(native.deleted).toEqual([]);
374 });
375
376 it("uploads draft attachments for threads whose ids contain colons", () => {
apps/mobile/src/state/composer-attachment-uploads.ts
+99 -79
@@ -1,16 +1,17 @@
1 -import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
1 import { useAtomValue } from "@effect/atom-react";
2 import { AuthOrchestrationOperateScope, type EnvironmentId } from "@t3tools/contracts";
3 +import * as Effect from "effect/Effect";
4 import * as Schema from "effect/Schema";
5 -import { Atom, AsyncResult } from "effect/reactivity";
5 +import { Atom } from "effect/reactivity";
6
7 -import { prepareTurnAttachments } from "../lib/attachmentUpload";
7 +import { uploadComposerAttachment } from "../lib/attachmentUpload";
8 import { retainComposerAttachmentFileForPreview } from "../lib/composerAttachmentPreviewRetention";
9 import {
10 isFileBackedComposerAttachment,
11 type DraftComposerAttachment,
12 } from "../lib/composerImages";
13 import {
14 + uploadError,
15 composerAttachmentUploadKey,
16 composerDraftEnvironmentId,
17 canUploadComposerAttachment,
@@ -22,8 +23,7 @@ import { environmentServerConfigsAtom } from "./server";
23 import {
24 flattenQueuedThreadMessages,
25 threadOutboxManager,
25 - threadOutboxRevision,
26 - updateThreadOutboxMessage,
26 + modifyThreadOutboxMessage,
27 type QueuedThreadMessage,
28 } from "./thread-outbox";
29 import { editingQueuedMessageIdsAtom } from "./use-thread-outbox";
@@ -136,33 +136,35 @@ function withUploadedAttachment(
136 };
137 }
138
139 -async function recordQueuedAttachmentUpload(
139 +const recordQueuedAttachmentUpload = Effect.fn("ComposerAttachments.recordQueuedUpload")(function* (
140 environmentId: EnvironmentId,
141 uploaded: DraftComposerAttachment,
142 -): Promise<boolean> {
143 - const awaiting = () => {
144 - const editing = appAtomRegistry.get(editingQueuedMessageIdsAtom);
145 - return flattenQueuedThreadMessages(
146 - appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
147 - ).flatMap((message) => {
148 - if (message.environmentId !== environmentId || editing[message.messageId]) return [];
149 - const updated = withUploadedAttachment(message, uploaded);
150 - return updated === null
151 - ? []
152 - : [{ updated, revision: threadOutboxRevision(message.messageId) }];
153 - });
154 - };
155 - let recorded = false;
156 - // A sibling attachment finishing at the same time bumps the revision; reread and retry.
157 - for (let attempt = 0; attempt < 3; attempt++) {
158 - const pending = awaiting();
159 - if (pending.length === 0) break;
160 - for (const { updated, revision } of pending) {
161 - recorded = (await updateThreadOutboxMessage(updated, revision)) || recorded;
162 - }
163 - }
164 - return recorded;
165 -}
142 +) {
143 + const editing = appAtomRegistry.get(editingQueuedMessageIdsAtom);
144 + const holders = flattenQueuedThreadMessages(
145 + appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
146 + ).filter(
147 + (message) =>
148 + message.environmentId === environmentId &&
149 + !editing[message.messageId] &&
150 + withUploadedAttachment(message, uploaded) !== null,
151 + );
152 + yield* Effect.forEach(
153 + holders,
154 + (message) =>
155 + Effect.tryPromise({
156 + // An editor that opened meanwhile owns the message; its draft records the upload.
157 + try: () =>
158 + modifyThreadOutboxMessage(message.messageId, (current) =>
159 + appAtomRegistry.get(editingQueuedMessageIdsAtom)[current.messageId]
160 + ? null
161 + : withUploadedAttachment(current, uploaded),
162 + ),
163 + catch: uploadError,
164 + }),
165 + { concurrency: "unbounded", discard: true },
166 + );
167 +});
168
169 // Each connected environment's session is read here so a granted or revoked
170 // operate scope re-syncs the queue.
@@ -193,8 +195,73 @@ const composerAttachmentUploadRequestsAtom = Atom.make((get) => {
195 });
196 }).pipe(Atom.withLabel("mobile:composer-attachment-upload-requests"));
197
198 +/** Saves a finished upload's id on every draft and queued message holding the attachment. */
199 +const recordComposerAttachmentUpload = Effect.fn("ComposerAttachments.recordUpload")(function* (
200 + request: ComposerAttachmentUploadRequest,
201 + uploadedId: string,
202 +) {
203 + const { environmentId, attachment } = request;
204 + const uploaded: DraftComposerAttachment = {
205 + ...attachment,
206 + uploadedAttachmentId: uploadedId,
207 + uploadEnvironmentId: environmentId,
208 + };
209 + const queued = flattenQueuedThreadMessages(
210 + appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
211 + );
212 + const knownEnvironmentIds = appAtomRegistry
213 + .get(workspaceConnections.environmentsAtom)
214 + .map((environment) => environment.environmentId);
215 + let draftsChanged = false;
216 + for (const [key, draft] of Object.entries(appAtomRegistry.get(composerDraftsAtom))) {
217 + if (
218 + composerDraftEnvironmentId(key, knownEnvironmentIds, queued, draft) === environmentId &&
219 + draft.attachments.some((candidate) => candidate.id === attachment.id)
220 + ) {
221 + draftsChanged = setComposerDraftAttachmentUpload(key, uploaded) || draftsChanged;
222 + }
223 + }
224 + yield* recordQueuedAttachmentUpload(environmentId, uploaded);
225 + if (!draftsChanged) return;
226 + // A failed draft save only costs a re-upload after restart; the outbox saves its own references.
227 + yield* Effect.tryPromise({ try: () => flushComposerDrafts(), catch: uploadError }).pipe(
228 + Effect.catchIf(
229 + (error) => isComposerDraftPersistenceError(error.cause),
230 + (error) =>
231 + Effect.logWarning(
232 + "[composer-attachments] could not save the uploaded reference",
233 + error.cause,
234 + ),
235 + ),
236 + );
237 +});
238 +
239 +function composerAttachmentUploads() {
240 + uploadQueue ??= createComposerAttachmentUploadQueue({
241 + onChange: (states) => appAtomRegistry.set(composerAttachmentUploadsAtom, states),
242 + upload: ({ environmentId, attachment }, signal, onProgress) => {
243 + const release = isFileBackedComposerAttachment(attachment)
244 + ? retainComposerAttachmentFileForPreview(attachment)
245 + : undefined;
246 + return uploadComposerAttachment(environmentId, attachment, signal, onProgress).finally(() =>
247 + release?.(),
248 + );
249 + },
250 + onUploaded: recordComposerAttachmentUpload,
251 + });
252 + return uploadQueue;
253 +}
254 +
255 +/** Every send uploads through here, so it joins the composer's upload of the same attachment. */
256 +export function uploadComposerAttachmentShared(
257 + environmentId: EnvironmentId,
258 + attachment: DraftComposerAttachment,
259 +) {
260 + return composerAttachmentUploads().upload({ environmentId, attachment });
261 +}
262 +
263 /**
197 - * Uploads draft attachments to their environment as soon as it is connected and
264 + * Uploads draft and queued attachments to their environment as soon as it is connected and
265 * operable. The queue follows the requests atom for its whole lifetime.
266 */
267 export function createComposerAttachmentUploadWorker(
@@ -203,54 +270,7 @@ export function createComposerAttachmentUploadWorker(
270 > = composerAttachmentUploadRequestsAtom,
271 ) {
272 ensureComposerDraftsLoaded();
206 - const queue = createComposerAttachmentUploadQueue({
207 - onChange: (states) => appAtomRegistry.set(composerAttachmentUploadsAtom, states),
208 - upload: async ({ environmentId, attachment }, signal, onProgress) => {
209 - const release = isFileBackedComposerAttachment(attachment)
210 - ? retainComposerAttachmentFileForPreview(attachment)
211 - : undefined;
212 - const prepared = await settlePromise(() =>
213 - prepareTurnAttachments({
214 - environmentId,
215 - attachments: [attachment],
216 - supportsImageUploads: true,
217 - signal,
218 - onUploadProgress: (_, progress) => onProgress(progress),
219 - persistUploadedReferences: async ([uploaded]) => {
220 - if (signal.aborted || !uploaded) return "abandon";
221 - const queued = flattenQueuedThreadMessages(
222 - appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
223 - );
224 - const knownEnvironmentIds = appAtomRegistry
225 - .get(workspaceConnections.environmentsAtom)
226 - .map((environment) => environment.environmentId);
227 - let retained = false;
228 - for (const [key, draft] of Object.entries(appAtomRegistry.get(composerDraftsAtom))) {
229 - if (
230 - composerDraftEnvironmentId(key, knownEnvironmentIds, queued, draft) ===
231 - environmentId &&
232 - draft.attachments.some((candidate) => candidate.id === attachment.id)
233 - ) {
234 - retained = setComposerDraftAttachmentUpload(key, uploaded) || retained;
235 - }
236 - }
237 - retained = (await recordQueuedAttachmentUpload(environmentId, uploaded)) || retained;
238 - if (!retained) return "abandon";
239 - // Draft-save failure only costs re-upload after restart; the outbox saves references independently, so preserve accepted uploads.
240 - await flushComposerDrafts().catch((error: unknown) => {
241 - if (!isComposerDraftPersistenceError(error)) throw error;
242 - console.warn("[composer-attachments] could not save the uploaded reference", error);
243 - });
244 - return "persisted";
245 - },
246 - }),
247 - );
248 - release?.();
249 - if (AsyncResult.isFailure(prepared)) throw squashAtomCommandFailure(prepared);
250 - return prepared.value.status === "ready";
251 - },
252 - });
253 - uploadQueue = queue;
273 + const queue = composerAttachmentUploads();
274 const unsubscribe = appAtomRegistry.subscribe(requestsAtom, (requests) => queue.sync(requests), {
275 immediate: true,
276 });
apps/mobile/src/state/thread-outbox-manager.ts
+41
@@ -176,6 +176,46 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
176 return true;
177 });
178
179 + /**
180 + * Applies `change` to the message as it stands when this mutation's turn comes, so concurrent
181 + * changes compose instead of failing on each other's revision. `null` leaves it unchanged.
182 + */
183 + const modify = (
184 + messageId: MessageId,
185 + change: (message: QueuedThreadMessage) => QueuedThreadMessage | null,
186 + ): Promise<boolean> =>
187 + serialize(async () => {
188 + const current = currentMessages().find((candidate) => candidate.messageId === messageId);
189 + const next = current === undefined ? null : change(current);
190 + if (current === undefined || next === null) return false;
191 + const revision = revisions.get(messageId) ?? 0;
192 + try {
193 + await options.storage.write(next);
194 + } catch (cause) {
195 + throw new ThreadOutboxManagerError({
196 + operation: "update",
197 + environmentId: next.environmentId,
198 + threadId: next.threadId,
199 + messageId,
200 + cause,
201 + });
202 + }
203 + // An enqueue publishes without waiting its turn; when one replaced the message during the
204 + // write, it wins and stays durable.
205 + if ((revisions.get(messageId) ?? 0) !== revision || !currentMessages().includes(current)) {
206 + const winner = currentMessages().find((candidate) => candidate.messageId === messageId);
207 + if (winner !== undefined) {
208 + try {
209 + await options.storage.write(winner);
210 + } catch {}
211 + }
212 + return false;
213 + }
214 + bumpRevision(messageId);
215 + setMessages(currentMessages().map((candidate) => (candidate === current ? next : candidate)));
216 + return true;
217 + });
218 +
219 // Check live ownership too; editor locks can change without message revision updates.
220 const remove = (
221 message: QueuedThreadMessage,
@@ -347,6 +387,7 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
387 confirmQueued,
388 revisionOf: (messageId: MessageId): number => revisions.get(messageId) ?? 0,
389 update,
390 + modify,
391 remove,
392 clearEnvironment,
393 };
apps/mobile/src/state/thread-outbox-model.ts
+3
@@ -288,6 +288,9 @@ export function shouldRetryThreadOutboxDelivery(error: unknown): boolean {
288 case "EnvironmentRpcUnavailableError":
289 case "EnvironmentNotRegisteredError":
290 return true;
291 + // A shared upload's failure decides by what made the upload fail.
292 + case "ComposerAttachmentUploadError":
293 + return "cause" in error && shouldRetryThreadOutboxDelivery(error.cause);
294 default:
295 break;
296 }
apps/mobile/src/state/thread-outbox.test.ts
+36
@@ -718,6 +718,42 @@ describe("thread outbox", () => {
718 registry.dispose();
719 });
720
721 + it("composes concurrent modifications of one message instead of rejecting the later one", async () => {
722 + const registry = AtomRegistry.make();
723 + const stored = new Map<MessageId, QueuedThreadMessage>();
724 + const manager = createThreadOutboxManager({
725 + registry,
726 + storage: {
727 + load: async () => ({ messages: [], errors: [] }),
728 + write: async (message) => {
729 + stored.set(message.messageId, message);
730 + },
731 + remove: async () => undefined,
732 + },
733 + });
734 + const message = queuedMessage({
735 + messageId: "message-two-uploads",
736 + createdAt: "2026-06-08T10:00:01.000Z",
737 + });
738 + await manager.enqueue(message);
739 +
740 + // Two attachments finishing together each record their upload on the same message.
741 + const results = await Promise.all([
742 + manager.modify(message.messageId, (current) => ({ ...current, text: `${current.text} a` })),
743 + manager.modify(message.messageId, (current) => ({ ...current, text: `${current.text} b` })),
744 + ]);
745 +
746 + expect(results).toEqual([true, true]);
747 + const composed = { ...message, text: `${message.text} a b` };
748 + expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({
749 + "environment-1:thread-1": [composed],
750 + });
751 + expect(stored.get(message.messageId)).toEqual(composed);
752 + await manager.remove(composed);
753 + await expect(manager.modify(message.messageId, (current) => current)).resolves.toBe(false);
754 + registry.dispose();
755 + });
756 +
757 it("rejects a stale revision before its payload reaches durable storage", async () => {
758 const registry = AtomRegistry.make();
759 const writes: string[] = [];
apps/mobile/src/state/thread-outbox.ts
+8
@@ -32,6 +32,14 @@ export function updateThreadOutboxMessage(
32 return threadOutboxManager.update(message, expectedRevision);
33 }
34
35 +/** Changes the message as it is when its turn comes; false when it is gone or `change` returns null. */
36 +export function modifyThreadOutboxMessage(
37 + messageId: QueuedThreadMessage["messageId"],
38 + change: (message: QueuedThreadMessage) => QueuedThreadMessage | null,
39 +): Promise<boolean> {
40 + return threadOutboxManager.modify(messageId, change);
41 +}
42 +
43 export function threadOutboxRevision(messageId: QueuedThreadMessage["messageId"]): number {
44 return threadOutboxManager.revisionOf(messageId);
45 }
apps/mobile/src/state/threadOutboxDelivery.permissions.test.ts
+24 -16
@@ -7,6 +7,8 @@ import {
7 ProviderInstanceId,
8 ThreadId,
9 } from "@t3tools/contracts";
10 +import { uploadError } from "../lib/composerAttachmentUploadQueue";
11 +import * as Effect from "effect/Effect";
12 import * as Cause from "effect/Cause";
13 import { AsyncResult, type Atom } from "effect/reactivity";
14 import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
@@ -107,6 +109,7 @@ vi.mock("./git", () => ({ gitEnvironment: { preparePullRequestThread: state.chec
109 vi.mock("../lib/modelOptions", () => ({ isModelSelectionUnavailable: state.modelUnavailable }));
110 vi.mock("../lib/uuid", () => ({ uuidv4: () => "uuid", randomHex: () => "abcd" }));
111 vi.mock("../lib/attachmentUpload", () => ({ prepareTurnAttachments: state.prepare }));
112 +vi.mock("./composer-attachment-uploads", () => ({ uploadComposerAttachmentShared: vi.fn() }));
113 vi.mock("./thread-outbox", async () => {
114 const { createThreadOutboxManager } = await import("./thread-outbox-manager");
115 const { appAtomRegistry } = await import("./atom-registry");
@@ -229,12 +232,14 @@ beforeEach(() => {
232 command.mockReset().mockResolvedValue(AsyncResult.success(undefined));
233 }
234 state.start.mockResolvedValue(AsyncResult.success({}));
232 - state.prepare.mockReset().mockImplementation(async ({ attachments }) => ({
233 - status: "ready",
234 - attachments: [],
235 - draftAttachments: attachments,
236 - pendingAttachmentIds: [],
237 - }));
235 + state.prepare.mockReset().mockImplementation(({ attachments }) =>
236 + Effect.succeed({
237 + status: "ready",
238 + attachments: [],
239 + draftAttachments: attachments,
240 + pendingAttachmentIds: [],
241 + }),
242 + );
243 });
244
245 describe("queued PR checkout", () => {
@@ -485,16 +490,19 @@ describe("queued task operation access", () => {
490 : {},
491 );
492 await state.manager.enqueue(queued);
488 - state.prepare.mockImplementationOnce(async ({ attachments }) => {
489 - setOperateGrant("secondary", false);
490 - if (uploadFails) throw new Error("This connection cannot upload attachments.");
491 - return {
492 - status: "ready",
493 - attachments: [],
494 - draftAttachments: attachments,
495 - pendingAttachmentIds: [],
496 - };
497 - });
493 + state.prepare.mockImplementationOnce(({ attachments }) =>
494 + Effect.suspend(() => {
495 + setOperateGrant("secondary", false);
496 + return uploadFails
497 + ? Effect.fail(uploadError(new Error("This connection cannot upload attachments.")))
498 + : Effect.succeed({
499 + status: "ready",
500 + attachments: [],
501 + draftAttachments: attachments,
502 + pendingAttachmentIds: [],
503 + });
504 + }),
505 + );
506 await runDrain();
507 expect(state.prepare).toHaveBeenCalledOnce();
508 expect(state.start).not.toHaveBeenCalled();
apps/mobile/src/state/threadOutboxDelivery.test.ts
+27 -19
@@ -2,6 +2,7 @@ import {
2 acknowledgedThreadMessagesAtom,
3 pruneCaughtUpAcknowledgedThreadMessages,
4 } from "./acknowledged-thread-messages";
5 +import * as Effect from "effect/Effect";
6 import {
7 CommandId,
8 EnvironmentId,
@@ -84,6 +85,7 @@ vi.mock("../lib/uuid", () => ({
85 vi.mock("../lib/attachmentUpload", () => ({
86 prepareTurnAttachments: harness.prepareTurnAttachments,
87 }));
88 +vi.mock("./composer-attachment-uploads", () => ({ uploadComposerAttachmentShared: vi.fn() }));
89
90 vi.mock("./projects", () => ({ environmentProjects: {} }));
91
@@ -241,12 +243,14 @@ describe("thread outbox attachment preparation", () => {
243 fileUri: "file:///documents/keep.pdf",
244 });
245 await harness.manager.enqueue(message);
244 - harness.prepareTurnAttachments.mockResolvedValueOnce({
245 - status: "ready",
246 - attachments: [],
247 - draftAttachments: message.attachments,
248 - pendingAttachmentIds: [],
249 - });
246 + harness.prepareTurnAttachments.mockReturnValueOnce(
247 + Effect.succeed({
248 + status: "ready",
249 + attachments: [],
250 + draftAttachments: message.attachments,
251 + pendingAttachmentIds: [],
252 + }),
253 + );
254 harness.canOperate = false;
255 await expect(prepareQueuedMessageAttachments(message)).resolves.toEqual({
256 status: "abandoned",
@@ -266,10 +270,12 @@ describe("thread outbox attachment preparation", () => {
270 );
271 const preparationStarted = Promise.withResolvers<void>();
272 const preparationBarrier = Promise.withResolvers<PreparedTurnAttachments>();
269 - harness.prepareTurnAttachments.mockImplementationOnce(async () => {
270 - preparationStarted.resolve();
271 - return preparationBarrier.promise;
272 - });
273 + harness.prepareTurnAttachments.mockImplementationOnce(() =>
274 + Effect.promise(() => {
275 + preparationStarted.resolve();
276 + return preparationBarrier.promise;
277 + }),
278 + );
279 await harness.manager.enqueue(message);
280 appAtomRegistry.set(editingQueuedMessageIdsAtom, { [message.messageId]: true });
281
@@ -304,15 +310,17 @@ describe("thread outbox attachment preparation", () => {
310 }
311 : attachment,
312 );
307 - harness.prepareTurnAttachments.mockImplementationOnce(async (input) => {
308 - expect(await input.persistUploadedReferences?.(uploadedAttachments)).toBe("persisted");
309 - return {
310 - status: "ready",
311 - attachments: [],
312 - draftAttachments: uploadedAttachments,
313 - pendingAttachmentIds: ["pending-new-upload"],
314 - };
315 - });
313 + harness.prepareTurnAttachments.mockImplementationOnce((input) =>
314 + Effect.gen(function* () {
315 + expect(yield* input.persistUploadedReferences!(uploadedAttachments)).toBe("persisted");
316 + return {
317 + status: "ready",
318 + attachments: [],
319 + draftAttachments: uploadedAttachments,
320 + pendingAttachmentIds: ["pending-new-upload"],
321 + } as const;
322 + }),
323 + );
324 await harness.manager.enqueue(message);
325 const revision = harness.manager.revisionOf(message.messageId);
326
apps/mobile/src/state/threadOutboxDelivery.ts
+24 -17
@@ -23,6 +23,7 @@ import {
23 } from "@t3tools/contracts";
24 import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";
25 import * as Cause from "effect/Cause";
26 +import * as Effect from "effect/Effect";
27 import { AsyncResult, Atom } from "effect/reactivity";
28
29 import { createDebugLogger } from "../lib/debugLog";
@@ -49,6 +50,7 @@ import {
50 import { environmentProjects } from "./projects";
51 import { environmentServerConfigsAtom, serverEnvironment } from "./server";
52 import { composerAttachmentUploadsAtom } from "./composer-attachment-upload-states";
53 +import { uploadComposerAttachmentShared } from "./composer-attachment-uploads";
54 import {
55 queuedAttachmentsStillUploading,
56 uploadingComposerAttachmentKeys,
@@ -229,23 +231,28 @@ export async function prepareQueuedMessageAttachments(queuedMessage: QueuedThrea
231 }
232 let persistedMessage = queuedMessage;
233 let deliveryRevision = revision;
232 - const result = await prepareTurnAttachments({
233 - environmentId: queuedMessage.environmentId,
234 - attachments: queuedMessage.attachments,
235 - supportsImageUploads: true,
236 - persistUploadedReferences: async (draftAttachments) => {
237 - if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) {
238 - return "abandon";
239 - }
240 - const updatedMessage = { ...queuedMessage, attachments: draftAttachments };
241 - if (!(await updateThreadOutboxMessage(updatedMessage, revision))) {
242 - return "abandon";
243 - }
244 - persistedMessage = updatedMessage;
245 - deliveryRevision = revision + 1;
246 - return "persisted";
247 - },
248 - });
234 + const result = await Effect.runPromise(
235 + prepareTurnAttachments({
236 + environmentId: queuedMessage.environmentId,
237 + attachments: queuedMessage.attachments,
238 + supportsImageUploads: true,
239 + uploadAttachment: (attachment) =>
240 + uploadComposerAttachmentShared(queuedMessage.environmentId, attachment),
241 + persistUploadedReferences: (draftAttachments) =>
242 + Effect.promise(async () => {
243 + if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) {
244 + return "abandon" as const;
245 + }
246 + const updatedMessage = { ...queuedMessage, attachments: draftAttachments };
247 + if (!(await updateThreadOutboxMessage(updatedMessage, revision))) {
248 + return "abandon" as const;
249 + }
250 + persistedMessage = updatedMessage;
251 + deliveryRevision = revision + 1;
252 + return "persisted" as const;
253 + }),
254 + }),
255 + );
256 if (
257 result.status === "abandoned" ||
258 !isQueuedMessagePayloadCurrent(persistedMessage, deliveryRevision)
apps/mobile/src/state/use-composer-drafts.test.ts
+60 -54
@@ -1,4 +1,6 @@
1 import { PrimaryConnectionTarget } from "@t3tools/client-runtime/connection";
2 +import * as Effect from "effect/Effect";
3 +import * as Fiber from "effect/Fiber";
4 import { createEnvironmentThreadShellAtoms } from "@t3tools/client-runtime/state/threads";
5 import {
6 applyShellStreamEvent,
@@ -1213,63 +1215,67 @@ describe("mobile composer drafts", () => {
1215 expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledExactlyOnceWith(image.fileUri);
1216 });
1217
1216 - it("keeps an image through an inline read after its draft is removed", async () => {
1217 - const { prepareTurnAttachments } =
1218 - await vi.importActual<typeof import("../lib/attachmentUpload")>("../lib/attachmentUpload");
1219 - const image = {
1220 - id: "image-reading",
1221 - type: "image" as const,
1222 - name: "photo.png",
1223 - mimeType: "image/png",
1224 - sizeBytes: 3,
1225 - fileUri: "file:///documents/t3-composer-attachments/photo.png",
1226 - previewUri: "file:///documents/t3-composer-attachments/photo.png",
1227 - };
1228 - const readStarted = Promise.withResolvers<void>();
1229 - const read = Promise.withResolvers<void>();
1230 - const removed = Promise.withResolvers<void>();
1231 - let imageExists = true;
1232 - composerDraftFileMocks.readImage.mockImplementation(async () => {
1233 - readStarted.resolve();
1234 - await read.promise;
1235 - if (!imageExists) throw new Error("The image was deleted during its read");
1236 - return "YWJj";
1237 - });
1238 - composerAttachmentCleanupMocks.remove.mockImplementationOnce(async () => {
1239 - imageExists = false;
1240 - removed.resolve();
1241 - });
1242 - appendComposerDraftAttachments("environment-1:thread-1", [image]);
1243 - await flushComposerDrafts();
1244 - const preparing = prepareTurnAttachments({
1245 - environmentId: EnvironmentId.make("environment-1"),
1246 - attachments: [image],
1247 - });
1248 - onTestFinished(async () => {
1249 - read.resolve();
1250 - await preparing.catch(() => undefined);
1251 - });
1252 - await readStarted.promise;
1253 - clearComposerDraftContent("environment-1:thread-1", { deferAttachmentCleanup: true });
1254 - await releaseUnusedComposerAttachmentFiles([image]);
1255 - expect(imageExists).toBe(true);
1256 -
1257 - read.resolve();
1258 - const prepared = await preparing;
1259 - expect(prepared.status).toBe("ready");
1260 - if (prepared.status !== "ready") return;
1261 - expect(prepared.attachments).toEqual([
1262 - {
1263 - type: "image",
1218 + it.effect("keeps an image through an inline read after its draft is removed", () =>
1219 + Effect.gen(function* () {
1220 + const { prepareTurnAttachments } = yield* Effect.promise(() =>
1221 + vi.importActual<typeof import("../lib/attachmentUpload")>("../lib/attachmentUpload"),
1222 + );
1223 + const image = {
1224 + id: "image-reading",
1225 + type: "image" as const,
1226 name: "photo.png",
1227 mimeType: "image/png",
1228 sizeBytes: 3,
1267 - dataUrl: "data:image/png;base64,YWJj",
1268 - },
1269 - ]);
1270 - await removed.promise;
1271 - expect(imageExists).toBe(false);
1272 - });
1229 + fileUri: "file:///documents/t3-composer-attachments/photo.png",
1230 + previewUri: "file:///documents/t3-composer-attachments/photo.png",
1231 + };
1232 + const readStarted = Promise.withResolvers<void>();
1233 + const read = Promise.withResolvers<void>();
1234 + const removed = Promise.withResolvers<void>();
1235 + let imageExists = true;
1236 + composerDraftFileMocks.readImage.mockImplementation(async () => {
1237 + readStarted.resolve();
1238 + await read.promise;
1239 + if (!imageExists) throw new Error("The image was deleted during its read");
1240 + return "YWJj";
1241 + });
1242 + composerAttachmentCleanupMocks.remove.mockImplementationOnce(async () => {
1243 + imageExists = false;
1244 + removed.resolve();
1245 + });
1246 + appendComposerDraftAttachments("environment-1:thread-1", [image]);
1247 + yield* Effect.promise(() => flushComposerDrafts());
1248 + // Without image uploads the image is inlined, so nothing goes through the upload registry.
1249 + const preparing = yield* Effect.forkChild(
1250 + prepareTurnAttachments({
1251 + environmentId: EnvironmentId.make("environment-1"),
1252 + attachments: [image],
1253 + uploadAttachment: vi.fn(),
1254 + }),
1255 + );
1256 + onTestFinished(() => read.resolve());
1257 + yield* Effect.promise(() => readStarted.promise);
1258 + clearComposerDraftContent("environment-1:thread-1", { deferAttachmentCleanup: true });
1259 + yield* Effect.promise(() => releaseUnusedComposerAttachmentFiles([image]));
1260 + expect(imageExists).toBe(true);
1261 +
1262 + read.resolve();
1263 + const prepared = yield* Fiber.join(preparing);
1264 + expect(prepared.status).toBe("ready");
1265 + if (prepared.status !== "ready") return;
1266 + expect(prepared.attachments).toEqual([
1267 + {
1268 + type: "image",
1269 + name: "photo.png",
1270 + mimeType: "image/png",
1271 + sizeBytes: 3,
1272 + dataUrl: "data:image/png;base64,YWJj",
1273 + },
1274 + ]);
1275 + yield* Effect.promise(() => removed.promise);
1276 + expect(imageExists).toBe(false);
1277 + }),
1278 + );
1279
1280 it("keeps a failed-send draft's pending upload for retry", async () => {
1281 const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
apps/mobile/src/state/use-thread-composer-state.ts
+11 -5
@@ -1,4 +1,5 @@
1 import { useComposerAttachmentActions } from "./use-composer-attachment-actions";
2 +import * as Effect from "effect/Effect";
3 import * as Dialog from "../components/ui/Dialog";
4 import { AuthOrchestrationOperateScope } from "@t3tools/contracts";
5 import { readEnvironmentScope } from "./session";
@@ -72,6 +73,7 @@ import { pendingThreadCreationMessage } from "./pending-thread-creation";
73 import {
74 composerAttachmentUploadBlockReason,
75 composerAttachmentUploadsAtom,
76 + uploadComposerAttachmentShared,
77 } from "./composer-attachment-uploads";
78 import {
79 appendComposerDraftAttachments,
@@ -510,11 +512,15 @@ export function useThreadComposerState(input: {
512 setIsSavingQueuedEdit(true);
513 const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities;
514 const prepared = await settlePromise(() =>
513 - prepareTurnAttachments({
514 - environmentId: thread.environmentId,
515 - attachments: draft.attachments,
516 - supportsImageUploads: capabilities !== undefined,
517 - }),
515 + Effect.runPromise(
516 + prepareTurnAttachments({
517 + environmentId: thread.environmentId,
518 + attachments: draft.attachments,
519 + supportsImageUploads: capabilities !== undefined,
520 + uploadAttachment: (attachment) =>
521 + uploadComposerAttachmentShared(thread.environmentId, attachment),
522 + }),
523 + ),
524 );
525 if (AsyncResult.isFailure(prepared)) {
526 savingQueuedEditRef.current = false;