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

attachmentUploadQueue.test.ts

844 lines27.0 KB

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 }
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 };
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 };
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 = {
242 ...makeFile("report"),
243 source: { _tag: "pasted-text" as const },
244 };
245 startAttachmentUpload({ environmentId: firstEnvironment, image: file });
246 await Promise.resolve();
247​
248 expect(mocks.runAtomCommand).toHaveBeenCalledWith(
249 expect.anything(),
250 mocks.createUploadUrl,
251 {
252 environmentId: firstEnvironment,
253 input: {
254 type: "file",
255 name: "report.pdf",
256 mimeType: "application/pdf",
257 sizeBytes: 3,
258 },
259 },
260 expect.anything(),
261 );
262​
263 const settled = awaitAttachmentUploads([file.id]);
264 TestXmlHttpRequest.requests[0]!.complete();
265 await settled;
266​
267 expect(getUploadedAttachments({ environmentId: firstEnvironment, images: [file] })).toEqual([
268 {
269 type: "file",
270 id: "pending-environment-1-report.pdf",
271 name: "report.pdf",
272 mimeType: "application/pdf",
273 sizeBytes: 3,
274 source: { _tag: "pasted-text" },
275 },
276 ]);
277 });
278​
279 it("uses the fallback MIME type for both the upload claim and request header", async () => {
280 const bytes = new File([new Uint8Array([1, 2, 3])], "unknown.bin");
281 const file: ComposerFileAttachment = {
282 type: "file",
283 id: "file-without-browser-mime",
284 name: bytes.name,
285 mimeType: "application/octet-stream",
286 sizeBytes: bytes.size,
287 file: bytes,
288 };
289​
290 startAttachmentUpload({ environmentId: firstEnvironment, image: file });
291 await Promise.resolve();
292​
293 expect(mocks.runAtomCommand).toHaveBeenCalledWith(
294 expect.anything(),
295 mocks.createUploadUrl,
296 {
297 environmentId: firstEnvironment,
298 input: {
299 type: "file",
300 name: "unknown.bin",
301 mimeType: "application/octet-stream",
302 sizeBytes: 3,
303 },
304 },
305 expect.anything(),
306 );
307 expect(TestXmlHttpRequest.requests[0]?.headers.get("Content-Type")).toBe(
308 "application/octet-stream",
309 );
310​
311 const settled = awaitAttachmentUploads([file.id]);
312 TestXmlHttpRequest.requests[0]!.complete();
313 await settled;
314 });
315​
316 it("persists a background completion's ids to the draft with no composer mounted", async () => {
317 const draftId = DraftId.make("draft-background-upload");
318 const file = makeFile("background");
319 const draftStore = useComposerDraftStore.getState();
320 draftStore.addFiles(draftId, [file]);
321 try {
322 startAttachmentUpload({
323 environmentId: firstEnvironment,
324 image: file,
325 draftTarget: draftId,
326 });
327 await Promise.resolve();
328​
329 // No composer effect is subscribed; only the queue can stamp the draft.
330 const settled = awaitAttachmentUploads([file.id]);
331 TestXmlHttpRequest.requests[0]!.complete();
332 await settled;
333​
334 expect(useComposerDraftStore.getState().getComposerDraft(draftId)?.files).toMatchObject([
335 {
336 id: file.id,
337 uploadedAttachmentId: "pending-environment-1-background.pdf",
338 uploadEnvironmentId: firstEnvironment,
339 },
340 ]);
341 } finally {
342 useComposerDraftStore.getState().clearComposerContent(draftId);
343 }
344 });
345​
346 it("persists a retried question upload without a mounted composer", async () => {
347 const draftId = DraftId.make("question-retry-upload");
348 const file = makeFile("question-retry");
349 const store = useComposerDraftStore.getState();
350 store.addFiles(draftId, [file]);
351 try {
352 startAttachmentUpload({ environmentId: firstEnvironment, image: file, draftTarget: draftId });
353 await Promise.resolve();
354 let settled = awaitAttachmentUploads([file.id]);
355 TestXmlHttpRequest.requests[0]!.complete(500);
356 await settled;
357 expect(store.getComposerDraft(draftId)?.files[0]?.uploadedAttachmentId).toBeUndefined();
358 retryAttachmentUpload({ environmentId: firstEnvironment, image: file, draftTarget: draftId });
359 await Promise.resolve();
360 settled = awaitAttachmentUploads([file.id]);
361 TestXmlHttpRequest.requests[1]!.complete();
362 await settled;
363 expect(store.getComposerDraft(draftId)?.files[0]).toMatchObject({
364 uploadedAttachmentId: "pending-environment-1-question-retry.pdf",
365 uploadEnvironmentId: firstEnvironment,
366 });
367 } finally {
368 store.clearComposerContent(draftId);
369 }
370 });
371​
372 it("verifies an uploaded file reference before restoring it", async () => {
373 const file: ComposerFileAttachment = {
374 ...makeFile("restored"),
375 file: null,
376 uploadedAttachmentId: "pending-restored-pdf",
377 uploadEnvironmentId: firstEnvironment,
378 };
379​
380 startAttachmentUpload({ environmentId: firstEnvironment, image: file });
381 await awaitAttachmentUploads([file.id]);
382​
383 expect(readAttachmentUpload(file.id)).toEqual({
384 status: "ready",
385 environmentId: firstEnvironment,
386 attachmentId: "pending-restored-pdf",
387 });
388 expect(mocks.createAssetUrl).toHaveBeenCalledWith({
389 environmentId: firstEnvironment,
390 input: { resource: { _tag: "attachment", attachmentId: "pending-restored-pdf" } },
391 });
392 expect(TestXmlHttpRequest.requests).toHaveLength(0);
393 });
394​
395 it("turns an expired persisted file into a marker that a re-pick can replace", async () => {
396 const draftId = DraftId.make("draft-expired-upload");
397 const file: ComposerFileAttachment = {
398 ...makeFile("expired"),
399 file: null,
400 uploadedAttachmentId: "pending-expired-pdf",
401 uploadEnvironmentId: firstEnvironment,
402 };
403 mocks.executeAtomQuery.mockResolvedValueOnce({
404 _tag: "Failure",
405 error: { _tag: "AssetAttachmentNotFoundError" },
406 });
407 useComposerDraftStore.getState().addFiles(draftId, [file]);
408​
409 try {
410 startAttachmentUpload({
411 environmentId: firstEnvironment,
412 image: file,
413 draftTarget: draftId,
414 });
415 await awaitAttachmentUploads([file.id]);
416​
417 const marker = useComposerDraftStore.getState().getComposerDraft(draftId)?.files[0];
418 expect(readAttachmentUpload(file.id)).toBeUndefined();
419 expect(marker?.uploadedAttachmentId).toBeUndefined();
420 expect(marker?.uploadEnvironmentId).toBeUndefined();
421 expect(marker && composerFileNeedsReattach(marker)).toBe(true);
422​
423 const replacementBytes = new File([new Uint8Array([1, 2, 3])], file.name, {
424 type: file.mimeType,
425 });
426 const replacement: ComposerFileAttachment = {
427 type: "file",
428 id: "expired-repicked",
429 name: file.name,
430 mimeType: file.mimeType,
431 sizeBytes: file.sizeBytes,
432 file: replacementBytes,
433 };
434 useComposerDraftStore.getState().addFiles(draftId, [replacement]);
435 expect(useComposerDraftStore.getState().getComposerDraft(draftId)?.files).toMatchObject([
436 { id: replacement.id, file: replacementBytes },
437 ]);
438​
439 startAttachmentUpload({
440 environmentId: firstEnvironment,
441 image: replacement,
442 draftTarget: draftId,
443 });
444 await Promise.resolve();
445 const settled = awaitAttachmentUploads([replacement.id]);
446 TestXmlHttpRequest.requests[0]!.complete();
447 await settled;
448​
449 expect(useComposerDraftStore.getState().getComposerDraft(draftId)?.files).toMatchObject([
450 {
451 id: replacement.id,
452 uploadedAttachmentId: "pending-environment-1-expired.pdf",
453 uploadEnvironmentId: firstEnvironment,
454 },
455 ]);
456 const removeCalls = mocks.runAtomCommand.mock.calls.filter(
457 ([, command]) => command === mocks.removeUpload,
458 );
459 expect(removeCalls).toEqual([]);
460 } finally {
461 useComposerDraftStore.getState().clearComposerContent(draftId);
462 }
463 });
464​
465 it("uploads the original file again when its persisted server upload expired", async () => {
466 const file: ComposerFileAttachment = {
467 ...makeFile("recoverable"),
468 uploadedAttachmentId: "pending-expired-pdf",
469 uploadEnvironmentId: firstEnvironment,
470 };
471 mocks.executeAtomQuery.mockResolvedValueOnce({
472 _tag: "Failure",
473 error: { _tag: "AssetAttachmentNotFoundError" },
474 });
475​
476 startAttachmentUpload({ environmentId: firstEnvironment, image: file });
477 // The verify-then-reupload path crosses several awaits before the
478 // transfer starts; drain microtasks until the XHR exists.
479 for (let hop = 0; hop < 20 && TestXmlHttpRequest.requests.length === 0; hop += 1) {
480 await Promise.resolve();
481 }
482​
483 const settled = awaitAttachmentUploads([file.id]);
484 TestXmlHttpRequest.requests[0]!.complete();
485 await settled;
486​
487 expect(readAttachmentUpload(file.id)).toMatchObject({
488 status: "ready",
489 attachmentId: "pending-environment-1-recoverable.pdf",
490 });
491 });
492​
493 it("removes a persisted upload when its draft is discarded during verification", async () => {
494 const file: ComposerFileAttachment = {
495 ...makeFile("checking"),
496 file: null,
497 uploadedAttachmentId: "pending-checking-pdf",
498 uploadEnvironmentId: firstEnvironment,
499 };
500 let resolveVerification: (result: {
501 readonly _tag: "Success";
502 readonly value: object;
503 }) => void = () => {};
504 mocks.executeAtomQuery.mockReturnValueOnce(
505 new Promise((resolve) => {
506 resolveVerification = resolve;
507 }),
508 );
509​
510 startAttachmentUpload({ environmentId: firstEnvironment, image: file });
511 releaseDraftAttachment(file);
512 resolveVerification({ _tag: "Success", value: {} });
513​
514 expect(mocks.runAtomCommand).toHaveBeenCalledWith(
515 expect.anything(),
516 mocks.removeUpload,
517 {
518 environmentId: firstEnvironment,
519 input: { attachmentId: "pending-checking-pdf" },
520 },
521 expect.anything(),
522 );
523 });
524​
525 it("keeps the persisted upload when retrying after a transient verification failure", async () => {
526 const draftId = DraftId.make("draft-transient-verification");
527 const file: ComposerFileAttachment = {
528 ...makeFile("flaky"),
529 file: null,
530 uploadedAttachmentId: "pending-flaky-pdf",
531 uploadEnvironmentId: firstEnvironment,
532 };
533 mocks.executeAtomQuery.mockResolvedValueOnce({
534 _tag: "Failure",
535 error: new Error("socket closed"),
536 });
537 useComposerDraftStore.getState().addFiles(draftId, [file]);
538​
539 try {
540 startAttachmentUpload({
541 environmentId: firstEnvironment,
542 image: file,
543 draftTarget: draftId,
544 });
545 await awaitAttachmentUploads([file.id]);
546 expect(readAttachmentUpload(file.id)).toMatchObject({
547 status: "failed",
548 reason: "Uploaded file could not be verified. Retry when the server reconnects.",
549 });
550 expect(useComposerDraftStore.getState().getComposerDraft(draftId)?.files).toMatchObject([
551 {
552 uploadedAttachmentId: "pending-flaky-pdf",
553 uploadEnvironmentId: firstEnvironment,
554 },
555 ]);
556​
557 // The persisted id is the only server copy of the bytes (`file` is null
558 // after a reload), so the retry must verify it again, not delete it.
559 retryAttachmentUpload({
560 environmentId: firstEnvironment,
561 image: file,
562 draftTarget: draftId,
563 });
564 await awaitAttachmentUploads([file.id]);
565​
566 expect(readAttachmentUpload(file.id)).toEqual({
567 status: "ready",
568 environmentId: firstEnvironment,
569 attachmentId: "pending-flaky-pdf",
570 });
571 expect(useComposerDraftStore.getState().getComposerDraft(draftId)?.files).toMatchObject([
572 {
573 uploadedAttachmentId: "pending-flaky-pdf",
574 uploadEnvironmentId: firstEnvironment,
575 },
576 ]);
577 const removeCalls = mocks.runAtomCommand.mock.calls.filter(
578 ([, command]) => command === mocks.removeUpload,
579 );
580 expect(removeCalls).toEqual([]);
581 } finally {
582 useComposerDraftStore.getState().clearComposerContent(draftId);
583 }
584 });
585​
586 it("keeps the persisted upload when an environment switch cancels its verification", async () => {
587 const file: ComposerFileAttachment = {
588 ...makeFile("moving"),
589 file: null,
590 uploadedAttachmentId: "pending-moving-pdf",
591 uploadEnvironmentId: firstEnvironment,
592 };
593 let resolveVerification: (result: {
594 readonly _tag: "Success";
595 readonly value: object;
596 }) => void = () => {};
597 mocks.executeAtomQuery.mockReturnValueOnce(
598 new Promise((resolve) => {
599 resolveVerification = resolve;
600 }),
601 );
602​
603 startAttachmentUpload({ environmentId: firstEnvironment, image: file });
604 // Switching environments cancels the in-flight verification. The draft
605 // still references the upload in the first environment, so the cancel
606 // must not delete it.
607 startAttachmentUpload({ environmentId: secondEnvironment, image: file });
608 resolveVerification({ _tag: "Success", value: {} });
609 await awaitAttachmentUploads([file.id]);
610​
611 const persistedRemoveCalls = mocks.runAtomCommand.mock.calls.filter(
612 ([, command, target]) =>
613 command === mocks.removeUpload &&
614 (target as { readonly input: { readonly attachmentId: string } }).input.attachmentId ===
615 "pending-moving-pdf",
616 );
617 expect(persistedRemoveCalls).toEqual([]);
618 });
619​
620 it("cancels persisted-upload verification when a stash discards its file", async () => {
621 const file: ComposerFileAttachment = {
622 ...makeFile("stashed-checking"),
623 file: null,
624 uploadedAttachmentId: "pending-stashed-checking-pdf",
625 uploadEnvironmentId: firstEnvironment,
626 };
627 let resolveVerification: (result: {
628 readonly _tag: "Success";
629 readonly value: object;
630 }) => void = () => {};
631 mocks.executeAtomQuery.mockReturnValueOnce(
632 new Promise((resolve) => {
633 resolveVerification = resolve;
634 }),
635 );
636​
637 startAttachmentUpload({ environmentId: firstEnvironment, image: file });
638 releasePersistedAttachmentUpload({
639 id: file.id,
640 environmentId: firstEnvironment,
641 attachmentId: "pending-stashed-checking-pdf",
642 });
643 resolveVerification({ _tag: "Success", value: {} });
644 await Promise.resolve();
645​
646 expect(readAttachmentUpload(file.id)).toBeUndefined();
647 expect(mocks.runAtomCommand).toHaveBeenCalledWith(
648 expect.anything(),
649 mocks.removeUpload,
650 {
651 environmentId: firstEnvironment,
652 input: { attachmentId: "pending-stashed-checking-pdf" },
653 },
654 expect.anything(),
655 );
656 });
657​
658 it("releases the persisted server upload when a hydrated draft is discarded after a reload", () => {
659 // After a reload the in-memory queue is empty; the draft file only carries
660 // its persisted attachment id. Discarding it must still delete the
661 // server-side pending upload.
662 const file: ComposerFileAttachment = {
663 ...makeFile("hydrated"),
664 file: null,
665 uploadedAttachmentId: "pending-hydrated-pdf",
666 uploadEnvironmentId: firstEnvironment,
667 };
668​
669 releaseDraftAttachment(file);
670​
671 expect(mocks.runAtomCommand).toHaveBeenCalledWith(
672 expect.anything(),
673 mocks.removeUpload,
674 {
675 environmentId: firstEnvironment,
676 input: { attachmentId: "pending-hydrated-pdf" },
677 },
678 expect.anything(),
679 );
680 });
681​
682 it("routes a live persisted upload through the queue release exactly once", async () => {
683 const file: ComposerFileAttachment = {
684 ...makeFile("live"),
685 file: null,
686 uploadedAttachmentId: "pending-live-pdf",
687 uploadEnvironmentId: firstEnvironment,
688 };
689 startAttachmentUpload({ environmentId: firstEnvironment, image: file });
690 await awaitAttachmentUploads([file.id]);
691 expect(readAttachmentUpload(file.id)).toMatchObject({ status: "ready" });
692​
693 releaseDraftAttachment(file);
694​
695 expect(readAttachmentUpload(file.id)).toBeUndefined();
696 const removeCalls = mocks.runAtomCommand.mock.calls.filter(
697 ([, command]) => command === mocks.removeUpload,
698 );
699 expect(removeCalls).toEqual([
700 [
701 expect.anything(),
702 mocks.removeUpload,
703 {
704 environmentId: firstEnvironment,
705 input: { attachmentId: "pending-live-pdf" },
706 },
707 expect.anything(),
708 ],
709 ]);
710 });
711​
712 it("deletes a persisted server upload even when browser upload state is gone", () => {
713 releasePersistedAttachmentUpload({
714 id: "stashed-report",
715 environmentId: firstEnvironment,
716 attachmentId: "pending-00000000-0000-4000-8000-000000000001-pdf",
717 });
718​
719 expect(mocks.runAtomCommand).toHaveBeenCalledWith(
720 expect.anything(),
721 mocks.removeUpload,
722 {
723 environmentId: firstEnvironment,
724 input: { attachmentId: "pending-00000000-0000-4000-8000-000000000001-pdf" },
725 },
726 expect.anything(),
727 );
728 });
729​
730 it("retries rejected uploads", async () => {
731 const image = makeImage("image-retry");
732 startAttachmentUpload({ environmentId: firstEnvironment, image });
733 await Promise.resolve();
734​
735 let settled = awaitAttachmentUploads([image.id]);
736 TestXmlHttpRequest.requests[0]!.complete(500);
737 await settled;
738 expect(readAttachmentUpload(image.id)).toMatchObject({
739 status: "failed",
740 reason: "Upload rejected (500)",
741 });
742​
743 retryAttachmentUpload({ environmentId: firstEnvironment, image });
744 await Promise.resolve();
745 settled = awaitAttachmentUploads([image.id]);
746 TestXmlHttpRequest.requests[1]!.complete();
747 await settled;
748​
749 expect(readAttachmentUpload(image.id)).toMatchObject({ status: "ready" });
750 });
751​
752 it("releases an upload URL that resolves after its image was removed", async () => {
753 const image = makeImage("image-cancelled");
754 const minted = {
755 _tag: "Success" as const,
756 value: {
757 attachmentId: "pending-environment-1-image-cancelled.png",
758 relativeUrl: "/api/attachments/upload/cancelled",
759 expiresAt: 1,
760 },
761 };
762 let resolveMint: (result: typeof minted) => void = () => {};
763 const pendingMint = new Promise<typeof minted>((resolve) => {
764 resolveMint = resolve;
765 });
766 let resolveDelete: () => void = () => {};
767 const deleted = new Promise<void>((resolve) => {
768 resolveDelete = resolve;
769 });
770 mocks.runAtomCommand.mockImplementation((_registry: unknown, command: unknown) => {
771 if (command === mocks.createUploadUrl) {
772 return pendingMint;
773 }
774 resolveDelete();
775 return Promise.resolve({ _tag: "Success", value: undefined });
776 });
777​
778 startAttachmentUpload({ environmentId: firstEnvironment, image });
779 releaseAttachmentUpload(image.id);
780 resolveMint(minted);
781 await deleted;
782​
783 expect(TestXmlHttpRequest.requests).toEqual([]);
784 expect(readAttachmentUpload(image.id)).toBeUndefined();
785 expect(mocks.runAtomCommand).toHaveBeenCalledWith(
786 expect.anything(),
787 mocks.removeUpload,
788 {
789 environmentId: firstEnvironment,
790 input: { attachmentId: minted.value.attachmentId },
791 },
792 expect.anything(),
793 );
794 });
795​
796 it("restores the previous environment after a replacement upload fails", async () => {
797 const image = makeImage("image-move");
798 startAttachmentUpload({ environmentId: firstEnvironment, image });
799 await Promise.resolve();
800 let settled = awaitAttachmentUploads([image.id]);
801 TestXmlHttpRequest.requests[0]!.complete();
802 await settled;
803​
804 startAttachmentUpload({ environmentId: secondEnvironment, image });
805 await Promise.resolve();
806 settled = awaitAttachmentUploads([image.id]);
807 TestXmlHttpRequest.requests[1]!.complete(500);
808 await settled;
809​
810 startAttachmentUpload({ environmentId: firstEnvironment, image });
811 expect(readAttachmentUpload(image.id)).toMatchObject({
812 status: "ready",
813 environmentId: firstEnvironment,
814 attachmentId: "pending-environment-1-image-move.png",
815 });
816 });
817​
818 it("does not let stalled uploads block another environment", async () => {
819 const images = ["image-a", "image-b", "image-c", "image-d"].map(makeImage);
820 for (const image of images) {
821 startAttachmentUpload({ environmentId: firstEnvironment, image });
822 }
823 const otherEnvironmentImage = makeImage("image-other");
824 startAttachmentUpload({ environmentId: secondEnvironment, image: otherEnvironmentImage });
825 await Promise.resolve();
826​
827 expect(TestXmlHttpRequest.requests).toHaveLength(4);
828 const otherRequest = TestXmlHttpRequest.requests.find((request) =>
829 request.url?.includes("environment-2"),
830 );
831 expect(otherRequest).toBeDefined();
832​
833 for (const request of TestXmlHttpRequest.requests) {
834 request.complete();
835 }
836 await Promise.all([
837 ...images.slice(0, 3).map((image) => awaitAttachmentUploads([image.id])),
838 awaitAttachmentUploads([otherEnvironmentImage.id]),
839 ]);
840 await Promise.resolve();
841 TestXmlHttpRequest.requests[4]!.complete();
842 await awaitAttachmentUploads([images[3]!.id]);
843 });
844});