TypeScript
fix(web): preserve images copied from unsent drafts (#17821)
Wout Stiens954d3bdd894f
diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsxindex 146393fcc8c..41a96d00973 100644--- a/apps/web/src/components/chat/ChatComposer.tsx+++ b/apps/web/src/components/chat/ChatComposer.tsx@@ -239,6 +239,7 @@ import {} from "~/lib/composerContextReferences";import {asKnownContextRecord,+ attachmentContextRecord,composerContextImportLookupIds,isSameComposerContextPayload,uploadedAttachmentContextRecord,@@ -257,6 +258,10 @@ import {threadContextRecord,threadContextReference,} from "~/lib/composerContextRecords";+import {+ copiedComposerAttachmentFile,+ rememberCopiedComposerAttachments,+} from "~/lib/copiedComposerAttachments";import { matchComposerThreadItems } from "@t3tools/client-runtime/composerThreadItems";import { useThreadContextDrop, threadContextDropTargetProps } from "./threadContextDrag";import { readThreadShell, useThreadShells } from "~/state/entities";@@ -2975,6 +2980,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)const setComposerDraftThreadContexts = useComposerDraftStore((store) => store.setThreadContexts);const buildContextClipboardFragment = (contextIds: ReadonlyArray<string>): string | null => {const wanted = new Set(contextIds);+ const copiedFiles = new Map<string, File>();for (const annotation of composerPreviewAnnotations) {if (wanted.has(previewAnnotationContextId(annotation.id)) &&@@ -3005,19 +3011,24 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)wanted.has(toKindScopedComposerContextId(attachment.type, attachment.id)),).flatMap((attachment) => {- const record = uploadedAttachmentContextRecord(- attachment,- uploadsByImageId[attachment.id],- );- return record ? [record] : [];+ const record =+ uploadedAttachmentContextRecord(attachment, uploadsByImageId[attachment.id]) ??+ (attachment.file+ ? attachmentContextRecord({ attachment, attachmentId: attachment.id })+ : null);+ if (!record) return [];+ if (attachment.file) copiedFiles.set(record.attachmentId, attachment.file);+ return [record];}),];if (records.length === 0) return null;- return encodeComposerContextFragment({+ const fragment = encodeComposerContextFragment({version: 1,source: { environmentId, ...(activeThread ? { threadId: activeThread.id } : {}) },records,});+ if (fragment) rememberCopiedComposerAttachments(environmentId, copiedFiles);+ return fragment;};const buildContextClipboardFragmentStable = useStableCallback(buildContextClipboardFragment);const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, { reportFailure: false });@@ -3049,11 +3060,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps));};const countReservedAttachmentsStable = useStableCallback(countReservedAttachments);- /**- * Bytes for a pasted image or file come back through the source environment's asset URL- * (the client is the only party that can reach both) and re-enter this draft as a normal- * attachment under a fresh id.- */const runAttachmentImport = async (record: Extract<ComposerContextRecord, { kind: "image" | "file" }>,localId: string,@@ -3067,29 +3073,32 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)description: `${reason} Remove the chip or attach the file again.`,});};- const sourceConnection = readPreparedConnection(sourceEnvironmentId);- if (!sourceConnection) {- fail("The environment it came from is not connected.");- return;- }- const result = await createAssetUrl({- environmentId: sourceEnvironmentId,- input: { resource: { _tag: "attachment", attachmentId: record.attachmentId } },- });- const url =- result._tag === "Success"- ? resolveAssetUrl(sourceConnection.httpBaseUrl, result.value.relativeUrl)- : null;- if (!url) {- fail("The original attachment is no longer available.");- return;- }- const blob = await downloadAttachmentBlob(url);- if (!blob) {- fail("Downloading it from the source failed.");- return;+ let file = copiedComposerAttachmentFile(sourceEnvironmentId, record.attachmentId);+ if (!file) {+ const sourceConnection = readPreparedConnection(sourceEnvironmentId);+ if (!sourceConnection) {+ fail("The environment it came from is not connected.");+ return;+ }+ const result = await createAssetUrl({+ environmentId: sourceEnvironmentId,+ input: { resource: { _tag: "attachment", attachmentId: record.attachmentId } },+ });+ const url =+ result._tag === "Success"+ ? resolveAssetUrl(sourceConnection.httpBaseUrl, result.value.relativeUrl)+ : null;+ if (!url) {+ fail("The original attachment is no longer available.");+ return;+ }+ const blob = await downloadAttachmentBlob(url);+ if (!blob) {+ fail("Downloading it from the source failed.");+ return;+ }+ file = new File([blob], record.name, { type: record.mimeType || blob.type });}- const file = new File([blob], record.name, { type: record.mimeType || blob.type });// The draft these bytes belong to may have been sent or switched away from while they// downloaded. Dropping them here keeps them out of whatever draft is open now.if (attachmentTargetKeyRef.current !== importTargetKey) return;@@ -3113,15 +3122,26 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)return;}if (record.kind === "image") {- const accepted = addComposerImage({- type: "image",- id: localId,- name: record.name,- mimeType: file.type,- sizeBytes: file.size,- previewUrl: URL.createObjectURL(file),- file,- });+ const accepted = addComposerDraftImages(+ attachmentDraftTarget,+ [+ {+ type: "image",+ id: localId,+ name: record.name,+ mimeType: file.type,+ sizeBytes: file.size,+ previewUrl: URL.createObjectURL(file),+ file,+ },+ ],+ {+ allowDuplicates:+ getComposerDraft(composerDraftTarget)?.previewAnnotations.some(+ (annotation) => annotation.id === localId,+ ) ?? false,+ },+ );if (!accepted.includes(localId))fail("The draft rejected this attachment (duplicate or attachment limit reached).");} else {@@ -3175,17 +3195,36 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)// re-minted under a fresh id so both survive the paste.const record = asKnownContextRecord(candidate);if (!record) continue;- const existing = composerContextImportLookupIds(record).flatMap((contextId) => {- const found = composerContextRecords.get(contextId);- return found ? [found] : [];- })[0];+ // A reminted annotation needs its screenshot under the new annotation id.+ const existing = dependentAttachmentLocalIds.has(record.contextId)+ ? undefined+ : composerContextImportLookupIds(record).flatMap((contextId) => {+ const found = composerContextRecords.get(contextId);+ return found ? [found] : [];+ })[0];+ // Upload completion can change the server id since copy; the local bytes still match.+ if (+ sourceEnvironmentId !== null &&+ (record.kind === "image" || record.kind === "file") &&+ (existing?.kind === "image" || existing?.kind === "file") &&+ existing.record.file !== null &&+ existing.record.file ===+ copiedComposerAttachmentFile(sourceEnvironmentId, record.attachmentId)+ )+ continue;const existingRecord =existing?.kind === "terminal"? terminalContextRecord(existing.record): existing?.kind === "review-comment"? reviewCommentContextRecord(existing.record): existing?.kind === "preview-annotation"- ? previewAnnotationContextRecord(existing.record)+ ? previewAnnotationContextRecord(existing.record, {+ screenshotContextId: composerImages.some(+ (image) => image.id === existing.record.id,+ )+ ? existing.record.id+ : undefined,+ }): existing?.kind === "thread"? existing.record: existingdiff --git a/apps/web/src/composerDraftStore.test.ts b/apps/web/src/composerDraftStore.test.tsindex 410aba2b39b..5a03c81a8f6 100644--- a/apps/web/src/composerDraftStore.test.ts+++ b/apps/web/src/composerDraftStore.test.ts@@ -80,6 +80,10 @@ import {import { removeLocalStorageItem, setLocalStorageItem } from "./hooks/useLocalStorage";import { insertInlineContextReference } from "./lib/composerContextReferences";import { terminalContextReference, threadContextRecord } from "./lib/composerContextRecords";+import {+ copiedComposerAttachmentFile,+ rememberCopiedComposerAttachments,+} from "./lib/copiedComposerAttachments";import {INLINE_TERMINAL_CONTEXT_PLACEHOLDER,formatTerminalContextReference,@@ -361,6 +365,62 @@ describe("composerDraftStore addImages", () => {});});+describe("composerDraftStore copied attachments", () => {+ beforeEach(resetComposerDraftStore);+ afterEach(() => {+ rememberCopiedComposerAttachments(TEST_ENVIRONMENT_ID, new Map());+ resetComposerDraftStore();+ vi.restoreAllMocks();+ });++ it("keeps unsent image and file bytes usable in another draft after source removal", async () => {+ const source = scopeThreadRef(TEST_ENVIRONMENT_ID, ThreadId.make("copy-source"));+ const target = scopeThreadRef(TEST_ENVIRONMENT_ID, ThreadId.make("copy-target"));+ const image = makeImage({ id: "uploading-image", previewUrl: "blob:source" });+ const file = makeFile("uploading-file");+ const revoke = vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {});+ const store = useComposerDraftStore.getState();+ store.addImages(source, [image]);+ store.addFiles(source, [file]);+ rememberCopiedComposerAttachments(+ TEST_ENVIRONMENT_ID,+ new Map([+ [image.id, image.file],+ [file.id, file.file!],+ ]),+ );++ store.removeImage(source, image.id);+ store.clearComposerContent(source);+ expect(store.getComposerDraft(source)).toBeNull();+ expect(revoke).toHaveBeenCalledWith(image.previewUrl);++ const copiedImage = copiedComposerAttachmentFile(TEST_ENVIRONMENT_ID, image.id);+ const copiedFile = copiedComposerAttachmentFile(TEST_ENVIRONMENT_ID, file.id);+ expect(copiedImage).toBe(image.file);+ expect(copiedFile).toBe(file.file);+ store.addImages(target, [{ ...image, file: copiedImage!, previewUrl: "blob:target" }]);+ store.addFiles(target, [{ ...file, file: copiedFile! }]);+ const draft = store.getComposerDraft(target)!;+ expect([...new Uint8Array(await draft.images[0]!.file.arrayBuffer())]).toEqual([1, 1, 1, 1]);+ expect(await draft.files[0]!.file!.text()).toBe("report");+ });++ it("does not reuse bytes from another environment or a superseded clipboard copy", () => {+ const first = makeImage({ id: "first", previewUrl: "blob:first" });+ const second = makeFile("second");+ rememberCopiedComposerAttachments(TEST_ENVIRONMENT_ID, new Map([[first.id, first.file]]));+ expect(copiedComposerAttachmentFile(OTHER_TEST_ENVIRONMENT_ID, first.id)).toBeUndefined();++ rememberCopiedComposerAttachments(TEST_ENVIRONMENT_ID, new Map([[second.id, second.file!]]));+ expect(copiedComposerAttachmentFile(TEST_ENVIRONMENT_ID, first.id)).toBeUndefined();+ expect(copiedComposerAttachmentFile(TEST_ENVIRONMENT_ID, second.id)).toBe(second.file);++ rememberCopiedComposerAttachments(TEST_ENVIRONMENT_ID, new Map());+ expect(copiedComposerAttachmentFile(TEST_ENVIRONMENT_ID, second.id)).toBeUndefined();+ });+});+describe("composerDraftStore clearComposerContent", () => {const threadId = ThreadId.make("thread-clear");const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId);diff --git a/apps/web/src/lib/composerContextRecords.ts b/apps/web/src/lib/composerContextRecords.tsindex b10ed8a0227..a1f7aae2725 100644--- a/apps/web/src/lib/composerContextRecords.ts+++ b/apps/web/src/lib/composerContextRecords.ts@@ -276,7 +276,7 @@ export interface BoundComposerAttachment {attachmentId: string;}-/** Clipboard payloads may only point at attachments that already exist on the server. */+/** Returns null until the attachment has a server id. */export function uploadedAttachmentContextRecord(attachment: ComposerImageAttachment | ComposerFileAttachment,upload: AttachmentUploadState | undefined,diff --git a/apps/web/src/lib/copiedComposerAttachments.ts b/apps/web/src/lib/copiedComposerAttachments.tsnew file mode 100644index 00000000000..7f0b5161397--- /dev/null+++ b/apps/web/src/lib/copiedComposerAttachments.ts@@ -0,0 +1,21 @@+import type { EnvironmentId } from "@t3tools/contracts";++// Keep the latest copy's files alive after source removal, including preview URL revocation.+// Replacing the copy releases the previous files instead of accumulating draft attachments.+let latestCopy: { environmentId: EnvironmentId; files: ReadonlyMap<string, File> } | null = null;++export function rememberCopiedComposerAttachments(+ environmentId: EnvironmentId,+ files: ReadonlyMap<string, File>,+): void {+ latestCopy = files.size > 0 ? { environmentId, files } : null;+}++export function copiedComposerAttachmentFile(+ environmentId: EnvironmentId,+ attachmentId: string,+): File | undefined {+ return latestCopy?.environmentId === environmentId+ ? latestCopy.files.get(attachmentId)+ : undefined;+}