From f581f707d55622fa732dd94298b76941945134b4 Mon Sep 17 00:00:00 2001 From: Muzammil Hussain <58479501+Muzammil-Bit@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:01:33 +0500 Subject: [PATCH 01/11] fix(web): sending during image compression waits instead of toasting Fixes #36143 Co-Authored-By: Claude Opus 5.5 --- apps/web/src/components/chat/ChatComposer.tsx | 16 ++- .../preparingComposerImages.browser.test.tsx | 97 +++++++++++++++++++ .../chat/preparingComposerImages.ts | 27 ++++++ 3 files changed, 131 insertions(+), 9 deletions(-) create mode 100644 apps/web/src/components/chat/preparingComposerImages.browser.test.tsx diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 69250e47b89c3..491b63bf4e64d 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -285,6 +285,7 @@ import { useComposerAttachmentIntake } from "./useComposerAttachmentIntake"; import { countPreparingComposerImages, usePreparingComposerImages, + useSubmitAfterPreparingImages, } from "./preparingComposerImages"; import { ComposerControlsBar } from "./ComposerControlsBar"; import { composerCommandKeyHandler } from "./composerCommandKey"; @@ -712,6 +713,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const preparingComposerImages = usePreparingComposerImages(attachmentTargetKey).filter( (image) => !image.hidden, ); + const submitAfterPreparingImages = useSubmitAfterPreparingImages(attachmentTargetKey); const nonPersistedComposerImageIds = attachmentDraft.nonPersistedImageIds; const uploadsByImageId = useAttachmentUploadStore((state) => state.uploadsByImageId); const openPrLink = useOpenPrLink(routeThreadRef); @@ -2184,16 +2186,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) event?.preventDefault(); return false; } - // A send while a pasted image is still compressing would strand that image: - // the turn snapshot wouldn't include it, and it would surface in the *next* - // draft instead. - if (activeThreadId && countPreparingComposerImages(attachmentTargetKey) > 0) { + // Sending now would leave a still-compressing image out of the turn, so wait for it. + if ( + activeThreadId && + submitAfterPreparingImages(() => submitComposerRef.current(dispatchMode, submissionIntent)) + ) { event?.preventDefault(); - toastManager.add({ - type: "info", - title: "Still compressing a pasted image.", - description: "Send again once its thumbnail appears.", - }); return false; } if (pendingDraftWork.has(attachmentTargetKey)) { diff --git a/apps/web/src/components/chat/preparingComposerImages.browser.test.tsx b/apps/web/src/components/chat/preparingComposerImages.browser.test.tsx new file mode 100644 index 0000000000000..dc9f024caaa47 --- /dev/null +++ b/apps/web/src/components/chat/preparingComposerImages.browser.test.tsx @@ -0,0 +1,97 @@ +import { useEffect } from "react"; +import { expect, it, vi } from "vite-plus/test"; +import { create } from "zustand"; + +import { act, render } from "../../../test/render"; +import { + addPreparingComposerImages, + cancelPreparingComposerImages, + removePreparingComposerImages, + useSubmitAfterPreparingImages, +} from "./preparingComposerImages"; + +type QueueSubmit = ReturnType; + +const useDraftImages = create<{ readonly ids: ReadonlyArray }>(() => ({ ids: [] })); + +// Mirrors ChatComposer: the send reads draft images that a later effect syncs from the store. +function Probe(props: { + targetKey: string; + onReady: (queue: QueueSubmit) => void; + onCommit?: (images: ReadonlyArray) => void; +}) { + const queue = useSubmitAfterPreparingImages(props.targetKey); + const draftImages = useDraftImages((state) => state.ids); + const { onCommit } = props; + useEffect(() => { + onCommit?.(draftImages); + }, [onCommit, draftImages]); + props.onReady(queue); + return null; +} + +function preparingImage(id: string) { + return { id, name: `${id}.png`, file: new File(["png"], `${id}.png`), hidden: false }; +} + +it("sends after pasted images finish compressing, with the compressed image in the draft", async () => { + const target = "submit-after-preparing"; + using _store = { + [Symbol.dispose]: () => { + cancelPreparingComposerImages(target); + useDraftImages.setState({ ids: [] }); + }, + }; + let queueSubmit: QueueSubmit | undefined; + let committedImages: ReadonlyArray = []; + await using _screen = await render( + { + committedImages = images; + }} + onReady={(queue) => { + queueSubmit = queue; + }} + />, + // A bare hook probe; nothing here navigates. + { router: false }, + ); + const submit = vi.fn(() => committedImages); + + expect(queueSubmit?.(submit)).toBe(false); + + addPreparingComposerImages(target, [preparingImage("first"), preparingImage("second")]); + expect(queueSubmit?.(submit)).toBe(true); + + await act(() => removePreparingComposerImages(target, new Set(["first"]))); + expect(submit).not.toHaveBeenCalled(); + + // Intake drops the placeholder and adds the compressed image in the same tick. + await act(() => { + removePreparingComposerImages(target, new Set(["second"])); + useDraftImages.setState({ ids: ["second"] }); + }); + expect(submit).toHaveBeenCalledOnce(); + expect(submit.mock.results[0]?.value).toEqual(["second"]); +}); + +it("drops a waiting send when the composer moves to another draft", async () => { + const target = "submit-after-preparing-old"; + using _store = { [Symbol.dispose]: () => cancelPreparingComposerImages(target) }; + let queueSubmit: QueueSubmit | undefined; + const onReady = (queue: QueueSubmit) => { + queueSubmit = queue; + }; + await using screen = await render(, { + // A bare hook probe; nothing here navigates. + router: false, + }); + const submit = vi.fn(); + addPreparingComposerImages(target, [preparingImage("pasted")]); + expect(queueSubmit?.(submit)).toBe(true); + + await screen.rerender(); + await act(() => removePreparingComposerImages(target, new Set(["pasted"]))); + expect(submit).not.toHaveBeenCalled(); +}); diff --git a/apps/web/src/components/chat/preparingComposerImages.ts b/apps/web/src/components/chat/preparingComposerImages.ts index 0e571510f764b..7d652b80c82e3 100644 --- a/apps/web/src/components/chat/preparingComposerImages.ts +++ b/apps/web/src/components/chat/preparingComposerImages.ts @@ -1,5 +1,8 @@ +import { useEffect, useRef } from "react"; import { create } from "zustand"; +import { useStableCallback } from "../../hooks/useStableCallback"; + export interface PreparingComposerImage { readonly id: string; readonly name: string; @@ -91,3 +94,27 @@ export function cancelPreparingComposerImages(targetKey: string): void { return { byTargetKey }; }); } + +/** + * Holds a send made while the target still has images compressing, and runs it once they finish, + * so the turn includes them. Returns false when nothing is compressing and the caller should send. + */ +export function useSubmitAfterPreparingImages(targetKey: string) { + const preparing = usePreparingComposerImages(targetKey); + const pendingRef = useRef<{ readonly targetKey: string; readonly submit: () => void } | null>( + null, + ); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- sends only after the render where the compressed images joined the draft + useEffect(() => { + const pending = pendingRef.current; + if (!pending || preparing.length > 0) return; + pendingRef.current = null; + // After the composer's later effects have synced its draft refs to this render. + if (pending.targetKey === targetKey) queueMicrotask(pending.submit); + }, [preparing, targetKey]); + return useStableCallback((submit: () => void) => { + if (countPreparingComposerImages(targetKey) === 0) return false; + pendingRef.current = { targetKey, submit }; + return true; + }); +} From 47d0946c1c7cfb73c33d4bd428f934f452c11772 Mon Sep 17 00:00:00 2001 From: Muzammil Hussain <58479501+Muzammil-Bit@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:11:55 +0500 Subject: [PATCH 02/11] fix(web): drop a held send when switching to a draft still compressing Co-Authored-By: Claude Opus 5.5 --- .../chat/preparingComposerImages.browser.test.tsx | 13 +++++++++++-- .../src/components/chat/preparingComposerImages.ts | 9 +++++++-- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/apps/web/src/components/chat/preparingComposerImages.browser.test.tsx b/apps/web/src/components/chat/preparingComposerImages.browser.test.tsx index dc9f024caaa47..114751d034200 100644 --- a/apps/web/src/components/chat/preparingComposerImages.browser.test.tsx +++ b/apps/web/src/components/chat/preparingComposerImages.browser.test.tsx @@ -78,7 +78,13 @@ it("sends after pasted images finish compressing, with the compressed image in t it("drops a waiting send when the composer moves to another draft", async () => { const target = "submit-after-preparing-old"; - using _store = { [Symbol.dispose]: () => cancelPreparingComposerImages(target) }; + const otherTarget = "submit-after-preparing-new"; + using _store = { + [Symbol.dispose]: () => { + cancelPreparingComposerImages(target); + cancelPreparingComposerImages(otherTarget); + }, + }; let queueSubmit: QueueSubmit | undefined; const onReady = (queue: QueueSubmit) => { queueSubmit = queue; @@ -91,7 +97,10 @@ it("drops a waiting send when the composer moves to another draft", async () => addPreparingComposerImages(target, [preparingImage("pasted")]); expect(queueSubmit?.(submit)).toBe(true); - await screen.rerender(); + // The other draft is still compressing too, so the switch alone must drop the send. + addPreparingComposerImages(otherTarget, [preparingImage("other")]); + await screen.rerender(); await act(() => removePreparingComposerImages(target, new Set(["pasted"]))); + await screen.rerender(); expect(submit).not.toHaveBeenCalled(); }); diff --git a/apps/web/src/components/chat/preparingComposerImages.ts b/apps/web/src/components/chat/preparingComposerImages.ts index 7d652b80c82e3..158a5bfa0dc0d 100644 --- a/apps/web/src/components/chat/preparingComposerImages.ts +++ b/apps/web/src/components/chat/preparingComposerImages.ts @@ -107,10 +107,15 @@ export function useSubmitAfterPreparingImages(targetKey: string) { // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- sends only after the render where the compressed images joined the draft useEffect(() => { const pending = pendingRef.current; - if (!pending || preparing.length > 0) return; + if (!pending) return; + if (pending.targetKey !== targetKey) { + pendingRef.current = null; + return; + } + if (preparing.length > 0) return; pendingRef.current = null; // After the composer's later effects have synced its draft refs to this render. - if (pending.targetKey === targetKey) queueMicrotask(pending.submit); + queueMicrotask(pending.submit); }, [preparing, targetKey]); return useStableCallback((submit: () => void) => { if (countPreparingComposerImages(targetKey) === 0) return false; From d49555ba56b0459ac9b9e3351f9085e434b5d37e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 16 Nov 2026 07:18:11 +0000 Subject: [PATCH 03/11] fix(web): a discarded draft no longer releases its held send as a resume Co-Authored-By: Claude Opus 5.5 --- apps/web/src/components/chat/ChatComposer.tsx | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 491b63bf4e64d..b1ce6dbabb6b8 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -2172,6 +2172,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const submitComposerRef = useRef< (dispatchMode?: ComposerDispatchMode, submissionIntent?: ComposerSubmissionIntent) => void >(() => {}); + // A discarded draft also ends compression; its held send must not turn into a resume. + const submitHeldComposer = useStableCallback( + (dispatchMode?: ComposerDispatchMode, submissionIntent?: ComposerSubmissionIntent) => { + if (composerDraftHasUserContent(composerDraft)) { + submitComposerRef.current(dispatchMode, submissionIntent); + } + }, + ); const submitComposer = ( event?: { preventDefault: () => void }, dispatchMode?: ComposerDispatchMode, @@ -2189,7 +2197,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) // Sending now would leave a still-compressing image out of the turn, so wait for it. if ( activeThreadId && - submitAfterPreparingImages(() => submitComposerRef.current(dispatchMode, submissionIntent)) + submitAfterPreparingImages(() => submitHeldComposer(dispatchMode, submissionIntent)) ) { event?.preventDefault(); return false; From 2208f3e584ee57487f6d6454793bcf2f88f72742 Mon Sep 17 00:00:00 2001 From: Muzammil Hussain <58479501+Muzammil-Bit@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:22:53 +0500 Subject: [PATCH 04/11] test(web): keep the draft image store local to each test Co-Authored-By: Claude Opus 5.5 --- .../preparingComposerImages.browser.test.tsx | 42 ++++++++++++------- 1 file changed, 26 insertions(+), 16 deletions(-) diff --git a/apps/web/src/components/chat/preparingComposerImages.browser.test.tsx b/apps/web/src/components/chat/preparingComposerImages.browser.test.tsx index 114751d034200..716f0ce9acba6 100644 --- a/apps/web/src/components/chat/preparingComposerImages.browser.test.tsx +++ b/apps/web/src/components/chat/preparingComposerImages.browser.test.tsx @@ -1,6 +1,6 @@ import { useEffect } from "react"; import { expect, it, vi } from "vite-plus/test"; -import { create } from "zustand"; +import { createStore, type StoreApi, useStore } from "zustand"; import { act, render } from "../../../test/render"; import { @@ -12,16 +12,21 @@ import { type QueueSubmit = ReturnType; -const useDraftImages = create<{ readonly ids: ReadonlyArray }>(() => ({ ids: [] })); +type DraftImagesStore = StoreApi<{ readonly ids: ReadonlyArray }>; + +function createDraftImagesStore(): DraftImagesStore { + return createStore(() => ({ ids: [] })); +} // Mirrors ChatComposer: the send reads draft images that a later effect syncs from the store. function Probe(props: { targetKey: string; + draftImagesStore: DraftImagesStore; onReady: (queue: QueueSubmit) => void; onCommit?: (images: ReadonlyArray) => void; }) { const queue = useSubmitAfterPreparingImages(props.targetKey); - const draftImages = useDraftImages((state) => state.ids); + const draftImages = useStore(props.draftImagesStore, (state) => state.ids); const { onCommit } = props; useEffect(() => { onCommit?.(draftImages); @@ -36,17 +41,14 @@ function preparingImage(id: string) { it("sends after pasted images finish compressing, with the compressed image in the draft", async () => { const target = "submit-after-preparing"; - using _store = { - [Symbol.dispose]: () => { - cancelPreparingComposerImages(target); - useDraftImages.setState({ ids: [] }); - }, - }; + using _store = { [Symbol.dispose]: () => cancelPreparingComposerImages(target) }; + const draftImagesStore = createDraftImagesStore(); let queueSubmit: QueueSubmit | undefined; let committedImages: ReadonlyArray = []; await using _screen = await render( { committedImages = images; }} @@ -70,7 +72,7 @@ it("sends after pasted images finish compressing, with the compressed image in t // Intake drops the placeholder and adds the compressed image in the same tick. await act(() => { removePreparingComposerImages(target, new Set(["second"])); - useDraftImages.setState({ ids: ["second"] }); + draftImagesStore.setState({ ids: ["second"] }); }); expect(submit).toHaveBeenCalledOnce(); expect(submit.mock.results[0]?.value).toEqual(["second"]); @@ -85,22 +87,30 @@ it("drops a waiting send when the composer moves to another draft", async () => cancelPreparingComposerImages(otherTarget); }, }; + const draftImagesStore = createDraftImagesStore(); let queueSubmit: QueueSubmit | undefined; const onReady = (queue: QueueSubmit) => { queueSubmit = queue; }; - await using screen = await render(, { - // A bare hook probe; nothing here navigates. - router: false, - }); + await using screen = await render( + , + { + // A bare hook probe; nothing here navigates. + router: false, + }, + ); const submit = vi.fn(); addPreparingComposerImages(target, [preparingImage("pasted")]); expect(queueSubmit?.(submit)).toBe(true); // The other draft is still compressing too, so the switch alone must drop the send. addPreparingComposerImages(otherTarget, [preparingImage("other")]); - await screen.rerender(); + await screen.rerender( + , + ); await act(() => removePreparingComposerImages(target, new Set(["pasted"]))); - await screen.rerender(); + await screen.rerender( + , + ); expect(submit).not.toHaveBeenCalled(); }); From 89b1434c89fad67db8a99d006346de0a312b129f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 16 Nov 2026 07:31:06 +0000 Subject: [PATCH 05/11] fix(mobile): a send during a native image paste goes out once the image joins the draft Co-Authored-By: Claude Opus 5.5 --- .../src/features/threads/ThreadComposer.tsx | 27 ++++++++++++++----- 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx index b1f2553618dca..8c213d5d5668b 100644 --- a/apps/mobile/src/features/threads/ThreadComposer.tsx +++ b/apps/mobile/src/features/threads/ThreadComposer.tsx @@ -261,6 +261,9 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps const [isFocused, setIsFocused] = useState(false); const pendingPastedTextAttachmentCountRef = useRef(0); const pendingNativeImagePasteCountRef = useRef(0); + type HeldSend = { readonly draftKey: string; readonly followUp?: ActiveTurnComposerAction }; + const heldSendRef = useRef(null); + const [releasedSend, setReleasedSend] = useState(null); const [pendingPastedTextAttachmentCount, setPendingPastedTextAttachmentCount] = useState(0); const settingsRoutePresentedRef = useRef(false); const settingsSheetPresentation = useThreadSettingsSheetPresentation({ @@ -524,13 +527,13 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps onEditorFocusChange?.(false); }; const handleSend = async (followUp?: ActiveTurnComposerAction) => { - if ( - isSubmissionLocked || - sendBlockedReason !== null || - pendingPastedTextAttachmentCountRef.current > 0 || - pendingNativeImagePasteCountRef.current > 0 - ) + if (isSubmissionLocked || sendBlockedReason !== null) return; + // Sending now would leave a still-converting pasted image out of the turn, so wait for it. + if (pendingNativeImagePasteCountRef.current > 0) { + heldSendRef.current = { draftKey: composerDraftKey, followUp }; return; + } + if (pendingPastedTextAttachmentCountRef.current > 0) return; if (usageLimitsOffered && isUsageLimitsCommand(draftMessage) && draftAttachments.length === 0) { if (openUsageLimits()) onChangeDraftMessage(""); return; @@ -567,6 +570,14 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps }); }; + const sendReleased = useEffectEvent((held: HeldSend) => { + if (held.draftKey === composerDraftKey) void handleSend(held.followUp); + }); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- sends from the render where the pasted images joined the draft + useEffect(() => { + if (releasedSend) sendReleased(releasedSend); + }, [releasedSend]); + const lockedProviderInstanceId = props.canSwitchProvider ? undefined : currentModelSelection.instanceId; @@ -854,6 +865,10 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps pendingNativeImagePasteCountRef.current += 1; void props.onNativePasteImages(uris).finally(() => { pendingNativeImagePasteCountRef.current -= 1; + if (pendingNativeImagePasteCountRef.current > 0) return; + const held = heldSendRef.current; + heldSendRef.current = null; + if (held) setReleasedSend(held); }); }} onPasteText={(paste) => { From bc8b198474669897af23c3a503e88553d233ddee Mon Sep 17 00:00:00 2001 From: Muzammil Hussain <58479501+Muzammil-Bit@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:29:52 +0500 Subject: [PATCH 06/11] fix(web): discarding a draft cancels its held send, answers still send Co-Authored-By: Claude Opus 5.5 --- apps/web/src/components/chat/ChatComposer.tsx | 10 +------- .../preparingComposerImages.browser.test.tsx | 8 ++++++- .../chat/preparingComposerImages.ts | 23 +++++++++++++++---- 3 files changed, 26 insertions(+), 15 deletions(-) diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index b1ce6dbabb6b8..491b63bf4e64d 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -2172,14 +2172,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const submitComposerRef = useRef< (dispatchMode?: ComposerDispatchMode, submissionIntent?: ComposerSubmissionIntent) => void >(() => {}); - // A discarded draft also ends compression; its held send must not turn into a resume. - const submitHeldComposer = useStableCallback( - (dispatchMode?: ComposerDispatchMode, submissionIntent?: ComposerSubmissionIntent) => { - if (composerDraftHasUserContent(composerDraft)) { - submitComposerRef.current(dispatchMode, submissionIntent); - } - }, - ); const submitComposer = ( event?: { preventDefault: () => void }, dispatchMode?: ComposerDispatchMode, @@ -2197,7 +2189,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) // Sending now would leave a still-compressing image out of the turn, so wait for it. if ( activeThreadId && - submitAfterPreparingImages(() => submitHeldComposer(dispatchMode, submissionIntent)) + submitAfterPreparingImages(() => submitComposerRef.current(dispatchMode, submissionIntent)) ) { event?.preventDefault(); return false; diff --git a/apps/web/src/components/chat/preparingComposerImages.browser.test.tsx b/apps/web/src/components/chat/preparingComposerImages.browser.test.tsx index 716f0ce9acba6..2ba3b6b987b43 100644 --- a/apps/web/src/components/chat/preparingComposerImages.browser.test.tsx +++ b/apps/web/src/components/chat/preparingComposerImages.browser.test.tsx @@ -78,7 +78,7 @@ it("sends after pasted images finish compressing, with the compressed image in t expect(submit.mock.results[0]?.value).toEqual(["second"]); }); -it("drops a waiting send when the composer moves to another draft", async () => { +it("drops a waiting send when the composer moves to another draft or discards it", async () => { const target = "submit-after-preparing-old"; const otherTarget = "submit-after-preparing-new"; using _store = { @@ -113,4 +113,10 @@ it("drops a waiting send when the composer moves to another draft", async () => , ); expect(submit).not.toHaveBeenCalled(); + + // Discarding the draft cancels its compression, which must not release the held send. + await act(() => addPreparingComposerImages(target, [preparingImage("discarded")])); + expect(queueSubmit?.(submit)).toBe(true); + await act(() => cancelPreparingComposerImages(target)); + expect(submit).not.toHaveBeenCalled(); }); diff --git a/apps/web/src/components/chat/preparingComposerImages.ts b/apps/web/src/components/chat/preparingComposerImages.ts index 158a5bfa0dc0d..b74be3f1bcf2c 100644 --- a/apps/web/src/components/chat/preparingComposerImages.ts +++ b/apps/web/src/components/chat/preparingComposerImages.ts @@ -85,8 +85,12 @@ export function removePreparingComposerImages( return removed; } +// Bumped on cancel so a send held for the cancelled images is dropped rather than released. +const cancelGenerations = new Map(); + /** Drops every image still preparing for the target, so its compression result is discarded. */ export function cancelPreparingComposerImages(targetKey: string): void { + cancelGenerations.set(targetKey, (cancelGenerations.get(targetKey) ?? 0) + 1); if (!usePreparingComposerImageStore.getState().byTargetKey[targetKey]) return; usePreparingComposerImageStore.setState((state) => { const byTargetKey = { ...state.byTargetKey }; @@ -101,14 +105,19 @@ export function cancelPreparingComposerImages(targetKey: string): void { */ export function useSubmitAfterPreparingImages(targetKey: string) { const preparing = usePreparingComposerImages(targetKey); - const pendingRef = useRef<{ readonly targetKey: string; readonly submit: () => void } | null>( - null, - ); + const pendingRef = useRef<{ + readonly targetKey: string; + readonly cancelGeneration: number; + readonly submit: () => void; + } | null>(null); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- sends only after the render where the compressed images joined the draft useEffect(() => { const pending = pendingRef.current; if (!pending) return; - if (pending.targetKey !== targetKey) { + if ( + pending.targetKey !== targetKey || + pending.cancelGeneration !== (cancelGenerations.get(targetKey) ?? 0) + ) { pendingRef.current = null; return; } @@ -119,7 +128,11 @@ export function useSubmitAfterPreparingImages(targetKey: string) { }, [preparing, targetKey]); return useStableCallback((submit: () => void) => { if (countPreparingComposerImages(targetKey) === 0) return false; - pendingRef.current = { targetKey, submit }; + pendingRef.current = { + targetKey, + cancelGeneration: cancelGenerations.get(targetKey) ?? 0, + submit, + }; return true; }); } From 0256bb7d5790a2614ccfa8a297843998d632de0f Mon Sep 17 00:00:00 2001 From: Muzammil Hussain <58479501+Muzammil-Bit@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:36:56 +0500 Subject: [PATCH 07/11] test(scenarios): Enter during image compression sends once it finishes Co-Authored-By: Claude Opus 5.5 --- ...uring-image-compression-sends-after.e2e.ts | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 scripts/scenarios/enter-during-image-compression-sends-after.e2e.ts diff --git a/scripts/scenarios/enter-during-image-compression-sends-after.e2e.ts b/scripts/scenarios/enter-during-image-compression-sends-after.e2e.ts new file mode 100644 index 0000000000000..72b63fd6365fb --- /dev/null +++ b/scripts/scenarios/enter-during-image-compression-sends-after.e2e.ts @@ -0,0 +1,32 @@ +import { expect } from "e2e"; + +import { + finishImageCompression, + holdImageCompression, + pasteWideScreenshot, +} from "./image-compression-hold.ts"; +import { test, WEB } from "./t3.ts"; + +test( + "Enter while a pasted image compresses sends the message with the image once it finishes", + WEB, + async ({ t3, app, browser, screen }) => { + await holdImageCompression(browser); + const project = await t3.project("demo"); + const thread = await t3.thread({ project, title: "Screenshot work", messages: ["first"] }); + await t3.open(thread); + await expect(screen.getByText("first fixture turn complete", { exact: false })).toBeVisible(); + + const composer = screen.getByRole("textbox"); + await composer.fill("What is in this screenshot?"); + await pasteWideScreenshot(browser); + await browser.keyboard.press("Enter"); + await app.screenshot("enter-while-compressing"); + + await finishImageCompression(browser); + await app.screenshot("after-compression"); + // Sent with the image: neither the prompt nor the image is left behind in the composer. + await expect(composer).not.toContainText("What is in this screenshot?"); + await expect(composer).not.toContainText("screenshot.png"); + }, +); From c25b2f5849b71cf02104cafba3dfdadbaaf7df24 Mon Sep 17 00:00:00 2001 From: Muzammil Hussain <58479501+Muzammil-Bit@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:12:14 +0500 Subject: [PATCH 08/11] test(scenarios): image-compression scenario checks the sent message has the prompt and image Co-Authored-By: Claude Opus 5.5 --- .../enter-during-image-compression-sends-after.e2e.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/scripts/scenarios/enter-during-image-compression-sends-after.e2e.ts b/scripts/scenarios/enter-during-image-compression-sends-after.e2e.ts index 72b63fd6365fb..a437b196bf995 100644 --- a/scripts/scenarios/enter-during-image-compression-sends-after.e2e.ts +++ b/scripts/scenarios/enter-during-image-compression-sends-after.e2e.ts @@ -25,7 +25,11 @@ test( await finishImageCompression(browser); await app.screenshot("after-compression"); - // Sent with the image: neither the prompt nor the image is left behind in the composer. + const conversation = screen.getByRole("region", "Conversation"); + await expect( + conversation.getByText("What is in this screenshot?", { exact: false }), + ).toBeVisible(); + await expect(conversation.getByRole("button", "Preview screenshot.png")).toBeVisible(); await expect(composer).not.toContainText("What is in this screenshot?"); await expect(composer).not.toContainText("screenshot.png"); }, From a2ec4eb333dc6765d4f397230b6149c2199d01e7 Mon Sep 17 00:00:00 2001 From: Muzammil Hussain <58479501+Muzammil-Bit@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:30:12 +0500 Subject: [PATCH 09/11] test(scenarios): image-compression scenario finds the prompt and image in one message Co-Authored-By: Claude Opus 5.5 --- .../enter-during-image-compression-sends-after.e2e.ts | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/scripts/scenarios/enter-during-image-compression-sends-after.e2e.ts b/scripts/scenarios/enter-during-image-compression-sends-after.e2e.ts index a437b196bf995..415e4288dedf4 100644 --- a/scripts/scenarios/enter-during-image-compression-sends-after.e2e.ts +++ b/scripts/scenarios/enter-during-image-compression-sends-after.e2e.ts @@ -25,11 +25,10 @@ test( await finishImageCompression(browser); await app.screenshot("after-compression"); - const conversation = screen.getByRole("region", "Conversation"); - await expect( - conversation.getByText("What is in this screenshot?", { exact: false }), - ).toBeVisible(); - await expect(conversation.getByRole("button", "Preview screenshot.png")).toBeVisible(); + const sentWithImage = browser + .locator('[data-message-role="user"]:has([aria-label="Preview screenshot.png"])') + .filter({ hasText: "What is in this screenshot?" }); + await expect(sentWithImage).toBeVisible(); await expect(composer).not.toContainText("What is in this screenshot?"); await expect(composer).not.toContainText("screenshot.png"); }, From fb15c9465f4ec2da6c381372e92c7ef98d70e004 Mon Sep 17 00:00:00 2001 From: Muzammil Hussain <58479501+Muzammil-Bit@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:35:31 +0500 Subject: [PATCH 10/11] fix(composer): retain deferred sends through attachment preparation --- .../src/features/threads/ThreadComposer.tsx | 31 ++--- .../features/threads/ThreadDetailScreen.tsx | 2 +- .../useSubmitAfterNativeImages.test.tsx | 114 ++++++++++++++++++ .../threads/useSubmitAfterNativeImages.ts | 60 +++++++++ .../state/use-composer-attachment-actions.ts | 20 +-- apps/mobile/vite.config.ts | 1 + apps/web/src/components/chat/ChatComposer.tsx | 5 +- .../preparingComposerImages.browser.test.tsx | 69 +++++++++-- .../chat/preparingComposerImages.ts | 14 ++- .../chat/useComposerAttachmentIntake.ts | 7 +- 10 files changed, 280 insertions(+), 43 deletions(-) create mode 100644 apps/mobile/src/features/threads/useSubmitAfterNativeImages.test.tsx create mode 100644 apps/mobile/src/features/threads/useSubmitAfterNativeImages.ts diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx index 8c213d5d5668b..ad7c48cf1429e 100644 --- a/apps/mobile/src/features/threads/ThreadComposer.tsx +++ b/apps/mobile/src/features/threads/ThreadComposer.tsx @@ -47,6 +47,7 @@ import { composerContextImportsAtom, countComposerDraftAttachmentsAfterSelection, useComposerDraft, + useComposerDraftResetGeneration, } from "../../state/use-composer-drafts"; import type { ComposerDocumentAttachment } from "../../lib/composerContext"; import { useProject, useVisibleThreadShells } from "../../state/entities"; @@ -100,6 +101,7 @@ import { resolveComposerSendPresentation, type ComposerSendPresentation, } from "./composerSendPresentation"; +import { useSubmitAfterNativeImages } from "./useSubmitAfterNativeImages"; import { ComposerCommandPopover } from "./ComposerCommandPopover"; import { ComposerPopoverAnchor } from "./ComposerPopoverAnchor"; import { ComposerQueuedEditAttachments } from "./ComposerQueuedEdit"; @@ -172,7 +174,7 @@ export interface ThreadComposerProps { readonly onChangeDraftMessage: (value: string) => void; readonly onPickDraftMedia: () => Promise; readonly onPickDraftFiles: () => Promise; - readonly onNativePasteImages: (uris: ReadonlyArray) => Promise; + readonly onNativePasteImages: (uris: ReadonlyArray) => Promise; readonly onNativePasteText: (paste: ComposerTextPaste) => Promise; readonly onRemoveDraftImage: (imageId: string) => void; readonly onStopThread: () => void; @@ -261,9 +263,6 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps const [isFocused, setIsFocused] = useState(false); const pendingPastedTextAttachmentCountRef = useRef(0); const pendingNativeImagePasteCountRef = useRef(0); - type HeldSend = { readonly draftKey: string; readonly followUp?: ActiveTurnComposerAction }; - const heldSendRef = useRef(null); - const [releasedSend, setReleasedSend] = useState(null); const [pendingPastedTextAttachmentCount, setPendingPastedTextAttachmentCount] = useState(0); const settingsRoutePresentedRef = useRef(false); const settingsSheetPresentation = useThreadSettingsSheetPresentation({ @@ -291,6 +290,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps const [previewVideo, setPreviewVideo] = useState(null); const composerOwnerKey = scopedThreadKey(props.environmentId, props.selectedThread.id); const composerDraftKey = props.draftKey ?? composerOwnerKey; + const readResetGeneration = useComposerDraftResetGeneration(composerDraftKey); const { text: draftMessage, attachments: draftAttachments, @@ -529,10 +529,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps const handleSend = async (followUp?: ActiveTurnComposerAction) => { if (isSubmissionLocked || sendBlockedReason !== null) return; // Sending now would leave a still-converting pasted image out of the turn, so wait for it. - if (pendingNativeImagePasteCountRef.current > 0) { - heldSendRef.current = { draftKey: composerDraftKey, followUp }; - return; - } + if (nativeImageSubmit.deferSend(followUp)) return; if (pendingPastedTextAttachmentCountRef.current > 0) return; if (usageLimitsOffered && isUsageLimitsCommand(draftMessage) && draftAttachments.length === 0) { if (openUsageLimits()) onChangeDraftMessage(""); @@ -570,13 +567,13 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps }); }; - const sendReleased = useEffectEvent((held: HeldSend) => { - if (held.draftKey === composerDraftKey) void handleSend(held.followUp); + const nativeImageSubmit = useSubmitAfterNativeImages({ + draftKey: composerDraftKey, + readResetGeneration, + blocked: isSubmissionLocked || sendBlockedReason !== null, + onPasteImages: props.onNativePasteImages, + onSubmit: (followUp) => void handleSend(followUp), }); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- sends from the render where the pasted images joined the draft - useEffect(() => { - if (releasedSend) sendReleased(releasedSend); - }, [releasedSend]); const lockedProviderInstanceId = props.canSwitchProvider ? undefined @@ -863,12 +860,8 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps onPasteImages={(uris) => { if (isSubmissionLocked) return; pendingNativeImagePasteCountRef.current += 1; - void props.onNativePasteImages(uris).finally(() => { + void nativeImageSubmit.pasteImages(uris).finally(() => { pendingNativeImagePasteCountRef.current -= 1; - if (pendingNativeImagePasteCountRef.current > 0) return; - const held = heldSendRef.current; - heldSendRef.current = null; - if (held) setReleasedSend(held); }); }} onPasteText={(paste) => { diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index 228713f07e9eb..a3fa9e4d7ea9e 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -284,7 +284,7 @@ export interface ThreadDetailScreenProps { readonly onChangeDraftMessage: (value: string) => void; readonly onPickDraftMedia: () => Promise; readonly onPickDraftFiles: () => Promise; - readonly onNativePasteImages: (uris: ReadonlyArray) => Promise; + readonly onNativePasteImages: (uris: ReadonlyArray) => Promise; readonly onNativePasteText: (paste: ComposerTextPaste) => Promise; readonly onRemoveDraftImage: (imageId: string) => void; readonly onStopThread: () => void; diff --git a/apps/mobile/src/features/threads/useSubmitAfterNativeImages.test.tsx b/apps/mobile/src/features/threads/useSubmitAfterNativeImages.test.tsx new file mode 100644 index 0000000000000..8451a7c49319d --- /dev/null +++ b/apps/mobile/src/features/threads/useSubmitAfterNativeImages.test.tsx @@ -0,0 +1,114 @@ +import { act, useLayoutEffect } from "react"; +import { createRoot } from "react-dom/client"; +import { expect, it, vi } from "vite-plus/test"; +import { useSubmitAfterNativeImages } from "./useSubmitAfterNativeImages"; + +function setup() { + const root = createRoot(document.createElement("div")); + let queue: ReturnType; + let generation = 0; + let blocked = false; + const onSubmit = vi.fn(); + const preparations: Array<(success: boolean) => void> = []; + const onPasteImages = () => new Promise((resolve) => preparations.push(resolve)); + function Probe() { + const current = useSubmitAfterNativeImages({ + draftKey: "draft", + readResetGeneration: () => generation, + blocked, + onPasteImages, + onSubmit: (action) => { + if (!blocked) onSubmit(action); + }, + }); + useLayoutEffect(() => { + queue = current; + }); + return null; + } + const render = () => act(() => root.render()); + render(); + return { + get queue() { + return queue!; + }, + onSubmit, + setBlocked(value: boolean) { + blocked = value; + render(); + }, + reset() { + generation += 1; + render(); + }, + async finish(success: boolean) { + await act(async () => { + preparations.shift()!(success); + }); + }, + [Symbol.dispose]() { + act(() => root.unmount()); + }, + }; +} + +it("does not send when conversion finishes without adding an image", async () => { + using state = setup(); + const paste = state.queue.pasteImages(["image"]); + expect(state.queue.deferSend()).toBe(true); + await state.finish(false); + await paste; + expect(state.onSubmit).not.toHaveBeenCalled(); + + const first = state.queue.pasteImages(["failed"]); + const second = state.queue.pasteImages(["successful"]); + state.queue.deferSend(); + await state.finish(false); + await state.finish(true); + await Promise.all([first, second]); + expect(state.onSubmit).not.toHaveBeenCalled(); + + const retry = state.queue.pasteImages(["retry"]); + state.queue.deferSend(); + await state.finish(true); + await retry; + expect(state.onSubmit).toHaveBeenCalledOnce(); +}); + +it("does not send a replacement draft after the original draft was discarded", async () => { + using state = setup(); + const paste = state.queue.pasteImages(["image"]); + state.queue.deferSend(); + state.reset(); + await state.finish(true); + await paste; + expect(state.onSubmit).not.toHaveBeenCalled(); + + const next = state.queue.pasteImages(["next"]); + state.queue.deferSend(); + state.setBlocked(true); + await state.finish(true); + await next; + state.reset(); + state.setBlocked(false); + expect(state.onSubmit).not.toHaveBeenCalled(); +}); + +it("waits for other attachment preparation and sends once after all images join the draft", async () => { + using state = setup(); + const first = state.queue.pasteImages(["first"]); + const second = state.queue.pasteImages(["second"]); + state.queue.deferSend("queue"); + state.queue.deferSend("steer"); + await state.finish(true); + expect(state.onSubmit).not.toHaveBeenCalled(); + state.setBlocked(true); + await state.finish(true); + await Promise.all([first, second]); + expect(state.onSubmit).not.toHaveBeenCalled(); + state.setBlocked(false); + expect(state.onSubmit).toHaveBeenCalledExactlyOnceWith("steer"); + state.setBlocked(true); + state.setBlocked(false); + expect(state.onSubmit).toHaveBeenCalledOnce(); +}); diff --git a/apps/mobile/src/features/threads/useSubmitAfterNativeImages.ts b/apps/mobile/src/features/threads/useSubmitAfterNativeImages.ts new file mode 100644 index 0000000000000..8b8209562719f --- /dev/null +++ b/apps/mobile/src/features/threads/useSubmitAfterNativeImages.ts @@ -0,0 +1,60 @@ +import { useEffect, useEffectEvent, useRef, useState } from "react"; +import type { ActiveTurnComposerAction } from "@t3tools/client-runtime/state/composer-dispatch"; + +export function useSubmitAfterNativeImages(props: { + readonly draftKey: string; + readonly readResetGeneration: () => number; + readonly blocked: boolean; + readonly onPasteImages: (uris: ReadonlyArray) => Promise; + readonly onSubmit: (followUp?: ActiveTurnComposerAction) => void; +}) { + type HeldSend = { + readonly draftKey: string; + readonly generation: number; + readonly followUp?: ActiveTurnComposerAction; + }; + const pendingCount = useRef(0); + const failed = useRef(false); + const heldSend = useRef(null); + const [releasedSend, setReleasedSend] = useState(null); + const consumedSend = useRef(null); + const sendReleased = useEffectEvent((held: HeldSend) => { + if (held.draftKey === props.draftKey && held.generation === props.readResetGeneration()) { + props.onSubmit(held.followUp); + } + }); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- submits from the render where the native images joined the draft + useEffect(() => { + if (!releasedSend || props.blocked || consumedSend.current === releasedSend) return; + consumedSend.current = releasedSend; + sendReleased(releasedSend); + }, [releasedSend, props.blocked]); + return { + deferSend: (followUp?: ActiveTurnComposerAction) => { + if (pendingCount.current === 0) return false; + heldSend.current = { + draftKey: props.draftKey, + generation: props.readResetGeneration(), + followUp, + }; + return true; + }, + pasteImages: (uris: ReadonlyArray) => { + if (pendingCount.current === 0) failed.current = false; + pendingCount.current += 1; + const finish = (success: boolean) => { + if (!success) failed.current = true; + pendingCount.current -= 1; + if (pendingCount.current === 0) { + const held = heldSend.current; + heldSend.current = null; + if (held && !failed.current) setReleasedSend(held); + } + }; + return props.onPasteImages(uris).then(finish, (error: unknown) => { + finish(false); + throw error; + }); + }, + }; +} diff --git a/apps/mobile/src/state/use-composer-attachment-actions.ts b/apps/mobile/src/state/use-composer-attachment-actions.ts index 2352f3f7848eb..cf5ee41acb143 100644 --- a/apps/mobile/src/state/use-composer-attachment-actions.ts +++ b/apps/mobile/src/state/use-composer-attachment-actions.ts @@ -45,9 +45,9 @@ export function useComposerAttachmentActions(props: { return appendComposerDraftAttachments(key, attachments, { appendReference: true, insertion }); }; // A picker may finish after its draft was discarded or the composer moved off it. - const withDraftOperation = async (key: string, work: (signal: AbortSignal) => Promise) => { + const withDraftOperation = async (key: string, work: (signal: AbortSignal) => Promise) => { const operation = startComposerDraftOperation(key); - await work(operation.signal).finally(operation.finish); + return work(operation.signal).finally(operation.finish); }; const report = (title: string, error: string | null | undefined, rejected: number) => { const problems = [ @@ -97,21 +97,23 @@ export function useComposerAttachmentActions(props: { }; const onNativePasteImages = async (uris: ReadonlyArray) => { const key = props.draftKey; - if (!key || props.locked || !uris.length) return; + if (!key || props.locked || !uris.length) return false; const insertion = captureComposerDraftInsertion(key); - await withDraftOperation(key, async (signal) => { + return withDraftOperation(key, async (signal) => { try { const result = await convertPastedImagesToAttachments({ uris }); - report( - "Could not paste images", - result.error, - await append(key, signal, result.attachments, insertion), - ); + const rejected = await append(key, signal, result.attachments, insertion); + report("Could not paste images", result.error, rejected); + if (signal.aborted) return false; + if (result.error) return false; + if (rejected > 0) return false; + return result.attachments.length > 0; } catch (error) { Dialog.alert( "Could not paste images", error instanceof Error ? error.message : "Try again.", ); + return false; } }); }; diff --git a/apps/mobile/vite.config.ts b/apps/mobile/vite.config.ts index e9f1260b514c3..45c29d07ac079 100644 --- a/apps/mobile/vite.config.ts +++ b/apps/mobile/vite.config.ts @@ -4,6 +4,7 @@ import { defineConfig, normalizePath } from "vite-plus"; import "vite-plus/test/config"; const reactTests = [ + "src/features/threads/useSubmitAfterNativeImages.test.tsx", "src/features/threads/git/GitBranchesSheet.test.tsx", "src/features/threads/new-task-flow-provider.test.tsx", "src/features/layout/workspace/workspace-tabs-state.test.ts", diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 491b63bf4e64d..ee5bb9e7eab84 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -713,7 +713,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const preparingComposerImages = usePreparingComposerImages(attachmentTargetKey).filter( (image) => !image.hidden, ); - const submitAfterPreparingImages = useSubmitAfterPreparingImages(attachmentTargetKey); const nonPersistedComposerImageIds = attachmentDraft.nonPersistedImageIds; const uploadsByImageId = useAttachmentUploadStore((state) => state.uploadsByImageId); const openPrLink = useOpenPrLink(routeThreadRef); @@ -1908,6 +1907,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) attachmentBlockReason, environmentUnavailable: environmentUnavailable !== null, }); + const submitAfterPreparingImages = useSubmitAfterPreparingImages( + attachmentTargetKey, + submissionBlocked, + ); // The pending Submit button follows the answer's own blockers, matching submitComposer. const primaryActionSendDisabledReason = (activePendingProgress ? attachmentBlockReason : sendDisabledReason) ?? diff --git a/apps/web/src/components/chat/preparingComposerImages.browser.test.tsx b/apps/web/src/components/chat/preparingComposerImages.browser.test.tsx index 2ba3b6b987b43..38a1bab533825 100644 --- a/apps/web/src/components/chat/preparingComposerImages.browser.test.tsx +++ b/apps/web/src/components/chat/preparingComposerImages.browser.test.tsx @@ -24,8 +24,9 @@ function Probe(props: { draftImagesStore: DraftImagesStore; onReady: (queue: QueueSubmit) => void; onCommit?: (images: ReadonlyArray) => void; + blocked?: boolean; }) { - const queue = useSubmitAfterPreparingImages(props.targetKey); + const queue = useSubmitAfterPreparingImages(props.targetKey, props.blocked); const draftImages = useStore(props.draftImagesStore, (state) => state.ids); const { onCommit } = props; useEffect(() => { @@ -45,16 +46,18 @@ it("sends after pasted images finish compressing, with the compressed image in t const draftImagesStore = createDraftImagesStore(); let queueSubmit: QueueSubmit | undefined; let committedImages: ReadonlyArray = []; - await using _screen = await render( + const onCommit = (images: ReadonlyArray) => { + committedImages = images; + }; + const onReady = (queue: QueueSubmit) => { + queueSubmit = queue; + }; + await using screen = await render( { - committedImages = images; - }} - onReady={(queue) => { - queueSubmit = queue; - }} + onCommit={onCommit} + onReady={onReady} />, // A bare hook probe; nothing here navigates. { router: false }, @@ -76,6 +79,31 @@ it("sends after pasted images finish compressing, with the compressed image in t }); expect(submit).toHaveBeenCalledOnce(); expect(submit.mock.results[0]?.value).toEqual(["second"]); + + submit.mockClear(); + await act(() => addPreparingComposerImages(target, [preparingImage("uploading")])); + expect(queueSubmit?.(submit)).toBe(true); + await screen.rerender( + , + ); + await act(() => removePreparingComposerImages(target, new Set(["uploading"]))); + expect(submit).not.toHaveBeenCalled(); + await screen.rerender( + , + ); + expect(submit).toHaveBeenCalledOnce(); + expect(submit.mock.results[0]?.value).toEqual(["second"]); }); it("drops a waiting send when the composer moves to another draft or discards it", async () => { @@ -120,3 +148,28 @@ it("drops a waiting send when the composer moves to another draft or discards it await act(() => cancelPreparingComposerImages(target)); expect(submit).not.toHaveBeenCalled(); }); + +it("keeps the draft unsent when image preparation fails", async () => { + const target = "submit-after-failed-preparation"; + using _store = { [Symbol.dispose]: () => cancelPreparingComposerImages(target) }; + const draftImagesStore = createDraftImagesStore(); + let queueSubmit: QueueSubmit | undefined; + await using _screen = await render( + { + queueSubmit = queue; + }} + />, + // A bare hook probe; nothing here navigates. + { router: false }, + ); + const submit = vi.fn(); + await act(() => addPreparingComposerImages(target, [preparingImage("failed")])); + expect(queueSubmit?.(submit)).toBe(true); + await act(() => + removePreparingComposerImages(target, new Set(["failed"]), { cancelSubmission: true }), + ); + expect(submit).not.toHaveBeenCalled(); +}); diff --git a/apps/web/src/components/chat/preparingComposerImages.ts b/apps/web/src/components/chat/preparingComposerImages.ts index b74be3f1bcf2c..754c1b4e4696a 100644 --- a/apps/web/src/components/chat/preparingComposerImages.ts +++ b/apps/web/src/components/chat/preparingComposerImages.ts @@ -63,6 +63,7 @@ export function isPreparingComposerImage(targetKey: string, imageId: string): bo export function removePreparingComposerImages( targetKey: string, imageIds: ReadonlySet, + options?: { readonly cancelSubmission?: boolean }, ): ReadonlySet { const current = usePreparingComposerImageStore.getState().byTargetKey[targetKey] ?? NO_PREPARING_IMAGES; @@ -70,6 +71,7 @@ export function removePreparingComposerImages( current.filter((image) => imageIds.has(image.id)).map((image) => image.id), ); if (removed.size === 0) return removed; + if (options?.cancelSubmission) invalidatePendingSubmit(targetKey); usePreparingComposerImageStore.setState((state) => { const remaining = (state.byTargetKey[targetKey] ?? NO_PREPARING_IMAGES).filter( (image) => !removed.has(image.id), @@ -88,9 +90,13 @@ export function removePreparingComposerImages( // Bumped on cancel so a send held for the cancelled images is dropped rather than released. const cancelGenerations = new Map(); +function invalidatePendingSubmit(targetKey: string) { + cancelGenerations.set(targetKey, (cancelGenerations.get(targetKey) ?? 0) + 1); +} + /** Drops every image still preparing for the target, so its compression result is discarded. */ export function cancelPreparingComposerImages(targetKey: string): void { - cancelGenerations.set(targetKey, (cancelGenerations.get(targetKey) ?? 0) + 1); + invalidatePendingSubmit(targetKey); if (!usePreparingComposerImageStore.getState().byTargetKey[targetKey]) return; usePreparingComposerImageStore.setState((state) => { const byTargetKey = { ...state.byTargetKey }; @@ -103,7 +109,7 @@ export function cancelPreparingComposerImages(targetKey: string): void { * Holds a send made while the target still has images compressing, and runs it once they finish, * so the turn includes them. Returns false when nothing is compressing and the caller should send. */ -export function useSubmitAfterPreparingImages(targetKey: string) { +export function useSubmitAfterPreparingImages(targetKey: string, blocked = false) { const preparing = usePreparingComposerImages(targetKey); const pendingRef = useRef<{ readonly targetKey: string; @@ -121,11 +127,11 @@ export function useSubmitAfterPreparingImages(targetKey: string) { pendingRef.current = null; return; } - if (preparing.length > 0) return; + if (preparing.length > 0 || blocked) return; pendingRef.current = null; // After the composer's later effects have synced its draft refs to this render. queueMicrotask(pending.submit); - }, [preparing, targetKey]); + }, [preparing, targetKey, blocked]); return useStableCallback((submit: () => void) => { if (countPreparingComposerImages(targetKey) === 0) return false; pendingRef.current = { diff --git a/apps/web/src/components/chat/useComposerAttachmentIntake.ts b/apps/web/src/components/chat/useComposerAttachmentIntake.ts index 481846a1fe30b..d8e47482634fa 100644 --- a/apps/web/src/components/chat/useComposerAttachmentIntake.ts +++ b/apps/web/src/components/chat/useComposerAttachmentIntake.ts @@ -304,6 +304,7 @@ export function useComposerAttachmentIntake(input: { const stillPreparingIds = removePreparingComposerImages( attachmentTargetKey, new Set(preparingImages.map((image) => image.id)), + { cancelSubmission: compressionErrors.size > 0 || questionDiscarded }, ); if (questionAttachmentTarget) changeQuestionAttachmentPreparation(questionAttachmentTarget, -stillPreparingIds.size); @@ -354,7 +355,11 @@ export function useComposerAttachmentIntake(input: { }; const removeComposerImage = (imageId: string) => { - if (removePreparingComposerImages(attachmentTargetKey, new Set([imageId])).size > 0) { + if ( + removePreparingComposerImages(attachmentTargetKey, new Set([imageId]), { + cancelSubmission: true, + }).size > 0 + ) { // Its compression finishes in the background and is dropped. if (questionAttachmentTarget) changeQuestionAttachmentPreparation(questionAttachmentTarget, -1); From 8bc1bc1a316ca67fc35d98685da1e3abbd1afe3c Mon Sep 17 00:00:00 2001 From: Muzammil Hussain <58479501+Muzammil-Bit@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:21:56 +0500 Subject: [PATCH 11/11] fix(web): drop stale pasted-image i18n key Co-Authored-By: Claude Opus 5.5 --- apps/web/src/i18n/translations/de.json | 3 +-- apps/web/src/i18n/translations/en.json | 3 +-- apps/web/src/i18n/translations/es.json | 3 +-- apps/web/src/i18n/translations/fr.json | 3 +-- apps/web/src/i18n/translations/ja.json | 3 +-- apps/web/src/i18n/translations/ko.json | 3 +-- apps/web/src/i18n/translations/pt-BR.json | 3 +-- apps/web/src/i18n/translations/ru.json | 3 +-- apps/web/src/i18n/translations/sv.json | 3 +-- apps/web/src/i18n/translations/zh.json | 3 +-- 10 files changed, 10 insertions(+), 20 deletions(-) diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 648fd58859dbe..7969ce24bc748 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -3156,8 +3156,6 @@ "164d3295a763dbad": "Der Snapshot ist nicht mehr verfügbar.", "f77ce9bc81a68882": "Der Snapshot ist noch nicht bereit zum Kopieren.", "68a4461e56df0896": "Spracheingabe wird vorbereitet", - "cfc4f3582964bf84": "Ein eingefügtes Bild wird noch komprimiert.", - "aedaf7f4faba8bd3": "Sende erneut, sobald die Miniatur erscheint.", "4bc6e68c58cbb173": "Angehängter Kontext wird noch in diese Nachricht übernommen.", "62bf4adef45b9830": "Sende erneut, sobald der Chip aufgelöst ist.", "d0e9c30191edf07e": "Antwort auf {titles}", @@ -4642,6 +4640,7 @@ "98c76143d9aae871": "Ablage-Eintrag kommt möglicherweise zurück", "a7101927759103ad": "Der Browserspeicher hat das Löschen abgelehnt, daher könnte dieser Prompt nach dem Neuladen wieder erscheinen.", "fb34cb404c4930dc": "Lege erneut ab, sobald der Chip aufgelöst ist.", + "cfc4f3582964bf84": "Ein eingefügtes Bild wird noch komprimiert.", "70b12bc1e1a26abb": "Lege erneut ab, sobald die Komprimierung abgeschlossen ist.", "f6b1ef37f7587664": "Hänge abgelegte Dateien erneut an oder entferne sie, bevor du ablegst", "120167bbfb6d5939": "Warte auf die Datei-Uploads, bevor du diesen Prompt ablegst", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 599944358b5bb..cb30b352e7095 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -3155,8 +3155,6 @@ "164d3295a763dbad": "Snapshot is no longer available.", "f77ce9bc81a68882": "The snapshot is not ready to copy.", "68a4461e56df0896": "Preparing voice input", - "cfc4f3582964bf84": "Still compressing a pasted image.", - "aedaf7f4faba8bd3": "Send again once its thumbnail appears.", "4bc6e68c58cbb173": "Still bringing attached context into this message.", "62bf4adef45b9830": "Send again once its chip resolves.", "d0e9c30191edf07e": "Replying to {titles}", @@ -4641,6 +4639,7 @@ "98c76143d9aae871": "Stash entry may come back", "a7101927759103ad": "Browser storage rejected the delete, so this prompt could reappear after a reload.", "fb34cb404c4930dc": "Stash again once its chip resolves.", + "cfc4f3582964bf84": "Still compressing a pasted image.", "70b12bc1e1a26abb": "Stash again once it finishes compressing.", "f6b1ef37f7587664": "Attach dropped files again or remove them before stashing", "120167bbfb6d5939": "Wait for file uploads before stashing this prompt", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 956f4e17a9617..aba7481449778 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -3155,8 +3155,6 @@ "164d3295a763dbad": "La instantánea ya no está disponible.", "f77ce9bc81a68882": "La instantánea no está lista para copiarla.", "68a4461e56df0896": "Preparando la entrada de voz", - "cfc4f3582964bf84": "Aún se está comprimiendo una imagen pegada.", - "aedaf7f4faba8bd3": "Vuelve a enviar cuando aparezca su miniatura.", "4bc6e68c58cbb173": "Aún se está incorporando el contexto adjunto a este mensaje.", "62bf4adef45b9830": "Vuelve a enviar cuando se resuelva su chip.", "d0e9c30191edf07e": "Respondiendo a {titles}", @@ -4639,6 +4637,7 @@ "98c76143d9aae871": "Puede que la entrada del stash vuelva", "a7101927759103ad": "El almacenamiento del navegador rechazó la eliminación, así que este prompt podría volver a aparecer tras recargar.", "fb34cb404c4930dc": "Vuelve a guardarlo en el stash cuando se resuelva su chip.", + "cfc4f3582964bf84": "Aún se está comprimiendo una imagen pegada.", "70b12bc1e1a26abb": "Vuelve a guardarlo en el stash cuando termine de comprimirse.", "f6b1ef37f7587664": "Vuelve a adjuntar los archivos soltados o quítalos antes de guardarlo en el stash", "120167bbfb6d5939": "Espera a que se suban los archivos antes de guardar este prompt en el stash", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 1c982cc6d6f58..df6190f7eb702 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -3155,8 +3155,6 @@ "164d3295a763dbad": "L’instantané n’est plus disponible.", "f77ce9bc81a68882": "L’instantané n’est pas prêt à être copié.", "68a4461e56df0896": "Préparation de la saisie vocale", - "cfc4f3582964bf84": "Compression d’une image collée en cours.", - "aedaf7f4faba8bd3": "Renvoyez quand sa miniature apparaît.", "4bc6e68c58cbb173": "Ajout du contexte joint à ce message en cours.", "62bf4adef45b9830": "Renvoyez quand sa puce est résolue.", "d0e9c30191edf07e": "Réponse à {titles}", @@ -4640,6 +4638,7 @@ "98c76143d9aae871": "L’entrée de la réserve peut revenir", "a7101927759103ad": "Le stockage du navigateur a refusé la suppression ; ce prompt pourrait donc réapparaître après un rechargement.", "fb34cb404c4930dc": "Mettez de côté à nouveau quand sa puce est résolue.", + "cfc4f3582964bf84": "Compression d’une image collée en cours.", "70b12bc1e1a26abb": "Mettez de côté à nouveau une fois la compression terminée.", "f6b1ef37f7587664": "Joignez à nouveau les fichiers retirés ou supprimez-les avant de mettre de côté", "120167bbfb6d5939": "Attendez la fin de l’envoi des fichiers avant de mettre ce prompt de côté", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 879531a396d2a..dc962e7a01c1e 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -3153,8 +3153,6 @@ "164d3295a763dbad": "スナップショットは利用できなくなりました。", "f77ce9bc81a68882": "スナップショットはまだコピーできる状態ではありません。", "68a4461e56df0896": "音声入力を準備しています", - "cfc4f3582964bf84": "貼り付けた画像をまだ圧縮しています。", - "aedaf7f4faba8bd3": "サムネイルが表示されたら、もう一度送信してください。", "4bc6e68c58cbb173": "添付したコンテキストをまだこのメッセージに取り込んでいます。", "62bf4adef45b9830": "チップが確定したら、もう一度送信してください。", "d0e9c30191edf07e": "{titles} に返信中", @@ -4629,6 +4627,7 @@ "98c76143d9aae871": "退避した項目が戻る可能性があります", "a7101927759103ad": "ブラウザーのストレージが削除を拒否したため、再読み込み後にこのプロンプトが再表示される可能性があります。", "fb34cb404c4930dc": "チップが確定したら、もう一度退避してください。", + "cfc4f3582964bf84": "貼り付けた画像をまだ圧縮しています。", "70b12bc1e1a26abb": "圧縮が終わったら、もう一度退避してください。", "f6b1ef37f7587664": "退避する前に、ドロップしたファイルをもう一度添付するか削除してください", "120167bbfb6d5939": "このプロンプトを退避する前に、ファイルのアップロードが終わるまでお待ちください", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index fae8ce2ec6fc4..ff5281e80cb8a 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -3154,8 +3154,6 @@ "164d3295a763dbad": "스냅샷을 더 이상 사용할 수 없습니다.", "f77ce9bc81a68882": "스냅샷을 복사할 준비가 되지 않았습니다.", "68a4461e56df0896": "음성 입력 준비 중", - "cfc4f3582964bf84": "붙여 넣은 이미지를 아직 압축하는 중입니다.", - "aedaf7f4faba8bd3": "썸네일이 표시되면 다시 보내세요.", "4bc6e68c58cbb173": "첨부한 컨텍스트를 아직 이 메시지로 가져오는 중입니다.", "62bf4adef45b9830": "칩이 확인되면 다시 보내세요.", "d0e9c30191edf07e": "{titles}에 답장하는 중", @@ -4626,6 +4624,7 @@ "98c76143d9aae871": "임시 저장함 항목이 다시 나타날 수 있습니다", "a7101927759103ad": "브라우저 저장소가 삭제를 거부해서 새로 고친 후 이 프롬프트가 다시 나타날 수 있습니다.", "fb34cb404c4930dc": "칩이 확인되면 다시 임시 저장하세요.", + "cfc4f3582964bf84": "붙여 넣은 이미지를 아직 압축하는 중입니다.", "70b12bc1e1a26abb": "압축이 끝나면 다시 임시 저장하세요.", "f6b1ef37f7587664": "임시 저장하기 전에 끌어다 놓은 파일을 다시 첨부하거나 제거하세요", "120167bbfb6d5939": "이 프롬프트를 임시 저장하기 전에 파일 업로드를 기다리세요", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 7010bef288b16..0a80119685c2d 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -3155,8 +3155,6 @@ "164d3295a763dbad": "O snapshot não está mais disponível.", "f77ce9bc81a68882": "O snapshot não está pronto para copiar.", "68a4461e56df0896": "Preparando a entrada de voz", - "cfc4f3582964bf84": "Ainda comprimindo uma imagem colada.", - "aedaf7f4faba8bd3": "Envie novamente quando a miniatura aparecer.", "4bc6e68c58cbb173": "Ainda trazendo o contexto anexado para esta mensagem.", "62bf4adef45b9830": "Envie novamente quando o chip carregar.", "d0e9c30191edf07e": "Respondendo a {titles}", @@ -4639,6 +4637,7 @@ "98c76143d9aae871": "O item guardado pode voltar", "a7101927759103ad": "O armazenamento do navegador rejeitou a exclusão, então este prompt pode reaparecer após recarregar.", "fb34cb404c4930dc": "Guarde novamente quando o chip carregar.", + "cfc4f3582964bf84": "Ainda comprimindo uma imagem colada.", "70b12bc1e1a26abb": "Guarde novamente quando a compressão terminar.", "f6b1ef37f7587664": "Anexe novamente os arquivos soltos ou remova-os antes de guardar", "120167bbfb6d5939": "Aguarde o upload dos arquivos antes de guardar este prompt", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 0766d953dd02d..f83ae70839ad0 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -3155,8 +3155,6 @@ "164d3295a763dbad": "Снимок больше недоступен.", "f77ce9bc81a68882": "Снимок ещё не готов к копированию.", "68a4461e56df0896": "Подготовка голосового ввода", - "cfc4f3582964bf84": "Вставленное изображение ещё сжимается.", - "aedaf7f4faba8bd3": "Отправьте снова, когда появится миниатюра.", "4bc6e68c58cbb173": "Прикреплённый контекст ещё добавляется в сообщение.", "62bf4adef45b9830": "Отправьте снова, когда чип загрузится.", "d0e9c30191edf07e": "Ответ на {titles}", @@ -4639,6 +4637,7 @@ "98c76143d9aae871": "Запись тайника может вернуться", "a7101927759103ad": "Хранилище браузера отклонило удаление, поэтому промпт может снова появиться после перезагрузки.", "fb34cb404c4930dc": "Спрячьте снова, когда чип загрузится.", + "cfc4f3582964bf84": "Вставленное изображение ещё сжимается.", "70b12bc1e1a26abb": "Спрячьте снова, когда сжатие завершится.", "f6b1ef37f7587664": "Прикрепите отброшенные файлы снова или удалите их перед откладыванием", "120167bbfb6d5939": "Дождитесь загрузки файлов, прежде чем откладывать этот промпт", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 5e6d1607edf31..16e6feff436b6 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -3155,8 +3155,6 @@ "164d3295a763dbad": "Ögonblicksbilden är inte längre tillgänglig.", "f77ce9bc81a68882": "Ögonblicksbilden är inte redo att kopieras.", "68a4461e56df0896": "Förbereder röstinmatning", - "cfc4f3582964bf84": "Komprimerar fortfarande en inklistrad bild.", - "aedaf7f4faba8bd3": "Skicka igen när miniatyrbilden visas.", "4bc6e68c58cbb173": "Hämtar fortfarande bifogad kontext till det här meddelandet.", "62bf4adef45b9830": "Skicka igen när dess etikett har lästs in.", "d0e9c30191edf07e": "Svarar på {titles}", @@ -4640,6 +4638,7 @@ "98c76143d9aae871": "Den undanlagda prompten kan komma tillbaka", "a7101927759103ad": "Webbläsarens lagring avvisade raderingen, så prompten kan dyka upp igen efter en omladdning.", "fb34cb404c4930dc": "Lägg undan igen när dess etikett har lästs in.", + "cfc4f3582964bf84": "Komprimerar fortfarande en inklistrad bild.", "70b12bc1e1a26abb": "Lägg undan igen när komprimeringen är klar.", "f6b1ef37f7587664": "Bifoga släppta filer igen eller ta bort dem innan du lägger undan", "120167bbfb6d5939": "Vänta på filuppladdningarna innan du lägger undan den här prompten", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index c86b9e6c55e41..3ab089125f8ae 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -3159,8 +3159,6 @@ "164d3295a763dbad": "快照已不可用。", "f77ce9bc81a68882": "快照尚未准备好复制。", "68a4461e56df0896": "正在准备语音输入", - "cfc4f3582964bf84": "粘贴的图片仍在压缩。", - "aedaf7f4faba8bd3": "缩略图出现后请再次发送。", "4bc6e68c58cbb173": "仍在把附加的上下文放入这条消息。", "62bf4adef45b9830": "标签加载完成后请再次发送。", "d0e9c30191edf07e": "回复 {titles}", @@ -4646,6 +4644,7 @@ "98c76143d9aae871": "暂存条目可能会再次出现", "a7101927759103ad": "浏览器存储拒绝了删除操作,所以刷新后这条提示词可能再次出现。", "fb34cb404c4930dc": "标签加载完成后请再次暂存。", + "cfc4f3582964bf84": "粘贴的图片仍在压缩。", "70b12bc1e1a26abb": "请在压缩完成后重新暂存。", "f6b1ef37f7587664": "暂存前请重新添加丢失的文件,或将其移除", "120167bbfb6d5939": "请等文件上传完成后再暂存这条提示词",