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("blocks files while config is unknown or file uploads are unsupported", () => {
143 expect(validateDraftFileAttachments({ attachments: [file], serverConfig: null })).toBe(
144 "Server attachment support is still loading.",
145 );
146 expect(
147 validateDraftFileAttachments({
148 attachments: [file],
149 serverConfig: { environment: { capabilities: { attachmentUploads: true } } },
150 }),
151 ).toBe("This server does not support file attachments.");
152 });
153
154 it("uses the current clamped limit and allows valid mixed attachments", () => {
155 const lowerLimit = {
156 environment: {
157 capabilities: {
158 attachmentUploads: true,
159 fileAttachments: { maxUploadBytes: 20 },
160 },
161 },
162 };
163 expect(validateDraftFileAttachments({ attachments: [file], serverConfig: lowerLimit })).toBe(
164 "'report.pdf' exceeds the 20 bytes attachment limit.",
165 );
166 const allowed = {
167 environment: {
168 capabilities: {
169 attachmentUploads: true,
170 fileAttachments: { maxUploadBytes: 100 },
171 },
172 },
173 };
174 expect(
175 validateDraftFileAttachments({ attachments: [image, file], serverConfig: allowed }),
176 ).toBeNull();
177 });
178});
179
180function removeCallsFor(attachmentId: string): number {
181 return mocks.runAtomCommand.mock.calls.filter(
182 ([, command, target]) =>
183 command === mocks.removeUpload &&
184 (target as { input: { attachmentId: string } }).input.attachmentId === attachmentId,
185 ).length;
186}
187
188describe("prepareTurnAttachments", () => {
189 beforeEach(() => {
190 mocks.canOperate = true;
191 mocks.documentUri = "file:///documents";
192 mocks.createAssetUrl.mockReset();
193 mocks.createAssetUrl.mockImplementation((target: unknown) => target);
194 mocks.executeAtomQuery.mockReset();
195 mocks.executeAtomQuery.mockResolvedValue({ _tag: "Success", value: {} });
196 mocks.runAtomCommand.mockReset();
197 mocks.readAtom.mockReset();
198 mocks.upload.mockReset();
199 mocks.writeFile.mockReset();
200 mocks.deleteFile.mockReset();
201 mocks.readBase64.mockReset();
202 mocks.readBase64.mockResolvedValue("YWJj");
203 mocks.readAtom.mockReturnValue(Option.some({ httpBaseUrl: "https://environment.example/" }));
204 mocks.runAtomCommand.mockImplementation(async (_registry: unknown, command: unknown) =>
205 command === mocks.createUploadUrl
206 ? {
207 _tag: "Success",
208 value: {
209 attachmentId: MINTED_ID,
210 relativeUrl: "/api/attachments/upload/signed",
211 expiresAt: 1,
212 },
213 }
214 : { _tag: "Success", value: undefined },
215 );
216 mocks.upload.mockResolvedValue({ status: 204, body: "", headers: {} });
217 });
218
219 it("does not mint or transfer attachments without task operation access", async () => {
220 mocks.canOperate = false;
221 await expect(
222 prepareTurnAttachments({
223 environmentId,
224 attachments: [fileBackedImage],
225 supportsImageUploads: true,
226 }),
227 ).rejects.toThrow("cannot upload attachments");
228 expect(mocks.runAtomCommand).not.toHaveBeenCalled();
229 expect(mocks.upload).not.toHaveBeenCalled();
230 });
231
232 it("rechecks access after a signed URL is minted before sending any bytes", async () => {
233 mocks.runAtomCommand.mockImplementationOnce(async () => {
234 mocks.canOperate = false;
235 return {
236 _tag: "Success",
237 value: {
238 attachmentId: MINTED_ID,
239 relativeUrl: "/api/attachments/upload/signed",
240 expiresAt: 1,
241 },
242 };
243 });
244 const warning = vi.spyOn(console, "warn").mockImplementation(() => {});
245 try {
246 await expect(
247 prepareTurnAttachments({
248 environmentId,
249 attachments: [fileBackedImage],
250 supportsImageUploads: true,
251 }),
252 ).rejects.toThrow("cannot upload attachments");
253 expect(mocks.upload).not.toHaveBeenCalled();
254 expect(mocks.runAtomCommand).toHaveBeenCalledTimes(1);
255 } finally {
256 warning.mockRestore();
257 }
258 });
259
260 it("does not replace an expired upload when access was revoked during verification", async () => {
261 mocks.executeAtomQuery.mockImplementationOnce(async () => {
262 mocks.canOperate = false;
263 return { _tag: "Failure", error: { _tag: "AssetAttachmentNotFoundError" } };
264 });
265 await expect(
266 prepareTurnAttachments({
267 environmentId,
268 attachments: [
269 {
270 ...fileBackedImage,
271 uploadedAttachmentId: MINTED_ID,
272 uploadEnvironmentId: environmentId,
273 },
274 ],
275 supportsImageUploads: true,
276 }),
277 ).rejects.toThrow("cannot upload attachments");
278 expect(mocks.runAtomCommand).not.toHaveBeenCalled();
279 expect(mocks.upload).not.toHaveBeenCalled();
280 });
281
282 it("rechecks deletion permission before retrying a failed cleanup", async () => {
283 mocks.runAtomCommand.mockImplementationOnce(async () => {
284 mocks.canOperate = false;
285 return { _tag: "Failure", error: new Error("Retry cleanup") };
286 });
287 await expect(releasePendingAttachmentUploads(environmentId, [MINTED_ID])).rejects.toThrow(
288 "cannot delete pending attachments",
289 );
290 expect(mocks.runAtomCommand).toHaveBeenCalledTimes(1);
291 });
292
293 it("inlines a file-backed image lazily when the server lacks image uploads", async () => {
294 const prepared = await prepareTurnAttachments({
295 environmentId,
296 attachments: [fileBackedImage],
297 });
298
299 expect(prepared.status).toBe("ready");
300 if (prepared.status !== "ready") return;
301 expect(prepared.attachments).toEqual([
302 {
303 type: "image",
304 name: "photo.png",
305 mimeType: "image/png",
306 sizeBytes: 3,
307 dataUrl: "data:image/png;base64,YWJj",
308 },
309 ]);
310 expect(mocks.readBase64).toHaveBeenCalledExactlyOnceWith(fileBackedImage.fileUri);
311 expect(mocks.upload).not.toHaveBeenCalled();
312 });
313
314 // regression: #9713 read file-backed image drafts before enabling them
315 it("reads restored images from the current iOS document container for legacy sends", async () => {
316 const fileName = "33333333-3333-4333-8333-333333333333-photo.png";
317 mocks.documentUri =
318 "file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents";
319 const oldUri = `file:///var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/${fileName}`;
320 const prepared = await prepareTurnAttachments({
321 environmentId,
322 attachments: [{ ...fileBackedImage, fileUri: oldUri, previewUri: oldUri }],
323 });
324 expect(prepared.status).toBe("ready");
325 expect(mocks.readBase64).toHaveBeenCalledExactlyOnceWith(
326 `${mocks.documentUri}/t3-composer-attachments/${fileName}`,
327 );
328 });
329
330 // regression: #9713 read file-backed image drafts before enabling them
331 it("rejects a legacy image without inline bytes or a file", async () => {
332 const { fileUri: _, ...missingImage } = fileBackedImage;
333 await expect(
334 prepareTurnAttachments({ environmentId, attachments: [missingImage] }),
335 ).rejects.toThrow("'photo.png' is no longer available. Attach the image again.");
336 });
337
338 it.each(["resolve", "reject"] as const)(
339 "abandons a canceled legacy image read that later %ss",
340 async (outcome) => {
341 const readStarted = Promise.withResolvers<void>();
342 const read = Promise.withResolvers<string>();
343 const controller = new AbortController();
344 mocks.readBase64.mockImplementation(() => {
345 readStarted.resolve();
346 return read.promise;
347 });
348 const preparing = prepareTurnAttachments({
349 environmentId,
350 attachments: [fileBackedImage],
351 signal: controller.signal,
352 });
353 await readStarted.promise;
354 controller.abort();
355 if (outcome === "resolve") read.resolve("YWJj");
356 else read.reject(new Error("Native read failed after cancellation"));
357
358 await expect(preparing).resolves.toEqual({ status: "abandoned" });
359 },
360 );
361
362 // regression: #9713 read file-backed image drafts before enabling them
363 it("uploads a file-backed image from its owned copy without staging base64", async () => {
364 const prepared = await prepareTurnAttachments({
365 environmentId,
366 attachments: [fileBackedImage],
367 supportsImageUploads: true,
368 });
369
370 expect(mocks.upload).toHaveBeenCalledWith(
371 fileBackedImage.fileUri,
372 "https://environment.example/api/attachments/upload/signed",
373 expect.objectContaining({ headers: { "Content-Type": "image/png" } }),
374 );
375 expect(mocks.readBase64).not.toHaveBeenCalled();
376 expect(mocks.writeFile).not.toHaveBeenCalled();
377 expect(mocks.deleteFile).not.toHaveBeenCalled();
378 expect(prepared.status).toBe("ready");
379 if (prepared.status !== "ready") return;
380 expect(prepared.attachments).toEqual([
381 {
382 type: "image",
383 id: MINTED_ID,
384 name: "photo.png",
385 mimeType: "image/png",
386 sizeBytes: 3,
387 },
388 ]);
389 });
390
391 it("sends a document-picked picture with the mime it was uploaded under", async () => {
392 const prepared = await prepareTurnAttachments({
393 environmentId,
394 attachments: [documentPickedImage],
395 });
396
397 expect(mocks.upload).toHaveBeenCalledWith(
398 "file:///documents/photo.png",
399 "https://environment.example/api/attachments/upload/signed",
400 expect.objectContaining({ headers: { "Content-Type": "image/png" } }),
401 );
402 expect(prepared.status).toBe("ready");
403 if (prepared.status !== "ready") return;
404 expect(prepared.attachments[0]).toEqual({
405 type: "image",
406 id: MINTED_ID,
407 name: "photo.png",
408 mimeType: "image/png",
409 sizeBytes: 3,
410 });
411 });
412
413 it("uploads generic file bytes directly and keeps mixed attachment order", async () => {
414 const pastedFile = {
415 ...file,
416 source: { _tag: "pasted-text" as const },
417 };
418 const prepared = await prepareTurnAttachments({
419 environmentId,
420 attachments: [pastedFile, image],
421 });
422
423 expect(mocks.upload).toHaveBeenCalledWith(
424 "file:///documents/report.pdf",
425 "https://environment.example/api/attachments/upload/signed",
426 expect.objectContaining({
427 httpMethod: "POST",
428 uploadType: 0,
429 headers: { "Content-Type": "application/pdf" },
430 }),
431 );
432 expect(prepared.status).toBe("ready");
433 if (prepared.status !== "ready") return;
434 expect(prepared.attachments[0]).toEqual({
435 type: "file",
436 id: MINTED_ID,
437 name: "report.pdf",
438 mimeType: "application/pdf",
439 sizeBytes: 42,
440 source: { _tag: "pasted-text" },
441 });
442 expect(prepared.attachments[1]?.type).toBe("image");
443 expect(prepared.pendingAttachmentIds).toEqual([MINTED_ID]);
444 expect(prepared.draftAttachments[0]).toEqual({
445 ...pastedFile,
446 uploadedAttachmentId: MINTED_ID,
447 uploadEnvironmentId: environmentId,
448 });
449 });
450
451 it("uses the current connection when an environment reconnects during URL creation", async () => {
452 mocks.readAtom
453 .mockReturnValueOnce(Option.some({ httpBaseUrl: "https://old-environment.example/" }))
454 .mockReturnValueOnce(Option.some({ httpBaseUrl: "https://new-environment.example/" }));
455
456 await prepareTurnAttachments({ environmentId, attachments: [file] });
457
458 expect(mocks.upload).toHaveBeenCalledWith(
459 file.fileUri,
460 "https://new-environment.example/api/attachments/upload/signed",
461 expect.anything(),
462 );
463 });
464
465 it("uploads a restored draft file from the current iOS document container", async () => {
466 const fileName = "33333333-3333-4333-8333-333333333333-report%20%23.pdf";
467 const restoredFile = {
468 ...file,
469 fileUri: `file:///private/var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/${fileName}`,
470 };
471 mocks.documentUri =
472 "file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents";
473 const currentUri = `${mocks.documentUri}/t3-composer-attachments/${fileName}`;
474 mocks.upload.mockImplementation(async (uri: string) => {
475 if (uri !== currentUri) {
476 throw new Error("File does not exist in the previous application container.");
477 }
478 return { status: 204, body: "", headers: {} };
479 });
480
481 const prepared = await prepareTurnAttachments({
482 environmentId,
483 attachments: [restoredFile],
484 });
485
486 expect(prepared.status).toBe("ready");
487 expect(mocks.upload).toHaveBeenCalledWith(
488 currentUri,
489 "https://environment.example/api/attachments/upload/signed",
490 expect.anything(),
491 );
492 });
493
494 it("adds uploaded file references to durable drafts without changing images", () => {
495 expect(
496 withUploadedMobileAttachmentReferences({
497 environmentId,
498 attachments: [file, image],
499 uploadedAttachments: [
500 {
501 type: "file",
502 id: "pending-existing-pdf",
503 name: file.name,
504 mimeType: file.mimeType,
505 sizeBytes: file.sizeBytes,
506 },
507 {
508 type: "image",
509 name: image.name,
510 mimeType: image.mimeType,
511 sizeBytes: image.sizeBytes,
512 dataUrl: image.dataUrl,
513 },
514 ],
515 }),
516 ).toEqual([
517 {
518 ...file,
519 uploadedAttachmentId: "pending-existing-pdf",
520 uploadEnvironmentId: environmentId,
521 },
522 image,
523 ]);
524 });
525
526 it("reuses a pending file upload from a previous outbox attempt", async () => {
527 const previouslyUploaded = {
528 ...file,
529 uploadedAttachmentId: "pending-existing-pdf",
530 uploadEnvironmentId: environmentId,
531 };
532
533 const prepared = await prepareTurnAttachments({
534 environmentId,
535 attachments: [previouslyUploaded, image],
536 });
537
538 expect(prepared.status).toBe("ready");
539 if (prepared.status !== "ready") return;
540 expect(prepared.attachments).toEqual([
541 {
542 type: "file",
543 id: "pending-existing-pdf",
544 name: "report.pdf",
545 mimeType: "application/pdf",
546 sizeBytes: 42,
547 },
548 {
549 type: "image",
550 name: "screenshot.png",
551 mimeType: "image/png",
552 sizeBytes: 3,
553 dataUrl: "data:image/png;base64,YWJj",
554 },
555 ]);
556 expect(prepared.pendingAttachmentIds).toEqual(["pending-existing-pdf"]);
557 expect(mocks.upload).not.toHaveBeenCalled();
558 expect(mocks.runAtomCommand).not.toHaveBeenCalled();
559 });
560
561 it("uploads a file again when its saved pending upload has expired", async () => {
562 mocks.executeAtomQuery.mockResolvedValueOnce({
563 _tag: "Failure",
564 error: { _tag: "AssetAttachmentNotFoundError" },
565 });
566 const previouslyUploaded = {
567 ...file,
568 uploadedAttachmentId: "pending-expired-pdf",
569 uploadEnvironmentId: environmentId,
570 };
571
572 const prepared = await prepareTurnAttachments({
573 environmentId,
574 attachments: [previouslyUploaded],
575 });
576
577 expect(mocks.upload).toHaveBeenCalledOnce();
578 expect(prepared.status).toBe("ready");
579 if (prepared.status !== "ready") return;
580 expect(prepared.pendingAttachmentIds).toEqual([MINTED_ID]);
581 });
582
583 it("uploads image bytes over HTTP while retaining the durable offline image", async () => {
584 const persisted = vi.fn(async () => "persisted" as const);
585 const prepared = await prepareTurnAttachments({
586 environmentId,
587 attachments: [image],
588 supportsImageUploads: true,
589 persistUploadedReferences: persisted,
590 });
591 expect(mocks.writeFile).toHaveBeenCalledWith("file:///cache/t3-upload-uuid", "YWJj", {
592 encoding: "base64",
593 });
594 expect(mocks.upload).toHaveBeenCalledWith(
595 "file:///cache/t3-upload-uuid",
596 "https://environment.example/api/attachments/upload/signed",
597 expect.objectContaining({ headers: { "Content-Type": "image/png" } }),
598 );
599 expect(mocks.deleteFile).toHaveBeenCalledExactlyOnceWith("file:///cache/t3-upload-uuid");
600 expect(prepared.status).toBe("ready");
601 if (prepared.status !== "ready") return;
602 expect(prepared.attachments).toEqual([
603 {
604 type: "image",
605 id: MINTED_ID,
606 name: image.name,
607 mimeType: image.mimeType,
608 sizeBytes: image.sizeBytes,
609 },
610 ]);
611 expect(prepared.draftAttachments).toEqual([
612 { ...image, uploadedAttachmentId: MINTED_ID, uploadEnvironmentId: environmentId },
613 ]);
614 expect(persisted).toHaveBeenCalledWith(prepared.draftAttachments);
615 });
616
617 it("reuses an uploaded image and reuploads its local bytes after server expiry", async () => {
618 const saved = {
619 ...image,
620 uploadedAttachmentId: "saved-image",
621 uploadEnvironmentId: environmentId,
622 };
623 const reused = await prepareTurnAttachments({
624 environmentId,
625 attachments: [saved],
626 supportsImageUploads: true,
627 });
628 expect(reused.status === "ready" && reused.attachments[0]).toEqual({
629 type: "image",
630 id: "saved-image",
631 name: image.name,
632 mimeType: image.mimeType,
633 sizeBytes: image.sizeBytes,
634 });
635 expect(mocks.upload).not.toHaveBeenCalled();
636 mocks.executeAtomQuery.mockResolvedValueOnce({
637 _tag: "Failure",
638 error: { _tag: "AssetAttachmentNotFoundError" },
639 });
640 const restored = await prepareTurnAttachments({
641 environmentId,
642 attachments: [saved],
643 supportsImageUploads: true,
644 });
645 expect(restored.status === "ready" && restored.draftAttachments[0]).toEqual({
646 ...saved,
647 uploadedAttachmentId: MINTED_ID,
648 });
649 expect(mocks.writeFile).toHaveBeenCalledWith("file:///cache/t3-upload-uuid", "YWJj", {
650 encoding: "base64",
651 });
652 });
653
654 it("does not reuse an image upload from another environment", async () => {
655 const prepared = await prepareTurnAttachments({
656 environmentId,
657 attachments: [
658 {
659 ...image,
660 uploadedAttachmentId: "other-image",
661 uploadEnvironmentId: EnvironmentId.make("other"),
662 },
663 ],
664 supportsImageUploads: true,
665 });
666 expect(mocks.executeAtomQuery).not.toHaveBeenCalled();
667 expect(mocks.upload).toHaveBeenCalledOnce();
668 expect(prepared.status === "ready" && prepared.draftAttachments[0]?.uploadEnvironmentId).toBe(
669 environmentId,
670 );
671 });
672
673 it("aborts an active transfer without dropping local bytes or stamping a partial upload", async () => {
674 const started = Promise.withResolvers<void>();
675 const controller = new AbortController();
676 const persist = vi.fn(async () => "persisted" as const);
677 mocks.upload.mockImplementation(
678 (_uri: string, _url: string, options: { signal: AbortSignal }) =>
679 new Promise((_, reject) => {
680 options.signal.addEventListener("abort", () => reject(new Error("cancelled")), {
681 once: true,
682 });
683 started.resolve();
684 }),
685 );
686 const preparing = prepareTurnAttachments({
687 environmentId,
688 attachments: [file],
689 signal: controller.signal,
690 persistUploadedReferences: persist,
691 });
692 await started.promise;
693 controller.abort();
694 expect(await preparing).toEqual({ status: "abandoned" });
695 expect(persist).not.toHaveBeenCalled();
696 expect(mocks.deleteFile).not.toHaveBeenCalled();
697 expect(removeCallsFor(MINTED_ID)).toBe(1);
698 });
699
700 it("removes pending uploads when the native HTTP request fails", async () => {
701 mocks.upload.mockResolvedValue({ status: 500, body: "failed", headers: {} });
702
703 await expect(prepareTurnAttachments({ environmentId, attachments: [file] })).rejects.toThrow(
704 "Upload failed for 'report.pdf' (500).",
705 );
706 expect(removeCallsFor(MINTED_ID)).toBe(1);
707 });
708
709 it("keeps a previously persisted upload when a later attachment fails", async () => {
710 const previouslyUploaded = {
711 ...file,
712 id: "file-existing",
713 uploadedAttachmentId: "pending-existing-pdf",
714 uploadEnvironmentId: environmentId,
715 };
716 mocks.upload.mockResolvedValue({ status: 500, body: "failed", headers: {} });
717
718 await expect(
719 prepareTurnAttachments({ environmentId, attachments: [previouslyUploaded, file] }),
720 ).rejects.toThrow("Upload failed for 'report.pdf' (500).");
721
722 expect(removeCallsFor("pending-existing-pdf")).toBe(0);
723 });
724
725 it("deletes the minted uploads when the owner abandons the send", async () => {
726 const result = await prepareTurnAttachments({
727 environmentId,
728 attachments: [file],
729 persistUploadedReferences: async () => "abandon",
730 });
731
732 expect(result.status).toBe("abandoned");
733 expect(removeCallsFor(MINTED_ID)).toBe(1);
734 });
735});
736
737describe("releasePendingAttachmentUploads", () => {
738 beforeEach(() => {
739 mocks.runAtomCommand.mockReset();
740 });
741
742 it("throws when a delete keeps failing so the caller sees the leak", async () => {
743 mocks.runAtomCommand.mockResolvedValue({ _tag: "Failure", error: new Error("offline") });
744
745 await expect(releasePendingAttachmentUploads(environmentId, ["pending-a"])).rejects.toThrow(
746 "pending-a",
747 );
748 });
749
750 it("treats an already-deleted pending upload as released", async () => {
751 mocks.runAtomCommand.mockResolvedValue({
752 _tag: "Failure",
753 error: { _tag: "AssetAttachmentNotFoundError" },
754 });
755
756 await expect(
757 releasePendingAttachmentUploads(environmentId, ["pending-a"]),
758 ).resolves.toBeUndefined();
759 expect(mocks.runAtomCommand).toHaveBeenCalledTimes(1);
760 });
761});