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