The best way to control Claude Code, Codex and more from any computer or phone

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