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

attachmentUploadQueue.test.ts

962 lines31.2 KB

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