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

attachmentUpload.test.ts

827 lines27.0 KB

1import { EnvironmentId, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES } from "@t3tools/contracts";
2import * as Option from "effect/Option";
3import { describe, expect, it } from "@effect/vitest";
4import { beforeEach, vi } from "vite-plus/test";
5​
6const mocks = vi.hoisted(() => ({
7 canOperate: true,
8 documentUri: "file:///documents",
9 createAssetUrl: vi.fn(),
10 createUploadUrl: Symbol("create-upload-url"),
11 executeAtomQuery: vi.fn(),
12 removeUpload: Symbol("remove-upload"),
13 preparedConnection: Symbol("prepared-connection"),
14 runAtomCommand: vi.fn(),
15 readAtom: vi.fn(),
16 upload: vi.fn(),
17 writeFile: vi.fn(),
18 deleteFile: vi.fn(),
19 readBase64: vi.fn(),
20}));
21​
22vi.mock("@t3tools/client-runtime/state/runtime", () => ({
23 createEnvironmentRpcCommand: () => Symbol("rpc-command"),
24 executeAtomQuery: mocks.executeAtomQuery,
25 runAtomCommand: mocks.runAtomCommand,
26 squashAtomCommandFailure: (result: { readonly error: unknown }) => result.error,
27}));
28​
29vi.mock("../state/atom-registry", () => ({
30 appAtomRegistry: { get: mocks.readAtom },
31}));
32​
33vi.mock("./composerAttachmentPreviewRetention", () => ({
34 retainComposerAttachmentFileForPreview: () => () => {},
35}));
36​
37vi.mock("../state/assets", () => ({
38 assetEnvironment: { createUrl: mocks.createAssetUrl },
39}));
40​
41vi.mock("../state/attachments", () => ({
42 attachmentEnvironment: {
43 createUploadUrl: mocks.createUploadUrl,
44 remove: mocks.removeUpload,
45 },
46}));
47​
48vi.mock("../state/session", () => ({
49 readEnvironmentScope: () => mocks.canOperate,
50 environmentSession: {
51 preparedConnectionValueAtom: () => mocks.preparedConnection,
52 },
53}));
54​
55// Cuts the expo-crypto -> react-native import chain out of the test graph.
56vi.mock("./uuid", () => ({
57 uuidv4: () => "uuid",
58 randomHex: () => "0000",
59}));
60​
61vi.mock("expo-file-system", () => ({
62 File: class {
63 readonly uri: string;
64 exists = true;
65 constructor(uri: string, name?: string) {
66 this.uri = name ? `${uri}/${name}` : uri;
67 }
68 create() {}
69 write(bytes: string, options: unknown) {
70 mocks.writeFile(this.uri, bytes, options);
71 }
72 delete() {
73 mocks.deleteFile(this.uri);
74 }
75​
76 async base64() {
77 return mocks.readBase64(this.uri);
78 }
79​
80 upload(url: string, options: unknown) {
81 return mocks.upload(this.uri, url, options);
82 }
83 },
84 Paths: {
85 cache: "file:///cache",
86 get document() {
87 return { uri: mocks.documentUri };
88 },
89 },
90 UploadType: { BINARY_CONTENT: 0 },
91}));
92​
93import * as Effect from "effect/Effect";
94import * as Exit from "effect/Exit";
95import * as Fiber from "effect/Fiber";
96import {
97 prepareTurnAttachments as prepareWithUploads,
98 releasePendingAttachmentUploads,
99 uploadComposerAttachment,
100 withUploadedMobileAttachmentReferences,
101} from "./attachmentUpload";
102​
103/** Uploads each attachment directly, as the shared registry does for one holder. */
104function prepare(
105 input: Omit<Parameters<typeof prepareWithUploads>[0], "uploadAttachment"> & {
106 readonly onUploadProgress?: (attachmentId: string, progress: number) => void;
107 },
108) {
109 return prepareWithUploads({
110 ...input,
111 uploadAttachment: (attachment) =>
112 uploadComposerAttachment(
113 input.environmentId,
114 attachment,
115 input.onUploadProgress
116 ? (progress) => input.onUploadProgress?.(attachment.id, progress)
117 : undefined,
118 ),
119 });
121import type { DraftComposerAttachment } from "./composerImages";
122​
123const environmentId = EnvironmentId.make("environment-1");
124const MINTED_ID = "pending-00000000-0000-4000-8000-000000000001-pdf";
125​
126const image = {
127 id: "image-1",
128 type: "image",
129 name: "screenshot.png",
130 mimeType: "image/png",
131 sizeBytes: 3,
132 dataUrl: "data:image/png;base64,YWJj",
133 previewUri: "file:///images/screenshot.png",
134} as const satisfies DraftComposerAttachment;
135​
136const fileBackedImage = {
137 id: "image-2",
138 type: "image",
139 name: "photo.png",
140 mimeType: "image/png",
141 sizeBytes: 3,
142 fileUri: "file:///documents/t3-composer-attachments/photo.png",
143 previewUri: "file:///documents/t3-composer-attachments/photo.png",
144} as const satisfies DraftComposerAttachment;
145​
146const file = {
147 id: "file-1",
148 type: "file",
149 name: "report.pdf",
150 mimeType: "application/pdf",
151 sizeBytes: 42,
152 fileUri: "file:///documents/report.pdf",
153} as const satisfies DraftComposerAttachment;
154​
155const documentPickedImage = {
156 id: "file-2",
157 type: "file",
158 name: "photo.png",
159 mimeType: "application/octet-stream",
160 sizeBytes: 3,
161 fileUri: "file:///documents/photo.png",
162} as const satisfies DraftComposerAttachment;
163​
164function removeCallsFor(attachmentId: string): number {
165 return mocks.runAtomCommand.mock.calls.filter(
166 ([, command, target]) =>
167 command === mocks.removeUpload &&
168 (target as { input: { attachmentId: string } }).input.attachmentId === attachmentId,
169 ).length;
171​
172describe("prepareTurnAttachments", () => {
173 beforeEach(() => {
174 mocks.canOperate = true;
175 mocks.documentUri = "file:///documents";
176 mocks.createAssetUrl.mockReset();
177 mocks.createAssetUrl.mockImplementation((target: unknown) => target);
178 mocks.executeAtomQuery.mockReset();
179 mocks.executeAtomQuery.mockResolvedValue({ _tag: "Success", value: {} });
180 mocks.runAtomCommand.mockReset();
181 mocks.readAtom.mockReset();
182 mocks.upload.mockReset();
183 mocks.writeFile.mockReset();
184 mocks.deleteFile.mockReset();
185 mocks.readBase64.mockReset();
186 mocks.readBase64.mockResolvedValue("YWJj");
187 mocks.readAtom.mockReturnValue(Option.some({ httpBaseUrl: "https://environment.example/" }));
188 mocks.runAtomCommand.mockImplementation(async (_registry: unknown, command: unknown) =>
189 command === mocks.createUploadUrl
190 ? {
191 _tag: "Success",
192 value: {
193 attachmentId: MINTED_ID,
194 relativeUrl: "/api/attachments/upload/signed",
195 expiresAt: 1,
196 },
197 }
198 : { _tag: "Success", value: undefined },
199 );
200 mocks.upload.mockResolvedValue({ status: 204, body: "", headers: {} });
201 });
202​
203 it.effect("does not mint or transfer attachments without task operation access", () =>
204 Effect.gen(function* () {
205 mocks.canOperate = false;
206 expect(
207 (yield* Effect.flip(
208 prepare({
209 environmentId,
210 attachments: [fileBackedImage],
211 supportsImageUploads: true,
212 }),
213 )).message,
214 ).toContain("cannot upload attachments");
215 expect(mocks.runAtomCommand).not.toHaveBeenCalled();
216 expect(mocks.upload).not.toHaveBeenCalled();
217 }),
218 );
219​
220 it.effect("rechecks access after a signed URL is minted before sending any bytes", () =>
221 Effect.gen(function* () {
222 mocks.runAtomCommand.mockImplementationOnce(async () => {
223 mocks.canOperate = false;
224 return {
225 _tag: "Success",
226 value: {
227 attachmentId: MINTED_ID,
228 relativeUrl: "/api/attachments/upload/signed",
229 expiresAt: 1,
230 },
231 };
232 });
233 const warning = vi.spyOn(console, "warn").mockImplementation(() => {});
234 try {
235 expect(
236 (yield* Effect.flip(
237 prepare({
238 environmentId,
239 attachments: [fileBackedImage],
240 supportsImageUploads: true,
241 }),
242 )).message,
243 ).toContain("cannot upload attachments");
244 expect(mocks.upload).not.toHaveBeenCalled();
245 expect(mocks.runAtomCommand).toHaveBeenCalledTimes(1);
246 } finally {
247 warning.mockRestore();
248 }
249 }),
250 );
251​
252 it.effect("does not replace an expired upload when access was revoked during verification", () =>
253 Effect.gen(function* () {
254 mocks.executeAtomQuery.mockImplementationOnce(async () => {
255 mocks.canOperate = false;
256 return { _tag: "Failure", error: { _tag: "AssetAttachmentNotFoundError" } };
257 });
258 expect(
259 (yield* Effect.flip(
260 prepare({
261 environmentId,
262 attachments: [
263 {
264 ...fileBackedImage,
265 uploadedAttachmentId: MINTED_ID,
266 uploadEnvironmentId: environmentId,
267 },
268 ],
269 supportsImageUploads: true,
270 }),
271 )).message,
272 ).toContain("cannot upload attachments");
273 expect(mocks.runAtomCommand).not.toHaveBeenCalled();
274 expect(mocks.upload).not.toHaveBeenCalled();
275 }),
276 );
277​
278 it("rechecks deletion permission before retrying a failed cleanup", async () => {
279 mocks.runAtomCommand.mockImplementationOnce(async () => {
280 mocks.canOperate = false;
281 return { _tag: "Failure", error: new Error("Retry cleanup") };
282 });
283 await expect(releasePendingAttachmentUploads(environmentId, [MINTED_ID])).rejects.toThrow(
284 "cannot delete pending attachments",
285 );
286 expect(mocks.runAtomCommand).toHaveBeenCalledTimes(1);
287 });
288​
289 it.effect("inlines a file-backed image lazily when the server lacks image uploads", () =>
290 Effect.gen(function* () {
291 const prepared = yield* prepare({
292 environmentId,
293 attachments: [fileBackedImage],
294 });
295​
296 expect(prepared.status).toBe("ready");
297 if (prepared.status !== "ready") return;
298 expect(prepared.attachments).toEqual([
299 {
300 type: "image",
301 name: "photo.png",
302 mimeType: "image/png",
303 sizeBytes: 3,
304 dataUrl: "data:image/png;base64,YWJj",
305 },
306 ]);
307 expect(mocks.readBase64).toHaveBeenCalledExactlyOnceWith(fileBackedImage.fileUri);
308 expect(mocks.upload).not.toHaveBeenCalled();
309 }),
310 );
311​
312 // regression: #9713 read file-backed image drafts before enabling them
313 it.effect("reads restored images from the current iOS document container for legacy sends", () =>
314 Effect.gen(function* () {
315 const fileName = "33333333-3333-4333-8333-333333333333-photo.png";
316 mocks.documentUri =
317 "file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents";
318 const oldUri = `file:///var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/${fileName}`;
319 const prepared = yield* prepare({
320 environmentId,
321 attachments: [{ ...fileBackedImage, fileUri: oldUri, previewUri: oldUri }],
322 });
323 expect(prepared.status).toBe("ready");
324 expect(mocks.readBase64).toHaveBeenCalledExactlyOnceWith(
325 `${mocks.documentUri}/t3-composer-attachments/${fileName}`,
326 );
327 }),
328 );
329​
330 // regression: #9713 read file-backed image drafts before enabling them
331 it.effect("rejects a legacy image without inline bytes or a file", () =>
332 Effect.gen(function* () {
333 const { fileUri: _, ...missingImage } = fileBackedImage;
334 expect(
335 (yield* Effect.flip(prepare({ environmentId, attachments: [missingImage] }))).message,
336 ).toContain("'photo.png' is no longer available. Attach the image again.");
337 }),
338 );
339​
340 it.effect.each(["resolve", "reject"] as const)(
341 "abandons a canceled legacy image read that later %ss",
342 (outcome) =>
343 Effect.gen(function* () {
344 const readStarted = Promise.withResolvers<void>();
345 const read = Promise.withResolvers<string>();
346 mocks.readBase64.mockImplementation(() => {
347 readStarted.resolve();
348 return read.promise;
349 });
350 const preparing = yield* Effect.forkChild(
351 prepare({ environmentId, attachments: [fileBackedImage] }),
352 );
353 yield* Effect.promise(() => readStarted.promise);
354 yield* Fiber.interrupt(preparing);
355 if (outcome === "resolve") read.resolve("YWJj");
356 else read.reject(new Error("Native read failed after cancellation"));
357​
358 expect(Exit.hasInterrupts(yield* Fiber.await(preparing))).toBe(true);
359 }),
360 );
361​
362 // regression: #9713 read file-backed image drafts before enabling them
363 it.effect("uploads a file-backed image from its owned copy without staging base64", () =>
364 Effect.gen(function* () {
365 mocks.upload.mockImplementation(
366 async (
367 _uri: string,
368 _url: string,
369 options: { onProgress?: (event: { bytesSent: unknown; totalBytes: unknown }) => void },
370 ) => {
371 // expo-modules-jsi delivers native Int64 progress counts as BigInt.
372 options.onProgress?.({ bytesSent: BigInt(1), totalBytes: BigInt(4) });
373 return { status: 204, body: "", headers: {} };
374 },
375 );
376 const progress: Array<number> = [];
377 const prepared = yield* prepare({
378 environmentId,
379 attachments: [fileBackedImage],
380 supportsImageUploads: true,
381 onUploadProgress: (_, value) => progress.push(value),
382 });
383​
384 expect(progress).toEqual([0.25]);
385​
386 expect(mocks.upload).toHaveBeenCalledWith(
387 fileBackedImage.fileUri,
388 "https://environment.example/api/attachments/upload/signed",
389 expect.objectContaining({ headers: { "Content-Type": "image/png" } }),
390 );
391 expect(mocks.readBase64).not.toHaveBeenCalled();
392 expect(mocks.writeFile).not.toHaveBeenCalled();
393 expect(mocks.deleteFile).not.toHaveBeenCalled();
394 expect(prepared.status).toBe("ready");
395 if (prepared.status !== "ready") return;
396 expect(prepared.attachments).toEqual([
397 {
398 type: "image",
399 id: MINTED_ID,
400 name: "photo.png",
401 mimeType: "image/png",
402 sizeBytes: 3,
403 },
404 ]);
405 }),
406 );
407​
408 it.effect("sends a document-picked picture with the mime it was uploaded under", () =>
409 Effect.gen(function* () {
410 const prepared = yield* prepare({
411 environmentId,
412 attachments: [documentPickedImage],
413 });
414​
415 expect(mocks.upload).toHaveBeenCalledWith(
416 "file:///documents/photo.png",
417 "https://environment.example/api/attachments/upload/signed",
418 expect.objectContaining({ headers: { "Content-Type": "image/png" } }),
419 );
420 expect(prepared.status).toBe("ready");
421 if (prepared.status !== "ready") return;
422 expect(prepared.attachments[0]).toEqual({
423 type: "image",
424 id: MINTED_ID,
425 name: "photo.png",
426 mimeType: "image/png",
427 sizeBytes: 3,
428 });
429 }),
430 );
431​
432 it.effect("uploads an oversized document-picked image as a file", () =>
433 Effect.gen(function* () {
434 const largeImage = {
435 ...documentPickedImage,
436 mimeType: "image/png",
437 sizeBytes: PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1,
438 };
439 const prepared = yield* prepare({ environmentId, attachments: [largeImage] });
440​
441 expect(mocks.runAtomCommand).toHaveBeenCalledWith(
442 expect.anything(),
443 mocks.createUploadUrl,
444 expect.objectContaining({
445 input: {
446 type: "file",
447 name: largeImage.name,
448 mimeType: "image/png",
449 sizeBytes: largeImage.sizeBytes,
450 },
451 }),
452 expect.anything(),
453 );
454 expect(prepared.status).toBe("ready");
455 if (prepared.status !== "ready") return;
456 expect(prepared.attachments).toEqual([
457 {
458 type: "file",
459 id: MINTED_ID,
460 name: largeImage.name,
461 mimeType: "image/png",
462 sizeBytes: largeImage.sizeBytes,
463 },
464 ]);
465 expect(mocks.readBase64).not.toHaveBeenCalled();
466 }),
467 );
468​
469 it.effect("uploads generic file bytes directly and keeps mixed attachment order", () =>
470 Effect.gen(function* () {
471 const pastedFile = {
472 ...file,
473 source: { _tag: "pasted-text" as const },
474 };
475 const prepared = yield* prepare({
476 environmentId,
477 attachments: [pastedFile, image],
478 });
479​
480 expect(mocks.upload).toHaveBeenCalledWith(
481 "file:///documents/report.pdf",
482 "https://environment.example/api/attachments/upload/signed",
483 expect.objectContaining({
484 httpMethod: "POST",
485 uploadType: 0,
486 headers: { "Content-Type": "application/pdf" },
487 }),
488 );
489 expect(prepared.status).toBe("ready");
490 if (prepared.status !== "ready") return;
491 expect(prepared.attachments[0]).toEqual({
492 type: "file",
493 id: MINTED_ID,
494 name: "report.pdf",
495 mimeType: "application/pdf",
496 sizeBytes: 42,
497 source: { _tag: "pasted-text" },
498 });
499 expect(prepared.attachments[1]?.type).toBe("image");
500 expect(prepared.pendingAttachmentIds).toEqual([MINTED_ID]);
501 expect(prepared.draftAttachments[0]).toEqual({
502 ...pastedFile,
503 uploadedAttachmentId: MINTED_ID,
504 uploadEnvironmentId: environmentId,
505 });
506 }),
507 );
508​
509 it.effect("uses the current connection when an environment reconnects during URL creation", () =>
510 Effect.gen(function* () {
511 mocks.readAtom
512 .mockReturnValueOnce(Option.some({ httpBaseUrl: "https://old-environment.example/" }))
513 .mockReturnValueOnce(Option.some({ httpBaseUrl: "https://new-environment.example/" }));
514​
515 yield* prepare({ environmentId, attachments: [file] });
516​
517 expect(mocks.upload).toHaveBeenCalledWith(
518 file.fileUri,
519 "https://new-environment.example/api/attachments/upload/signed",
520 expect.anything(),
521 );
522 }),
523 );
524​
525 it.effect("uploads a restored draft file from the current iOS document container", () =>
526 Effect.gen(function* () {
527 const fileName = "33333333-3333-4333-8333-333333333333-report%20%23.pdf";
528 const restoredFile = {
529 ...file,
530 fileUri: `file:///private/var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/${fileName}`,
531 };
532 mocks.documentUri =
533 "file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents";
534 const currentUri = `${mocks.documentUri}/t3-composer-attachments/${fileName}`;
535 mocks.upload.mockImplementation(async (uri: string) => {
536 if (uri !== currentUri) {
537 throw new Error("File does not exist in the previous application container.");
538 }
539 return { status: 204, body: "", headers: {} };
540 });
541​
542 const prepared = yield* prepare({
543 environmentId,
544 attachments: [restoredFile],
545 });
546​
547 expect(prepared.status).toBe("ready");
548 expect(mocks.upload).toHaveBeenCalledWith(
549 currentUri,
550 "https://environment.example/api/attachments/upload/signed",
551 expect.anything(),
552 );
553 }),
554 );
555​
556 it("adds uploaded file references to durable drafts without changing images", () => {
557 expect(
558 withUploadedMobileAttachmentReferences({
559 environmentId,
560 attachments: [file, image],
561 uploadedAttachments: [
562 {
563 type: "file",
564 id: "pending-existing-pdf",
565 name: file.name,
566 mimeType: file.mimeType,
567 sizeBytes: file.sizeBytes,
568 },
569 {
570 type: "image",
571 name: image.name,
572 mimeType: image.mimeType,
573 sizeBytes: image.sizeBytes,
574 dataUrl: image.dataUrl,
575 },
576 ],
577 }),
578 ).toEqual([
579 {
580 ...file,
581 uploadedAttachmentId: "pending-existing-pdf",
582 uploadEnvironmentId: environmentId,
583 },
584 image,
585 ]);
586 });
587​
588 it.effect("reuses a pending file upload from a previous outbox attempt", () =>
589 Effect.gen(function* () {
590 const previouslyUploaded = {
591 ...file,
592 uploadedAttachmentId: "pending-existing-pdf",
593 uploadEnvironmentId: environmentId,
594 };
595​
596 const prepared = yield* prepare({
597 environmentId,
598 attachments: [previouslyUploaded, image],
599 });
600​
601 expect(prepared.status).toBe("ready");
602 if (prepared.status !== "ready") return;
603 expect(prepared.attachments).toEqual([
604 {
605 type: "file",
606 id: "pending-existing-pdf",
607 name: "report.pdf",
608 mimeType: "application/pdf",
609 sizeBytes: 42,
610 },
611 {
612 type: "image",
613 name: "screenshot.png",
614 mimeType: "image/png",
615 sizeBytes: 3,
616 dataUrl: "data:image/png;base64,YWJj",
617 },
618 ]);
619 expect(prepared.pendingAttachmentIds).toEqual(["pending-existing-pdf"]);
620 expect(mocks.upload).not.toHaveBeenCalled();
621 expect(mocks.runAtomCommand).not.toHaveBeenCalled();
622 }),
623 );
624​
625 it.effect("uploads a file again when its saved pending upload has expired", () =>
626 Effect.gen(function* () {
627 mocks.executeAtomQuery.mockResolvedValueOnce({
628 _tag: "Failure",
629 error: { _tag: "AssetAttachmentNotFoundError" },
630 });
631 const previouslyUploaded = {
632 ...file,
633 uploadedAttachmentId: "pending-expired-pdf",
634 uploadEnvironmentId: environmentId,
635 };
636​
637 const prepared = yield* prepare({
638 environmentId,
639 attachments: [previouslyUploaded],
640 });
641​
642 expect(mocks.upload).toHaveBeenCalledOnce();
643 expect(prepared.status).toBe("ready");
644 if (prepared.status !== "ready") return;
645 expect(prepared.pendingAttachmentIds).toEqual([MINTED_ID]);
646 }),
647 );
648​
649 it.effect("uploads image bytes over HTTP while retaining the durable offline image", () =>
650 Effect.gen(function* () {
651 const persisted = vi.fn(() => Effect.succeed("persisted" as const));
652 const prepared = yield* prepare({
653 environmentId,
654 attachments: [image],
655 supportsImageUploads: true,
656 persistUploadedReferences: persisted,
657 });
658 expect(mocks.writeFile).toHaveBeenCalledWith("file:///cache/t3-upload-uuid", "YWJj", {
659 encoding: "base64",
660 });
661 expect(mocks.upload).toHaveBeenCalledWith(
662 "file:///cache/t3-upload-uuid",
663 "https://environment.example/api/attachments/upload/signed",
664 expect.objectContaining({ headers: { "Content-Type": "image/png" } }),
665 );
666 expect(mocks.deleteFile).toHaveBeenCalledExactlyOnceWith("file:///cache/t3-upload-uuid");
667 expect(prepared.status).toBe("ready");
668 if (prepared.status !== "ready") return;
669 expect(prepared.attachments).toEqual([
670 {
671 type: "image",
672 id: MINTED_ID,
673 name: image.name,
674 mimeType: image.mimeType,
675 sizeBytes: image.sizeBytes,
676 },
677 ]);
678 expect(prepared.draftAttachments).toEqual([
679 { ...image, uploadedAttachmentId: MINTED_ID, uploadEnvironmentId: environmentId },
680 ]);
681 expect(persisted).toHaveBeenCalledWith(prepared.draftAttachments);
682 }),
683 );
684​
685 it.effect("reuses an uploaded image and reuploads its local bytes after server expiry", () =>
686 Effect.gen(function* () {
687 const saved = {
688 ...image,
689 uploadedAttachmentId: "saved-image",
690 uploadEnvironmentId: environmentId,
691 };
692 const reused = yield* prepare({
693 environmentId,
694 attachments: [saved],
695 supportsImageUploads: true,
696 });
697 expect(reused.status === "ready" && reused.attachments[0]).toEqual({
698 type: "image",
699 id: "saved-image",
700 name: image.name,
701 mimeType: image.mimeType,
702 sizeBytes: image.sizeBytes,
703 });
704 expect(mocks.upload).not.toHaveBeenCalled();
705 mocks.executeAtomQuery.mockResolvedValueOnce({
706 _tag: "Failure",
707 error: { _tag: "AssetAttachmentNotFoundError" },
708 });
709 const restored = yield* prepare({
710 environmentId,
711 attachments: [saved],
712 supportsImageUploads: true,
713 });
714 expect(restored.status === "ready" && restored.draftAttachments[0]).toEqual({
715 ...saved,
716 uploadedAttachmentId: MINTED_ID,
717 });
718 expect(mocks.writeFile).toHaveBeenCalledWith("file:///cache/t3-upload-uuid", "YWJj", {
719 encoding: "base64",
720 });
721 }),
722 );
723​
724 it.effect("does not reuse an image upload from another environment", () =>
725 Effect.gen(function* () {
726 const prepared = yield* prepare({
727 environmentId,
728 attachments: [
729 {
730 ...image,
731 uploadedAttachmentId: "other-image",
732 uploadEnvironmentId: EnvironmentId.make("other"),
733 },
734 ],
735 supportsImageUploads: true,
736 });
737 expect(mocks.executeAtomQuery).not.toHaveBeenCalled();
738 expect(mocks.upload).toHaveBeenCalledOnce();
739 expect(prepared.status === "ready" && prepared.draftAttachments[0]?.uploadEnvironmentId).toBe(
740 environmentId,
741 );
742 }),
743 );
744​
745 it.effect(
746 "aborts an active transfer without dropping local bytes or stamping a partial upload",
747 () =>
748 Effect.gen(function* () {
749 const started = Promise.withResolvers<void>();
750 const persist = vi.fn(() => Effect.succeed("persisted" as const));
751 mocks.upload.mockImplementation(
752 (_uri: string, _url: string, options: { signal: AbortSignal }) =>
753 new Promise((_, reject) => {
754 options.signal.addEventListener("abort", () => reject(new Error("cancelled")), {
755 once: true,
756 });
757 started.resolve();
758 }),
759 );
760 const preparing = yield* Effect.forkChild(
761 prepare({ environmentId, attachments: [file], persistUploadedReferences: persist }),
762 );
763 yield* Effect.promise(() => started.promise);
764 yield* Fiber.interrupt(preparing);
765 expect(Exit.hasInterrupts(yield* Fiber.await(preparing))).toBe(true);
766 expect(persist).not.toHaveBeenCalled();
767 expect(mocks.deleteFile).not.toHaveBeenCalled();
768 expect(removeCallsFor(MINTED_ID)).toBe(1);
769 }),
770 );
771​
772 it.effect("removes pending uploads when the native HTTP request fails", () =>
773 Effect.gen(function* () {
774 mocks.upload.mockResolvedValue({ status: 500, body: "failed", headers: {} });
775​
776 expect(
777 (yield* Effect.flip(prepare({ environmentId, attachments: [file] }))).message,
778 ).toContain("Upload failed for 'report.pdf' (500).");
779 expect(removeCallsFor(MINTED_ID)).toBe(1);
780 }),
781 );
782​
783 it.effect("keeps a previously persisted upload when a later attachment fails", () =>
784 Effect.gen(function* () {
785 const previouslyUploaded = {
786 ...file,
787 id: "file-existing",
788 uploadedAttachmentId: "pending-existing-pdf",
789 uploadEnvironmentId: environmentId,
790 };
791 mocks.upload.mockResolvedValue({ status: 500, body: "failed", headers: {} });
792​
793 expect(
794 (yield* Effect.flip(prepare({ environmentId, attachments: [previouslyUploaded, file] })))
795 .message,
796 ).toContain("Upload failed for 'report.pdf' (500).");
797​
798 expect(removeCallsFor("pending-existing-pdf")).toBe(0);
799 }),
800 );
801});
802​
803describe("releasePendingAttachmentUploads", () => {
804 beforeEach(() => {
805 mocks.runAtomCommand.mockReset();
806 });
807​
808 it("throws when a delete keeps failing so the caller sees the leak", async () => {
809 mocks.runAtomCommand.mockResolvedValue({ _tag: "Failure", error: new Error("offline") });
810​
811 await expect(releasePendingAttachmentUploads(environmentId, ["pending-a"])).rejects.toThrow(
812 "pending-a",
813 );
814 });
815​
816 it("treats an already-deleted pending upload as released", async () => {
817 mocks.runAtomCommand.mockResolvedValue({
818 _tag: "Failure",
819 error: { _tag: "AssetAttachmentNotFoundError" },
820 });
821​
822 await expect(
823 releasePendingAttachmentUploads(environmentId, ["pending-a"]),
824 ).resolves.toBeUndefined();
825 expect(mocks.runAtomCommand).toHaveBeenCalledTimes(1);
826 });
827});