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

attachmentUpload.test.ts

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