Skip to content

Commit 36f6d76

Browse files
t3dotggclaude
andcommitted
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 <[email protected]>
1 parent 03196ef commit 36f6d76

6 files changed

Lines changed: 77 additions & 15 deletions

File tree

‎apps/mobile/src/lib/composerImages.ts‎

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -158,10 +158,7 @@ export async function pasteComposerClipboard(input: { readonly existingCount: nu
158158

159159
const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
160160

161-
if (await clipboard.hasImageAsync()) {
162-
if (!IMAGE_ATTACH_ENABLED) {
163-
return { images: [], text: null, error: IMAGE_ATTACH_UNAVAILABLE_MESSAGE };
164-
}
161+
if ((await clipboard.hasImageAsync()) && IMAGE_ATTACH_ENABLED) {
165162
if (remainingSlots <= 0) {
166163
return {
167164
images: [],
@@ -205,14 +202,26 @@ export async function pasteComposerClipboard(input: { readonly existingCount: nu
205202
};
206203
}
207204

205+
// Reached with attach disabled even when the clipboard holds an image:
206+
// mixed copy payloads (common on iOS) must still paste their text, with
207+
// the image drop surfaced rather than silently swallowed.
208208
if (await clipboard.hasStringAsync()) {
209209
const text = await clipboard.getStringAsync();
210+
const droppedImage = !IMAGE_ATTACH_ENABLED && (await clipboard.hasImageAsync());
210211
return {
211212
images: [],
212213
text: text.length > 0 ? text : null,
213-
error: text.length > 0 ? null : "Clipboard is empty.",
214+
error: droppedImage
215+
? IMAGE_ATTACH_UNAVAILABLE_MESSAGE
216+
: text.length > 0
217+
? null
218+
: "Clipboard is empty.",
214219
};
215220
}
221+
if (!IMAGE_ATTACH_ENABLED && (await clipboard.hasImageAsync())) {
222+
// Image-only clipboard while attach is disabled.
223+
return { images: [], text: null, error: IMAGE_ATTACH_UNAVAILABLE_MESSAGE };
224+
}
216225

217226
return {
218227
images: [],

‎apps/server/src/assets/AttachmentUpload.test.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,8 +73,11 @@ describe("AttachmentUpload", () => {
7373
expect(stored).toEqual({ ok: true });
7474
const finalPath = NodePath.join(config.attachmentsDir, `${issued.attachmentId}.png`);
7575
expect(NodeFS.existsSync(finalPath)).toBe(true);
76-
// No .part residue after a successful store.
77-
expect(NodeFS.existsSync(`${finalPath}.part`)).toBe(false);
76+
// No .part residue after a successful store (suffix is per-request).
77+
const partResidue = NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
78+
entry.endsWith(".part"),
79+
);
80+
expect(partResidue).toEqual([]);
7881
}).pipe(Effect.provide(testLayer)),
7982
);
8083

‎apps/server/src/assets/AttachmentUpload.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
// @effect-diagnostics nodeBuiltinImport:off
2+
import * as NodeCrypto from "node:crypto";
3+
14
import {
25
ATTACHMENT_UPLOAD_URL_TTL_MS,
36
type AttachmentCreateUploadUrlInput,
@@ -147,9 +150,12 @@ export const storeAttachmentUpload = Effect.fn("AttachmentUpload.store")(functio
147150
attachmentsDir: config.attachmentsDir,
148151
relativePath,
149152
});
153+
// Unique per request: two concurrent POSTs of the same token must not
154+
// interleave writes into one temp file. Both rename onto the final path
155+
// atomically; last one wins with identical claims-validated content.
150156
const partPath = resolveAttachmentRelativePath({
151157
attachmentsDir: config.attachmentsDir,
152-
relativePath: `${relativePath}.part`,
158+
relativePath: `${relativePath}.${NodeCrypto.randomUUID()}.part`,
153159
});
154160
if (!finalPath || !partPath) {
155161
return { ok: false, status: 500, detail: "Failed to resolve attachment path." };

‎apps/web/src/components/ChatView.tsx‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -205,7 +205,7 @@ import {
205205
useComposerDraftStore,
206206
type DraftId,
207207
} from "../composerDraftStore";
208-
import { awaitAttachmentUploads } from "../lib/attachmentUploadQueue";
208+
import { awaitAttachmentUploads, releaseComposerAttachment } from "../lib/attachmentUploadQueue";
209209
import { readyAttachmentRefs, summarizeAttachmentUploads } from "../lib/attachmentUploadState";
210210
import {
211211
appendTerminalContextsToPrompt,
@@ -4977,6 +4977,12 @@ function ChatViewContent(props: ChatViewProps) {
49774977
planMarkdown: activeProposedPlan.planMarkdown,
49784978
});
49794979
promptRef.current = "";
4980+
// The follow-up sends text only; any attached images are being
4981+
// discarded with the rest of the composer, so their uploads and
4982+
// server-side bytes are released like a chip removal.
4983+
for (const image of composerImages) {
4984+
releaseComposerAttachment(image);
4985+
}
49804986
clearComposerDraftContent(composerDraftTarget);
49814987
composerRef.current?.resetCursorState();
49824988
await onSubmitPlanFollowUp({

‎apps/web/src/components/chat/ChatComposer.tsx‎

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1502,15 +1502,29 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
15021502
// ------------------------------------------------------------------
15031503
// The bytes live in exactly one environment. When a draft is pointed at a
15041504
// different one, an attachment we still hold the File for is silently
1505-
// re-uploaded (releasing the old environment's copy first, so nothing
1506-
// orphans there). One restored after a reload has no File to re-send; its
1507-
// ready state is left intact and the mismatch is rendered and send-gated
1508-
// as a derived condition, so switching back recovers it.
1505+
// re-uploaded; the old environment's copy is released only after the new
1506+
// upload lands (`supersedes`), so a failed re-upload never destroys the
1507+
// only server copy. One restored after a reload has no File to re-send;
1508+
// its ready state is left intact and the mismatch is rendered and
1509+
// send-gated as a derived condition, so switching back recovers it.
15091510
useEffect(() => {
15101511
for (const image of composerImages) {
15111512
if (resolveAttachmentEnvironmentAction(image, environmentId) === "reupload") {
1512-
releaseComposerAttachment(image);
1513-
startAttachmentUpload({ target: composerDraftTarget, environmentId, image });
1513+
const previousUpload = image.upload;
1514+
cancelAttachmentUpload(image.id);
1515+
startAttachmentUpload({
1516+
target: composerDraftTarget,
1517+
environmentId,
1518+
image,
1519+
...(previousUpload.status === "ready"
1520+
? {
1521+
supersedes: {
1522+
environmentId: previousUpload.environmentId,
1523+
attachmentId: previousUpload.attachmentId,
1524+
},
1525+
}
1526+
: {}),
1527+
});
15141528
}
15151529
}
15161530
}, [composerDraftTarget, composerImages, environmentId]);

‎apps/web/src/lib/attachmentUploadQueue.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,15 @@ interface UploadJob {
3131
/** Mutable: a draft move retargets live jobs (`retargetAttachmentUploads`). */
3232
target: ComposerThreadTarget;
3333
readonly environmentId: EnvironmentId;
34+
/**
35+
* A prior copy of the same image in another environment, deleted only once
36+
* this upload succeeds. Deleting it up front would leave zero server copies
37+
* if the re-upload fails.
38+
*/
39+
readonly supersedes: {
40+
readonly environmentId: EnvironmentId;
41+
readonly attachmentId: string;
42+
} | null;
3443
readonly file: File;
3544
readonly name: string;
3645
readonly mimeType: string;
@@ -87,6 +96,14 @@ interface ByteUpload {
8796
readonly abort: () => void;
8897
}
8998

99+
/**
100+
* Hard ceiling on one upload attempt. Compressed images are a few MB at most,
101+
* so five minutes only ever triggers on a genuinely stalled connection —
102+
* without it a stalled POST never settles, the chip stays `uploading`, and
103+
* everything gated on settlement (send, pick-and-send) hangs with it.
104+
*/
105+
const UPLOAD_TIMEOUT_MS = 5 * 60_000;
106+
90107
function postBytes(
91108
url: string,
92109
file: File,
@@ -96,6 +113,7 @@ function postBytes(
96113
const xhr = new XMLHttpRequest();
97114
const done = new Promise<"ok" | "aborted">((resolve, reject) => {
98115
xhr.open("POST", url, true);
116+
xhr.timeout = UPLOAD_TIMEOUT_MS;
99117
xhr.setRequestHeader("Content-Type", mimeType);
100118
xhr.upload.addEventListener("progress", (event) => {
101119
if (event.lengthComputable && event.total > 0) {
@@ -162,6 +180,9 @@ async function runJob(job: UploadJob): Promise<void> {
162180
attachmentId: minted.value.attachmentId,
163181
environmentId: job.environmentId,
164182
});
183+
if (job.supersedes) {
184+
deleteAttachment(job.supersedes.environmentId, job.supersedes.attachmentId);
185+
}
165186
} catch (error) {
166187
if (job.cancelled) return;
167188
setUploadState(job, {
@@ -198,6 +219,8 @@ export function startAttachmentUpload(input: {
198219
target: ComposerThreadTarget;
199220
environmentId: EnvironmentId;
200221
image: ComposerImageAttachment;
222+
/** See UploadJob.supersedes — set when re-uploading across environments. */
223+
supersedes?: { readonly environmentId: EnvironmentId; readonly attachmentId: string };
201224
}): void {
202225
const { image } = input;
203226
if (!image.file || jobsByImageId.has(image.id)) {
@@ -211,6 +234,7 @@ export function startAttachmentUpload(input: {
211234
imageId: image.id,
212235
target: input.target,
213236
environmentId: input.environmentId,
237+
supersedes: input.supersedes ?? null,
214238
file: image.file,
215239
name: image.name,
216240
mimeType: image.mimeType,

0 commit comments

Comments
 (0)