Open History to see the last commit
1import { EnvironmentId } from "@t3tools/contracts";
2import * as Option from "effect/Option";
3import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
4
5const mocks = vi.hoisted(() => ({
6 canOperate: true,
7 documentUri: "file:///documents",
8 createAssetUrl: vi.fn(),
9 createUploadUrl: Symbol("create-upload-url"),
10 executeAtomQuery: vi.fn(),
11 removeUpload: Symbol("remove-upload"),
12 preparedConnection: Symbol("prepared-connection"),
13 runAtomCommand: vi.fn(),
14 readAtom: vi.fn(),
15 upload: vi.fn(),
16 writeFile: vi.fn(),
17 deleteFile: vi.fn(),
18 readBase64: vi.fn(),
19}));
20
21vi.mock("@t3tools/client-runtime/state/runtime", () => ({
22 createEnvironmentRpcCommand: () => Symbol("rpc-command"),
23 executeAtomQuery: mocks.executeAtomQuery,
24 runAtomCommand: mocks.runAtomCommand,
25 squashAtomCommandFailure: (result: { readonly error: unknown }) => result.error,
26}));
27
28vi.mock("../state/atom-registry", () => ({
29 appAtomRegistry: { get: mocks.readAtom },
30}));
31
32vi.mock("./composerAttachmentPreviewRetention", () => ({
33 retainComposerAttachmentFileForPreview: () => () => {},
34}));
35
36vi.mock("../state/assets", () => ({
37 assetEnvironment: { createUrl: mocks.createAssetUrl },
38}));
39
40vi.mock("../state/attachments", () => ({
41 attachmentEnvironment: {
42 createUploadUrl: mocks.createUploadUrl,
43 remove: mocks.removeUpload,
44 },
45}));
46
47vi.mock("../state/session", () => ({
48 readEnvironmentScope: () => mocks.canOperate,
49 environmentSession: {
50 preparedConnectionValueAtom: () => mocks.preparedConnection,
51 },
52}));
53
54// Cuts the expo-crypto -> react-native import chain out of the test graph.
55vi.mock("./uuid", () => ({
56 uuidv4: () => "uuid",
57 randomHex: () => "0000",
58}));
59
60vi.mock("expo-file-system", () => ({
61 File: class {
62 readonly uri: string;
63 exists = true;
64 constructor(uri: string, name?: string) {
65 this.uri = name ? `${uri}/${name}` : uri;
66 }
67 create() {}
68 write(bytes: string, options: unknown) {
69 mocks.writeFile(this.uri, bytes, options);
70 }
71 delete() {
72 mocks.deleteFile(this.uri);
73 }
74
75 async base64() {
76 return mocks.readBase64(this.uri);
77 }
78
79 upload(url: string, options: unknown) {
80 return mocks.upload(this.uri, url, options);
81 }
82 },
83 Paths: {
84 cache: "file:///cache",
85 get document() {
86 return { uri: mocks.documentUri };
87 },
88 },
89 UploadType: { BINARY_CONTENT: 0 },
90}));
91
92import {
93 prepareTurnAttachments,
94 releasePendingAttachmentUploads,
95 withUploadedMobileAttachmentReferences,
96 validateDraftFileAttachments,
97} from "./attachmentUpload";
98import type { DraftComposerAttachment } from "./composerImages";
99
100const environmentId = EnvironmentId.make("environment-1");
101const MINTED_ID = "pending-00000000-0000-4000-8000-000000000001-pdf";
102
103const image = {
104 id: "image-1",
105 type: "image",
106 name: "screenshot.png",
107 mimeType: "image/png",
108 sizeBytes: 3,
109 dataUrl: "data:image/png;base64,YWJj",
110 previewUri: "file:///images/screenshot.png",
111} as const satisfies DraftComposerAttachment;
112
113const fileBackedImage = {
114 id: "image-2",
115 type: "image",
116 name: "photo.png",
117 mimeType: "image/png",
118 sizeBytes: 3,
119 fileUri: "file:///documents/t3-composer-attachments/photo.png",
120 previewUri: "file:///documents/t3-composer-attachments/photo.png",
121} as const satisfies DraftComposerAttachment;
122
123const file = {
124 id: "file-1",
125 type: "file",
126 name: "report.pdf",
127 mimeType: "application/pdf",
128 sizeBytes: 42,
129 fileUri: "file:///documents/report.pdf",
130} as const satisfies DraftComposerAttachment;
131
132const documentPickedImage = {
133 id: "file-2",
134 type: "file",
135 name: "photo.png",
136 mimeType: "application/octet-stream",
137 sizeBytes: 3,
138 fileUri: "file:///documents/photo.png",
139} as const satisfies DraftComposerAttachment;
140
141describe("validateDraftFileAttachments", () => {
142 it("allows legacy image-only sends without server config", () => {
143 expect(validateDraftFileAttachments({ attachments: [image], serverConfig: null })).toBeNull();
144 });
145
146 it("blocks files while config is unknown or file uploads are unsupported", () => {
147 expect(validateDraftFileAttachments({ attachments: [file], serverConfig: null })).toBe(
148 "Server attachment support is still loading.",
149 );
150 expect(
151 validateDraftFileAttachments({
152 attachments: [file],
153 serverConfig: { environment: { capabilities: { attachmentUploads: true } } },
154 }),
155 ).toBe("This server does not support file attachments.");
156 });
157
158 it("uses the current clamped limit and allows valid mixed attachments", () => {
159 const lowerLimit = {
160 environment: {
161 capabilities: {
162 attachmentUploads: true,
163 fileAttachments: { maxUploadBytes: 20 },
164 },
165 },
166 };
167 expect(validateDraftFileAttachments({ attachments: [file], serverConfig: lowerLimit })).toBe(
168 "'report.pdf' exceeds the 20 bytes attachment limit.",
169 );
170 const allowed = {
171 environment: {
172 capabilities: {
173 attachmentUploads: true,
174 fileAttachments: { maxUploadBytes: 100 },
175 },
176 },
177 };
178 expect(
179 validateDraftFileAttachments({ attachments: [image, file], serverConfig: allowed }),
180 ).toBeNull();
181 });
182});
183
184function removeCallsFor(attachmentId: string): number {
185 return mocks.runAtomCommand.mock.calls.filter(
186 ([, command, target]) =>
187 command === mocks.removeUpload &&
188 (target as { input: { attachmentId: string } }).input.attachmentId === attachmentId,
189 ).length;
190}
191
192describe("prepareTurnAttachments", () => {
193 beforeEach(() => {
194 mocks.canOperate = true;
195 mocks.documentUri = "file:///documents";
196 mocks.createAssetUrl.mockReset();
197 mocks.createAssetUrl.mockImplementation((target: unknown) => target);
198 mocks.executeAtomQuery.mockReset();
199 mocks.executeAtomQuery.mockResolvedValue({ _tag: "Success", value: {} });
200 mocks.runAtomCommand.mockReset();
201 mocks.readAtom.mockReset();
202 mocks.upload.mockReset();
203 mocks.writeFile.mockReset();
204 mocks.deleteFile.mockReset();
205 mocks.readBase64.mockReset();
206 mocks.readBase64.mockResolvedValue("YWJj");
207 mocks.readAtom.mockReturnValue(Option.some({ httpBaseUrl: "https://environment.example/" }));
208 mocks.runAtomCommand.mockImplementation(async (_registry: unknown, command: unknown) =>
209 command === mocks.createUploadUrl
210 ? {
211 _tag: "Success",
212 value: {
213 attachmentId: MINTED_ID,
214 relativeUrl: "/api/attachments/upload/signed",
215 expiresAt: 1,
216 },
217 }
218 : { _tag: "Success", value: undefined },
219 );
220 mocks.upload.mockResolvedValue({ status: 204, body: "", headers: {} });
221 });
222
223 it("does not mint or transfer attachments without task operation access", async () => {
224 mocks.canOperate = false;
225 await expect(
226 prepareTurnAttachments({
227 environmentId,
228 attachments: [fileBackedImage],
229 supportsImageUploads: true,
230 }),
231 ).rejects.toThrow("cannot upload attachments");
232 expect(mocks.runAtomCommand).not.toHaveBeenCalled();
233 expect(mocks.upload).not.toHaveBeenCalled();
234 });
235
236 it("rechecks access after a signed URL is minted before sending any bytes", async () => {
237 mocks.runAtomCommand.mockImplementationOnce(async () => {
238 mocks.canOperate = false;
239 return {
240 _tag: "Success",
241 value: {
242 attachmentId: MINTED_ID,
243 relativeUrl: "/api/attachments/upload/signed",
244 expiresAt: 1,
245 },
246 };
247 });
248 const warning = vi.spyOn(console, "warn").mockImplementation(() => {});
249 try {
250 await expect(
251 prepareTurnAttachments({
252 environmentId,
253 attachments: [fileBackedImage],
254 supportsImageUploads: true,
255 }),
256 ).rejects.toThrow("cannot upload attachments");
257 expect(mocks.upload).not.toHaveBeenCalled();
258 expect(mocks.runAtomCommand).toHaveBeenCalledTimes(1);
259 } finally {
260 warning.mockRestore();
261 }
262 });
263
264 it("does not replace an expired upload when access was revoked during verification", async () => {
265 mocks.executeAtomQuery.mockImplementationOnce(async () => {
266 mocks.canOperate = false;
267 return { _tag: "Failure", error: { _tag: "AssetAttachmentNotFoundError" } };
268 });
269 await expect(
270 prepareTurnAttachments({
271 environmentId,
272 attachments: [
273 {
274 ...fileBackedImage,
275 uploadedAttachmentId: MINTED_ID,
276 uploadEnvironmentId: environmentId,
277 },
278 ],
279 supportsImageUploads: true,
280 }),
281 ).rejects.toThrow("cannot upload attachments");
282 expect(mocks.runAtomCommand).not.toHaveBeenCalled();
283 expect(mocks.upload).not.toHaveBeenCalled();
284 });
285
286 it("rechecks deletion permission before retrying a failed cleanup", async () => {
287 mocks.runAtomCommand.mockImplementationOnce(async () => {
288 mocks.canOperate = false;
289 return { _tag: "Failure", error: new Error("Retry cleanup") };
290 });
291 await expect(releasePendingAttachmentUploads(environmentId, [MINTED_ID])).rejects.toThrow(
292 "cannot delete pending attachments",
293 );
294 expect(mocks.runAtomCommand).toHaveBeenCalledTimes(1);
295 });
296
297 it("keeps existing image attachments on the legacy wire path", async () => {
298 const prepared = await prepareTurnAttachments({ environmentId, attachments: [image] });
299
300 expect(prepared.status).toBe("ready");
301 if (prepared.status !== "ready") return;
302 expect(prepared.attachments).toEqual([
303 {
304 type: "image",
305 name: "screenshot.png",
306 mimeType: "image/png",
307 sizeBytes: 3,
308 dataUrl: "data:image/png;base64,YWJj",
309 },
310 ]);
311 expect(prepared.pendingAttachmentIds).toEqual([]);
312 expect(mocks.upload).not.toHaveBeenCalled();
313 });
314
315 it("inlines a file-backed image lazily when the server lacks image uploads", async () => {
316 const prepared = await prepareTurnAttachments({
317 environmentId,
318 attachments: [fileBackedImage],
319 });
320
321 expect(prepared.status).toBe("ready");
322 if (prepared.status !== "ready") return;
323 expect(prepared.attachments).toEqual([
324 {
325 type: "image",
326 name: "photo.png",
327 mimeType: "image/png",
328 sizeBytes: 3,
329 dataUrl: "data:image/png;base64,YWJj",
330 },
331 ]);
332 expect(mocks.readBase64).toHaveBeenCalledExactlyOnceWith(fileBackedImage.fileUri);
333 expect(mocks.upload).not.toHaveBeenCalled();
334 });
335
336 it("reads restored images from the current iOS document container for legacy sends", async () => {
337 const fileName = "33333333-3333-4333-8333-333333333333-photo.png";
338 mocks.documentUri =
339 "file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents";
340 const oldUri = `file:///var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/${fileName}`;
341 const prepared = await prepareTurnAttachments({
342 environmentId,
343 attachments: [{ ...fileBackedImage, fileUri: oldUri, previewUri: oldUri }],
344 });
345 expect(prepared.status).toBe("ready");
346 expect(mocks.readBase64).toHaveBeenCalledExactlyOnceWith(
347 `${mocks.documentUri}/t3-composer-attachments/${fileName}`,
348 );
349 });
350
351 it("rejects a legacy image without inline bytes or a file", async () => {
352 const { fileUri: _, ...missingImage } = fileBackedImage;
353 await expect(
354 prepareTurnAttachments({ environmentId, attachments: [missingImage] }),
355 ).rejects.toThrow("'photo.png' is no longer available. Attach the image again.");
356 });
357
358 it.each(["resolve", "reject"] as const)(
359 "abandons a canceled legacy image read that later %ss",
360 async (outcome) => {
361 const readStarted = Promise.withResolvers<void>();
362 const read = Promise.withResolvers<string>();
363 const controller = new AbortController();
364 mocks.readBase64.mockImplementation(() => {
365 readStarted.resolve();
366 return read.promise;
367 });
368 const preparing = prepareTurnAttachments({
369 environmentId,
370 attachments: [fileBackedImage],
371 signal: controller.signal,
372 });
373 await readStarted.promise;
374 controller.abort();
375 if (outcome === "resolve") read.resolve("YWJj");
376 else read.reject(new Error("Native read failed after cancellation"));
377
378 await expect(preparing).resolves.toEqual({ status: "abandoned" });
379 },
380 );
381
382 it("uploads a file-backed image from its owned copy without staging base64", async () => {
383 const prepared = await prepareTurnAttachments({
384 environmentId,
385 attachments: [fileBackedImage],
386 supportsImageUploads: true,
387 });
388
389 expect(mocks.upload).toHaveBeenCalledWith(
390 fileBackedImage.fileUri,
391 "https://environment.example/api/attachments/upload/signed",
392 expect.objectContaining({ headers: { "Content-Type": "image/png" } }),
393 );
394 expect(mocks.readBase64).not.toHaveBeenCalled();
395 expect(mocks.writeFile).not.toHaveBeenCalled();
396 expect(mocks.deleteFile).not.toHaveBeenCalled();
397 expect(prepared.status).toBe("ready");
398 if (prepared.status !== "ready") return;
399 expect(prepared.attachments).toEqual([
400 {
401 type: "image",
402 id: MINTED_ID,
403 name: "photo.png",
404 mimeType: "image/png",
405 sizeBytes: 3,
406 },
407 ]);
408 });
409
410 it("sends a document-picked picture with the mime it was uploaded under", async () => {
411 const prepared = await prepareTurnAttachments({
412 environmentId,
413 attachments: [documentPickedImage],
414 });
415
416 expect(mocks.upload).toHaveBeenCalledWith(
417 "file:///documents/photo.png",
418 "https://environment.example/api/attachments/upload/signed",
419 expect.objectContaining({ headers: { "Content-Type": "image/png" } }),
420 );
421 expect(prepared.status).toBe("ready");
422 if (prepared.status !== "ready") return;
423 expect(prepared.attachments[0]).toEqual({
424 type: "image",
425 id: MINTED_ID,
426 name: "photo.png",
427 mimeType: "image/png",
428 sizeBytes: 3,
429 });
430 });
431
432 it("uploads generic file bytes directly and keeps mixed attachment order", async () => {
433 const pastedFile = {
434 ...file,
435 source: { _tag: "pasted-text" as const },
436 };
437 const prepared = await prepareTurnAttachments({
438 environmentId,
439 attachments: [pastedFile, image],
440 });
441
442 expect(mocks.upload).toHaveBeenCalledWith(
443 "file:///documents/report.pdf",
444 "https://environment.example/api/attachments/upload/signed",
445 expect.objectContaining({
446 httpMethod: "POST",
447 uploadType: 0,
448 headers: { "Content-Type": "application/pdf" },
449 }),
450 );
451 expect(prepared.status).toBe("ready");
452 if (prepared.status !== "ready") return;
453 expect(prepared.attachments[0]).toEqual({
454 type: "file",
455 id: MINTED_ID,
456 name: "report.pdf",
457 mimeType: "application/pdf",
458 sizeBytes: 42,
459 source: { _tag: "pasted-text" },
460 });
461 expect(prepared.attachments[1]?.type).toBe("image");
462 expect(prepared.pendingAttachmentIds).toEqual([MINTED_ID]);
463 expect(prepared.draftAttachments[0]).toEqual({
464 ...pastedFile,
465 uploadedAttachmentId: MINTED_ID,
466 uploadEnvironmentId: environmentId,
467 });
468 });
469
470 it("uses the current connection when an environment reconnects during URL creation", async () => {
471 mocks.readAtom
472 .mockReturnValueOnce(Option.some({ httpBaseUrl: "https://old-environment.example/" }))
473 .mockReturnValueOnce(Option.some({ httpBaseUrl: "https://new-environment.example/" }));
474
475 await prepareTurnAttachments({ environmentId, attachments: [file] });
476
477 expect(mocks.upload).toHaveBeenCalledWith(
478 file.fileUri,
479 "https://new-environment.example/api/attachments/upload/signed",
480 expect.anything(),
481 );
482 });
483
484 it("uploads a restored draft file from the current iOS document container", async () => {
485 const fileName = "33333333-3333-4333-8333-333333333333-report%20%23.pdf";
486 const restoredFile = {
487 ...file,
488 fileUri: `file:///private/var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/${fileName}`,
489 };
490 mocks.documentUri =
491 "file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents";
492 const currentUri = `${mocks.documentUri}/t3-composer-attachments/${fileName}`;
493 mocks.upload.mockImplementation(async (uri: string) => {
494 if (uri !== currentUri) {
495 throw new Error("File does not exist in the previous application container.");
496 }
497 return { status: 204, body: "", headers: {} };
498 });
499
500 const prepared = await prepareTurnAttachments({
501 environmentId,
502 attachments: [restoredFile],
503 });
504
505 expect(prepared.status).toBe("ready");
506 expect(mocks.upload).toHaveBeenCalledWith(
507 currentUri,
508 "https://environment.example/api/attachments/upload/signed",
509 expect.anything(),
510 );
511 });
512
513 it("adds uploaded file references to durable drafts without changing images", () => {
514 expect(
515 withUploadedMobileAttachmentReferences({
516 environmentId,
517 attachments: [file, image],
518 uploadedAttachments: [
519 {
520 type: "file",
521 id: "pending-existing-pdf",
522 name: file.name,
523 mimeType: file.mimeType,
524 sizeBytes: file.sizeBytes,
525 },
526 {
527 type: "image",
528 name: image.name,
529 mimeType: image.mimeType,
530 sizeBytes: image.sizeBytes,
531 dataUrl: image.dataUrl,
532 },
533 ],
534 }),
535 ).toEqual([
536 {
537 ...file,
538 uploadedAttachmentId: "pending-existing-pdf",
539 uploadEnvironmentId: environmentId,
540 },
541 image,
542 ]);
543 });
544
545 it("keeps the uploaded id when a document-picked picture uploads as an image", () => {
546 expect(
547 withUploadedMobileAttachmentReferences({
548 environmentId,
549 attachments: [documentPickedImage],
550 uploadedAttachments: [
551 {
552 type: "image",
553 id: "pending-promoted-png",
554 name: documentPickedImage.name,
555 mimeType: "image/png",
556 sizeBytes: documentPickedImage.sizeBytes,
557 },
558 ],
559 }),
560 ).toEqual([
561 {
562 ...documentPickedImage,
563 uploadedAttachmentId: "pending-promoted-png",
564 uploadEnvironmentId: environmentId,
565 },
566 ]);
567 });
568
569 it("reuses a pending file upload from a previous outbox attempt", async () => {
570 const previouslyUploaded = {
571 ...file,
572 uploadedAttachmentId: "pending-existing-pdf",
573 uploadEnvironmentId: environmentId,
574 };
575
576 const prepared = await prepareTurnAttachments({
577 environmentId,
578 attachments: [previouslyUploaded, image],
579 });
580
581 expect(prepared.status).toBe("ready");
582 if (prepared.status !== "ready") return;
583 expect(prepared.attachments).toEqual([
584 {
585 type: "file",
586 id: "pending-existing-pdf",
587 name: "report.pdf",
588 mimeType: "application/pdf",
589 sizeBytes: 42,
590 },
591 {
592 type: "image",
593 name: "screenshot.png",
594 mimeType: "image/png",
595 sizeBytes: 3,
596 dataUrl: "data:image/png;base64,YWJj",
597 },
598 ]);
599 expect(prepared.pendingAttachmentIds).toEqual(["pending-existing-pdf"]);
600 expect(mocks.upload).not.toHaveBeenCalled();
601 expect(mocks.runAtomCommand).not.toHaveBeenCalled();
602 });
603
604 it("uploads a file again when its saved pending upload has expired", async () => {
605 mocks.executeAtomQuery.mockResolvedValueOnce({
606 _tag: "Failure",
607 error: { _tag: "AssetAttachmentNotFoundError" },
608 });
609 const previouslyUploaded = {
610 ...file,
611 uploadedAttachmentId: "pending-expired-pdf",
612 uploadEnvironmentId: environmentId,
613 };
614
615 const prepared = await prepareTurnAttachments({
616 environmentId,
617 attachments: [previouslyUploaded],
618 });
619
620 expect(mocks.upload).toHaveBeenCalledOnce();
621 expect(prepared.status).toBe("ready");
622 if (prepared.status !== "ready") return;
623 expect(prepared.pendingAttachmentIds).toEqual([MINTED_ID]);
624 });
625
626 it("uploads image bytes over HTTP while retaining the durable offline image", async () => {
627 const persisted = vi.fn(async () => "persisted" as const);
628 const prepared = await prepareTurnAttachments({
629 environmentId,
630 attachments: [image],
631 supportsImageUploads: true,
632 persistUploadedReferences: persisted,
633 });
634 expect(mocks.writeFile).toHaveBeenCalledWith("file:///cache/t3-upload-uuid", "YWJj", {
635 encoding: "base64",
636 });
637 expect(mocks.upload).toHaveBeenCalledWith(
638 "file:///cache/t3-upload-uuid",
639 "https://environment.example/api/attachments/upload/signed",
640 expect.objectContaining({ headers: { "Content-Type": "image/png" } }),
641 );
642 expect(mocks.deleteFile).toHaveBeenCalledExactlyOnceWith("file:///cache/t3-upload-uuid");
643 expect(prepared.status).toBe("ready");
644 if (prepared.status !== "ready") return;
645 expect(prepared.attachments).toEqual([
646 {
647 type: "image",
648 id: MINTED_ID,
649 name: image.name,
650 mimeType: image.mimeType,
651 sizeBytes: image.sizeBytes,
652 },
653 ]);
654 expect(prepared.draftAttachments).toEqual([
655 { ...image, uploadedAttachmentId: MINTED_ID, uploadEnvironmentId: environmentId },
656 ]);
657 expect(persisted).toHaveBeenCalledWith(prepared.draftAttachments);
658 });
659
660 it("reuses an uploaded image and reuploads its local bytes after server expiry", async () => {
661 const saved = {
662 ...image,
663 uploadedAttachmentId: "saved-image",
664 uploadEnvironmentId: environmentId,
665 };
666 const reused = await prepareTurnAttachments({
667 environmentId,
668 attachments: [saved],
669 supportsImageUploads: true,
670 });
671 expect(reused.status === "ready" && reused.attachments[0]).toEqual({
672 type: "image",
673 id: "saved-image",
674 name: image.name,
675 mimeType: image.mimeType,
676 sizeBytes: image.sizeBytes,
677 });
678 expect(mocks.upload).not.toHaveBeenCalled();
679 mocks.executeAtomQuery.mockResolvedValueOnce({
680 _tag: "Failure",
681 error: { _tag: "AssetAttachmentNotFoundError" },
682 });
683 const restored = await prepareTurnAttachments({
684 environmentId,
685 attachments: [saved],
686 supportsImageUploads: true,
687 });
688 expect(restored.status === "ready" && restored.draftAttachments[0]).toEqual({
689 ...saved,
690 uploadedAttachmentId: MINTED_ID,
691 });
692 expect(mocks.writeFile).toHaveBeenCalledWith("file:///cache/t3-upload-uuid", "YWJj", {
693 encoding: "base64",
694 });
695 });
696
697 it("does not reuse an image upload from another environment", async () => {
698 const prepared = await prepareTurnAttachments({
699 environmentId,
700 attachments: [
701 {
702 ...image,
703 uploadedAttachmentId: "other-image",
704 uploadEnvironmentId: EnvironmentId.make("other"),
705 },
706 ],
707 supportsImageUploads: true,
708 });
709 expect(mocks.executeAtomQuery).not.toHaveBeenCalled();
710 expect(mocks.upload).toHaveBeenCalledOnce();
711 expect(prepared.status === "ready" && prepared.draftAttachments[0]?.uploadEnvironmentId).toBe(
712 environmentId,
713 );
714 });
715
716 it("aborts an active transfer without dropping local bytes or stamping a partial upload", async () => {
717 const started = Promise.withResolvers<void>();
718 const controller = new AbortController();
719 const persist = vi.fn(async () => "persisted" as const);
720 mocks.upload.mockImplementation(
721 (_uri: string, _url: string, options: { signal: AbortSignal }) =>
722 new Promise((_, reject) => {
723 options.signal.addEventListener("abort", () => reject(new Error("cancelled")), {
724 once: true,
725 });
726 started.resolve();
727 }),
728 );
729 const preparing = prepareTurnAttachments({
730 environmentId,
731 attachments: [file],
732 signal: controller.signal,
733 persistUploadedReferences: persist,
734 });
735 await started.promise;
736 controller.abort();
737 expect(await preparing).toEqual({ status: "abandoned" });
738 expect(persist).not.toHaveBeenCalled();
739 expect(mocks.deleteFile).not.toHaveBeenCalled();
740 expect(removeCallsFor(MINTED_ID)).toBe(1);
741 });
742
743 it("removes pending uploads when the native HTTP request fails", async () => {
744 mocks.upload.mockResolvedValue({ status: 500, body: "failed", headers: {} });
745
746 await expect(prepareTurnAttachments({ environmentId, attachments: [file] })).rejects.toThrow(
747 "Upload failed for 'report.pdf' (500).",
748 );
749 expect(removeCallsFor(MINTED_ID)).toBe(1);
750 });
751
752 it("keeps a previously persisted upload when a later attachment fails", async () => {
753 const previouslyUploaded = {
754 ...file,
755 id: "file-existing",
756 uploadedAttachmentId: "pending-existing-pdf",
757 uploadEnvironmentId: environmentId,
758 };
759 mocks.upload.mockResolvedValue({ status: 500, body: "failed", headers: {} });
760
761 await expect(
762 prepareTurnAttachments({ environmentId, attachments: [previouslyUploaded, file] }),
763 ).rejects.toThrow("Upload failed for 'report.pdf' (500).");
764
765 expect(removeCallsFor("pending-existing-pdf")).toBe(0);
766 });
767
768 it("deletes the minted uploads when the owner abandons the send", async () => {
769 const result = await prepareTurnAttachments({
770 environmentId,
771 attachments: [file],
772 persistUploadedReferences: async () => "abandon",
773 });
774
775 expect(result.status).toBe("abandoned");
776 expect(removeCallsFor(MINTED_ID)).toBe(1);
777 });
778
779 it("deletes the minted uploads when persisting the references throws", async () => {
780 await expect(
781 prepareTurnAttachments({
782 environmentId,
783 attachments: [file],
784 persistUploadedReferences: async () => {
785 throw new Error("draft write failed");
786 },
787 }),
788 ).rejects.toThrow("draft write failed");
789
790 expect(removeCallsFor(MINTED_ID)).toBe(1);
791 });
792
793 it("skips persisting when every reference is already stored", async () => {
794 const previouslyUploaded = {
795 ...file,
796 uploadedAttachmentId: "pending-existing-pdf",
797 uploadEnvironmentId: environmentId,
798 };
799 const persist = vi.fn(async () => "persisted" as const);
800
801 const prepared = await prepareTurnAttachments({
802 environmentId,
803 attachments: [previouslyUploaded],
804 persistUploadedReferences: persist,
805 });
806
807 expect(prepared.status).toBe("ready");
808 expect(persist).not.toHaveBeenCalled();
809 });
810});
811
812describe("releasePendingAttachmentUploads", () => {
813 beforeEach(() => {
814 mocks.runAtomCommand.mockReset();
815 });
816
817 it("retries a failed delete once before reporting it", async () => {
818 mocks.runAtomCommand
819 .mockResolvedValueOnce({ _tag: "Failure", error: new Error("offline") })
820 .mockResolvedValue({ _tag: "Success", value: undefined });
821
822 await expect(
823 releasePendingAttachmentUploads(environmentId, ["pending-a"]),
824 ).resolves.toBeUndefined();
825 expect(mocks.runAtomCommand).toHaveBeenCalledTimes(2);
826 });
827
828 it("throws when a delete keeps failing so the caller sees the leak", async () => {
829 mocks.runAtomCommand.mockResolvedValue({ _tag: "Failure", error: new Error("offline") });
830
831 await expect(releasePendingAttachmentUploads(environmentId, ["pending-a"])).rejects.toThrow(
832 "pending-a",
833 );
834 });
835
836 it("treats an already-deleted pending upload as released", async () => {
837 mocks.runAtomCommand.mockResolvedValue({
838 _tag: "Failure",
839 error: { _tag: "AssetAttachmentNotFoundError" },
840 });
841
842 await expect(
843 releasePendingAttachmentUploads(environmentId, ["pending-a"]),
844 ).resolves.toBeUndefined();
845 expect(mocks.runAtomCommand).toHaveBeenCalledTimes(1);
846 });
847});