@devries-cameron20 / t3code Mirror · read-only / commits / 0cd6a73433
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 19:45 UTC

fix(web): pasting an image the draft already has no longer flashes a preparing tile (#35265)

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

Srijan Dubey committed Nov 12, 2026 at 23:08 UTC 0cd6a73433c3b9c1e328560d591fd297e72d7ef9
8 files changed +191 -20
apps/web/src/components/chat/ChatComposer.tsx
+3 -1
@@ -698,7 +698,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
698 uncommittedSnapShotIds,
699 standaloneComposerImages,
700 } = useComposerImageGroups(attachmentDraftTarget, composerImages, composerPreviewAnnotations);
701 - const preparingComposerImages = usePreparingComposerImages(attachmentTargetKey);
701 + const preparingComposerImages = usePreparingComposerImages(attachmentTargetKey).filter(
702 + (image) => !image.hidden,
703 + );
704 const nonPersistedComposerImageIds = attachmentDraft.nonPersistedImageIds;
705 const uploadsByImageId = useAttachmentUploadStore((state) => state.uploadsByImageId);
706 const openPrLink = useOpenPrLink(routeThreadRef);
apps/web/src/components/chat/composerAttachmentFiles.ts
+22
@@ -61,6 +61,28 @@ export function normalizeComposerImageFileMimeType(file: File): File {
61 });
62 }
63
64 +export function composerImageDedupKey(
65 + image: Pick<ComposerImageAttachment, "mimeType" | "sizeBytes" | "name">,
66 +): string {
67 + // Hydrated images get fresh lastModified values, so exclude it from dedupe.
68 + return `${image.mimeType}\u0000${image.sizeBytes}\u0000${image.name}`;
69 +}
70 +
71 +// Compression changes an image's bytes, so a compressed image answers for the file it came from.
72 +const composerImageSourceKeys = new WeakMap<File, string>();
73 +
74 +/** The draft store's image dedupe key, taken from the file as pasted rather than as compressed. */
75 +export function composerImageSourceKey(file: File): string {
76 + return (
77 + composerImageSourceKeys.get(file) ??
78 + composerImageDedupKey({ mimeType: file.type, sizeBytes: file.size, name: file.name || "image" })
79 + );
80 +}
81 +
82 +export function rememberComposerImageSource(source: File, prepared: File): void {
83 + if (prepared !== source) composerImageSourceKeys.set(prepared, composerImageSourceKey(source));
84 +}
85 +
86 function isDngFile(file: Pick<File, "name" | "type">): boolean {
87 const mimeType = file.type.split(";", 1)[0]?.trim().toLowerCase();
88 return (
apps/web/src/components/chat/preparingComposerImages.ts
+9 -1
@@ -5,6 +5,8 @@ export interface PreparingComposerImage {
5 readonly name: string;
6 /** The uncompressed source, thumbnailed so the placeholder shows the image itself. */
7 readonly file: File;
8 + /** Looks like an image the draft already has: it holds its slot but shows no tile. */
9 + readonly hidden: boolean;
10 }
11
12 const NO_PREPARING_IMAGES: ReadonlyArray<PreparingComposerImage> = [];
@@ -24,8 +26,14 @@ export function usePreparingComposerImages(targetKey: string) {
26 );
27 }
28
29 +export function getPreparingComposerImages(
30 + targetKey: string,
31 +): ReadonlyArray<PreparingComposerImage> {
32 + return usePreparingComposerImageStore.getState().byTargetKey[targetKey] ?? NO_PREPARING_IMAGES;
33 +}
34 +
35 export function countPreparingComposerImages(targetKey: string): number {
28 - return usePreparingComposerImageStore.getState().byTargetKey[targetKey]?.length ?? 0;
36 + return getPreparingComposerImages(targetKey).length;
37 }
38
39 export function addPreparingComposerImages(
apps/web/src/components/chat/useComposerAttachmentIntake.browser.test.tsx new
+125
@@ -0,0 +1,125 @@
1 +import { useEffect } from "react";
2 +import { ThreadId } from "@t3tools/contracts";
3 +import { expect, it, vi } from "vite-plus/test";
4 +
5 +import { act, render } from "../../../test/render";
6 +import {
7 + type ComposerImageAttachment,
8 + DraftId,
9 + useComposerDraftStore,
10 +} from "../../composerDraftStore";
11 +import { getPreparingComposerImages } from "./preparingComposerImages";
12 +import { useComposerAttachmentIntake } from "./useComposerAttachmentIntake";
13 +
14 +const compression = vi.hoisted(() => ({ prepare: vi.fn() }));
15 +vi.mock("../../lib/imageCompression", async (importOriginal) => ({
16 + ...(await importOriginal<typeof import("../../lib/imageCompression")>()),
17 + prepareImageForAttachment: compression.prepare,
18 +}));
19 +
20 +type IntakeInput = Parameters<typeof useComposerAttachmentIntake>[0];
21 +type Intake = ReturnType<typeof useComposerAttachmentIntake>;
22 +
23 +function Harness({ input, ready }: { input: IntakeInput; ready: (value: Intake) => void }) {
24 + const intake = useComposerAttachmentIntake(input);
25 + useEffect(() => ready(intake));
26 + return null;
27 +}
28 +
29 +function deferred<T>() {
30 + let resolve!: (value: T) => void;
31 + const promise = new Promise<T>((fulfill) => {
32 + resolve = fulfill;
33 + });
34 + return { promise, resolve };
35 +}
36 +
37 +// A clipboard image arrives as a new File named image.png on every paste.
38 +const pastedImage = (fill = 0) =>
39 + new File([new Uint8Array(100).fill(fill)], "image.png", { type: "image/png" });
40 +// Compression shrinks an image, so the draft's copy no longer matches the pasted bytes; images
41 +// with different pixels compress to different sizes.
42 +const compress = async (source: File) => {
43 + const [firstByte = 0] = new Uint8Array(await source.arrayBuffer());
44 + return {
45 + ok: true as const,
46 + file: new File([new Uint8Array(60 + firstByte)], "image.png", { type: "image/png" }),
47 + recompressed: true as const,
48 + };
49 +};
50 +const visiblePreparing = (targetKey: string) =>
51 + getPreparingComposerImages(targetKey).filter((image) => !image.hidden);
52 +
53 +it("prepares a repeated paste without a tile, and still keeps a different image", async () => {
54 + const target = DraftId.make("intake-repeat-paste");
55 + const store = useComposerDraftStore.getState();
56 + using _draft = { [Symbol.dispose]: () => store.clearComposerContent(target) };
57 + const firstCompression = deferred<void>();
58 + compression.prepare
59 + .mockReset()
60 + .mockImplementationOnce(async (file: File) => {
61 + await firstCompression.promise;
62 + return compress(file);
63 + })
64 + .mockImplementation(compress);
65 + const composerImagesRef = { current: [] as ComposerImageAttachment[] };
66 + const addImages = (images: ComposerImageAttachment[]) => {
67 + const ids = store.addImages(target, images);
68 + composerImagesRef.current =
69 + useComposerDraftStore.getState().getComposerDraft(target)?.images ?? [];
70 + return ids;
71 + };
72 + const input = {
73 + activeThreadId: ThreadId.make("thread"),
74 + activePendingProgress: null,
75 + activePendingIsResponding: false,
76 + pendingUserInputs: [],
77 + supportsQuestionAttachments: false,
78 + isLiteralPendingAnswer: false,
79 + projectSelectionRequired: false,
80 + questionAttachmentTarget: null,
81 + attachmentTargetKey: target,
82 + fileStagingLimit: null,
83 + promptRef: { current: "" },
84 + composerImagesRef,
85 + composerFilesRef: { current: [] },
86 + composerEditorRef: { current: null },
87 + isRevertingCheckpointRef: { current: false },
88 + setThreadError: () => {},
89 + countReservedAttachments: () =>
90 + composerImagesRef.current.length + getPreparingComposerImages(target).length,
91 + addComposerImage: (image) => addImages([image]),
92 + addComposerImagesToDraft: addImages,
93 + addComposerFilesToDraft: () => [],
94 + removeComposerImageFromDraft: () => {},
95 + insertAttachmentReferences: () => false,
96 + } satisfies IntakeInput;
97 + let intake!: Intake;
98 + await using _screen = await render(
99 + <Harness
100 + input={input}
101 + ready={(value) => {
102 + intake = value;
103 + }}
104 + />,
105 + );
106 +
107 + const first = intake.addComposerAttachments([pastedImage()]);
108 + const whileCompressing = intake.addComposerAttachments([pastedImage()]);
109 + expect(visiblePreparing(target)).toHaveLength(1);
110 + await act(async () => {
111 + firstCompression.resolve();
112 + await Promise.all([first, whileCompressing]);
113 + });
114 +
115 + const afterCompression = intake.addComposerAttachments([pastedImage()]);
116 + expect(visiblePreparing(target)).toHaveLength(0);
117 + await act(() => afterCompression);
118 + expect(composerImagesRef.current).toHaveLength(1);
119 +
120 + // Same name, type and size, different pixels: it compresses differently and is kept.
121 + const different = intake.addComposerAttachments([pastedImage(7)]);
122 + expect(visiblePreparing(target)).toHaveLength(0);
123 + await act(() => different);
124 + expect(composerImagesRef.current).toHaveLength(2);
125 +});
apps/web/src/components/chat/useComposerAttachmentIntake.ts
+18 -6
@@ -26,7 +26,9 @@ import {
26 import {
27 classifyComposerAttachmentFile,
28 composerFileAttachmentMimeType,
29 + composerImageSourceKey,
30 normalizeComposerImageFileMimeType,
31 + rememberComposerImageSource,
32 } from "./composerAttachmentFiles";
33 import {
34 fileAttachmentTooLargeMessage,
@@ -48,6 +50,7 @@ import { toastManager } from "../ui/toast";
50 import { type RefObject, useRef } from "react";
51 import {
52 addPreparingComposerImages,
53 + getPreparingComposerImages,
54 isPreparingComposerImage,
55 removePreparingComposerImages,
56 } from "./preparingComposerImages";
@@ -241,13 +244,21 @@ export function useComposerAttachmentIntake(input: {
244 }
245 if (acceptedImages.length === 0) return insertedAny;
246
247 + // The store drops a repeated image only after compressing it, so a likely repeat prepares
248 + // without a tile instead of flashing one. Only the store decides it is a duplicate.
249 + const imageSourceKeys = new Set(
250 + [...composerImagesRef.current, ...getPreparingComposerImages(attachmentTargetKey)].map(
251 + (image) => composerImageSourceKey(image.file),
252 + ),
253 + );
254 // The draft image reuses its placeholder's id and thumbnail so the strip tile stays exactly
255 // as it is when the compressed file replaces it.
246 - const preparingImages = acceptedImages.map((file) => ({
247 - id: randomUUID(),
248 - name: file.name || "image",
249 - file,
250 - }));
256 + const preparingImages = acceptedImages.map((file) => {
257 + const sourceKey = composerImageSourceKey(file);
258 + const hidden = imageSourceKeys.has(sourceKey);
259 + imageSourceKeys.add(sourceKey);
260 + return { id: randomUUID(), name: file.name || "image", file, hidden };
261 + });
262 addPreparingComposerImages(attachmentTargetKey, preparingImages);
263 if (questionAttachmentTarget)
264 changeQuestionAttachmentPreparation(questionAttachmentTarget, acceptedImages.length);
@@ -272,7 +283,8 @@ export function useComposerAttachmentIntake(input: {
283 );
284 continue;
285 }
275 - inheritComposerImageThumbnail(file, result.file);
286 + await inheritComposerImageThumbnail(file, result.file);
287 + rememberComposerImageSource(file, result.file);
288 compressed.push({ id, file: result.file });
289 }
290 const questionDiscarded =
apps/web/src/composerDraftStore.ts
+4 -6
@@ -1,5 +1,8 @@
1 import { stripInlineContextReferences } from "./lib/composerContextReferences";
2 -import { composerFileAttachmentMimeType } from "./components/chat/composerAttachmentFiles";
2 +import {
3 + composerFileAttachmentMimeType,
4 + composerImageDedupKey,
5 +} from "./components/chat/composerAttachmentFiles";
6 import { elementContextToPreviewAnnotation } from "./lib/elementContext";
7 import {
8 ResponseContextRecord,
@@ -907,11 +910,6 @@ function createEmptyThreadDraft(): ComposerThreadDraftState {
910 };
911 }
912
910 -function composerImageDedupKey(image: ComposerImageAttachment): string {
911 - // Hydrated images get fresh lastModified values, so exclude it from dedupe.
912 - return `${image.mimeType}\u0000${image.sizeBytes}\u0000${image.name}`;
913 -}
914 -
913 export function composerFileDedupKey(
914 file: Pick<ComposerFileAttachment, "mimeType" | "sizeBytes" | "name">,
915 ): string {
apps/web/src/lib/imageCompression.test.ts
+5 -3
@@ -254,11 +254,13 @@ describe("composer image thumbnails", () => {
254 stubCanvasPipeline(() => 3);
255 const source = makeFile(3);
256 const compressed = makeFile(2, "image/webp");
257 - const sourceThumbnail = await createComposerImageThumbnail(source);
258 - expect(sourceThumbnail).toMatch(/^data:image\/png;base64,/);
257 + // Compression can finish before the placeholder's thumbnail does.
258 + const pendingThumbnail = createComposerImageThumbnail(source);
259
260 - inheritComposerImageThumbnail(source, compressed);
260 + await inheritComposerImageThumbnail(source, compressed);
261
262 + const sourceThumbnail = await pendingThumbnail;
263 + expect(sourceThumbnail).toMatch(/^data:image\/png;base64,/);
264 expect(readComposerImageThumbnail(compressed)).toBe(sourceThumbnail);
265 expect(await createComposerImageThumbnail(compressed)).toBe(sourceThumbnail);
266 expect(createImageBitmap).toHaveBeenCalledTimes(1);
apps/web/src/lib/imageCompression.ts
+5 -3
@@ -227,16 +227,18 @@ export function createComposerImageThumbnail(file: File): Promise<string | null>
227 /**
228 * Pasted images are re-encoded after their placeholder already shows the source's thumbnail.
229 * Reusing it keeps the tile from flashing back to its fallback while the new file is decoded.
230 + * Resolves once the target's thumbnail is readable, so a tile swapped to it paints at once even
231 + * when compression finished before the source's thumbnail did.
232 */
231 -export function inheritComposerImageThumbnail(source: File, target: File): void {
233 +export async function inheritComposerImageThumbnail(source: File, target: File): Promise<void> {
234 const sourceThumbnail = composerThumbnails.get(source);
235 if (source === target || !sourceThumbnail || composerThumbnails.has(target)) return;
234 - const settled = settledComposerThumbnails.get(source);
235 - if (settled) settledComposerThumbnails.set(target, settled);
236 cacheComposerImageThumbnail(
237 target,
238 sourceThumbnail.then((src) => src ?? renderComposerImageThumbnail(target)),
239 );
240 + const src = await sourceThumbnail;
241 + if (src) settledComposerThumbnails.set(target, src);
242 }
243
244 async function renderComposerImageThumbnail(file: File): Promise<string | null> {