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

attachmentUpload.test.ts

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