Open History to see the last commit
1import { EnvironmentId, ProjectId } from "@t3tools/contracts";
2import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
3import { Atom, AsyncResult } from "effect/reactivity";
4import { appAtomRegistry } from "../rpc/atomRegistry";
5
6import {
7 composerFileNeedsReattach,
8 DraftId,
9 useComposerDraftStore,
10 type ComposerFileAttachment,
11 type ComposerImageAttachment,
12} from "../composerDraftStore";
13
14const mocks = vi.hoisted(() => ({
15 checkHttpOrigin: Symbol("check-http-origin"),
16 connectionStateAtom: vi.fn(),
17 createAssetUrl: vi.fn(),
18 createUploadUrl: Symbol("create-upload-url"),
19 executeAtomQuery: vi.fn(),
20 removeUpload: Symbol("remove-upload"),
21 runAtomCommand: vi.fn(),
22 readEnvironmentScope: vi.fn(),
23 readPreparedConnection: vi.fn(),
24 // Verification and minting run as Effects; tests steer them with the settled results above.
25 settledEffect: (
26 Effect: typeof import("effect/Effect"),
27 settle: () => Promise<{
28 readonly _tag: string;
29 readonly value?: unknown;
30 readonly error?: object;
31 }>,
32 ) =>
33 Effect.promise(settle).pipe(
34 Effect.flatMap((result) =>
35 result._tag === "Success" ? Effect.succeed(result.value) : Effect.fail(result.error),
36 ),
37 ),
38}));
39
40vi.mock("@t3tools/client-runtime/state/runtime", async () => {
41 const Effect = await import("effect/Effect");
42 return {
43 awaitAtomResult: (...args: ReadonlyArray<unknown>) =>
44 mocks.settledEffect(Effect, () => mocks.executeAtomQuery(...args)),
45 runAtomCommand: mocks.runAtomCommand,
46 squashAtomCommandFailure: (result: { readonly error: unknown }) => result.error,
47 };
48});
49
50vi.mock("../rpc/atomRegistry", async () => {
51 const { AtomRegistry } = await import("effect/reactivity");
52 return { appAtomRegistry: AtomRegistry.make() };
53});
54
55vi.mock("../connection/catalog", () => ({
56 environmentCatalog: {
57 stateAtom: mocks.connectionStateAtom,
58 checkHttpOrigin: mocks.checkHttpOrigin,
59 },
60}));
61
62vi.mock("../state/assets", () => ({
63 assetEnvironment: { createUrl: mocks.createAssetUrl },
64}));
65
66vi.mock("../state/attachments", async () => {
67 const Effect = await import("effect/Effect");
68 return {
69 attachmentEnvironment: {
70 createUploadUrl: {
71 run: (registry: unknown, input: unknown) =>
72 mocks.settledEffect(Effect, () =>
73 mocks.runAtomCommand(registry, mocks.createUploadUrl, input),
74 ),
75 },
76 remove: mocks.removeUpload,
77 },
78 };
79});
80
81vi.mock("../state/session", () => ({
82 readEnvironmentScope: mocks.readEnvironmentScope,
83 readPreparedConnection: mocks.readPreparedConnection,
84}));
85
86import {
87 awaitAttachmentUploads,
88 getUploadedAttachments,
89 readAttachmentUpload,
90 refreshExpiredAttachmentUploads,
91 releaseAttachmentUpload,
92 releaseDraftAttachment,
93 releaseDraftAttachments,
94 releasePersistedAttachmentUpload,
95 retryAttachmentUpload,
96 startAttachmentUpload,
97 useAttachmentUploadStore,
98} from "./attachmentUploadQueue";
99
100type ProgressListener = (event: {
101 readonly lengthComputable: boolean;
102 readonly loaded: number;
103 readonly total: number;
104}) => void;
105
106class TestXmlHttpRequest {
107 static requests: TestXmlHttpRequest[] = [];
108
109 status = 0;
110 timeout = 0;
111 method: string | null = null;
112 url: string | null = null;
113 readonly headers = new Map<string, string>();
114 readonly listeners = new Map<string, () => void>();
115 progressListener: ProgressListener | null = null;
116
117 readonly upload = {
118 addEventListener: (_event: string, listener: ProgressListener) => {
119 this.progressListener = listener;
120 },
121 };
122
123 constructor() {
124 TestXmlHttpRequest.requests.push(this);
125 }
126
127 open(method: string, url: string): void {
128 this.method = method;
129 this.url = url;
130 }
131
132 setRequestHeader(name: string, value: string): void {
133 this.headers.set(name, value);
134 }
135
136 addEventListener(event: string, listener: () => void): void {
137 this.listeners.set(event, listener);
138 }
139
140 send(): void {}
141
142 abort(): void {
143 this.listeners.get("abort")?.();
144 }
145
146 progress(loaded: number, total: number): void {
147 this.progressListener?.({ lengthComputable: true, loaded, total });
148 }
149
150 complete(status = 204): void {
151 this.status = status;
152 this.listeners.get("load")?.();
153 }
154
155 fail(): void {
156 this.listeners.get("error")?.();
157 }
158}
159
160const firstEnvironment = EnvironmentId.make("environment-1");
161const secondEnvironment = EnvironmentId.make("environment-2");
162
163function makeImage(id: string): ComposerImageAttachment {
164 const file = new File([new Uint8Array([1, 2, 3])], `${id}.png`, { type: "image/png" });
165 return {
166 type: "image",
167 id,
168 name: file.name,
169 mimeType: file.type,
170 sizeBytes: file.size,
171 previewUrl: `blob:${id}`,
172 file,
173 };
174}
175
176function makeFile(id: string): ComposerFileAttachment {
177 const file = new File([new Uint8Array([1, 2, 3])], `${id}.pdf`, {
178 type: "application/pdf",
179 });
180 return {
181 type: "file",
182 id,
183 name: file.name,
184 mimeType: file.type,
185 sizeBytes: file.size,
186 file,
187 };
188}
189
190const connectionStates = Atom.family((_environmentId: EnvironmentId) =>
191 Atom.make(AsyncResult.success({ phase: "connected" })),
192);
193
194function setConnected(environmentId: EnvironmentId, connected: boolean) {
195 appAtomRegistry.set(
196 connectionStates(environmentId),
197 AsyncResult.success({ phase: connected ? "connected" : "backoff" }),
198 );
199}
200
201describe("attachmentUploadQueue", () => {
202 beforeEach(() => {
203 mocks.connectionStateAtom.mockImplementation(connectionStates);
204 setConnected(firstEnvironment, true);
205 setConnected(secondEnvironment, true);
206 TestXmlHttpRequest.requests = [];
207 mocks.createAssetUrl.mockReset();
208 mocks.createAssetUrl.mockImplementation((target: unknown) => target);
209 mocks.executeAtomQuery.mockReset();
210 mocks.executeAtomQuery.mockResolvedValue({ _tag: "Success", value: {} });
211 mocks.runAtomCommand.mockReset();
212 mocks.readEnvironmentScope.mockReset().mockReturnValue(true);
213 mocks.readPreparedConnection.mockReset();
214 mocks.readPreparedConnection.mockReturnValue({ httpBaseUrl: "https://environment.test/" });
215 mocks.runAtomCommand.mockImplementation(
216 async (
217 _registry: unknown,
218 command: unknown,
219 target: {
220 readonly environmentId: EnvironmentId;
221 readonly input: { readonly name?: string };
222 },
223 ) => {
224 if (command === mocks.createUploadUrl) {
225 const attachmentId = `pending-${target.environmentId}-${target.input.name}`;
226 return {
227 _tag: "Success",
228 value: {
229 attachmentId,
230 relativeUrl: `/api/attachments/upload/${attachmentId}`,
231 expiresAt: 1,
232 },
233 };
234 }
235 return { _tag: "Success", value: undefined };
236 },
237 );
238 vi.stubGlobal("XMLHttpRequest", TestXmlHttpRequest);
239 });
240
241 afterEach(() => {
242 for (const imageId of Object.keys(useAttachmentUploadStore.getState().uploadsByImageId)) {
243 releaseAttachmentUpload(imageId);
244 }
245 vi.unstubAllGlobals();
246 });
247
248 it("reuploads an expired image while retaining other ready images", async () => {
249 const images = [makeImage("first"), makeImage("second")].map((image) => ({
250 ...image,
251 name: "image.png",
252 }));
253 let minted = 0;
254 mocks.runAtomCommand.mockImplementation(async (_registry, command) => {
255 if (command !== mocks.createUploadUrl) return { _tag: "Success", value: undefined };
256 const attachmentId = `pending-test-${++minted}`;
257 return {
258 _tag: "Success",
259 value: {
260 attachmentId,
261 relativeUrl: `/api/attachments/upload/${attachmentId}`,
262 expiresAt: 1,
263 },
264 };
265 });
266 for (const image of images) startAttachmentUpload({ environmentId: firstEnvironment, image });
267 await Promise.resolve();
268 const initial = awaitAttachmentUploads(images.map((image) => image.id));
269 TestXmlHttpRequest.requests.forEach((request) => request.complete());
270 await initial;
271 mocks.executeAtomQuery.mockImplementation(
272 async (_registry, target: { input: { resource: { attachmentId: string } } }) =>
273 target.input.resource.attachmentId === "pending-test-1"
274 ? { _tag: "Failure", error: { _tag: "AssetAttachmentNotFoundError" } }
275 : { _tag: "Success", value: {} },
276 );
277 const refreshing = refreshExpiredAttachmentUploads({ environmentId: firstEnvironment, images });
278 await vi.waitFor(() => expect(TestXmlHttpRequest.requests).toHaveLength(3));
279 TestXmlHttpRequest.requests[2]!.complete();
280 await refreshing;
281 expect(
282 getUploadedAttachments({ environmentId: firstEnvironment, images })?.map((image) => image.id),
283 ).toEqual(["pending-test-3", "pending-test-2"]);
284 expect(TestXmlHttpRequest.requests).toHaveLength(3);
285 });
286
287 it("reuploads local file bytes after its persisted upload is known to be missing", async () => {
288 const file = {
289 ...makeFile("expired-saved-file"),
290 uploadedAttachmentId: "pending-expired",
291 uploadEnvironmentId: firstEnvironment,
292 };
293 useAttachmentUploadStore.setState({
294 uploadsByImageId: {
295 [file.id]: {
296 status: "ready",
297 environmentId: firstEnvironment,
298 attachmentId: "pending-expired",
299 },
300 },
301 });
302 mocks.executeAtomQuery
303 .mockResolvedValueOnce({
304 _tag: "Failure",
305 error: { _tag: "AssetAttachmentNotFoundError" },
306 })
307 .mockResolvedValue({ _tag: "Failure", error: new Error("Connection interrupted") });
308 let uploadStarted!: () => void;
309 const started = new Promise<void>((resolve) => {
310 uploadStarted = resolve;
311 });
312 const runCommand = mocks.runAtomCommand.getMockImplementation()!;
313 mocks.runAtomCommand.mockImplementation(async (...args) => {
314 const result = await runCommand(...args);
315 if (args[1] === mocks.createUploadUrl) uploadStarted();
316 return result;
317 });
318 const refresh = refreshExpiredAttachmentUploads({
319 environmentId: firstEnvironment,
320 images: [file],
321 });
322 expect(await Promise.race([started.then(() => "upload"), refresh.then(() => "settled")])).toBe(
323 "upload",
324 );
325 expect(TestXmlHttpRequest.requests).toHaveLength(1);
326 TestXmlHttpRequest.requests[0]!.complete();
327 await refresh;
328 expect(mocks.executeAtomQuery).toHaveBeenCalledTimes(1);
329 expect(
330 getUploadedAttachments({ environmentId: firstEnvironment, images: [file] }),
331 ).toMatchObject([{ id: "pending-environment-1-expired-saved-file.pdf" }]);
332 });
333
334 it.each([false, true])(
335 "retains cleanup identity after verification fails (retry: %s)",
336 async (retry) => {
337 const image = makeImage("connection-failure");
338 useAttachmentUploadStore.setState({
339 uploadsByImageId: {
340 [image.id]: {
341 status: "ready",
342 environmentId: firstEnvironment,
343 attachmentId: "pending-original",
344 },
345 },
346 });
347 mocks.executeAtomQuery.mockRejectedValueOnce(new Error("offline"));
348 await refreshExpiredAttachmentUploads({ environmentId: firstEnvironment, images: [image] });
349 expect(readAttachmentUpload(image.id)).toMatchObject({ status: "failed" });
350 expect(
351 getUploadedAttachments({ environmentId: firstEnvironment, images: [image] }),
352 ).toBeNull();
353 expect(TestXmlHttpRequest.requests).toHaveLength(0);
354 if (retry) retryAttachmentUpload({ environmentId: firstEnvironment, image });
355 releaseAttachmentUpload(image.id);
356 expect(readAttachmentUpload(image.id)).toBeUndefined();
357 expect(mocks.runAtomCommand).toHaveBeenCalledExactlyOnceWith(
358 expect.anything(),
359 mocks.removeUpload,
360 { environmentId: firstEnvironment, input: { attachmentId: "pending-original" } },
361 expect.anything(),
362 );
363 },
364 );
365
366 it("reuploads local bytes for a connection without read permission", async () => {
367 const image = makeImage("operate-only");
368 useAttachmentUploadStore.setState({
369 uploadsByImageId: {
370 [image.id]: {
371 status: "ready",
372 environmentId: firstEnvironment,
373 attachmentId: "pending-original",
374 },
375 },
376 });
377 mocks.readEnvironmentScope.mockImplementation(
378 (_environmentId, scope) => scope !== "orchestration:read",
379 );
380 const refresh = refreshExpiredAttachmentUploads({
381 environmentId: firstEnvironment,
382 images: [image],
383 });
384 await vi.waitFor(() => expect(TestXmlHttpRequest.requests).toHaveLength(1));
385 TestXmlHttpRequest.requests[0]!.complete();
386 await refresh;
387 expect(readAttachmentUpload(image.id)).toMatchObject({
388 status: "ready",
389 attachmentId: "pending-environment-1-operate-only.png",
390 });
391 expect(mocks.executeAtomQuery).not.toHaveBeenCalled();
392 });
393
394 it("does not resurrect an image removed while its upload is being checked", async () => {
395 const image = makeImage("removed-during-verification");
396 useAttachmentUploadStore.setState({
397 uploadsByImageId: {
398 [image.id]: {
399 status: "ready",
400 environmentId: firstEnvironment,
401 attachmentId: "pending-original",
402 },
403 },
404 });
405 let finish!: (value: unknown) => void;
406 mocks.executeAtomQuery.mockReturnValueOnce(
407 new Promise((resolve) => {
408 finish = resolve;
409 }),
410 );
411 const refresh = refreshExpiredAttachmentUploads({
412 environmentId: firstEnvironment,
413 images: [image],
414 });
415 releaseAttachmentUpload(image.id);
416 finish({ _tag: "Failure", error: { _tag: "AssetAttachmentNotFoundError" } });
417 await refresh;
418 expect(readAttachmentUpload(image.id)).toBeUndefined();
419 expect(TestXmlHttpRequest.requests).toHaveLength(0);
420 });
421
422 it("keeps an attachment local until its own environment grants write access", async () => {
423 const image = makeImage("permission-gain");
424 mocks.readEnvironmentScope.mockImplementation(
425 (environmentId) => environmentId === firstEnvironment,
426 );
427
428 startAttachmentUpload({ environmentId: secondEnvironment, image });
429 expect(mocks.runAtomCommand).not.toHaveBeenCalled();
430 expect(TestXmlHttpRequest.requests).toHaveLength(0);
431 expect(readAttachmentUpload(image.id)).toBeUndefined();
432 expect(image.file).not.toBeNull();
433
434 mocks.readEnvironmentScope.mockReturnValue(true);
435 startAttachmentUpload({ environmentId: secondEnvironment, image });
436 await Promise.resolve();
437 const settled = awaitAttachmentUploads([image.id]);
438 TestXmlHttpRequest.requests[0]!.complete();
439 await settled;
440
441 expect(readAttachmentUpload(image.id)).toMatchObject({
442 status: "ready",
443 environmentId: secondEnvironment,
444 });
445 });
446
447 it("does not transfer bytes or retry when access is revoked while minting an upload", async () => {
448 const image = makeImage("revoke-before-bytes");
449 let finishMint: (() => void) | undefined;
450 mocks.runAtomCommand.mockImplementationOnce(
451 () =>
452 new Promise((resolve) => {
453 finishMint = () =>
454 resolve({
455 _tag: "Success",
456 value: {
457 attachmentId: "pending-revoked",
458 relativeUrl: "/api/attachments/upload/pending-revoked",
459 expiresAt: 1,
460 },
461 });
462 }),
463 );
464 startAttachmentUpload({ environmentId: firstEnvironment, image });
465 const settled = awaitAttachmentUploads([image.id]);
466 mocks.readEnvironmentScope.mockReturnValue(false);
467 finishMint!();
468 await settled;
469
470 expect(TestXmlHttpRequest.requests).toHaveLength(0);
471 expect(readAttachmentUpload(image.id)).toMatchObject({
472 status: "failed",
473 reason: "This connection cannot upload attachments.",
474 attachmentId: "pending-revoked",
475 });
476 retryAttachmentUpload({ environmentId: firstEnvironment, image });
477 expect(readAttachmentUpload(image.id)?.status).toBe("failed");
478 releaseAttachmentUpload(image.id);
479 expect(readAttachmentUpload(image.id)).toBeUndefined();
480 expect(mocks.runAtomCommand).toHaveBeenCalledTimes(1);
481 });
482
483 it("does not delete a persisted upload using another environment's grant", () => {
484 mocks.readEnvironmentScope.mockImplementation(
485 (environmentId) => environmentId === firstEnvironment,
486 );
487 releasePersistedAttachmentUpload({
488 id: "local-file",
489 environmentId: secondEnvironment,
490 attachmentId: "persisted-file",
491 });
492 expect(mocks.runAtomCommand).not.toHaveBeenCalled();
493
494 mocks.readEnvironmentScope.mockReturnValue(true);
495 releasePersistedAttachmentUpload({
496 id: "local-file",
497 environmentId: secondEnvironment,
498 attachmentId: "persisted-file",
499 });
500 expect(mocks.runAtomCommand).toHaveBeenCalledWith(
501 expect.anything(),
502 mocks.removeUpload,
503 { environmentId: secondEnvironment, input: { attachmentId: "persisted-file" } },
504 expect.anything(),
505 );
506 });
507
508 it("uploads images immediately and sends attachment references", async () => {
509 const image = {
510 ...makeImage("image-1"),
511 source: {
512 kind: "snap-shot" as const,
513 capturedAt: "2026-08-24T11:00:00.000Z",
514 appName: "Terminal",
515 windowTitle: "Tests",
516 },
517 };
518 startAttachmentUpload({ environmentId: firstEnvironment, image });
519 await Promise.resolve();
520
521 const request = TestXmlHttpRequest.requests[0]!;
522 expect(request.method).toBe("POST");
523 expect(request.url).toBe(
524 "https://environment.test/api/attachments/upload/pending-environment-1-image-1.png",
525 );
526 request.progress(1, 3);
527 expect(readAttachmentUpload(image.id)).toMatchObject({ status: "uploading", progress: 1 / 3 });
528
529 const settled = awaitAttachmentUploads([image.id]);
530 request.complete();
531 await settled;
532
533 expect(getUploadedAttachments({ environmentId: firstEnvironment, images: [image] })).toEqual([
534 {
535 type: "image",
536 id: "pending-environment-1-image-1.png",
537 name: "image-1.png",
538 mimeType: "image/png",
539 sizeBytes: 3,
540 source: {
541 kind: "snap-shot",
542 capturedAt: "2026-08-24T11:00:00.000Z",
543 appName: "Terminal",
544 windowTitle: "Tests",
545 },
546 },
547 ]);
548
549 releaseDraftAttachments([image]);
550 expect(readAttachmentUpload(image.id)).toBeUndefined();
551 expect(mocks.runAtomCommand).toHaveBeenCalledWith(
552 expect.anything(),
553 mocks.removeUpload,
554 {
555 environmentId: firstEnvironment,
556 input: { attachmentId: "pending-environment-1-image-1.png" },
557 },
558 expect.anything(),
559 );
560 });
561
562 it("persists a background completion's ids to the draft with no composer mounted", async () => {
563 const draftId = DraftId.make("draft-background-upload");
564 const file = makeFile("background");
565 const draftStore = useComposerDraftStore.getState();
566 draftStore.addFiles(draftId, [file]);
567 try {
568 startAttachmentUpload({
569 environmentId: firstEnvironment,
570 image: file,
571 draftTarget: draftId,
572 });
573 await Promise.resolve();
574
575 const settled = awaitAttachmentUploads([file.id]);
576 TestXmlHttpRequest.requests[0]!.complete();
577 await settled;
578
579 expect(useComposerDraftStore.getState().getComposerDraft(draftId)?.files).toMatchObject([
580 {
581 id: file.id,
582 uploadedAttachmentId: "pending-environment-1-background.pdf",
583 uploadEnvironmentId: firstEnvironment,
584 },
585 ]);
586 } finally {
587 useComposerDraftStore.getState().clearComposerContent(draftId);
588 }
589 });
590
591 it("stamps a file that lands in a draft after its upload finished", async () => {
592 const draftId = DraftId.make("draft-restored-upload");
593 const file = makeFile("restored");
594 try {
595 startAttachmentUpload({ environmentId: firstEnvironment, image: file, draftTarget: draftId });
596 await Promise.resolve();
597 const settled = awaitAttachmentUploads([file.id]);
598 TestXmlHttpRequest.requests[0]!.complete();
599 await settled;
600
601 useComposerDraftStore.getState().addFiles(draftId, [file]);
602 startAttachmentUpload({ environmentId: firstEnvironment, image: file, draftTarget: draftId });
603
604 expect(TestXmlHttpRequest.requests).toHaveLength(1);
605 expect(useComposerDraftStore.getState().getComposerDraft(draftId)?.files).toMatchObject([
606 {
607 id: file.id,
608 uploadedAttachmentId: "pending-environment-1-restored.pdf",
609 uploadEnvironmentId: firstEnvironment,
610 },
611 ]);
612 } finally {
613 useComposerDraftStore.getState().clearComposerContent(draftId);
614 }
615 });
616
617 it("turns an expired persisted file into a marker that a re-pick can replace", async () => {
618 const draftId = DraftId.make("draft-expired-upload");
619 const file: ComposerFileAttachment = {
620 ...makeFile("expired"),
621 file: null,
622 uploadedAttachmentId: "pending-expired-pdf",
623 uploadEnvironmentId: firstEnvironment,
624 };
625 mocks.executeAtomQuery.mockResolvedValueOnce({
626 _tag: "Failure",
627 error: { _tag: "AssetAttachmentNotFoundError" },
628 });
629 useComposerDraftStore.getState().addFiles(draftId, [file]);
630
631 try {
632 startAttachmentUpload({
633 environmentId: firstEnvironment,
634 image: file,
635 draftTarget: draftId,
636 });
637 await awaitAttachmentUploads([file.id]);
638
639 const marker = useComposerDraftStore.getState().getComposerDraft(draftId)?.files[0];
640 expect(readAttachmentUpload(file.id)).toBeUndefined();
641 expect(marker?.uploadedAttachmentId).toBeUndefined();
642 expect(marker?.uploadEnvironmentId).toBeUndefined();
643 expect(marker && composerFileNeedsReattach(marker)).toBe(true);
644
645 const replacementBytes = new File([new Uint8Array([1, 2, 3])], file.name, {
646 type: file.mimeType,
647 });
648 const replacement: ComposerFileAttachment = {
649 type: "file",
650 id: "expired-repicked",
651 name: file.name,
652 mimeType: file.mimeType,
653 sizeBytes: file.sizeBytes,
654 file: replacementBytes,
655 };
656 useComposerDraftStore.getState().addFiles(draftId, [replacement]);
657 expect(useComposerDraftStore.getState().getComposerDraft(draftId)?.files).toMatchObject([
658 { id: replacement.id, file: replacementBytes },
659 ]);
660
661 startAttachmentUpload({
662 environmentId: firstEnvironment,
663 image: replacement,
664 draftTarget: draftId,
665 });
666 await Promise.resolve();
667 const settled = awaitAttachmentUploads([replacement.id]);
668 TestXmlHttpRequest.requests[0]!.complete();
669 await settled;
670
671 expect(useComposerDraftStore.getState().getComposerDraft(draftId)?.files).toMatchObject([
672 {
673 id: replacement.id,
674 uploadedAttachmentId: "pending-environment-1-expired.pdf",
675 uploadEnvironmentId: firstEnvironment,
676 },
677 ]);
678 const removeCalls = mocks.runAtomCommand.mock.calls.filter(
679 ([, command]) => command === mocks.removeUpload,
680 );
681 expect(removeCalls).toEqual([]);
682 } finally {
683 useComposerDraftStore.getState().clearComposerContent(draftId);
684 }
685 });
686
687 it("removes a persisted upload when its draft is discarded during verification", async () => {
688 const file: ComposerFileAttachment = {
689 ...makeFile("checking"),
690 file: null,
691 uploadedAttachmentId: "pending-checking-pdf",
692 uploadEnvironmentId: firstEnvironment,
693 };
694 let resolveVerification: (result: {
695 readonly _tag: "Success";
696 readonly value: object;
697 }) => void = () => {};
698 mocks.executeAtomQuery.mockReturnValueOnce(
699 new Promise((resolve) => {
700 resolveVerification = resolve;
701 }),
702 );
703
704 startAttachmentUpload({ environmentId: firstEnvironment, image: file });
705 releaseDraftAttachment(file);
706 resolveVerification({ _tag: "Success", value: {} });
707
708 expect(mocks.runAtomCommand).toHaveBeenCalledWith(
709 expect.anything(),
710 mocks.removeUpload,
711 {
712 environmentId: firstEnvironment,
713 input: { attachmentId: "pending-checking-pdf" },
714 },
715 expect.anything(),
716 );
717 });
718
719 it("keeps the persisted upload when retrying after a transient verification failure", async () => {
720 const draftId = DraftId.make("draft-transient-verification");
721 const file: ComposerFileAttachment = {
722 ...makeFile("flaky"),
723 file: null,
724 uploadedAttachmentId: "pending-flaky-pdf",
725 uploadEnvironmentId: firstEnvironment,
726 };
727 mocks.executeAtomQuery.mockResolvedValueOnce({
728 _tag: "Failure",
729 error: new Error("socket closed"),
730 });
731 useComposerDraftStore.getState().addFiles(draftId, [file]);
732
733 try {
734 startAttachmentUpload({
735 environmentId: firstEnvironment,
736 image: file,
737 draftTarget: draftId,
738 });
739 await awaitAttachmentUploads([file.id]);
740 expect(readAttachmentUpload(file.id)).toMatchObject({
741 status: "failed",
742 reason: "Uploaded file could not be verified. Retry when the server reconnects.",
743 });
744 expect(useComposerDraftStore.getState().getComposerDraft(draftId)?.files).toMatchObject([
745 {
746 uploadedAttachmentId: "pending-flaky-pdf",
747 uploadEnvironmentId: firstEnvironment,
748 },
749 ]);
750
751 retryAttachmentUpload({
752 environmentId: firstEnvironment,
753 image: file,
754 draftTarget: draftId,
755 });
756 await awaitAttachmentUploads([file.id]);
757
758 expect(readAttachmentUpload(file.id)).toEqual({
759 status: "ready",
760 environmentId: firstEnvironment,
761 attachmentId: "pending-flaky-pdf",
762 });
763 expect(useComposerDraftStore.getState().getComposerDraft(draftId)?.files).toMatchObject([
764 {
765 uploadedAttachmentId: "pending-flaky-pdf",
766 uploadEnvironmentId: firstEnvironment,
767 },
768 ]);
769 const removeCalls = mocks.runAtomCommand.mock.calls.filter(
770 ([, command]) => command === mocks.removeUpload,
771 );
772 expect(removeCalls).toEqual([]);
773 } finally {
774 useComposerDraftStore.getState().clearComposerContent(draftId);
775 }
776 });
777
778 it("routes a live persisted upload through the queue release exactly once", async () => {
779 const file: ComposerFileAttachment = {
780 ...makeFile("live"),
781 file: null,
782 uploadedAttachmentId: "pending-live-pdf",
783 uploadEnvironmentId: firstEnvironment,
784 };
785 startAttachmentUpload({ environmentId: firstEnvironment, image: file });
786 await awaitAttachmentUploads([file.id]);
787 expect(readAttachmentUpload(file.id)).toMatchObject({ status: "ready" });
788
789 releaseDraftAttachment(file);
790
791 expect(readAttachmentUpload(file.id)).toBeUndefined();
792 const removeCalls = mocks.runAtomCommand.mock.calls.filter(
793 ([, command]) => command === mocks.removeUpload,
794 );
795 expect(removeCalls).toEqual([
796 [
797 expect.anything(),
798 mocks.removeUpload,
799 {
800 environmentId: firstEnvironment,
801 input: { attachmentId: "pending-live-pdf" },
802 },
803 expect.anything(),
804 ],
805 ]);
806 });
807
808 it("releases an upload URL that resolves after its image was removed", async () => {
809 const image = makeImage("image-cancelled");
810 const minted = {
811 _tag: "Success" as const,
812 value: {
813 attachmentId: "pending-environment-1-image-cancelled.png",
814 relativeUrl: "/api/attachments/upload/cancelled",
815 expiresAt: 1,
816 },
817 };
818 let resolveMint: (result: typeof minted) => void = () => {};
819 const pendingMint = new Promise<typeof minted>((resolve) => {
820 resolveMint = resolve;
821 });
822 let resolveDelete: () => void = () => {};
823 const deleted = new Promise<void>((resolve) => {
824 resolveDelete = resolve;
825 });
826 mocks.runAtomCommand.mockImplementation((_registry: unknown, command: unknown) => {
827 if (command === mocks.createUploadUrl) {
828 return pendingMint;
829 }
830 resolveDelete();
831 return Promise.resolve({ _tag: "Success", value: undefined });
832 });
833
834 startAttachmentUpload({ environmentId: firstEnvironment, image });
835 releaseAttachmentUpload(image.id);
836 resolveMint(minted);
837 await deleted;
838
839 expect(TestXmlHttpRequest.requests).toEqual([]);
840 expect(readAttachmentUpload(image.id)).toBeUndefined();
841 expect(mocks.runAtomCommand).toHaveBeenCalledWith(
842 expect.anything(),
843 mocks.removeUpload,
844 {
845 environmentId: firstEnvironment,
846 input: { attachmentId: minted.value.attachmentId },
847 },
848 expect.anything(),
849 );
850 });
851
852 it.each(["image", "file"] as const)(
853 "restores the previous environment after a replacement upload fails: %s",
854 async (kind) => {
855 const draftId = DraftId.make("draft-environment-roundtrip");
856 const store = useComposerDraftStore.getState();
857 const image = kind === "image" ? makeImage("image-move") : makeFile("file-move");
858 const moveDraftTo = (environmentId: EnvironmentId) => {
859 store.setProjectDraftThreadId(
860 { environmentId, projectId: ProjectId.make("project") },
861 draftId,
862 );
863 startAttachmentUpload({ environmentId, image, draftTarget: draftId });
864 };
865 try {
866 if (image.type === "file") store.addFiles(draftId, [image]);
867 moveDraftTo(firstEnvironment);
868 await Promise.resolve();
869 let settled = awaitAttachmentUploads([image.id]);
870 TestXmlHttpRequest.requests[0]!.complete();
871 await settled;
872
873 moveDraftTo(secondEnvironment);
874 await Promise.resolve();
875 settled = awaitAttachmentUploads([image.id]);
876 TestXmlHttpRequest.requests[1]!.complete(500);
877 await settled;
878
879 moveDraftTo(firstEnvironment);
880 const attachmentId = `pending-environment-1-${image.name}`;
881 expect(readAttachmentUpload(image.id)).toMatchObject({
882 status: "ready",
883 environmentId: firstEnvironment,
884 attachmentId,
885 });
886 if (image.type === "file") {
887 expect(store.getComposerDraft(draftId)?.files).toMatchObject([
888 {
889 id: image.id,
890 uploadedAttachmentId: attachmentId,
891 uploadEnvironmentId: firstEnvironment,
892 },
893 ]);
894 }
895 } finally {
896 store.clearDraftThread(draftId);
897 }
898 },
899 );
900
901 it("does not let stalled uploads block another environment", async () => {
902 const images = ["image-a", "image-b", "image-c", "image-d"].map(makeImage);
903 for (const image of images) {
904 startAttachmentUpload({ environmentId: firstEnvironment, image });
905 }
906 const otherEnvironmentImage = makeImage("image-other");
907 startAttachmentUpload({ environmentId: secondEnvironment, image: otherEnvironmentImage });
908 await Promise.resolve();
909
910 expect(TestXmlHttpRequest.requests).toHaveLength(4);
911 const otherRequest = TestXmlHttpRequest.requests.find((request) =>
912 request.url?.includes("environment-2"),
913 );
914 expect(otherRequest).toBeDefined();
915
916 for (const request of TestXmlHttpRequest.requests) {
917 request.complete();
918 }
919 await Promise.all([
920 ...images.slice(0, 3).map((image) => awaitAttachmentUploads([image.id])),
921 awaitAttachmentUploads([otherEnvironmentImage.id]),
922 ]);
923 await Promise.resolve();
924 TestXmlHttpRequest.requests[4]!.complete();
925 await awaitAttachmentUploads([images[3]!.id]);
926 });
927
928 it("checks the HTTP origin on transport error and auto-retries after route failover, not on HTTP status rejection", async () => {
929 const image = makeImage("image-stale-dns");
930 const statusImage = makeImage("image-http-500");
931
932 startAttachmentUpload({ environmentId: firstEnvironment, image: statusImage });
933 await Promise.resolve();
934 const statusSettled = awaitAttachmentUploads([statusImage.id]);
935 TestXmlHttpRequest.requests[0]!.complete(500);
936 await statusSettled;
937 expect(mocks.runAtomCommand).not.toHaveBeenCalledWith(
938 expect.anything(),
939 mocks.checkHttpOrigin,
940 expect.anything(),
941 expect.anything(),
942 );
943 releaseAttachmentUpload(statusImage.id);
944
945 startAttachmentUpload({ environmentId: firstEnvironment, image });
946 await Promise.resolve();
947 const failedSettled = awaitAttachmentUploads([image.id]);
948 TestXmlHttpRequest.requests[1]!.fail();
949 await failedSettled;
950
951 expect(readAttachmentUpload(image.id)).toMatchObject({
952 status: "failed",
953 environmentId: firstEnvironment,
954 });
955 expect(mocks.runAtomCommand).toHaveBeenCalledWith(
956 expect.anything(),
957 mocks.checkHttpOrigin,
958 firstEnvironment,
959 { reportFailure: false, reportDefect: false },
960 );
961
962 // Simulates supervisor switching to a working route (connected -> connecting -> connected).
963 mocks.readPreparedConnection.mockReturnValue({ httpBaseUrl: "https://renamed.test/" });
964 setConnected(firstEnvironment, false);
965 setConnected(firstEnvironment, true);
966 await vi.waitFor(() => expect(TestXmlHttpRequest.requests).toHaveLength(3));
967 expect(TestXmlHttpRequest.requests[2]!.url).toContain("https://renamed.test/");
968 const retriedSettled = awaitAttachmentUploads([image.id]);
969 TestXmlHttpRequest.requests[2]!.complete();
970 await retriedSettled;
971 expect(readAttachmentUpload(image.id)).toMatchObject({
972 status: "ready",
973 environmentId: firstEnvironment,
974 });
975 });
976});