TypeScript
perf(composer): reuse persisted image bytes when attachments change (#22340)
Victor Vogele9485df15271
diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsxindex e08e74a4906..c4963ad73ba 100644--- a/apps/web/src/components/chat/ChatComposer.tsx+++ b/apps/web/src/components/chat/ChatComposer.tsx@@ -79,7 +79,6 @@ import { DEFAULT_COMPOSER_PLACEHOLDER } from "../../composerPlaceholder";import {deriveComposerSendState,getAntigravitySendBlockReason,- readFileAsDataUrl,resolveComposerInteractionMode,threadShellHasStarted,} from "../ChatView.logic";@@ -87,6 +86,7 @@ import {dataTransferHasComposerMention,makeComposerMentionDragHandlers,} from "./composerMentionDrag";+import { serializeComposerImages } from "./composerImagePersistence";import {isInsideCollapsedComposerControls,isInsideRestingComposerControlScope,@@ -96,7 +96,6 @@ import {type ComposerFileAttachment,type ComposerImageAttachment,type DraftId,- type PersistedComposerImageAttachment,composerFileNeedsReattach,composerDraftHasUserContent,composerTargetKey,@@ -1522,31 +1521,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)getComposerDraft(attachmentDraftTarget)?.persistedAttachments ?? [];try {const currentPersistedAttachments = getPersistedAttachmentsForThread();- const existingPersistedById = new Map(- currentPersistedAttachments.map((attachment) => [attachment.id, attachment]),+ const serialized = await serializeComposerImages(+ composerImages,+ currentPersistedAttachments,);- const stagedAttachmentById = new Map<string, PersistedComposerImageAttachment>();- await Promise.all(- composerImages.map(async (image) => {- try {- const dataUrl = await readFileAsDataUrl(image.file);- stagedAttachmentById.set(image.id, {- id: image.id,- name: image.name,- mimeType: image.mimeType,- sizeBytes: image.sizeBytes,- dataUrl,- ...(image.source ? { source: image.source } : {}),- });- } catch {- const existingPersisted = existingPersistedById.get(image.id);- if (existingPersisted) {- stagedAttachmentById.set(image.id, existingPersisted);- }- }- }),- );- const serialized = Array.from(stagedAttachmentById.values());if (cancelled) return;syncComposerDraftPersistedAttachments(attachmentDraftTarget, serialized);} catch {diff --git a/apps/web/src/components/chat/composerImagePersistence.test.ts b/apps/web/src/components/chat/composerImagePersistence.test.tsnew file mode 100644index 00000000000..5d8a210977b--- /dev/null+++ b/apps/web/src/components/chat/composerImagePersistence.test.ts@@ -0,0 +1,98 @@+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";++import type { ComposerImageAttachment } from "../../composerDraftStore";+import { readFileAsDataUrl } from "../../lib/imageCompression";+import { serializeComposerImages } from "./composerImagePersistence";++vi.mock("../../lib/imageCompression", () => ({ readFileAsDataUrl: vi.fn() }));++function image(id: string): ComposerImageAttachment {+ const file = new File([id], `${id}.png`, { type: "image/png" });+ return {+ type: "image",+ id,+ name: file.name,+ mimeType: file.type,+ sizeBytes: file.size,+ previewUrl: `blob:${id}`,+ file,+ };+}++describe("serializeComposerImages", () => {+ beforeEach(() => {+ vi.mocked(readFileAsDataUrl).mockReset();+ });++ it("reads only new images and drops removed images without rereading retained bytes", async () => {+ const a = image("a");+ const b = image("b");+ vi.mocked(readFileAsDataUrl).mockImplementation(async (file) =>+ file === a.file ? "data:image/png;base64,YQ==" : "data:image/png;base64,Yg==",+ );++ const first = await serializeComposerImages([a], []);+ expect(first).toEqual([+ {+ id: "a",+ name: "a.png",+ mimeType: "image/png",+ sizeBytes: 1,+ dataUrl: "data:image/png;base64,YQ==",+ },+ ]);+ expect(readFileAsDataUrl).toHaveBeenCalledTimes(1);++ const second = await serializeComposerImages([a, b], first);+ expect(second).toEqual([+ first[0],+ {+ id: "b",+ name: "b.png",+ mimeType: "image/png",+ sizeBytes: 1,+ dataUrl: "data:image/png;base64,Yg==",+ },+ ]);+ expect(readFileAsDataUrl).toHaveBeenCalledTimes(2);+ expect(readFileAsDataUrl).toHaveBeenNthCalledWith(2, b.file);++ expect(await serializeComposerImages([a], second)).toEqual(first);+ expect(await serializeComposerImages([], second)).toEqual([]);+ expect(readFileAsDataUrl).toHaveBeenCalledTimes(2);+ });++ it("preserves cached bytes without trying to read an unavailable file", async () => {+ const a = image("a");+ const persisted = {+ id: a.id,+ name: a.name,+ mimeType: a.mimeType,+ sizeBytes: a.sizeBytes,+ dataUrl: "data:image/png;base64,YQ==",+ };+ vi.mocked(readFileAsDataUrl).mockRejectedValue(new Error("File is unavailable"));++ expect(await serializeComposerImages([a], [persisted])).toEqual([persisted]);+ expect(readFileAsDataUrl).not.toHaveBeenCalled();+ });++ it("omits failed uncached reads while keeping successfully serialized images", async () => {+ const a = image("a");+ const b = image("b");+ vi.mocked(readFileAsDataUrl)+ .mockRejectedValueOnce(new Error("File is unavailable"))+ .mockResolvedValueOnce("data:image/png;base64,Yg==");++ expect(await serializeComposerImages([a, b], [])).toEqual([+ {+ id: "b",+ name: "b.png",+ mimeType: "image/png",+ sizeBytes: 1,+ dataUrl: "data:image/png;base64,Yg==",+ },+ ]);+ expect(readFileAsDataUrl).toHaveBeenCalledTimes(2);+ });+});diff --git a/apps/web/src/components/chat/composerImagePersistence.ts b/apps/web/src/components/chat/composerImagePersistence.tsnew file mode 100644index 00000000000..ad189b5224c--- /dev/null+++ b/apps/web/src/components/chat/composerImagePersistence.ts@@ -0,0 +1,37 @@+import type {+ ComposerImageAttachment,+ PersistedComposerImageAttachment,+} from "../../composerDraftStore";+import { readFileAsDataUrl } from "../../lib/imageCompression";++export async function serializeComposerImages(+ images: ReadonlyArray<ComposerImageAttachment>,+ persistedAttachments: ReadonlyArray<PersistedComposerImageAttachment>,+): Promise<PersistedComposerImageAttachment[]> {+ const existingPersistedById = new Map(+ persistedAttachments.map((attachment) => [attachment.id, attachment]),+ );+ const stagedAttachmentById = new Map<string, PersistedComposerImageAttachment>();+ await Promise.all(+ images.map(async (image) => {+ try {+ const dataUrl =+ existingPersistedById.get(image.id)?.dataUrl ?? (await readFileAsDataUrl(image.file));+ stagedAttachmentById.set(image.id, {+ id: image.id,+ name: image.name,+ mimeType: image.mimeType,+ sizeBytes: image.sizeBytes,+ dataUrl,+ ...(image.source ? { source: image.source } : {}),+ });+ } catch {+ const existingPersisted = existingPersistedById.get(image.id);+ if (existingPersisted) {+ stagedAttachmentById.set(image.id, existingPersisted);+ }+ }+ }),+ );+ return Array.from(stagedAttachmentById.values());+}