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]>
This commit is contained in:
1 parent
03196ef7ad
commit
36f6d76bd5
6 files changed
+77
-15
No files matched your search
@@ -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: [],
|
||||
|
||||
@@ -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)),
|
||||
);
|
||||
|
||||
|
||||
@@ -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." };
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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]);
|
||||
|
||||
@@ -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<void> {
|
||||
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,
|
||||
|
||||
Reference in new issue
Block a user