Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

attachmentUpload.test.ts

756 lines24.5 KB

1import { EnvironmentId, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES } 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} from "./attachmentUpload";
97import type { DraftComposerAttachment } from "./composerImages";
98​
99const environmentId = EnvironmentId.make("environment-1");
100const MINTED_ID = "pending-00000000-0000-4000-8000-000000000001-pdf";
101​
102const image = {
103 id: "image-1",
104 type: "image",
105 name: "screenshot.png",
106 mimeType: "image/png",
107 sizeBytes: 3,
108 dataUrl: "data:image/png;base64,YWJj",
109 previewUri: "file:///images/screenshot.png",
110} as const satisfies DraftComposerAttachment;
111​
112const fileBackedImage = {
113 id: "image-2",
114 type: "image",
115 name: "photo.png",
116 mimeType: "image/png",
117 sizeBytes: 3,
118 fileUri: "file:///documents/t3-composer-attachments/photo.png",
119 previewUri: "file:///documents/t3-composer-attachments/photo.png",
120} as const satisfies DraftComposerAttachment;
121​
122const file = {
123 id: "file-1",
124 type: "file",
125 name: "report.pdf",
126 mimeType: "application/pdf",
127 sizeBytes: 42,
128 fileUri: "file:///documents/report.pdf",
129} as const satisfies DraftComposerAttachment;
130​
131const documentPickedImage = {
132 id: "file-2",
133 type: "file",
134 name: "photo.png",
135 mimeType: "application/octet-stream",
136 sizeBytes: 3,
137 fileUri: "file:///documents/photo.png",
138} as const satisfies DraftComposerAttachment;
139​
140function removeCallsFor(attachmentId: string): number {
141 return mocks.runAtomCommand.mock.calls.filter(
142 ([, command, target]) =>
143 command === mocks.removeUpload &&
144 (target as { input: { attachmentId: string } }).input.attachmentId === attachmentId,
145 ).length;
147​
148describe("prepareTurnAttachments", () => {
149 beforeEach(() => {
150 mocks.canOperate = true;
151 mocks.documentUri = "file:///documents";
152 mocks.createAssetUrl.mockReset();
153 mocks.createAssetUrl.mockImplementation((target: unknown) => target);
154 mocks.executeAtomQuery.mockReset();
155 mocks.executeAtomQuery.mockResolvedValue({ _tag: "Success", value: {} });
156 mocks.runAtomCommand.mockReset();
157 mocks.readAtom.mockReset();
158 mocks.upload.mockReset();
159 mocks.writeFile.mockReset();
160 mocks.deleteFile.mockReset();
161 mocks.readBase64.mockReset();
162 mocks.readBase64.mockResolvedValue("YWJj");
163 mocks.readAtom.mockReturnValue(Option.some({ httpBaseUrl: "https://environment.example/" }));
164 mocks.runAtomCommand.mockImplementation(async (_registry: unknown, command: unknown) =>
165 command === mocks.createUploadUrl
166 ? {
167 _tag: "Success",
168 value: {
169 attachmentId: MINTED_ID,
170 relativeUrl: "/api/attachments/upload/signed",
171 expiresAt: 1,
172 },
173 }
174 : { _tag: "Success", value: undefined },
175 );
176 mocks.upload.mockResolvedValue({ status: 204, body: "", headers: {} });
177 });
178​
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 () => {
194 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");
213 expect(mocks.upload).not.toHaveBeenCalled();
214 expect(mocks.runAtomCommand).toHaveBeenCalledTimes(1);
215 } finally {
216 warning.mockRestore();
217 }
218 });
219​
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,
233 },
234 ],
235 supportsImageUploads: true,
236 }),
237 ).rejects.toThrow("cannot upload attachments");
238 expect(mocks.runAtomCommand).not.toHaveBeenCalled();
239 expect(mocks.upload).not.toHaveBeenCalled();
240 });
241​
242 it("rechecks deletion permission before retrying a failed cleanup", async () => {
243 mocks.runAtomCommand.mockImplementationOnce(async () => {
244 mocks.canOperate = false;
245 return { _tag: "Failure", error: new Error("Retry cleanup") };
246 });
247 await expect(releasePendingAttachmentUploads(environmentId, [MINTED_ID])).rejects.toThrow(
248 "cannot delete pending attachments",
249 );
250 expect(mocks.runAtomCommand).toHaveBeenCalledTimes(1);
251 });
252​
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 });
258​
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 });
273​
274 // 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 });
289​
290 // 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 });
297​
298 it.each(["resolve", "reject"] as const)(
299 "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({
309 environmentId,
310 attachments: [fileBackedImage],
311 signal: controller.signal,
312 });
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"));
317​
318 await expect(preparing).resolves.toEqual({ status: "abandoned" });
319 },
320 );
321​
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 const prepared = await prepareTurnAttachments({
325 environmentId,
326 attachments: [fileBackedImage],
327 supportsImageUploads: true,
328 });
329​
330 expect(mocks.upload).toHaveBeenCalledWith(
331 fileBackedImage.fileUri,
332 "https://environment.example/api/attachments/upload/signed",
333 expect.objectContaining({ headers: { "Content-Type": "image/png" } }),
334 );
335 expect(mocks.readBase64).not.toHaveBeenCalled();
336 expect(mocks.writeFile).not.toHaveBeenCalled();
337 expect(mocks.deleteFile).not.toHaveBeenCalled();
338 expect(prepared.status).toBe("ready");
339 if (prepared.status !== "ready") return;
340 expect(prepared.attachments).toEqual([
341 {
342 type: "image",
343 id: MINTED_ID,
344 name: "photo.png",
345 mimeType: "image/png",
346 sizeBytes: 3,
347 },
348 ]);
349 });
350​
351 it("sends a document-picked picture with the mime it was uploaded under", async () => {
352 const prepared = await prepareTurnAttachments({
353 environmentId,
354 attachments: [documentPickedImage],
355 });
356​
357 expect(mocks.upload).toHaveBeenCalledWith(
358 "file:///documents/photo.png",
359 "https://environment.example/api/attachments/upload/signed",
360 expect.objectContaining({ headers: { "Content-Type": "image/png" } }),
361 );
362 expect(prepared.status).toBe("ready");
363 if (prepared.status !== "ready") return;
364 expect(prepared.attachments[0]).toEqual({
365 type: "image",
366 id: MINTED_ID,
367 name: "photo.png",
368 mimeType: "image/png",
369 sizeBytes: 3,
370 });
371 });
372​
373 it("uploads an oversized document-picked image as a file", async () => {
374 const largeImage = {
375 ...documentPickedImage,
376 mimeType: "image/png",
377 sizeBytes: PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1,
378 };
379 const prepared = await prepareTurnAttachments({ environmentId, attachments: [largeImage] });
380​
381 expect(mocks.runAtomCommand).toHaveBeenCalledWith(
382 expect.anything(),
383 mocks.createUploadUrl,
384 expect.objectContaining({
385 input: {
386 type: "file",
387 name: largeImage.name,
388 mimeType: "image/png",
389 sizeBytes: largeImage.sizeBytes,
390 },
391 }),
392 expect.anything(),
393 );
394 expect(prepared.status).toBe("ready");
395 if (prepared.status !== "ready") return;
396 expect(prepared.attachments).toEqual([
397 {
398 type: "file",
399 id: MINTED_ID,
400 name: largeImage.name,
401 mimeType: "image/png",
402 sizeBytes: largeImage.sizeBytes,
403 },
404 ]);
405 expect(mocks.readBase64).not.toHaveBeenCalled();
406 });
407​
408 it("uploads generic file bytes directly and keeps mixed attachment order", async () => {
409 const pastedFile = {
410 ...file,
411 source: { _tag: "pasted-text" as const },
412 };
413 const prepared = await prepareTurnAttachments({
414 environmentId,
415 attachments: [pastedFile, image],
416 });
417​
418 expect(mocks.upload).toHaveBeenCalledWith(
419 "file:///documents/report.pdf",
420 "https://environment.example/api/attachments/upload/signed",
421 expect.objectContaining({
422 httpMethod: "POST",
423 uploadType: 0,
424 headers: { "Content-Type": "application/pdf" },
425 }),
426 );
427 expect(prepared.status).toBe("ready");
428 if (prepared.status !== "ready") return;
429 expect(prepared.attachments[0]).toEqual({
430 type: "file",
431 id: MINTED_ID,
432 name: "report.pdf",
433 mimeType: "application/pdf",
434 sizeBytes: 42,
435 source: { _tag: "pasted-text" },
436 });
437 expect(prepared.attachments[1]?.type).toBe("image");
438 expect(prepared.pendingAttachmentIds).toEqual([MINTED_ID]);
439 expect(prepared.draftAttachments[0]).toEqual({
440 ...pastedFile,
441 uploadedAttachmentId: MINTED_ID,
442 uploadEnvironmentId: environmentId,
443 });
444 });
445​
446 it("uses the current connection when an environment reconnects during URL creation", async () => {
447 mocks.readAtom
448 .mockReturnValueOnce(Option.some({ httpBaseUrl: "https://old-environment.example/" }))
449 .mockReturnValueOnce(Option.some({ httpBaseUrl: "https://new-environment.example/" }));
450​
451 await prepareTurnAttachments({ environmentId, attachments: [file] });
452​
453 expect(mocks.upload).toHaveBeenCalledWith(
454 file.fileUri,
455 "https://new-environment.example/api/attachments/upload/signed",
456 expect.anything(),
457 );
458 });
459​
460 it("uploads a restored draft file from the current iOS document container", async () => {
461 const fileName = "33333333-3333-4333-8333-333333333333-report%20%23.pdf";
462 const restoredFile = {
463 ...file,
464 fileUri: `file:///private/var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/${fileName}`,
465 };
466 mocks.documentUri =
467 "file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents";
468 const currentUri = `${mocks.documentUri}/t3-composer-attachments/${fileName}`;
469 mocks.upload.mockImplementation(async (uri: string) => {
470 if (uri !== currentUri) {
471 throw new Error("File does not exist in the previous application container.");
472 }
473 return { status: 204, body: "", headers: {} };
474 });
475​
476 const prepared = await prepareTurnAttachments({
477 environmentId,
478 attachments: [restoredFile],
479 });
480​
481 expect(prepared.status).toBe("ready");
482 expect(mocks.upload).toHaveBeenCalledWith(
483 currentUri,
484 "https://environment.example/api/attachments/upload/signed",
485 expect.anything(),
486 );
487 });
488​
489 it("adds uploaded file references to durable drafts without changing images", () => {
490 expect(
491 withUploadedMobileAttachmentReferences({
492 environmentId,
493 attachments: [file, image],
494 uploadedAttachments: [
495 {
496 type: "file",
497 id: "pending-existing-pdf",
498 name: file.name,
499 mimeType: file.mimeType,
500 sizeBytes: file.sizeBytes,
501 },
502 {
503 type: "image",
504 name: image.name,
505 mimeType: image.mimeType,
506 sizeBytes: image.sizeBytes,
507 dataUrl: image.dataUrl,
508 },
509 ],
510 }),
511 ).toEqual([
512 {
513 ...file,
514 uploadedAttachmentId: "pending-existing-pdf",
515 uploadEnvironmentId: environmentId,
516 },
517 image,
518 ]);
519 });
520​
521 it("reuses a pending file upload from a previous outbox attempt", async () => {
522 const previouslyUploaded = {
523 ...file,
524 uploadedAttachmentId: "pending-existing-pdf",
525 uploadEnvironmentId: environmentId,
526 };
527​
528 const prepared = await prepareTurnAttachments({
529 environmentId,
530 attachments: [previouslyUploaded, image],
531 });
532​
533 expect(prepared.status).toBe("ready");
534 if (prepared.status !== "ready") return;
535 expect(prepared.attachments).toEqual([
536 {
537 type: "file",
538 id: "pending-existing-pdf",
539 name: "report.pdf",
540 mimeType: "application/pdf",
541 sizeBytes: 42,
542 },
543 {
544 type: "image",
545 name: "screenshot.png",
546 mimeType: "image/png",
547 sizeBytes: 3,
548 dataUrl: "data:image/png;base64,YWJj",
549 },
550 ]);
551 expect(prepared.pendingAttachmentIds).toEqual(["pending-existing-pdf"]);
552 expect(mocks.upload).not.toHaveBeenCalled();
553 expect(mocks.runAtomCommand).not.toHaveBeenCalled();
554 });
555​
556 it("uploads a file again when its saved pending upload has expired", async () => {
557 mocks.executeAtomQuery.mockResolvedValueOnce({
558 _tag: "Failure",
559 error: { _tag: "AssetAttachmentNotFoundError" },
560 });
561 const previouslyUploaded = {
562 ...file,
563 uploadedAttachmentId: "pending-expired-pdf",
564 uploadEnvironmentId: environmentId,
565 };
566​
567 const prepared = await prepareTurnAttachments({
568 environmentId,
569 attachments: [previouslyUploaded],
570 });
571​
572 expect(mocks.upload).toHaveBeenCalledOnce();
573 expect(prepared.status).toBe("ready");
574 if (prepared.status !== "ready") return;
575 expect(prepared.pendingAttachmentIds).toEqual([MINTED_ID]);
576 });
577​
578 it("uploads image bytes over HTTP while retaining the durable offline image", async () => {
579 const persisted = vi.fn(async () => "persisted" as const);
580 const prepared = await prepareTurnAttachments({
581 environmentId,
582 attachments: [image],
583 supportsImageUploads: true,
584 persistUploadedReferences: persisted,
585 });
586 expect(mocks.writeFile).toHaveBeenCalledWith("file:///cache/t3-upload-uuid", "YWJj", {
587 encoding: "base64",
588 });
589 expect(mocks.upload).toHaveBeenCalledWith(
590 "file:///cache/t3-upload-uuid",
591 "https://environment.example/api/attachments/upload/signed",
592 expect.objectContaining({ headers: { "Content-Type": "image/png" } }),
593 );
594 expect(mocks.deleteFile).toHaveBeenCalledExactlyOnceWith("file:///cache/t3-upload-uuid");
595 expect(prepared.status).toBe("ready");
596 if (prepared.status !== "ready") return;
597 expect(prepared.attachments).toEqual([
598 {
599 type: "image",
600 id: MINTED_ID,
601 name: image.name,
602 mimeType: image.mimeType,
603 sizeBytes: image.sizeBytes,
604 },
605 ]);
606 expect(prepared.draftAttachments).toEqual([
607 { ...image, uploadedAttachmentId: MINTED_ID, uploadEnvironmentId: environmentId },
608 ]);
609 expect(persisted).toHaveBeenCalledWith(prepared.draftAttachments);
610 });
611​
612 it("reuses an uploaded image and reuploads its local bytes after server expiry", async () => {
613 const saved = {
614 ...image,
615 uploadedAttachmentId: "saved-image",
616 uploadEnvironmentId: environmentId,
617 };
618 const reused = await prepareTurnAttachments({
619 environmentId,
620 attachments: [saved],
621 supportsImageUploads: true,
622 });
623 expect(reused.status === "ready" && reused.attachments[0]).toEqual({
624 type: "image",
625 id: "saved-image",
626 name: image.name,
627 mimeType: image.mimeType,
628 sizeBytes: image.sizeBytes,
629 });
630 expect(mocks.upload).not.toHaveBeenCalled();
631 mocks.executeAtomQuery.mockResolvedValueOnce({
632 _tag: "Failure",
633 error: { _tag: "AssetAttachmentNotFoundError" },
634 });
635 const restored = await prepareTurnAttachments({
636 environmentId,
637 attachments: [saved],
638 supportsImageUploads: true,
639 });
640 expect(restored.status === "ready" && restored.draftAttachments[0]).toEqual({
641 ...saved,
642 uploadedAttachmentId: MINTED_ID,
643 });
644 expect(mocks.writeFile).toHaveBeenCalledWith("file:///cache/t3-upload-uuid", "YWJj", {
645 encoding: "base64",
646 });
647 });
648​
649 it("does not reuse an image upload from another environment", async () => {
650 const prepared = await prepareTurnAttachments({
651 environmentId,
652 attachments: [
653 {
654 ...image,
655 uploadedAttachmentId: "other-image",
656 uploadEnvironmentId: EnvironmentId.make("other"),
657 },
658 ],
659 supportsImageUploads: true,
660 });
661 expect(mocks.executeAtomQuery).not.toHaveBeenCalled();
662 expect(mocks.upload).toHaveBeenCalledOnce();
663 expect(prepared.status === "ready" && prepared.draftAttachments[0]?.uploadEnvironmentId).toBe(
664 environmentId,
665 );
666 });
667​
668 it("aborts an active transfer without dropping local bytes or stamping a partial upload", async () => {
669 const started = Promise.withResolvers<void>();
670 const controller = new AbortController();
671 const persist = vi.fn(async () => "persisted" as const);
672 mocks.upload.mockImplementation(
673 (_uri: string, _url: string, options: { signal: AbortSignal }) =>
674 new Promise((_, reject) => {
675 options.signal.addEventListener("abort", () => reject(new Error("cancelled")), {
676 once: true,
677 });
678 started.resolve();
679 }),
680 );
681 const preparing = prepareTurnAttachments({
682 environmentId,
683 attachments: [file],
684 signal: controller.signal,
685 persistUploadedReferences: persist,
686 });
687 await started.promise;
688 controller.abort();
689 expect(await preparing).toEqual({ status: "abandoned" });
690 expect(persist).not.toHaveBeenCalled();
691 expect(mocks.deleteFile).not.toHaveBeenCalled();
692 expect(removeCallsFor(MINTED_ID)).toBe(1);
693 });
694​
695 it("removes pending uploads when the native HTTP request fails", async () => {
696 mocks.upload.mockResolvedValue({ status: 500, body: "failed", headers: {} });
697​
698 await expect(prepareTurnAttachments({ environmentId, attachments: [file] })).rejects.toThrow(
699 "Upload failed for 'report.pdf' (500).",
700 );
701 expect(removeCallsFor(MINTED_ID)).toBe(1);
702 });
703​
704 it("keeps a previously persisted upload when a later attachment fails", async () => {
705 const previouslyUploaded = {
706 ...file,
707 id: "file-existing",
708 uploadedAttachmentId: "pending-existing-pdf",
709 uploadEnvironmentId: environmentId,
710 };
711 mocks.upload.mockResolvedValue({ status: 500, body: "failed", headers: {} });
712​
713 await expect(
714 prepareTurnAttachments({ environmentId, attachments: [previouslyUploaded, file] }),
715 ).rejects.toThrow("Upload failed for 'report.pdf' (500).");
716​
717 expect(removeCallsFor("pending-existing-pdf")).toBe(0);
718 });
719​
720 it("deletes the minted uploads when the owner abandons the send", async () => {
721 const result = await prepareTurnAttachments({
722 environmentId,
723 attachments: [file],
724 persistUploadedReferences: async () => "abandon",
725 });
726​
727 expect(result.status).toBe("abandoned");
728 expect(removeCallsFor(MINTED_ID)).toBe(1);
729 });
730});
731​
732describe("releasePendingAttachmentUploads", () => {
733 beforeEach(() => {
734 mocks.runAtomCommand.mockReset();
735 });
736​
737 it("throws when a delete keeps failing so the caller sees the leak", async () => {
738 mocks.runAtomCommand.mockResolvedValue({ _tag: "Failure", error: new Error("offline") });
739​
740 await expect(releasePendingAttachmentUploads(environmentId, ["pending-a"])).rejects.toThrow(
741 "pending-a",
742 );
743 });
744​
745 it("treats an already-deleted pending upload as released", async () => {
746 mocks.runAtomCommand.mockResolvedValue({
747 _tag: "Failure",
748 error: { _tag: "AssetAttachmentNotFoundError" },
749 });
750​
751 await expect(
752 releasePendingAttachmentUploads(environmentId, ["pending-a"]),
753 ).resolves.toBeUndefined();
754 expect(mocks.runAtomCommand).toHaveBeenCalledTimes(1);
755 });
756});