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("../state/use-composer-drafts", () => ({
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 prepared = await prepareTurnAttachments({ environmentId, attachments: [file, image] });
364
365 expect(mocks.upload).toHaveBeenCalledWith(
366 "file:///documents/report.pdf",
367 "https://environment.example/api/attachments/upload/signed",
368 expect.objectContaining({
369 httpMethod: "POST",
370 uploadType: 0,
371 headers: { "Content-Type": "application/pdf" },
372 }),
373 );
374 expect(prepared.status).toBe("ready");
375 if (prepared.status !== "ready") return;
376 expect(prepared.attachments[0]).toEqual({
377 type: "file",
378 id: MINTED_ID,
379 name: "report.pdf",
380 mimeType: "application/pdf",
381 sizeBytes: 42,
382 });
383 expect(prepared.attachments[1]?.type).toBe("image");
384 expect(prepared.pendingAttachmentIds).toEqual([MINTED_ID]);
385 expect(prepared.draftAttachments[0]).toEqual({
386 ...file,
387 uploadedAttachmentId: MINTED_ID,
388 uploadEnvironmentId: environmentId,
389 });
390 });
391
392 it("uses the current connection when an environment reconnects during URL creation", async () => {
393 mocks.readAtom
394 .mockReturnValueOnce(Option.some({ httpBaseUrl: "https://old-environment.example/" }))
395 .mockReturnValueOnce(Option.some({ httpBaseUrl: "https://new-environment.example/" }));
396
397 await prepareTurnAttachments({ environmentId, attachments: [file] });
398
399 expect(mocks.upload).toHaveBeenCalledWith(
400 file.fileUri,
401 "https://new-environment.example/api/attachments/upload/signed",
402 expect.anything(),
403 );
404 });
405
406 it("uploads a restored draft file from the current iOS document container", async () => {
407 const fileName = "33333333-3333-4333-8333-333333333333-report%20%23.pdf";
408 const restoredFile = {
409 ...file,
410 fileUri: `file:///private/var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/${fileName}`,
411 };
412 mocks.documentUri =
413 "file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents";
414 const currentUri = `${mocks.documentUri}/t3-composer-attachments/${fileName}`;
415 mocks.upload.mockImplementation(async (uri: string) => {
416 if (uri !== currentUri) {
417 throw new Error("File does not exist in the previous application container.");
418 }
419 return { status: 204, body: "", headers: {} };
420 });
421
422 const prepared = await prepareTurnAttachments({
423 environmentId,
424 attachments: [restoredFile],
425 });
426
427 expect(prepared.status).toBe("ready");
428 expect(mocks.upload).toHaveBeenCalledWith(
429 currentUri,
430 "https://environment.example/api/attachments/upload/signed",
431 expect.anything(),
432 );
433 });
434
435 it("adds uploaded file references to durable drafts without changing images", () => {
436 expect(
437 withUploadedMobileAttachmentReferences({
438 environmentId,
439 attachments: [file, image],
440 uploadedAttachments: [
441 {
442 type: "file",
443 id: "pending-existing-pdf",
444 name: file.name,
445 mimeType: file.mimeType,
446 sizeBytes: file.sizeBytes,
447 },
448 {
449 type: "image",
450 name: image.name,
451 mimeType: image.mimeType,
452 sizeBytes: image.sizeBytes,
453 dataUrl: image.dataUrl,
454 },
455 ],
456 }),
457 ).toEqual([
458 {
459 ...file,
460 uploadedAttachmentId: "pending-existing-pdf",
461 uploadEnvironmentId: environmentId,
462 },
463 image,
464 ]);
465 });
466
467 it("keeps the uploaded id when a document-picked picture uploads as an image", () => {
468 // The draft stays `type: "file"` while the upload is promoted to `"image"`. Comparing the
469 // two types drops the id, so a later send re-uploads the bytes and the draft chip points at
470 // a local id nobody can resolve.
471 expect(
472 withUploadedMobileAttachmentReferences({
473 environmentId,
474 attachments: [documentPickedImage],
475 uploadedAttachments: [
476 {
477 type: "image",
478 id: "pending-promoted-png",
479 name: documentPickedImage.name,
480 mimeType: "image/png",
481 sizeBytes: documentPickedImage.sizeBytes,
482 },
483 ],
484 }),
485 ).toEqual([
486 {
487 ...documentPickedImage,
488 uploadedAttachmentId: "pending-promoted-png",
489 uploadEnvironmentId: environmentId,
490 },
491 ]);
492 });
493
494 it("reuses a pending file upload from a previous outbox attempt", async () => {
495 const previouslyUploaded = {
496 ...file,
497 uploadedAttachmentId: "pending-existing-pdf",
498 uploadEnvironmentId: environmentId,
499 };
500
501 const prepared = await prepareTurnAttachments({
502 environmentId,
503 attachments: [previouslyUploaded, image],
504 });
505
506 expect(prepared.status).toBe("ready");
507 if (prepared.status !== "ready") return;
508 expect(prepared.attachments).toEqual([
509 {
510 type: "file",
511 id: "pending-existing-pdf",
512 name: "report.pdf",
513 mimeType: "application/pdf",
514 sizeBytes: 42,
515 },
516 {
517 type: "image",
518 name: "screenshot.png",
519 mimeType: "image/png",
520 sizeBytes: 3,
521 dataUrl: "data:image/png;base64,YWJj",
522 },
523 ]);
524 expect(prepared.pendingAttachmentIds).toEqual(["pending-existing-pdf"]);
525 expect(mocks.upload).not.toHaveBeenCalled();
526 expect(mocks.runAtomCommand).not.toHaveBeenCalled();
527 });
528
529 it("uploads a file again when its saved pending upload has expired", async () => {
530 mocks.executeAtomQuery.mockResolvedValueOnce({
531 _tag: "Failure",
532 error: { _tag: "AssetAttachmentNotFoundError" },
533 });
534 const previouslyUploaded = {
535 ...file,
536 uploadedAttachmentId: "pending-expired-pdf",
537 uploadEnvironmentId: environmentId,
538 };
539
540 const prepared = await prepareTurnAttachments({
541 environmentId,
542 attachments: [previouslyUploaded],
543 });
544
545 expect(mocks.upload).toHaveBeenCalledOnce();
546 expect(prepared.status).toBe("ready");
547 if (prepared.status !== "ready") return;
548 expect(prepared.pendingAttachmentIds).toEqual([MINTED_ID]);
549 });
550
551 it("uploads image bytes over HTTP while retaining the durable offline image", async () => {
552 const persisted = vi.fn(async () => "persisted" as const);
553 const prepared = await prepareTurnAttachments({
554 environmentId,
555 attachments: [image],
556 supportsImageUploads: true,
557 persistUploadedReferences: persisted,
558 });
559 expect(mocks.writeFile).toHaveBeenCalledWith("file:///cache/t3-upload-uuid", "YWJj", {
560 encoding: "base64",
561 });
562 expect(mocks.upload).toHaveBeenCalledWith(
563 "file:///cache/t3-upload-uuid",
564 "https://environment.example/api/attachments/upload/signed",
565 expect.objectContaining({ headers: { "Content-Type": "image/png" } }),
566 );
567 expect(mocks.deleteFile).toHaveBeenCalledExactlyOnceWith("file:///cache/t3-upload-uuid");
568 expect(prepared.status).toBe("ready");
569 if (prepared.status !== "ready") return;
570 expect(prepared.attachments).toEqual([
571 {
572 type: "image",
573 id: MINTED_ID,
574 name: image.name,
575 mimeType: image.mimeType,
576 sizeBytes: image.sizeBytes,
577 },
578 ]);
579 expect(prepared.draftAttachments).toEqual([
580 { ...image, uploadedAttachmentId: MINTED_ID, uploadEnvironmentId: environmentId },
581 ]);
582 expect(persisted).toHaveBeenCalledWith(prepared.draftAttachments);
583 });
584
585 it("reuses an uploaded image and reuploads its local bytes after server expiry", async () => {
586 const saved = {
587 ...image,
588 uploadedAttachmentId: "saved-image",
589 uploadEnvironmentId: environmentId,
590 };
591 const reused = await prepareTurnAttachments({
592 environmentId,
593 attachments: [saved],
594 supportsImageUploads: true,
595 });
596 expect(reused.status === "ready" && reused.attachments[0]).toEqual({
597 type: "image",
598 id: "saved-image",
599 name: image.name,
600 mimeType: image.mimeType,
601 sizeBytes: image.sizeBytes,
602 });
603 expect(mocks.upload).not.toHaveBeenCalled();
604 mocks.executeAtomQuery.mockResolvedValueOnce({
605 _tag: "Failure",
606 error: { _tag: "AssetAttachmentNotFoundError" },
607 });
608 const restored = await prepareTurnAttachments({
609 environmentId,
610 attachments: [saved],
611 supportsImageUploads: true,
612 });
613 expect(restored.status === "ready" && restored.draftAttachments[0]).toEqual({
614 ...saved,
615 uploadedAttachmentId: MINTED_ID,
616 });
617 expect(mocks.writeFile).toHaveBeenCalledWith("file:///cache/t3-upload-uuid", "YWJj", {
618 encoding: "base64",
619 });
620 });
621
622 it("does not reuse an image upload from another environment", async () => {
623 const prepared = await prepareTurnAttachments({
624 environmentId,
625 attachments: [
626 {
627 ...image,
628 uploadedAttachmentId: "other-image",
629 uploadEnvironmentId: EnvironmentId.make("other"),
630 },
631 ],
632 supportsImageUploads: true,
633 });
634 expect(mocks.executeAtomQuery).not.toHaveBeenCalled();
635 expect(mocks.upload).toHaveBeenCalledOnce();
636 expect(prepared.status === "ready" && prepared.draftAttachments[0]?.uploadEnvironmentId).toBe(
637 environmentId,
638 );
639 });
640
641 it("aborts an active transfer without dropping local bytes or stamping a partial upload", async () => {
642 const started = Promise.withResolvers<void>();
643 const controller = new AbortController();
644 const persist = vi.fn(async () => "persisted" as const);
645 mocks.upload.mockImplementation(
646 (_uri: string, _url: string, options: { signal: AbortSignal }) =>
647 new Promise((_, reject) => {
648 options.signal.addEventListener("abort", () => reject(new Error("cancelled")), {
649 once: true,
650 });
651 started.resolve();
652 }),
653 );
654 const preparing = prepareTurnAttachments({
655 environmentId,
656 attachments: [file],
657 signal: controller.signal,
658 persistUploadedReferences: persist,
659 });
660 await started.promise;
661 controller.abort();
662 expect(await preparing).toEqual({ status: "abandoned" });
663 expect(persist).not.toHaveBeenCalled();
664 expect(mocks.deleteFile).not.toHaveBeenCalled();
665 expect(removeCallsFor(MINTED_ID)).toBe(1);
666 });
667
668 it("removes pending uploads when the native HTTP request fails", async () => {
669 mocks.upload.mockResolvedValue({ status: 500, body: "failed", headers: {} });
670
671 await expect(prepareTurnAttachments({ environmentId, attachments: [file] })).rejects.toThrow(
672 "Upload failed for 'report.pdf' (500).",
673 );
674 expect(removeCallsFor(MINTED_ID)).toBe(1);
675 });
676
677 it("keeps a previously persisted upload when a later attachment fails", async () => {
678 const previouslyUploaded = {
679 ...file,
680 id: "file-existing",
681 uploadedAttachmentId: "pending-existing-pdf",
682 uploadEnvironmentId: environmentId,
683 };
684 mocks.upload.mockResolvedValue({ status: 500, body: "failed", headers: {} });
685
686 await expect(
687 prepareTurnAttachments({ environmentId, attachments: [previouslyUploaded, file] }),
688 ).rejects.toThrow("Upload failed for 'report.pdf' (500).");
689
690 expect(removeCallsFor("pending-existing-pdf")).toBe(0);
691 });
692
693 it("deletes the minted uploads when the owner abandons the send", async () => {
694 const result = await prepareTurnAttachments({
695 environmentId,
696 attachments: [file],
697 persistUploadedReferences: async () => "abandon",
698 });
699
700 expect(result.status).toBe("abandoned");
701 expect(removeCallsFor(MINTED_ID)).toBe(1);
702 });
703
704 it("deletes the minted uploads when persisting the references throws", async () => {
705 await expect(
706 prepareTurnAttachments({
707 environmentId,
708 attachments: [file],
709 persistUploadedReferences: async () => {
710 throw new Error("draft write failed");
711 },
712 }),
713 ).rejects.toThrow("draft write failed");
714
715 expect(removeCallsFor(MINTED_ID)).toBe(1);
716 });
717
718 it("skips persisting when every reference is already stored", async () => {
719 const previouslyUploaded = {
720 ...file,
721 uploadedAttachmentId: "pending-existing-pdf",
722 uploadEnvironmentId: environmentId,
723 };
724 const persist = vi.fn(async () => "persisted" as const);
725
726 const prepared = await prepareTurnAttachments({
727 environmentId,
728 attachments: [previouslyUploaded],
729 persistUploadedReferences: persist,
730 });
731
732 expect(prepared.status).toBe("ready");
733 expect(persist).not.toHaveBeenCalled();
734 });
735});
736
737describe("releasePendingAttachmentUploads", () => {
738 beforeEach(() => {
739 mocks.runAtomCommand.mockReset();
740 });
741
742 it("retries a failed delete once before reporting it", async () => {
743 mocks.runAtomCommand
744 .mockResolvedValueOnce({ _tag: "Failure", error: new Error("offline") })
745 .mockResolvedValue({ _tag: "Success", value: undefined });
746
747 await expect(
748 releasePendingAttachmentUploads(environmentId, ["pending-a"]),
749 ).resolves.toBeUndefined();
750 expect(mocks.runAtomCommand).toHaveBeenCalledTimes(2);
751 });
752
753 it("throws when a delete keeps failing so the caller sees the leak", async () => {
754 mocks.runAtomCommand.mockResolvedValue({ _tag: "Failure", error: new Error("offline") });
755
756 await expect(releasePendingAttachmentUploads(environmentId, ["pending-a"])).rejects.toThrow(
757 "pending-a",
758 );
759 });
760
761 it("treats an already-deleted pending upload as released", async () => {
762 mocks.runAtomCommand.mockResolvedValue({
763 _tag: "Failure",
764 error: { _tag: "AssetAttachmentNotFoundError" },
765 });
766
767 await expect(
768 releasePendingAttachmentUploads(environmentId, ["pending-a"]),
769 ).resolves.toBeUndefined();
770 expect(mocks.runAtomCommand).toHaveBeenCalledTimes(1);
771 });
772});