@devries-cameron20 / t3code-1 / commits / f2c944947d
Fork 0

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

fix(web): recover expired composer uploads before sending (#32910)

Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: Julius Marminge <julius0216@outlook.com>

Adamulek123 committed Nov 15, 2026 at 09:20 UTC f2c944947ddf2b343395049aa4ffb9792b714a04
10 files changed +488 -58
apps/web/src/components/ChatView.browser.test.tsx
+5
@@ -60,6 +60,10 @@ function acceptAttachmentUploads(): Disposable {
60 const mint = answerRpc(WS_METHODS.attachmentsCreateUploadUrl, () =>
61 Effect.succeed({ attachmentId: "upload-1", relativeUrl: "/upload", expiresAt: 0 }),
62 );
63 + // Sending verifies each ready upload still exists on the server.
64 + const verify = answerRpc(WS_METHODS.assetsCreateUrl, () =>
65 + Effect.succeed({ relativeUrl: "/upload-1", expiresAt: 0 }),
66 + );
67 const status = vi.spyOn(XMLHttpRequest.prototype, "status", "get").mockReturnValue(200);
68 const send = vi.spyOn(XMLHttpRequest.prototype, "send").mockImplementation(function (
69 this: XMLHttpRequest,
@@ -71,6 +75,7 @@ function acceptAttachmentUploads(): Disposable {
75 send.mockRestore();
76 status.mockRestore();
77 mint[Symbol.dispose]();
78 + verify[Symbol.dispose]();
79 },
80 };
81 }
apps/web/src/components/chat/chatViewSend.ts
+12 -3
@@ -16,7 +16,10 @@ import {
16 type AtomCommandResult,
17 } from "@t3tools/client-runtime/state/runtime";
18 import { readLocalApi } from "../../localApi";
19 -import { awaitAttachmentUploads, getUploadedAttachments } from "../../lib/attachmentUploadQueue";
19 +import {
20 + getUploadedAttachments,
21 + refreshExpiredAttachmentUploads,
22 +} from "../../lib/attachmentUploadQueue";
23 import { findRevertCheckpoint } from "../../session-logic";
24 import { type ChatMessage } from "../../types";
25 import { randomUUID } from "~/lib/utils";
@@ -25,6 +28,7 @@ import { newThreadId } from "~/lib/utils";
28 import {
29 type ComposerFileAttachment,
30 type ComposerImageAttachment,
31 + type ComposerThreadTarget,
32 useComposerDraftStore,
33 DraftId,
34 } from "../../composerDraftStore";
@@ -328,12 +332,17 @@ export function prepareTurnAttachments(input: {
332 readonly environmentId: EnvironmentId;
333 readonly attachments: ReadonlyArray<ComposerImageAttachment | ComposerFileAttachment>;
334 readonly usesAttachmentUploads: boolean;
335 + readonly draftTarget: ComposerThreadTarget;
336 }) {
332 - const { environmentId, usesAttachmentUploads } = input;
337 + const { environmentId, usesAttachmentUploads, draftTarget } = input;
338 return Promise.all(
339 input.attachments.map(async (attachment) => {
340 if (usesAttachmentUploads) {
336 - await awaitAttachmentUploads([attachment.id]);
341 + await refreshExpiredAttachmentUploads({
342 + environmentId,
343 + images: [attachment],
344 + draftTarget,
345 + });
346 const uploaded = getUploadedAttachments({ environmentId, images: [attachment] })?.[0];
347 if (!uploaded) {
348 throw new Error(`Attachment '${attachment.name}' failed to upload.`);
apps/web/src/components/chat/composerSend.logic.test.ts
+42
@@ -1,11 +1,13 @@
1 import { EnvironmentId, ThreadId } from "@t3tools/contracts";
2 import { scopeThreadRef } from "@t3tools/client-runtime/environment";
3 import { describe, expect, it } from "vite-plus/test";
4 +import type { ComposerThreadDraftState } from "../../composerDraftStore";
5 import { formatInlineContextReference } from "../../lib/composerContextReferences";
6 import { threadContextReference } from "../../lib/composerContextRecords";
7 import { threadContextRecord } from "@t3tools/shared/composerContextReferences";
8 import {
9 approvalRedirectNotice,
10 + composerDraftContentChanged,
11 loadBalancingSendWarning,
12 multipleModelSendBlock,
13 referencedThreadContexts,
@@ -16,6 +18,46 @@ const remote = EnvironmentId.make("remote");
18 const localThread = threadContextRecord(scopeThreadRef(local, ThreadId.make("a")), "Local");
19 const remoteThread = threadContextRecord(scopeThreadRef(remote, ThreadId.make("b")), "Remote");
20
21 +it("detects draft edits during upload preparation without treating upload metadata as an edit", () => {
22 + const draft: ComposerThreadDraftState = {
23 + prompt: "before",
24 + images: [],
25 + files: [
26 + {
27 + type: "file",
28 + id: "file",
29 + name: "a.pdf",
30 + mimeType: "application/pdf",
31 + sizeBytes: 1,
32 + file: null,
33 + },
34 + ],
35 + nonPersistedImageIds: [],
36 + persistedAttachments: [],
37 + terminalContexts: [],
38 + previewAnnotations: [],
39 + reviewComments: [],
40 + threadContexts: [],
41 + environmentContexts: [],
42 + replyTo: null,
43 + modelSelectionByProvider: {},
44 + activeProvider: null,
45 + runtimeMode: null,
46 + interactionMode: null,
47 + };
48 + expect(
49 + composerDraftContentChanged(draft, {
50 + ...draft,
51 + files: [{ ...draft.files[0]!, uploadedAttachmentId: "upload", uploadEnvironmentId: local }],
52 + }),
53 + ).toBe(false);
54 + expect(composerDraftContentChanged(draft, { ...draft, prompt: "after" })).toBe(true);
55 + expect(composerDraftContentChanged(draft, { ...draft, files: [] })).toBe(true);
56 + expect(composerDraftContentChanged(draft, { ...draft, threadContexts: [localThread] })).toBe(
57 + true,
58 + );
59 +});
60 +
61 describe("referencedThreadContexts", () => {
62 it("keeps only the attached threads the prompt still links", () => {
63 const prompt = `see ${formatInlineContextReference(threadContextReference(remoteThread))}`;
apps/web/src/components/chat/composerSend.logic.ts
+23
@@ -1,5 +1,28 @@
1 import type { EnvironmentId, ThreadContextRecord } from "@t3tools/contracts";
2 import { collectInlineContextIds } from "../../lib/composerContextReferences";
3 +import type { ComposerThreadDraftState } from "../../composerDraftStore";
4 +
5 +/** Compare immutable user content without copying image bytes or upload metadata. */
6 +export function composerDraftContentChanged(
7 + before: ComposerThreadDraftState | null,
8 + after: ComposerThreadDraftState | null,
9 +): boolean {
10 + if (before === after) return false;
11 + if (!before || !after) return true;
12 + const sameIds = (left: ReadonlyArray<{ id: string }>, right: ReadonlyArray<{ id: string }>) =>
13 + left.length === right.length && left.every((item, index) => item.id === right[index]?.id);
14 + return (
15 + before.prompt !== after.prompt ||
16 + !sameIds(before.images, after.images) ||
17 + !sameIds(before.files, after.files) ||
18 + before.terminalContexts !== after.terminalContexts ||
19 + before.previewAnnotations !== after.previewAnnotations ||
20 + before.reviewComments !== after.reviewComments ||
21 + before.threadContexts !== after.threadContexts ||
22 + before.environmentContexts !== after.environmentContexts ||
23 + before.replyTo !== after.replyTo
24 + );
25 +}
26
27 /** Attached threads the prompt still links to; replacing linked text leaves stale records. */
28 export function referencedThreadContexts(draft: {
apps/web/src/components/chat/useComposerSend.ts
+39 -2
@@ -99,6 +99,7 @@ import { useStableCallback } from "../../hooks/useStableCallback";
99 import { environmentPresentations } from "../../state/presentation";
100 import {
101 approvalRedirectNotice,
102 + composerDraftContentChanged,
103 loadBalancingSendWarning,
104 multipleModelSendBlock,
105 referencedThreadContexts,
@@ -106,8 +107,8 @@ import {
107 import { useMultipleModelSend } from "./useMultipleModelSend";
108 import { type ComposerDispatchMode } from "@t3tools/client-runtime/state/composer-dispatch";
109 import {
109 - awaitAttachmentUploads,
110 getUploadedAttachments,
111 + refreshExpiredAttachmentUploads,
112 readAttachmentUpload,
113 releaseDraftAttachments,
114 retryAttachmentUpload,
@@ -872,6 +873,14 @@ export function useComposerSend(input: ComposerSendInput) {
873 multipleTargets.push(resolved);
874 }
875
876 + const draftBeforePreparation = useComposerDraftStore
877 + .getState()
878 + .getComposerDraft(composerDraftTarget);
879 + const draftChangedDuringPreparation = () => {
880 + if (composerRef.current?.hasPendingAttachments() === true) return true;
881 + const draft = useComposerDraftStore.getState().getComposerDraft(composerDraftTarget);
882 + return composerDraftContentChanged(draftBeforePreparation, draft);
883 + };
884 sendInFlightRef.current = true;
885 const sendGeneration = ++composerSendGenerationRef.current;
886 const attachmentCapabilitiesBeforeUpload = readLiveAttachmentCapabilities();
@@ -919,6 +928,17 @@ export function useComposerSend(input: ComposerSendInput) {
928 }
929
930 const attachmentCapabilitiesBeforeDispatch = readLiveAttachmentCapabilities();
931 + if (draftChangedDuringPreparation()) {
932 + sendInFlightRef.current = false;
933 + setThreadError(
934 + threadIdForSend,
935 + "Draft changed while preparing this message. Review it and send again.",
936 + );
937 + setDockedDraftHeroThreadKey((currentThreadKey) =>
938 + currentThreadKey === activeThreadKey ? null : currentThreadKey,
939 + );
940 + return;
941 + }
942 if (
943 !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) ||
944 attachmentCapabilitiesBeforeDispatch.fileBlockReason !== null
@@ -940,7 +960,22 @@ export function useComposerSend(input: ComposerSendInput) {
960 composerAttachmentsSnapshot.length > 0 &&
961 (sendCtx?.shownPendingApprovalIds.length ?? 0) > 0
962 ) {
943 - await awaitAttachmentUploads(composerAttachmentsSnapshot.map((attachment) => attachment.id));
963 + await refreshExpiredAttachmentUploads({
964 + environmentId,
965 + images: composerAttachmentsSnapshot,
966 + draftTarget: composerDraftTarget,
967 + });
968 + if (draftChangedDuringPreparation()) {
969 + sendInFlightRef.current = false;
970 + setThreadError(
971 + threadIdForSend,
972 + "Draft changed while preparing this message. Review it and send again.",
973 + );
974 + setDockedDraftHeroThreadKey((currentThreadKey) =>
975 + currentThreadKey === activeThreadKey ? null : currentThreadKey,
976 + );
977 + return;
978 + }
979 const uploadBlockReason =
980 readLiveAttachmentCapabilities().fileBlockReason ??
981 (getUploadedAttachments({ environmentId, images: composerAttachmentsSnapshot }) === null
@@ -1103,6 +1138,7 @@ export function useComposerSend(input: ComposerSendInput) {
1138 environmentId,
1139 attachments: composerAttachmentsSnapshot,
1140 usesAttachmentUploads: turnUsesAttachmentUploads,
1141 + draftTarget: composerDraftTarget,
1142 });
1143 if (multipleModelSelections !== null) {
1144 await sendToMultipleModels({
@@ -1118,6 +1154,7 @@ export function useComposerSend(input: ComposerSendInput) {
1154 readFileBlockReason: () => readLiveAttachmentCapabilities().fileBlockReason,
1155 buildOutgoingMessageContext,
1156 isCurrentSend: () => composerSendGenerationRef.current === sendGeneration,
1157 + draftChangedDuringPreparation,
1158 });
1159 return;
1160 }
apps/web/src/components/chat/useMultipleModelSend.ts
+4
@@ -97,6 +97,7 @@ export function useMultipleModelSend(input: MultipleModelSendInput) {
97 readFileBlockReason,
98 buildOutgoingMessageContext,
99 isCurrentSend,
100 + draftChangedDuringPreparation,
101 }: {
102 readonly threadId: ThreadId;
103 readonly project: EnvironmentProject;
@@ -113,6 +114,7 @@ export function useMultipleModelSend(input: MultipleModelSendInput) {
114 ) => ReturnType<typeof buildMessageContext>;
115 /** False once a newer send from this composer started. */
116 readonly isCurrentSend: () => boolean;
117 + readonly draftChangedDuringPreparation: () => boolean;
118 }) => {
119 const { attachments: attachmentsSnapshot, messageText } = sendSnapshot;
120 const failedSelections: ModelSelection[] = [];
@@ -124,6 +126,8 @@ export function useMultipleModelSend(input: MultipleModelSendInput) {
126 // fails every selection; the draft restore below still runs.
127 const sendResult = await settlePromise(async () => {
128 const attachments = await attachmentsPromise;
129 + if (draftChangedDuringPreparation())
130 + throw new Error("Draft changed while preparing this message. Review it and send again.");
131 const fileBlockReason = readFileBlockReason();
132 if (fileBlockReason !== null) throw new Error(fileBlockReason);
133 const context = buildOutgoingMessageContext(
apps/web/src/components/chat/usePendingThreadRequests.ts
+96 -49
@@ -25,7 +25,12 @@ import {
25 useComposerDraftStore,
26 } from "../../composerDraftStore";
27 import { useStableCallback } from "../../hooks/useStableCallback";
28 -import { getUploadedAttachments, useAttachmentUploadStore } from "../../lib/attachmentUploadQueue";
28 +import {
29 + getUploadedAttachments,
30 + refreshExpiredAttachmentUploads,
31 + useAttachmentUploadStore,
32 +} from "../../lib/attachmentUploadQueue";
33 +import { composerDraftContentChanged } from "./composerSend.logic";
34 import {
35 buildPendingUserInputAnswers,
36 setPendingUserInputCustomAnswer,
@@ -390,60 +395,102 @@ export function usePendingThreadRequests(input: {
395 if (!pendingInput || pendingInput.responseCapability === "not_resumable") return;
396 const responseKey = JSON.stringify([environmentId, activeThreadId, requestId]);
397 if (userInputResponsesInFlight.current.has(responseKey)) return;
393 - const attachmentsByQuestionId = new Map<string, UserInputAttachments[string]>();
394 - const providerAnswers = { ...answers };
395 - const threadDraft = useComposerDraftStore.getState().getComposerDraft(composerDraftTarget);
396 - for (const question of pendingInput.questions) {
397 - const target = questionAttachmentDraftId(
398 - environmentId,
399 - activeThreadId,
400 - requestId,
401 - question.id,
402 - );
403 - if ((useQuestionAttachmentPreparation.getState().counts[target] ?? 0) > 0) return;
404 - const draft = useComposerDraftStore.getState().getComposerDraft(target);
405 - providerAnswers[question.id] = projectPendingUserInputAnswer(
406 - answers[question.id],
407 - answerContextRecords(draft, threadDraft),
408 - );
409 - const attachments = draft ? [...draft.images, ...draft.files] : [];
410 - if (attachments.length === 0) continue;
411 - const uploaded = getUploadedAttachments({ environmentId, images: attachments });
412 - if (!uploaded) {
398 + userInputResponsesInFlight.current.add(responseKey);
399 + const answerDraftKey = userInputDraftKey(environmentId, activeThreadId, requestId);
400 + const answerDraftBeforePreparation = usePendingUserInputAnswers.getState()[answerDraftKey];
401 + setRespondingUserInputRequestIds((existing) =>
402 + existing.includes(requestId) ? existing : [...existing, requestId],
403 + );
404 + const prepareAndRespond = async () => {
405 + const attachmentsByQuestionId = new Map<string, UserInputAttachments[string]>();
406 + const providerAnswers = { ...answers };
407 + const threadDraft = useComposerDraftStore.getState().getComposerDraft(composerDraftTarget);
408 + const questionDrafts = pendingInput.questions.map((question) => {
409 + const target = questionAttachmentDraftId(
410 + environmentId,
411 + activeThreadId,
412 + requestId,
413 + question.id,
414 + );
415 + const draft = useComposerDraftStore.getState().getComposerDraft(target);
416 + return { question, target, draft };
417 + });
418 + for (const { question, target, draft } of questionDrafts) {
419 + if ((useQuestionAttachmentPreparation.getState().counts[target] ?? 0) > 0) return;
420 + providerAnswers[question.id] = projectPendingUserInputAnswer(
421 + answers[question.id],
422 + answerContextRecords(draft, threadDraft),
423 + );
424 + const attachments = draft ? [...draft.images, ...draft.files] : [];
425 + if (attachments.length === 0) continue;
426 + await refreshExpiredAttachmentUploads({
427 + environmentId,
428 + images: attachments,
429 + draftTarget: target,
430 + });
431 + if (
432 + composerDraftContentChanged(
433 + draft,
434 + useComposerDraftStore.getState().getComposerDraft(target),
435 + )
436 + ) {
437 + setThreadError(
438 + activeThreadId,
439 + "Answer changed while preparing attachments. Review it and send again.",
440 + );
441 + return;
442 + }
443 + const uploaded = getUploadedAttachments({ environmentId, images: attachments });
444 + if (!uploaded) {
445 + setThreadError(
446 + activeThreadId,
447 + "Wait for attachments to finish uploading, or remove failed uploads.",
448 + );
449 + return;
450 + }
451 + attachmentsByQuestionId.set(question.id, uploaded as UserInputAttachments[string]);
452 + }
453 + if (
454 + usePendingUserInputAnswers.getState()[answerDraftKey] !== answerDraftBeforePreparation ||
455 + questionDrafts.some(
456 + ({ target, draft }) =>
457 + (useQuestionAttachmentPreparation.getState().counts[target] ?? 0) > 0 ||
458 + composerDraftContentChanged(
459 + draft,
460 + useComposerDraftStore.getState().getComposerDraft(target),
461 + ),
462 + )
463 + ) {
464 setThreadError(
465 activeThreadId,
415 - "Wait for attachments to finish uploading, or remove failed uploads.",
466 + "Answer changed while preparing attachments. Review it and send again.",
467 );
468 return;
469 }
419 - attachmentsByQuestionId.set(question.id, uploaded as UserInputAttachments[string]);
420 - }
421 - userInputResponsesInFlight.current.add(responseKey);
422 -
423 - setRespondingUserInputRequestIds((existing) =>
424 - existing.includes(requestId) ? existing : [...existing, requestId],
425 - );
426 - const result = await respondToThreadUserInput({
427 - environmentId,
428 - input: {
429 - threadId: activeThreadId,
430 - requestId,
431 - answers: providerAnswers,
432 - ...(attachmentsByQuestionId.size > 0
433 - ? { attachmentsByQuestionId: Object.fromEntries(attachmentsByQuestionId) }
434 - : {}),
435 - },
470 + const result = await respondToThreadUserInput({
471 + environmentId,
472 + input: {
473 + threadId: activeThreadId,
474 + requestId,
475 + answers: providerAnswers,
476 + ...(attachmentsByQuestionId.size > 0
477 + ? { attachmentsByQuestionId: Object.fromEntries(attachmentsByQuestionId) }
478 + : {}),
479 + },
480 + });
481 + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
482 + const error = squashAtomCommandFailure(result);
483 + setThreadError(
484 + activeThreadId,
485 + error instanceof Error ? error.message : "Failed to submit user input.",
486 + );
487 + }
488 + return result;
489 + };
490 + return prepareAndRespond().finally(() => {
491 + userInputResponsesInFlight.current.delete(responseKey);
492 + setRespondingUserInputRequestIds((existing) => existing.filter((id) => id !== requestId));
493 });
437 - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
438 - const error = squashAtomCommandFailure(result);
439 - setThreadError(
440 - activeThreadId,
441 - error instanceof Error ? error.message : "Failed to submit user input.",
442 - );
443 - }
444 - userInputResponsesInFlight.current.delete(responseKey);
445 - setRespondingUserInputRequestIds((existing) => existing.filter((id) => id !== requestId));
446 - return result;
494 };
495
496 const onDismissUserInput = async (requestId: RuntimeRequestId) => {
apps/web/src/components/chat/useQueuedRunEdit.ts
+23 -2
@@ -38,6 +38,7 @@ import { useStableCallback } from "../../hooks/useStableCallback";
38 import {
39 awaitAttachmentUploads,
40 getUploadedAttachments,
41 + refreshExpiredAttachmentUploads,
42 releaseDraftAttachments,
43 startAttachmentUpload,
44 } from "../../lib/attachmentUploadQueue";
@@ -60,6 +61,7 @@ import { useAtomCommand } from "../../state/use-atom-command";
61 import { stackedThreadToast, toastManager } from "../ui/toast";
62 import type { ChatComposerHandle } from "./ChatComposer";
63 import { fileAttachmentCapabilityBlockReason } from "./composerAttachmentFiles";
64 +import { composerDraftContentChanged } from "./composerSend.logic";
65 import {
66 discardQueuedEditDraft,
67 prepareQueuedEditAttachments,
@@ -105,6 +107,7 @@ async function submitQueuedRunEdit(input: {
107 readonly editing: EditingQueuedRun;
108 readonly content: QueuedRunEditContent;
109 readonly editQueuedRun: ReturnType<typeof useEditQueuedRunCommand>;
110 + readonly draftChanged: () => boolean;
111 }): Promise<string | null> {
112 const { environmentId, draftTarget, editing, content } = input;
113 const editText = content.prompt.trim();
@@ -124,6 +127,7 @@ async function submitQueuedRunEdit(input: {
127 validateFiles();
128 for (const file of files) startAttachmentUpload({ environmentId, image: file, draftTarget });
129 await awaitAttachmentUploads(files.map((file) => file.id));
130 + await refreshExpiredAttachmentUploads({ environmentId, images: files, draftTarget });
131 validateFiles();
132 const uploaded = getUploadedAttachments({ environmentId, images: files });
133 if (uploaded === null) throw new Error("Retry or remove failed uploads before saving.");
@@ -137,6 +141,8 @@ async function submitQueuedRunEdit(input: {
141 readImage: readFileAsDataUrl,
142 uploadFiles,
143 });
144 + if (input.draftChanged())
145 + return "Draft changed while preparing this message. Review it and save again.";
146 // The edit draft owns thread and machine mentions, so a chip removed while editing is dropped.
147 const keptRecords = (editing.context?.records ?? []).filter(
148 (record) =>
@@ -363,15 +369,29 @@ export function useQueuedRunEdit(input: {
369 // The save's result decides the edit's fate, even if the run starts meanwhile.
370 const finishSave = queuedRunEdits.startSave(editKey);
371 if (finishSave === null) return;
372 + const draftBeforeSave = useComposerDraftStore.getState().getComposerDraft(draftTarget);
373 + const draftChanged = () =>
374 + appAtomRegistry.get(queuedRunEdits.atom)[editKey] !== editing ||
375 + composerDraftContentChanged(
376 + draftBeforeSave,
377 + useComposerDraftStore.getState().getComposerDraft(draftTarget),
378 + );
379 const error = await submitQueuedRunEdit({
380 environmentId,
381 draftTarget,
382 editing,
383 content,
384 editQueuedRun: editQueuedRunCommand,
385 + draftChanged,
386 });
373 - setThreadError(editing.threadId, error);
374 - const current = finishSave(error === null);
387 + const changedAfterSave = error === null && draftChanged();
388 + setThreadError(
389 + editing.threadId,
390 + changedAfterSave
391 + ? "The earlier edit was saved. Review your newer changes and save again."
392 + : error,
393 + );
394 + const current = finishSave(error === null && !changedAfterSave);
395 if (!current) {
396 // A failed save can recover into the thread draft; a newer edit can also retain resources.
397 const drafts = Object.values(useComposerDraftStore.getState().draftsByThreadKey);
@@ -394,6 +414,7 @@ export function useQueuedRunEdit(input: {
414 return;
415 }
416 if (error !== null) return;
417 + if (changedAfterSave) return;
418 releaseDraftAttachments(newAttachments);
419 promptRef.current = "";
420 clearEditDraft(editing.runId);
apps/web/src/lib/attachmentUploadQueue.test.ts
+175
@@ -57,6 +57,7 @@ import {
57 awaitAttachmentUploads,
58 getUploadedAttachments,
59 readAttachmentUpload,
60 + refreshExpiredAttachmentUploads,
61 releaseAttachmentUpload,
62 releaseDraftAttachment,
63 releaseDraftAttachments,
@@ -210,6 +211,180 @@ describe("attachmentUploadQueue", () => {
211 vi.unstubAllGlobals();
212 });
213
214 + it("reuploads an expired image while retaining other ready images", async () => {
215 + const images = [makeImage("first"), makeImage("second")].map((image) => ({
216 + ...image,
217 + name: "image.png",
218 + }));
219 + let minted = 0;
220 + mocks.runAtomCommand.mockImplementation(async (_registry, command) => {
221 + if (command !== mocks.createUploadUrl) return { _tag: "Success", value: undefined };
222 + const attachmentId = `pending-test-${++minted}`;
223 + return {
224 + _tag: "Success",
225 + value: {
226 + attachmentId,
227 + relativeUrl: `/api/attachments/upload/${attachmentId}`,
228 + expiresAt: 1,
229 + },
230 + };
231 + });
232 + for (const image of images) startAttachmentUpload({ environmentId: firstEnvironment, image });
233 + await Promise.resolve();
234 + const initial = awaitAttachmentUploads(images.map((image) => image.id));
235 + TestXmlHttpRequest.requests.forEach((request) => request.complete());
236 + await initial;
237 + mocks.executeAtomQuery.mockImplementation(
238 + async (_registry, target: { input: { resource: { attachmentId: string } } }) =>
239 + target.input.resource.attachmentId === "pending-test-1"
240 + ? { _tag: "Failure", error: { _tag: "AssetAttachmentNotFoundError" } }
241 + : { _tag: "Success", value: {} },
242 + );
243 + const refreshing = refreshExpiredAttachmentUploads({ environmentId: firstEnvironment, images });
244 + await vi.waitFor(() => expect(TestXmlHttpRequest.requests).toHaveLength(3));
245 + TestXmlHttpRequest.requests[2]!.complete();
246 + await refreshing;
247 + expect(
248 + getUploadedAttachments({ environmentId: firstEnvironment, images })?.map((image) => image.id),
249 + ).toEqual(["pending-test-3", "pending-test-2"]);
250 + expect(TestXmlHttpRequest.requests).toHaveLength(3);
251 + });
252 +
253 + it("reuploads local file bytes after its persisted upload is known to be missing", async () => {
254 + const file = {
255 + ...makeFile("expired-saved-file"),
256 + uploadedAttachmentId: "pending-expired",
257 + uploadEnvironmentId: firstEnvironment,
258 + };
259 + useAttachmentUploadStore.setState({
260 + uploadsByImageId: {
261 + [file.id]: {
262 + status: "ready",
263 + environmentId: firstEnvironment,
264 + attachmentId: "pending-expired",
265 + },
266 + },
267 + });
268 + mocks.executeAtomQuery
269 + .mockResolvedValueOnce({
270 + _tag: "Failure",
271 + error: { _tag: "AssetAttachmentNotFoundError" },
272 + })
273 + .mockResolvedValue({ _tag: "Failure", error: new Error("Connection interrupted") });
274 + let uploadStarted!: () => void;
275 + const started = new Promise<void>((resolve) => {
276 + uploadStarted = resolve;
277 + });
278 + const runCommand = mocks.runAtomCommand.getMockImplementation()!;
279 + mocks.runAtomCommand.mockImplementation(async (...args) => {
280 + const result = await runCommand(...args);
281 + if (args[1] === mocks.createUploadUrl) uploadStarted();
282 + return result;
283 + });
284 + const refresh = refreshExpiredAttachmentUploads({
285 + environmentId: firstEnvironment,
286 + images: [file],
287 + });
288 + expect(await Promise.race([started.then(() => "upload"), refresh.then(() => "settled")])).toBe(
289 + "upload",
290 + );
291 + expect(TestXmlHttpRequest.requests).toHaveLength(1);
292 + TestXmlHttpRequest.requests[0]!.complete();
293 + await refresh;
294 + expect(mocks.executeAtomQuery).toHaveBeenCalledTimes(1);
295 + expect(
296 + getUploadedAttachments({ environmentId: firstEnvironment, images: [file] }),
297 + ).toMatchObject([{ id: "pending-environment-1-expired-saved-file.pdf" }]);
298 + });
299 +
300 + it.each([false, true])(
301 + "retains cleanup identity after verification fails (retry: %s)",
302 + async (retry) => {
303 + const image = makeImage("connection-failure");
304 + useAttachmentUploadStore.setState({
305 + uploadsByImageId: {
306 + [image.id]: {
307 + status: "ready",
308 + environmentId: firstEnvironment,
309 + attachmentId: "pending-original",
310 + },
311 + },
312 + });
313 + mocks.executeAtomQuery.mockRejectedValueOnce(new Error("offline"));
314 + await refreshExpiredAttachmentUploads({ environmentId: firstEnvironment, images: [image] });
315 + expect(readAttachmentUpload(image.id)).toMatchObject({ status: "failed" });
316 + expect(
317 + getUploadedAttachments({ environmentId: firstEnvironment, images: [image] }),
318 + ).toBeNull();
319 + expect(TestXmlHttpRequest.requests).toHaveLength(0);
320 + if (retry) retryAttachmentUpload({ environmentId: firstEnvironment, image });
321 + releaseAttachmentUpload(image.id);
322 + expect(readAttachmentUpload(image.id)).toBeUndefined();
323 + expect(mocks.runAtomCommand).toHaveBeenCalledExactlyOnceWith(
324 + expect.anything(),
325 + mocks.removeUpload,
326 + { environmentId: firstEnvironment, input: { attachmentId: "pending-original" } },
327 + expect.anything(),
328 + );
329 + },
330 + );
331 +
332 + it("reuploads local bytes for a connection without read permission", async () => {
333 + const image = makeImage("operate-only");
334 + useAttachmentUploadStore.setState({
335 + uploadsByImageId: {
336 + [image.id]: {
337 + status: "ready",
338 + environmentId: firstEnvironment,
339 + attachmentId: "pending-original",
340 + },
341 + },
342 + });
343 + mocks.readEnvironmentScope.mockImplementation(
344 + (_environmentId, scope) => scope !== "orchestration:read",
345 + );
346 + const refresh = refreshExpiredAttachmentUploads({
347 + environmentId: firstEnvironment,
348 + images: [image],
349 + });
350 + await vi.waitFor(() => expect(TestXmlHttpRequest.requests).toHaveLength(1));
351 + TestXmlHttpRequest.requests[0]!.complete();
352 + await refresh;
353 + expect(readAttachmentUpload(image.id)).toMatchObject({
354 + status: "ready",
355 + attachmentId: "pending-environment-1-operate-only.png",
356 + });
357 + expect(mocks.executeAtomQuery).not.toHaveBeenCalled();
358 + });
359 +
360 + it("does not resurrect an image removed while its upload is being checked", async () => {
361 + const image = makeImage("removed-during-verification");
362 + useAttachmentUploadStore.setState({
363 + uploadsByImageId: {
364 + [image.id]: {
365 + status: "ready",
366 + environmentId: firstEnvironment,
367 + attachmentId: "pending-original",
368 + },
369 + },
370 + });
371 + let finish!: (value: unknown) => void;
372 + mocks.executeAtomQuery.mockReturnValueOnce(
373 + new Promise((resolve) => {
374 + finish = resolve;
375 + }),
376 + );
377 + const refresh = refreshExpiredAttachmentUploads({
378 + environmentId: firstEnvironment,
379 + images: [image],
380 + });
381 + releaseAttachmentUpload(image.id);
382 + finish({ _tag: "Failure", error: { _tag: "AssetAttachmentNotFoundError" } });
383 + await refresh;
384 + expect(readAttachmentUpload(image.id)).toBeUndefined();
385 + expect(TestXmlHttpRequest.requests).toHaveLength(0);
386 + });
387 +
388 it("keeps an attachment local until its own environment grants write access", async () => {
389 const image = makeImage("permission-gain");
390 mocks.readEnvironmentScope.mockImplementation(
apps/web/src/lib/attachmentUploadQueue.ts
+69 -2
@@ -1,5 +1,6 @@
1 import {
2 AuthOrchestrationOperateScope,
3 + AuthOrchestrationReadScope,
4 PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES,
5 type ChatAttachment,
6 type EnvironmentId,
@@ -395,6 +396,7 @@ export function startAttachmentUpload(input: {
396 readonly environmentId: EnvironmentId;
397 readonly image: ComposerImageAttachment | ComposerFileAttachment;
398 readonly draftTarget?: ComposerThreadTarget;
399 + readonly force?: boolean;
400 }): void {
401 if (!readEnvironmentScope(input.environmentId, AuthOrchestrationOperateScope)) return;
402 const existingJob = jobsByImageId.get(input.image.id);
@@ -403,7 +405,11 @@ export function startAttachmentUpload(input: {
405 }
406
407 const existing = readAttachmentUpload(input.image.id);
406 - if (existing?.status === "ready" && existing.environmentId === input.environmentId) {
408 + if (
409 + !input.force &&
410 + existing?.status === "ready" &&
411 + existing.environmentId === input.environmentId
412 + ) {
413 // A file restored into a draft after its upload finished (stash, failed send) missed the
414 // completion stamp; stamping here keeps it from re-uploading after a reload.
415 stampDraftFileUpload(input, existing.attachmentId);
@@ -440,7 +446,8 @@ export function startAttachmentUpload(input: {
446 environmentId: input.environmentId,
447 ...(input.draftTarget !== undefined ? { draftTarget: input.draftTarget } : {}),
448 ...(previous ? { previous } : {}),
443 - ...(input.image.type === "file" &&
449 + ...(!input.force &&
450 + input.image.type === "file" &&
451 input.image.uploadEnvironmentId === input.environmentId &&
452 input.image.uploadedAttachmentId
453 ? { persistedAttachmentId: input.image.uploadedAttachmentId }
@@ -582,6 +589,66 @@ export async function awaitAttachmentUploads(imageIds: ReadonlyArray<string>): P
589 await Promise.all(imageIds.map((imageId) => jobsByImageId.get(imageId)?.settled));
590 }
591
592 +/** Revalidate ready uploads at send time; a long-lived draft can outlive server cleanup. */
593 +export async function refreshExpiredAttachmentUploads(input: {
594 + readonly environmentId: EnvironmentId;
595 + readonly images: ReadonlyArray<ComposerImageAttachment | ComposerFileAttachment>;
596 + readonly draftTarget?: ComposerThreadTarget;
597 +}): Promise<void> {
598 + const canVerify = readEnvironmentScope(input.environmentId, AuthOrchestrationReadScope);
599 + await Promise.all(
600 + input.images.map(async (image) => {
601 + const upload = readAttachmentUpload(image.id);
602 + if (upload?.status !== "ready" || upload.environmentId !== input.environmentId) return;
603 + if (!canVerify) {
604 + if (image.file) {
605 + startAttachmentUpload({
606 + environmentId: input.environmentId,
607 + image,
608 + force: true,
609 + ...(input.draftTarget !== undefined ? { draftTarget: input.draftTarget } : {}),
610 + });
611 + } else {
612 + setUploadState(image.id, {
613 + status: "failed",
614 + environmentId: input.environmentId,
615 + previous: upload,
616 + reason: "Uploaded attachment could not be verified. Attach the file again.",
617 + });
618 + }
619 + return;
620 + }
621 + const verification = await verifyStashedAttachmentUpload({
622 + environmentId: input.environmentId,
623 + attachmentId: upload.attachmentId,
624 + }).catch((error: unknown): PersistedAttachmentVerification => ({ status: "failed", error }));
625 + // The user may have removed or replaced the attachment while verification was in flight.
626 + if (readAttachmentUpload(image.id) !== upload) return;
627 + if (verification.status === "verified") return;
628 + if (verification.status === "missing" && image.file) {
629 + clearUploadState(image.id);
630 + startAttachmentUpload({
631 + environmentId: input.environmentId,
632 + image,
633 + force: true,
634 + ...(input.draftTarget !== undefined ? { draftTarget: input.draftTarget } : {}),
635 + });
636 + return;
637 + }
638 + setUploadState(image.id, {
639 + status: "failed",
640 + environmentId: input.environmentId,
641 + previous: upload,
642 + reason:
643 + verification.status === "missing"
644 + ? "Uploaded attachment expired. Remove it and attach it again."
645 + : "Uploaded attachment could not be verified. Retry when the server reconnects.",
646 + });
647 + }),
648 + );
649 + await awaitAttachmentUploads(input.images.map((image) => image.id));
650 +}
651 +
652 export function getUploadedAttachments(input: {
653 readonly environmentId: EnvironmentId;
654 readonly images: ReadonlyArray<ComposerImageAttachment | ComposerFileAttachment>;