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