@devries-cameron20 / t3code-1 / commits / 954d3bdd89
Fork 0

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

fix(web): preserve images copied from unsent drafts (#17821)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

Wout Stiens committed Oct 19, 2026 at 20:47 UTC 954d3bdd894ff6f24c4affe37189ea00df7d9f52
4 files changed +168 -48
apps/web/src/components/chat/ChatComposer.tsx
+86 -47
@@ -239,6 +239,7 @@ import {
239 } from "~/lib/composerContextReferences";
240 import {
241 asKnownContextRecord,
242 + attachmentContextRecord,
243 composerContextImportLookupIds,
244 isSameComposerContextPayload,
245 uploadedAttachmentContextRecord,
@@ -257,6 +258,10 @@ import {
258 threadContextRecord,
259 threadContextReference,
260 } from "~/lib/composerContextRecords";
261 +import {
262 + copiedComposerAttachmentFile,
263 + rememberCopiedComposerAttachments,
264 +} from "~/lib/copiedComposerAttachments";
265 import { matchComposerThreadItems } from "@t3tools/client-runtime/composerThreadItems";
266 import { useThreadContextDrop, threadContextDropTargetProps } from "./threadContextDrag";
267 import { readThreadShell, useThreadShells } from "~/state/entities";
@@ -2975,6 +2980,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
2980 const setComposerDraftThreadContexts = useComposerDraftStore((store) => store.setThreadContexts);
2981 const buildContextClipboardFragment = (contextIds: ReadonlyArray<string>): string | null => {
2982 const wanted = new Set(contextIds);
2983 + const copiedFiles = new Map<string, File>();
2984 for (const annotation of composerPreviewAnnotations) {
2985 if (
2986 wanted.has(previewAnnotationContextId(annotation.id)) &&
@@ -3005,19 +3011,24 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
3011 wanted.has(toKindScopedComposerContextId(attachment.type, attachment.id)),
3012 )
3013 .flatMap((attachment) => {
3008 - const record = uploadedAttachmentContextRecord(
3009 - attachment,
3010 - uploadsByImageId[attachment.id],
3011 - );
3012 - return record ? [record] : [];
3014 + const record =
3015 + uploadedAttachmentContextRecord(attachment, uploadsByImageId[attachment.id]) ??
3016 + (attachment.file
3017 + ? attachmentContextRecord({ attachment, attachmentId: attachment.id })
3018 + : null);
3019 + if (!record) return [];
3020 + if (attachment.file) copiedFiles.set(record.attachmentId, attachment.file);
3021 + return [record];
3022 }),
3023 ];
3024 if (records.length === 0) return null;
3016 - return encodeComposerContextFragment({
3025 + const fragment = encodeComposerContextFragment({
3026 version: 1,
3027 source: { environmentId, ...(activeThread ? { threadId: activeThread.id } : {}) },
3028 records,
3029 });
3030 + if (fragment) rememberCopiedComposerAttachments(environmentId, copiedFiles);
3031 + return fragment;
3032 };
3033 const buildContextClipboardFragmentStable = useStableCallback(buildContextClipboardFragment);
3034 const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, { reportFailure: false });
@@ -3049,11 +3060,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
3060 );
3061 };
3062 const countReservedAttachmentsStable = useStableCallback(countReservedAttachments);
3052 - /**
3053 - * Bytes for a pasted image or file come back through the source environment's asset URL
3054 - * (the client is the only party that can reach both) and re-enter this draft as a normal
3055 - * attachment under a fresh id.
3056 - */
3063 const runAttachmentImport = async (
3064 record: Extract<ComposerContextRecord, { kind: "image" | "file" }>,
3065 localId: string,
@@ -3067,29 +3073,32 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
3073 description: `${reason} Remove the chip or attach the file again.`,
3074 });
3075 };
3070 - const sourceConnection = readPreparedConnection(sourceEnvironmentId);
3071 - if (!sourceConnection) {
3072 - fail("The environment it came from is not connected.");
3073 - return;
3074 - }
3075 - const result = await createAssetUrl({
3076 - environmentId: sourceEnvironmentId,
3077 - input: { resource: { _tag: "attachment", attachmentId: record.attachmentId } },
3078 - });
3079 - const url =
3080 - result._tag === "Success"
3081 - ? resolveAssetUrl(sourceConnection.httpBaseUrl, result.value.relativeUrl)
3082 - : null;
3083 - if (!url) {
3084 - fail("The original attachment is no longer available.");
3085 - return;
3086 - }
3087 - const blob = await downloadAttachmentBlob(url);
3088 - if (!blob) {
3089 - fail("Downloading it from the source failed.");
3090 - return;
3076 + let file = copiedComposerAttachmentFile(sourceEnvironmentId, record.attachmentId);
3077 + if (!file) {
3078 + const sourceConnection = readPreparedConnection(sourceEnvironmentId);
3079 + if (!sourceConnection) {
3080 + fail("The environment it came from is not connected.");
3081 + return;
3082 + }
3083 + const result = await createAssetUrl({
3084 + environmentId: sourceEnvironmentId,
3085 + input: { resource: { _tag: "attachment", attachmentId: record.attachmentId } },
3086 + });
3087 + const url =
3088 + result._tag === "Success"
3089 + ? resolveAssetUrl(sourceConnection.httpBaseUrl, result.value.relativeUrl)
3090 + : null;
3091 + if (!url) {
3092 + fail("The original attachment is no longer available.");
3093 + return;
3094 + }
3095 + const blob = await downloadAttachmentBlob(url);
3096 + if (!blob) {
3097 + fail("Downloading it from the source failed.");
3098 + return;
3099 + }
3100 + file = new File([blob], record.name, { type: record.mimeType || blob.type });
3101 }
3092 - const file = new File([blob], record.name, { type: record.mimeType || blob.type });
3102 // The draft these bytes belong to may have been sent or switched away from while they
3103 // downloaded. Dropping them here keeps them out of whatever draft is open now.
3104 if (attachmentTargetKeyRef.current !== importTargetKey) return;
@@ -3113,15 +3122,26 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
3122 return;
3123 }
3124 if (record.kind === "image") {
3116 - const accepted = addComposerImage({
3117 - type: "image",
3118 - id: localId,
3119 - name: record.name,
3120 - mimeType: file.type,
3121 - sizeBytes: file.size,
3122 - previewUrl: URL.createObjectURL(file),
3123 - file,
3124 - });
3125 + const accepted = addComposerDraftImages(
3126 + attachmentDraftTarget,
3127 + [
3128 + {
3129 + type: "image",
3130 + id: localId,
3131 + name: record.name,
3132 + mimeType: file.type,
3133 + sizeBytes: file.size,
3134 + previewUrl: URL.createObjectURL(file),
3135 + file,
3136 + },
3137 + ],
3138 + {
3139 + allowDuplicates:
3140 + getComposerDraft(composerDraftTarget)?.previewAnnotations.some(
3141 + (annotation) => annotation.id === localId,
3142 + ) ?? false,
3143 + },
3144 + );
3145 if (!accepted.includes(localId))
3146 fail("The draft rejected this attachment (duplicate or attachment limit reached).");
3147 } else {
@@ -3175,17 +3195,36 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
3195 // re-minted under a fresh id so both survive the paste.
3196 const record = asKnownContextRecord(candidate);
3197 if (!record) continue;
3178 - const existing = composerContextImportLookupIds(record).flatMap((contextId) => {
3179 - const found = composerContextRecords.get(contextId);
3180 - return found ? [found] : [];
3181 - })[0];
3198 + // A reminted annotation needs its screenshot under the new annotation id.
3199 + const existing = dependentAttachmentLocalIds.has(record.contextId)
3200 + ? undefined
3201 + : composerContextImportLookupIds(record).flatMap((contextId) => {
3202 + const found = composerContextRecords.get(contextId);
3203 + return found ? [found] : [];
3204 + })[0];
3205 + // Upload completion can change the server id since copy; the local bytes still match.
3206 + if (
3207 + sourceEnvironmentId !== null &&
3208 + (record.kind === "image" || record.kind === "file") &&
3209 + (existing?.kind === "image" || existing?.kind === "file") &&
3210 + existing.record.file !== null &&
3211 + existing.record.file ===
3212 + copiedComposerAttachmentFile(sourceEnvironmentId, record.attachmentId)
3213 + )
3214 + continue;
3215 const existingRecord =
3216 existing?.kind === "terminal"
3217 ? terminalContextRecord(existing.record)
3218 : existing?.kind === "review-comment"
3219 ? reviewCommentContextRecord(existing.record)
3220 : existing?.kind === "preview-annotation"
3188 - ? previewAnnotationContextRecord(existing.record)
3221 + ? previewAnnotationContextRecord(existing.record, {
3222 + screenshotContextId: composerImages.some(
3223 + (image) => image.id === existing.record.id,
3224 + )
3225 + ? existing.record.id
3226 + : undefined,
3227 + })
3228 : existing?.kind === "thread"
3229 ? existing.record
3230 : existing
apps/web/src/composerDraftStore.test.ts
+60
@@ -80,6 +80,10 @@ import {
80 import { removeLocalStorageItem, setLocalStorageItem } from "./hooks/useLocalStorage";
81 import { insertInlineContextReference } from "./lib/composerContextReferences";
82 import { terminalContextReference, threadContextRecord } from "./lib/composerContextRecords";
83 +import {
84 + copiedComposerAttachmentFile,
85 + rememberCopiedComposerAttachments,
86 +} from "./lib/copiedComposerAttachments";
87 import {
88 INLINE_TERMINAL_CONTEXT_PLACEHOLDER,
89 formatTerminalContextReference,
@@ -361,6 +365,62 @@ describe("composerDraftStore addImages", () => {
365 });
366 });
367
368 +describe("composerDraftStore copied attachments", () => {
369 + beforeEach(resetComposerDraftStore);
370 + afterEach(() => {
371 + rememberCopiedComposerAttachments(TEST_ENVIRONMENT_ID, new Map());
372 + resetComposerDraftStore();
373 + vi.restoreAllMocks();
374 + });
375 +
376 + it("keeps unsent image and file bytes usable in another draft after source removal", async () => {
377 + const source = scopeThreadRef(TEST_ENVIRONMENT_ID, ThreadId.make("copy-source"));
378 + const target = scopeThreadRef(TEST_ENVIRONMENT_ID, ThreadId.make("copy-target"));
379 + const image = makeImage({ id: "uploading-image", previewUrl: "blob:source" });
380 + const file = makeFile("uploading-file");
381 + const revoke = vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {});
382 + const store = useComposerDraftStore.getState();
383 + store.addImages(source, [image]);
384 + store.addFiles(source, [file]);
385 + rememberCopiedComposerAttachments(
386 + TEST_ENVIRONMENT_ID,
387 + new Map([
388 + [image.id, image.file],
389 + [file.id, file.file!],
390 + ]),
391 + );
392 +
393 + store.removeImage(source, image.id);
394 + store.clearComposerContent(source);
395 + expect(store.getComposerDraft(source)).toBeNull();
396 + expect(revoke).toHaveBeenCalledWith(image.previewUrl);
397 +
398 + const copiedImage = copiedComposerAttachmentFile(TEST_ENVIRONMENT_ID, image.id);
399 + const copiedFile = copiedComposerAttachmentFile(TEST_ENVIRONMENT_ID, file.id);
400 + expect(copiedImage).toBe(image.file);
401 + expect(copiedFile).toBe(file.file);
402 + store.addImages(target, [{ ...image, file: copiedImage!, previewUrl: "blob:target" }]);
403 + store.addFiles(target, [{ ...file, file: copiedFile! }]);
404 + const draft = store.getComposerDraft(target)!;
405 + expect([...new Uint8Array(await draft.images[0]!.file.arrayBuffer())]).toEqual([1, 1, 1, 1]);
406 + expect(await draft.files[0]!.file!.text()).toBe("report");
407 + });
408 +
409 + it("does not reuse bytes from another environment or a superseded clipboard copy", () => {
410 + const first = makeImage({ id: "first", previewUrl: "blob:first" });
411 + const second = makeFile("second");
412 + rememberCopiedComposerAttachments(TEST_ENVIRONMENT_ID, new Map([[first.id, first.file]]));
413 + expect(copiedComposerAttachmentFile(OTHER_TEST_ENVIRONMENT_ID, first.id)).toBeUndefined();
414 +
415 + rememberCopiedComposerAttachments(TEST_ENVIRONMENT_ID, new Map([[second.id, second.file!]]));
416 + expect(copiedComposerAttachmentFile(TEST_ENVIRONMENT_ID, first.id)).toBeUndefined();
417 + expect(copiedComposerAttachmentFile(TEST_ENVIRONMENT_ID, second.id)).toBe(second.file);
418 +
419 + rememberCopiedComposerAttachments(TEST_ENVIRONMENT_ID, new Map());
420 + expect(copiedComposerAttachmentFile(TEST_ENVIRONMENT_ID, second.id)).toBeUndefined();
421 + });
422 +});
423 +
424 describe("composerDraftStore clearComposerContent", () => {
425 const threadId = ThreadId.make("thread-clear");
426 const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId);
apps/web/src/lib/composerContextRecords.ts
+1 -1
@@ -276,7 +276,7 @@ export interface BoundComposerAttachment {
276 attachmentId: string;
277 }
278
279 -/** Clipboard payloads may only point at attachments that already exist on the server. */
279 +/** Returns null until the attachment has a server id. */
280 export function uploadedAttachmentContextRecord(
281 attachment: ComposerImageAttachment | ComposerFileAttachment,
282 upload: AttachmentUploadState | undefined,
apps/web/src/lib/copiedComposerAttachments.ts new
+21
@@ -0,0 +1,21 @@
1 +import type { EnvironmentId } from "@t3tools/contracts";
2 +
3 +// Keep the latest copy's files alive after source removal, including preview URL revocation.
4 +// Replacing the copy releases the previous files instead of accumulating draft attachments.
5 +let latestCopy: { environmentId: EnvironmentId; files: ReadonlyMap<string, File> } | null = null;
6 +
7 +export function rememberCopiedComposerAttachments(
8 + environmentId: EnvironmentId,
9 + files: ReadonlyMap<string, File>,
10 +): void {
11 + latestCopy = files.size > 0 ? { environmentId, files } : null;
12 +}
13 +
14 +export function copiedComposerAttachmentFile(
15 + environmentId: EnvironmentId,
16 + attachmentId: string,
17 +): File | undefined {
18 + return latestCopy?.environmentId === environmentId
19 + ? latestCopy.files.get(attachmentId)
20 + : undefined;
21 +}