From 36f6d76bd54320cf4593ee5f30eccf68eb50be24 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Thu, 13 Aug 2026 18:17:01 -0700 Subject: [PATCH] fix: harden upload lifecycle from second review round - Unique per-request .part suffix so concurrent POSTs of one token cannot interleave into a shared temp file. - xhr.timeout on uploads: a stalled POST now fails into the retryable state instead of blocking send (and pick-and-send) forever. - Cross-environment re-upload keeps the old environment's copy until the new upload succeeds (supersedes), so a failed re-upload never destroys the only server copy. - The plan follow-up branch releases attached images before clearing the composer instead of orphaning their pending files. - Mobile: a mixed text+image clipboard still pastes its text while attach is disabled, and the image drop is surfaced. Co-Authored-By: Claude Fable 5 --- apps/mobile/src/lib/composerImages.ts | 19 ++++++++++---- .../src/assets/AttachmentUpload.test.ts | 7 +++-- apps/server/src/assets/AttachmentUpload.ts | 8 +++++- apps/web/src/components/ChatView.tsx | 8 +++++- apps/web/src/components/chat/ChatComposer.tsx | 26 ++++++++++++++----- apps/web/src/lib/attachmentUploadQueue.ts | 24 +++++++++++++++++ 6 files changed, 77 insertions(+), 15 deletions(-) diff --git a/apps/mobile/src/lib/composerImages.ts b/apps/mobile/src/lib/composerImages.ts index c136c68dd6..8e99e6ea1a 100644 --- a/apps/mobile/src/lib/composerImages.ts +++ b/apps/mobile/src/lib/composerImages.ts @@ -158,10 +158,7 @@ export async function pasteComposerClipboard(input: { readonly existingCount: nu const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount; - if (await clipboard.hasImageAsync()) { - if (!IMAGE_ATTACH_ENABLED) { - return { images: [], text: null, error: IMAGE_ATTACH_UNAVAILABLE_MESSAGE }; - } + if ((await clipboard.hasImageAsync()) && IMAGE_ATTACH_ENABLED) { if (remainingSlots <= 0) { return { images: [], @@ -205,14 +202,26 @@ export async function pasteComposerClipboard(input: { readonly existingCount: nu }; } + // Reached with attach disabled even when the clipboard holds an image: + // mixed copy payloads (common on iOS) must still paste their text, with + // the image drop surfaced rather than silently swallowed. if (await clipboard.hasStringAsync()) { const text = await clipboard.getStringAsync(); + const droppedImage = !IMAGE_ATTACH_ENABLED && (await clipboard.hasImageAsync()); return { images: [], text: text.length > 0 ? text : null, - error: text.length > 0 ? null : "Clipboard is empty.", + error: droppedImage + ? IMAGE_ATTACH_UNAVAILABLE_MESSAGE + : text.length > 0 + ? null + : "Clipboard is empty.", }; } + if (!IMAGE_ATTACH_ENABLED && (await clipboard.hasImageAsync())) { + // Image-only clipboard while attach is disabled. + return { images: [], text: null, error: IMAGE_ATTACH_UNAVAILABLE_MESSAGE }; + } return { images: [], diff --git a/apps/server/src/assets/AttachmentUpload.test.ts b/apps/server/src/assets/AttachmentUpload.test.ts index 3a35628149..4b4cfa3a52 100644 --- a/apps/server/src/assets/AttachmentUpload.test.ts +++ b/apps/server/src/assets/AttachmentUpload.test.ts @@ -73,8 +73,11 @@ describe("AttachmentUpload", () => { expect(stored).toEqual({ ok: true }); const finalPath = NodePath.join(config.attachmentsDir, `${issued.attachmentId}.png`); expect(NodeFS.existsSync(finalPath)).toBe(true); - // No .part residue after a successful store. - expect(NodeFS.existsSync(`${finalPath}.part`)).toBe(false); + // No .part residue after a successful store (suffix is per-request). + const partResidue = NodeFS.readdirSync(config.attachmentsDir).filter((entry) => + entry.endsWith(".part"), + ); + expect(partResidue).toEqual([]); }).pipe(Effect.provide(testLayer)), ); diff --git a/apps/server/src/assets/AttachmentUpload.ts b/apps/server/src/assets/AttachmentUpload.ts index 0cf4327bed..14baab2db5 100644 --- a/apps/server/src/assets/AttachmentUpload.ts +++ b/apps/server/src/assets/AttachmentUpload.ts @@ -1,3 +1,6 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeCrypto from "node:crypto"; + import { ATTACHMENT_UPLOAD_URL_TTL_MS, type AttachmentCreateUploadUrlInput, @@ -147,9 +150,12 @@ export const storeAttachmentUpload = Effect.fn("AttachmentUpload.store")(functio attachmentsDir: config.attachmentsDir, relativePath, }); + // Unique per request: two concurrent POSTs of the same token must not + // interleave writes into one temp file. Both rename onto the final path + // atomically; last one wins with identical claims-validated content. const partPath = resolveAttachmentRelativePath({ attachmentsDir: config.attachmentsDir, - relativePath: `${relativePath}.part`, + relativePath: `${relativePath}.${NodeCrypto.randomUUID()}.part`, }); if (!finalPath || !partPath) { return { ok: false, status: 500, detail: "Failed to resolve attachment path." }; diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 2563a83d5e..ccd7fc91f6 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -205,7 +205,7 @@ import { useComposerDraftStore, type DraftId, } from "../composerDraftStore"; -import { awaitAttachmentUploads } from "../lib/attachmentUploadQueue"; +import { awaitAttachmentUploads, releaseComposerAttachment } from "../lib/attachmentUploadQueue"; import { readyAttachmentRefs, summarizeAttachmentUploads } from "../lib/attachmentUploadState"; import { appendTerminalContextsToPrompt, @@ -4977,6 +4977,12 @@ function ChatViewContent(props: ChatViewProps) { planMarkdown: activeProposedPlan.planMarkdown, }); promptRef.current = ""; + // The follow-up sends text only; any attached images are being + // discarded with the rest of the composer, so their uploads and + // server-side bytes are released like a chip removal. + for (const image of composerImages) { + releaseComposerAttachment(image); + } clearComposerDraftContent(composerDraftTarget); composerRef.current?.resetCursorState(); await onSubmitPlanFollowUp({ diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index a660d85036..7d34177e1d 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -1502,15 +1502,29 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) // ------------------------------------------------------------------ // The bytes live in exactly one environment. When a draft is pointed at a // different one, an attachment we still hold the File for is silently - // re-uploaded (releasing the old environment's copy first, so nothing - // orphans there). One restored after a reload has no File to re-send; its - // ready state is left intact and the mismatch is rendered and send-gated - // as a derived condition, so switching back recovers it. + // re-uploaded; the old environment's copy is released only after the new + // upload lands (`supersedes`), so a failed re-upload never destroys the + // only server copy. One restored after a reload has no File to re-send; + // its ready state is left intact and the mismatch is rendered and + // send-gated as a derived condition, so switching back recovers it. useEffect(() => { for (const image of composerImages) { if (resolveAttachmentEnvironmentAction(image, environmentId) === "reupload") { - releaseComposerAttachment(image); - startAttachmentUpload({ target: composerDraftTarget, environmentId, image }); + const previousUpload = image.upload; + cancelAttachmentUpload(image.id); + startAttachmentUpload({ + target: composerDraftTarget, + environmentId, + image, + ...(previousUpload.status === "ready" + ? { + supersedes: { + environmentId: previousUpload.environmentId, + attachmentId: previousUpload.attachmentId, + }, + } + : {}), + }); } } }, [composerDraftTarget, composerImages, environmentId]); diff --git a/apps/web/src/lib/attachmentUploadQueue.ts b/apps/web/src/lib/attachmentUploadQueue.ts index 7633b5f49e..1f3014a126 100644 --- a/apps/web/src/lib/attachmentUploadQueue.ts +++ b/apps/web/src/lib/attachmentUploadQueue.ts @@ -31,6 +31,15 @@ interface UploadJob { /** Mutable: a draft move retargets live jobs (`retargetAttachmentUploads`). */ target: ComposerThreadTarget; readonly environmentId: EnvironmentId; + /** + * A prior copy of the same image in another environment, deleted only once + * this upload succeeds. Deleting it up front would leave zero server copies + * if the re-upload fails. + */ + readonly supersedes: { + readonly environmentId: EnvironmentId; + readonly attachmentId: string; + } | null; readonly file: File; readonly name: string; readonly mimeType: string; @@ -87,6 +96,14 @@ interface ByteUpload { readonly abort: () => void; } +/** + * Hard ceiling on one upload attempt. Compressed images are a few MB at most, + * so five minutes only ever triggers on a genuinely stalled connection — + * without it a stalled POST never settles, the chip stays `uploading`, and + * everything gated on settlement (send, pick-and-send) hangs with it. + */ +const UPLOAD_TIMEOUT_MS = 5 * 60_000; + function postBytes( url: string, file: File, @@ -96,6 +113,7 @@ function postBytes( const xhr = new XMLHttpRequest(); const done = new Promise<"ok" | "aborted">((resolve, reject) => { xhr.open("POST", url, true); + xhr.timeout = UPLOAD_TIMEOUT_MS; xhr.setRequestHeader("Content-Type", mimeType); xhr.upload.addEventListener("progress", (event) => { if (event.lengthComputable && event.total > 0) { @@ -162,6 +180,9 @@ async function runJob(job: UploadJob): Promise { attachmentId: minted.value.attachmentId, environmentId: job.environmentId, }); + if (job.supersedes) { + deleteAttachment(job.supersedes.environmentId, job.supersedes.attachmentId); + } } catch (error) { if (job.cancelled) return; setUploadState(job, { @@ -198,6 +219,8 @@ export function startAttachmentUpload(input: { target: ComposerThreadTarget; environmentId: EnvironmentId; image: ComposerImageAttachment; + /** See UploadJob.supersedes — set when re-uploading across environments. */ + supersedes?: { readonly environmentId: EnvironmentId; readonly attachmentId: string }; }): void { const { image } = input; if (!image.file || jobsByImageId.has(image.id)) { @@ -211,6 +234,7 @@ export function startAttachmentUpload(input: { imageId: image.id, target: input.target, environmentId: input.environmentId, + supersedes: input.supersedes ?? null, file: image.file, name: image.name, mimeType: image.mimeType,