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