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