From 7b5e6b953a3d82431f943a891f6581745081d74b Mon Sep 17 00:00:00 2001 From: DonPauer <18126559+gordon-vidal@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:02:28 +0100 Subject: [PATCH 1/4] fix(web): send queued dictation to original thread after switching threads --- apps/web/src/components/ChatView.tsx | 3 +- apps/web/src/components/chat/ChatComposer.tsx | 92 ++++++++++++++++++- .../src/components/chat/useComposerSend.ts | 92 ++++++++++++++----- ...useEnvironmentSpeechInput.browser.test.tsx | 28 ++++++ .../src/speech/useEnvironmentSpeechInput.ts | 30 ++---- apps/web/src/speech/voiceInputSession.ts | 48 +++++++++- 6 files changed, 238 insertions(+), 55 deletions(-) diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 77c47d668daf..ea16d027fcfe 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -3054,7 +3054,7 @@ export default function ChatView(props: ChatViewProps) { scrollToEnd, setThreadError, }); - const { onSend } = useComposerSend({ + const { onSend, captureDetachedSend } = useComposerSend({ environmentId, routeThreadKey, currentRouteThreadKeyRef, @@ -3895,6 +3895,7 @@ export default function ChatView(props: ChatViewProps) { onPageScrollRelease={onComposerPageScrollReleaseStable} onCompactContext={onComposerCompactContextStable} onSend={onComposerSendStable} + captureDetachedSend={captureDetachedSend} onResume={onComposerResumeStable} onInterrupt={onInterruptStable} onSelectActivePendingUserInputOption={ diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 9038e6717ba0..7fea05e3ff8c 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -460,6 +460,19 @@ export interface ChatComposerProps { dispatchMode?: ComposerDispatchMode, submissionIntent?: ComposerSubmissionIntent, ) => void; + captureDetachedSend?: () => ( + e?: { preventDefault: () => void }, + dispatchMode?: ComposerDispatchMode, + submissionIntent?: ComposerSubmissionIntent, + directAnnotation?: { + annotation: PreviewAnnotationPayload; + image: ComposerImageAttachment | null; + }, + detachedOverride?: { + readonly prompt: string; + readonly sendContext: ReturnType; + }, + ) => void; onResume: () => void; onInterrupt: () => void; onSelectActivePendingUserInputOption: (questionId: string, optionValue: string) => void; @@ -562,6 +575,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) onPageScrollRelease, onCompactContext, onSend, + captureDetachedSend, onResume, onInterrupt, onSelectActivePendingUserInputOption, @@ -1861,6 +1875,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) environmentId, projectId: activeProjectId, projectName, + threadId: activeThread?.id ?? null, ownerKey: questionAttachmentTarget ?? composerDraftTargetKey, disabled: dictationDisabled, label: activeThread?.title ?? null, @@ -2185,16 +2200,82 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) }; const submitComposerRef = useRef< - (dispatchMode?: ComposerDispatchMode, submissionIntent?: ComposerSubmissionIntent) => void + ( + dispatchMode?: ComposerDispatchMode, + submissionIntent?: ComposerSubmissionIntent, + options?: { readonly afterDictation?: boolean }, + ) => void >(() => {}); const submitComposer = ( event?: { preventDefault: () => void }, dispatchMode?: ComposerDispatchMode, submissionIntent?: ComposerSubmissionIntent, + options?: { readonly afterDictation?: boolean }, ) => { - if (voiceInputActive) { + if (voiceInputActive && !options?.afterDictation) { event?.preventDefault(); - submitAfterDictation(() => submitComposerRef.current(dispatchMode, submissionIntent)); + const queuedOwnerKey = attachmentTargetKey; + const capturedDraftTarget = composerDraftTarget; + const resolvedDispatchMode = + dispatchMode ?? + resolveComposerDispatchMode({ + running: phase === "running" || phase === "connecting", + alternateModifier: false, + activeTurnDefault: followUpBehavior, + canSteer, + }); + const capturedDetachedSend = + questionAttachmentTarget === null ? (captureDetachedSend?.() ?? null) : null; + const capturedSendContext = + capturedDetachedSend !== null ? (composerRef.current?.getSendContext() ?? null) : null; + const capturedSubmissionTarget = submissionTarget; + submitAfterDictation((transcribedText) => { + const stillLive = + composerMountedRef.current && attachmentTargetKeyRef.current === queuedOwnerKey; + if (stillLive) { + submitComposerRef.current(dispatchMode, submissionIntent, { afterDictation: true }); + return; + } + if ( + !capturedDetachedSend || + !capturedSendContext || + pendingDraftWork.has(queuedOwnerKey) || + countPreparingComposerImages(queuedOwnerKey) > 0 + ) { + return; + } + const liveTarget = resolveLiveComposerDraftTarget(capturedDraftTarget); + const latestDraft = + liveTarget !== null + ? useComposerDraftStore.getState().getComposerDraft(liveTarget) + : null; + submitComposerDraft({ + prompt: transcribedText, + submissionTarget: capturedSubmissionTarget, + event: undefined, + onSend: (sendEvent) => { + capturedDetachedSend(sendEvent, resolvedDispatchMode, submissionIntent, undefined, { + prompt: transcribedText, + sendContext: { + ...capturedSendContext, + ...(latestDraft + ? { + images: latestDraft.images, + files: latestDraft.files, + terminalContexts: latestDraft.terminalContexts, + previewAnnotations: latestDraft.previewAnnotations, + reviewComments: latestDraft.reviewComments, + threadContexts: latestDraft.threadContexts, + environmentContexts: latestDraft.environmentContexts, + } + : {}), + prompt: transcribedText, + }, + }); + return true; + }, + }); + }); return false; } if (submissionBlocked || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) { @@ -2219,7 +2300,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) return false; } // An empty draft has nothing to send; Enter does what the Resume thread button does. - if (showResumeAction && !activePendingProgress) { + if (showResumeAction && !activePendingProgress && promptRef.current.trim().length === 0) { event?.preventDefault(); if (isSendBusy || environmentUnavailable !== null) return false; onResume(); @@ -2256,7 +2337,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const submitComposerStable = useStableCallback(submitComposer); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes the committed submission handler to the asynchronous dictation completion useLayoutEffect(() => { - submitComposerRef.current = (mode, intent) => submitComposerStable(undefined, mode, intent); + submitComposerRef.current = (mode, intent, options) => + submitComposerStable(undefined, mode, intent, options); }, [submitComposerStable]); useDictationSubmissionShortcut({ enabled: voiceInputActive && !speechInput.preparing, diff --git a/apps/web/src/components/chat/useComposerSend.ts b/apps/web/src/components/chat/useComposerSend.ts index 45c135bce1a1..c1f72d0a5f05 100644 --- a/apps/web/src/components/chat/useComposerSend.ts +++ b/apps/web/src/components/chat/useComposerSend.ts @@ -420,27 +420,35 @@ export function useComposerSend(input: ComposerSendInput) { annotation: PreviewAnnotationPayload; image: ComposerImageAttachment | null; }, + detachedOverride?: { + readonly prompt: string; + readonly sendContext: ReturnType["getSendContext"]>; + }, ) => { e?.preventDefault(); // What the user pressed send on; uploads below can take a while, and a redirect must not // decline approvals for a draft that changed meanwhile. - const promptAtSend = promptRef.current; + const promptAtSend = detachedOverride ? detachedOverride.prompt : promptRef.current; if ( usageLimitsOffered && usageLimitsKey !== null && !directAnnotation && !draftHasNonPromptContent(composerDraftTarget) && - isUsageLimitsCommand(promptRef.current) + isUsageLimitsCommand(promptAtSend) ) { if (openUsageLimits()) { - promptRef.current = ""; setComposerDraftPrompt(composerDraftTarget, ""); - composerRef.current?.resetCursorState(); + if (currentRouteThreadKeyRef.current === routeThreadKey) { + promptRef.current = ""; + composerRef.current?.resetCursorState(); + } } return; } - const sendCtx = composerRef.current?.getSendContext(); + const sendCtx = detachedOverride + ? detachedOverride.sendContext + : composerRef.current?.getSendContext(); // `/side` beats an open question and a plan follow-up, which would send the text to main. const sideChatCommand = sendCtx && !directAnnotation && !queuedRunEdit.isEditing @@ -636,8 +644,10 @@ export function useComposerSend(input: ComposerSendInput) { // Cleared at send, like a regular message, so nothing in it can change or vanish mid-start. if (sendsDraft) { clearComposerDraftContent(composerDraftTarget); - promptRef.current = ""; - composerRef.current?.resetCursorState(); + if (currentRouteThreadKeyRef.current === routeThreadKey) { + promptRef.current = ""; + composerRef.current?.resetCursorState(); + } } const started = await settlePromise(async () => { if (!hasSendableContent) return onSideChat(undefined); @@ -783,10 +793,10 @@ export function useComposerSend(input: ComposerSendInput) { // A direct "send annotation" writes the draft and sends in the same tick; the reference // must be in the text now, not after the next render. const draftPrompt = directAnnotation - ? ensureInlineContextReferences(promptRef.current, [ + ? ensureInlineContextReferences(promptAtSend, [ previewAnnotationContextReference(directAnnotation.annotation), ]) - : promptRef.current; + : promptAtSend; const replyTo = useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.replyTo ?? null; const promptForSend = withReplyReference(draftPrompt, replyTo); @@ -870,9 +880,11 @@ export function useComposerSend(input: ComposerSendInput) { createdAt: new Date().toISOString(), }, clearDraft: () => { - promptRef.current = ""; clearComposerDraftContent(composerDraftTarget); - composerRef.current?.resetCursorState(); + if (currentRouteThreadKeyRef.current === routeThreadKey) { + promptRef.current = ""; + composerRef.current?.resetCursorState(); + } }, onUpdate: (submission) => { setFeedbackSubmissionsByThreadKey((current) => { @@ -910,9 +922,11 @@ export function useComposerSend(input: ComposerSendInput) { replyTo === null; if (freshSessionAvailable && composerHoldsOnlyText && isClearComposerCommand(trimmed)) { armFreshSession(routeThreadKey); - promptRef.current = ""; clearComposerDraftContent(composerDraftTarget); - composerRef.current?.resetCursorState(); + if (currentRouteThreadKeyRef.current === routeThreadKey) { + promptRef.current = ""; + composerRef.current?.resetCursorState(); + } return; } // Read once: an arm made while this send is in flight belongs to the next message. @@ -1024,7 +1038,11 @@ export function useComposerSend(input: ComposerSendInput) { effort: ctxSelectedPromptEffort, text: messageTextForSend || ATTACHMENT_ONLY_BOOTSTRAP_PROMPT, }); - if (composerRef.current?.validateProviderInput(outgoingMessageText) === false) { + const isCurrentRouteThread = () => currentRouteThreadKeyRef.current === routeThreadKey; + if ( + isCurrentRouteThread() && + composerRef.current?.validateProviderInput(outgoingMessageText) === false + ) { return; } @@ -1041,7 +1059,11 @@ export function useComposerSend(input: ComposerSendInput) { setThreadError(threadIdForSend, resolved.error); return; } - if (composerRef.current?.validateProviderInput(resolved.text) === false) return; + if ( + isCurrentRouteThread() && + composerRef.current?.validateProviderInput(resolved.text) === false + ) + return; multipleTargets.push(resolved); } @@ -1049,7 +1071,8 @@ export function useComposerSend(input: ComposerSendInput) { .getState() .getComposerDraft(composerDraftTarget); const draftChangedDuringPreparation = () => { - if (composerRef.current?.hasPendingAttachments() === true) return true; + if (isCurrentRouteThread() && composerRef.current?.hasPendingAttachments() === true) + return true; const draft = useComposerDraftStore.getState().getComposerDraft(composerDraftTarget); return composerDraftContentChanged(draftBeforePreparation, draft); }; @@ -1173,20 +1196,25 @@ export function useComposerSend(input: ComposerSendInput) { const sameIds = (left: ReadonlyArray, right: ReadonlyArray) => left.length === right.length && left.every((id, index) => id === right[index]); const draftChangedSinceSend = () => { - if (composerRef.current?.hasPendingAttachments() === true) return true; - const sendContext = composerRef.current?.getSendContext(); + const liveDraft = useComposerDraftStore.getState().getComposerDraft(composerDraftTarget); + const onCurrentThread = isCurrentRouteThread(); + if (onCurrentThread && composerRef.current?.hasPendingAttachments() === true) return true; + const sendContext = onCurrentThread ? composerRef.current?.getSendContext() : undefined; const attachmentIds = sendContext ? [...sendContext.images, ...sendContext.files].map((attachment) => attachment.id) - : attachmentIdsAtSend; - const promptUnchanged = - promptRef.current === promptAtSend || promptRef.current === promptForSend; + : liveDraft + ? [...liveDraft.images, ...liveDraft.files].map((attachment) => attachment.id) + : attachmentIdsAtSend; + const livePrompt = onCurrentThread + ? promptRef.current + : (liveDraft?.prompt ?? promptAtSend); + const promptUnchanged = livePrompt === promptAtSend || livePrompt === promptForSend; const attachmentsUnchanged = sameIds(attachmentIds, attachmentIdsAtSend) || (annotationImageId !== undefined && sameIds(attachmentIds, attachmentIdsBeforeAnnotation)); // The reply is not in the prompt, so cancelling or changing it is checked on its own. - const liveReply = - useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.replyTo ?? null; + const liveReply = liveDraft?.replyTo ?? null; return !promptUnchanged || !attachmentsUnchanged || liveReply !== replyTo; }; const draftBeforeDecline = useComposerDraftStore @@ -1713,5 +1741,21 @@ export function useComposerSend(input: ComposerSendInput) { }); if (ready) return onSendLatest(...args); }; - return { onSend: onSendWithRouting }; + const captureDetachedSend = useStableCallback( + () => + async (...args: Parameters) => { + args[0]?.preventDefault(); + const refresh = + args[3] || sendInFlightRef.current || readPendingEnvironmentChange() !== null + ? null + : refreshBeforeSend(); + if (refresh === null) return onSend(...args); + sendInFlightRef.current = true; + const ready = await refresh.finally(() => { + sendInFlightRef.current = false; + }); + if (ready) return onSend(...args); + }, + ); + return { onSend: onSendWithRouting, captureDetachedSend }; } diff --git a/apps/web/src/speech/useEnvironmentSpeechInput.browser.test.tsx b/apps/web/src/speech/useEnvironmentSpeechInput.browser.test.tsx index 8519d6a1ce0c..99cbff1c14a1 100644 --- a/apps/web/src/speech/useEnvironmentSpeechInput.browser.test.tsx +++ b/apps/web/src/speech/useEnvironmentSpeechInput.browser.test.tsx @@ -987,3 +987,31 @@ it("lets the user retry after a status failure without reselecting the destinati await act(() => mocks.voice.stop()); expect(mocks.transcribeCalls).toEqual(["env-a"]); }); + +it("delivers a queued submission for a persistent draft after switching owners", async () => { + setup({ destination: "env-a" }); + const submit = vi.fn(); + await using screen = await render(); + await act(() => mocks.voice.start()); + expect(mocks.voice.state.phase).toBe("recording"); + await act(async () => { + mocks.voice.submitAfterDictation(submit); + await screen.rerender(); + }); + await vi.waitFor(() => expect(submit).toHaveBeenCalledExactlyOnceWith("dictated")); + expect(mocks.storedDraft).toBe("dictated"); +}); + +it("drops a queued submission for a non-persistent draft when switching owners", async () => { + setup({ destination: "env-a" }); + const submit = vi.fn(); + await using screen = await render(); + await act(() => mocks.voice.start()); + expect(mocks.voice.state.phase).toBe("recording"); + await act(async () => { + mocks.voice.submitAfterDictation(submit); + await screen.rerender(); + }); + await vi.waitFor(() => expect(mocks.voice.state.phase).toBe("idle")); + expect(submit).not.toHaveBeenCalled(); +}); diff --git a/apps/web/src/speech/useEnvironmentSpeechInput.ts b/apps/web/src/speech/useEnvironmentSpeechInput.ts index 0ad3c4b2054e..e294c67c42d9 100644 --- a/apps/web/src/speech/useEnvironmentSpeechInput.ts +++ b/apps/web/src/speech/useEnvironmentSpeechInput.ts @@ -15,6 +15,7 @@ import type { EnvironmentSpeechStatus, ProjectId, SpeechBenchmarkTier, + ThreadId, } from "@t3tools/contracts"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { chooseSetupSpeechModel } from "@t3tools/shared/speech"; @@ -83,6 +84,8 @@ type HookInput = { /** The draft's project: its vocabulary on that environment and its name become recognition hints. */ readonly projectId?: ProjectId | null | undefined; readonly projectName?: string | null | undefined; + /** The active thread: used on the server to enrich optional transcript cleanup with live context. */ + readonly threadId?: ThreadId | null | undefined; readonly ownerKey: string; readonly disabled?: boolean | undefined; /** @@ -217,11 +220,6 @@ export function useEnvironmentSpeechInput(input: HookInput) { const busyElsewhere = !owns && voiceInputBlocksSubmission(snapshot.state); const startRequestRef = useRef(0); - const pendingSubmissionRef = useRef<{ - ownerKey: string; - submit: (text: string) => void; - text?: string; - } | null>(null); const latestRef = useRef({ input, clientSettings, cleanupPrepared, projectWords, session }); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes committed props before an async completion can read them through the session useLayoutEffect(() => { @@ -233,7 +231,6 @@ export function useEnvironmentSpeechInput(input: HookInput) { mountedRef.current = true; return () => { mountedRef.current = false; - pendingSubmissionRef.current = null; startRequestRef.current += 1; session?.ownerChanged(latestRef.current.input.ownerKey); }; @@ -292,36 +289,23 @@ export function useEnvironmentSpeechInput(input: HookInput) { }, [prepared, setup.downloading, setup.open, setupModelId]); const previousOwnerRef = useRef(input.ownerKey); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- abandons any queued submission, and a recording that cannot outlive its editor, when the draft's owner changes + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- abandons a recording that cannot outlive its editor when the draft's owner changes useEffect(() => { const previous = previousOwnerRef.current; if (previous === input.ownerKey && !input.disabled) return; previousOwnerRef.current = input.ownerKey; - pendingSubmissionRef.current = null; startRequestRef.current += 1; if (previous !== input.ownerKey) session?.ownerChanged(previous); else if (session?.ownerKey === input.ownerKey) session.cancel(); }, [input.ownerKey, input.disabled, session]); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- delivers a queued submission only after the transcript has committed to the draft - useEffect(() => { - const pending = pendingSubmissionRef.current; - if (state.phase === "error") pendingSubmissionRef.current = null; - if (state.phase !== "idle" || !pending) return; - pendingSubmissionRef.current = null; - if (!input.disabled && pending.ownerKey === input.ownerKey && pending.text !== undefined) - pending.submit(pending.text); - }, [state, input.ownerKey, input.disabled]); - const submitAfterDictation = useStableCallback((submit: (text: string) => void) => { if (latestRef.current.input.disabled || state.phase === "preparing") return; if (!session || !voiceInputBlocksSubmission(state)) { submit(latestRef.current.input.readDraft().text); return; } - if (pendingSubmissionRef.current) return; - pendingSubmissionRef.current = { ownerKey: latestRef.current.input.ownerKey, submit }; - if (session.state.phase === "recording") void session.stop(); + session.queueSubmission(latestRef.current.input.ownerKey, submit); }); const createTarget = useStableCallback((): VoiceInputTarget => { @@ -330,6 +314,7 @@ export function useEnvironmentSpeechInput(input: HookInput) { const current = latestRef.current; return { environmentId: current.input.environmentId, + threadId: current.input.threadId ?? null, projectName: current.input.projectName ?? null, projectWords: current.projectWords, clientSettings: current.clientSettings, @@ -359,8 +344,6 @@ export function useEnvironmentSpeechInput(input: HookInput) { } if (latestRef.current.input.disabled) return; latestRef.current.input.commitDraft(text, selection); - if (pendingSubmissionRef.current?.ownerKey === owner) - pendingSubmissionRef.current.text = text; }, readContext: () => (live() ? readContext() : startContext), }; @@ -585,7 +568,6 @@ export function useEnvironmentSpeechInput(input: HookInput) { submitAfterDictation, stop: useStableCallback(() => (owns && session ? session.stop() : Promise.resolve())), cancel: useStableCallback(() => { - pendingSubmissionRef.current = null; startRequestRef.current += 1; setSetup(INITIAL_SETUP); if (owns) session?.cancel(); diff --git a/apps/web/src/speech/voiceInputSession.ts b/apps/web/src/speech/voiceInputSession.ts index f21285457aa1..152c0fde71cb 100644 --- a/apps/web/src/speech/voiceInputSession.ts +++ b/apps/web/src/speech/voiceInputSession.ts @@ -18,6 +18,7 @@ import type { SpeechPostProcessingOptions, SpeechStreamText, SpeechTranscriptionOptions, + ThreadId, } from "@t3tools/contracts"; import { DEFAULT_CLIENT_SETTINGS, EnvironmentInternalError } from "@t3tools/contracts"; import { resolveSpeechVocabulary } from "@t3tools/shared/speech"; @@ -47,6 +48,7 @@ type DraftInput = { /** What a recording needs from its editor, read once when it starts. */ export type VoiceRecordingContext = { readonly environmentId: EnvironmentId; + readonly threadId?: ThreadId | null | undefined; readonly projectName: string | null; readonly projectWords: SpeechCustomWords; readonly clientSettings: ClientSettings; @@ -108,6 +110,11 @@ export class VoiceInputSession { readonly key: SessionKey; private readonly controller: VoiceInputController; private target: VoiceInputTarget | null = null; + private pendingSubmission: { + readonly ownerKey: string; + readonly submit: (text: string) => void; + text?: string; + } | null = null; private snapshot: VoiceInputSessionSnapshot = { state: IDLE_VOICE_STATE, target: null, @@ -127,6 +134,7 @@ export class VoiceInputSession { readonly cleanup: SpeechPostProcessingOptions | null; readonly cleanupGrant: string | null; readonly cleanupPrepared: PreparedConnection | null; + readonly threadId: ThreadId | null; } | undefined; const platformInput = { @@ -150,6 +158,7 @@ export class VoiceInputSession { recordingPreferences = { cleanupGrant, cleanupPrepared: context.cleanupPrepared, + threadId: context.threadId ?? null, cleanup: cleanupEnabled ? { speechCustomWords, @@ -209,6 +218,7 @@ export class VoiceInputSession { cleanupContext(options.draft), preferences.cleanup, () => hasAudioConsent() && preferences.cleanupGrant === readCleanupGrant(), + preferences.threadId, ), options, ).then((result) => result.text); @@ -237,7 +247,13 @@ export class VoiceInputSession { const draft = target?.readDraft(); return target && draft ? { ownerKey: target.ownerKey, ...draft } : null; }, - commitDraft: (text, selection) => this.target?.commitDraft(text, selection), + commitDraft: (text, selection) => { + const ownerKey = this.target?.ownerKey ?? null; + this.target?.commitDraft(text, selection); + if (ownerKey !== null && this.pendingSubmission?.ownerKey === ownerKey) { + this.pendingSubmission.text = text; + } + }, onStateChange: (state) => { if (this.disposed) return; const recordingStartedAt = @@ -245,6 +261,15 @@ export class VoiceInputSession { this.publish({ ...this.snapshot, state, recordingStartedAt }); if (state.phase !== "recording" && state.phase !== "transcribing") this.publishActivity(SILENT_ACTIVITY); + if (state.phase === "error") { + this.pendingSubmission = null; + return; + } + if (state.phase === "idle" && this.pendingSubmission !== null) { + const pending = this.pendingSubmission; + this.pendingSubmission = null; + if (pending.text !== undefined) pending.submit(pending.text); + } }, }); } @@ -281,6 +306,7 @@ export class VoiceInputSession { voiceInputBlocksSubmission(this.controller.currentState) && this.target?.ownerKey !== target.ownerKey; if (busyElsewhere) return Promise.resolve(); + this.pendingSubmission = null; this.target = target; this.onSpeechStatus = onSpeechStatus; this.publishActivity(SILENT_ACTIVITY); @@ -295,11 +321,29 @@ export class VoiceInputSession { this.publish({ ...this.snapshot, target }); } + /** Queues a submission to run once the active dictation commits its transcript. */ + queueSubmission(ownerKey: string, submit: (text: string) => void): boolean { + if ( + this.disposed || + this.target?.ownerKey !== ownerKey || + !voiceInputBlocksSubmission(this.controller.currentState) || + this.pendingSubmission !== null + ) { + return false; + } + this.pendingSubmission = { ownerKey, submit }; + if (this.controller.currentState.phase === "recording") { + void this.controller.stop(); + } + return true; + } + stop(): Promise { return this.controller.stop(); } cancel(): void { + this.pendingSubmission = null; this.controller.cancel(); } @@ -310,11 +354,13 @@ export class VoiceInputSession { /** The editor for `ownerKey` now shows another draft; only a persistent target keeps going. */ ownerChanged(ownerKey: string): void { if (this.target?.ownerKey !== ownerKey || this.target.persistent) return; + this.pendingSubmission = null; this.controller.ownerChanged(); } dispose(): void { this.disposed = true; + this.pendingSubmission = null; this.controller.dispose(); this.listeners.clear(); this.activityListeners.clear(); From d1f9ce5a9306feef13c5a621b3340aa236c3e5bc Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 21:13:44 +0000 Subject: [PATCH 2/4] fix(web): drop unused thread id from dictation cleanup postProcessEnvironmentTranscript takes no thread id; the extra argument was not part of this fix. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/components/chat/ChatComposer.tsx | 1 - apps/web/src/speech/useEnvironmentSpeechInput.ts | 4 ---- apps/web/src/speech/voiceInputSession.ts | 5 ----- 3 files changed, 10 deletions(-) diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 7fea05e3ff8c..2c3bc34529ff 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -1875,7 +1875,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) environmentId, projectId: activeProjectId, projectName, - threadId: activeThread?.id ?? null, ownerKey: questionAttachmentTarget ?? composerDraftTargetKey, disabled: dictationDisabled, label: activeThread?.title ?? null, diff --git a/apps/web/src/speech/useEnvironmentSpeechInput.ts b/apps/web/src/speech/useEnvironmentSpeechInput.ts index e294c67c42d9..c7915685727b 100644 --- a/apps/web/src/speech/useEnvironmentSpeechInput.ts +++ b/apps/web/src/speech/useEnvironmentSpeechInput.ts @@ -15,7 +15,6 @@ import type { EnvironmentSpeechStatus, ProjectId, SpeechBenchmarkTier, - ThreadId, } from "@t3tools/contracts"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { chooseSetupSpeechModel } from "@t3tools/shared/speech"; @@ -84,8 +83,6 @@ type HookInput = { /** The draft's project: its vocabulary on that environment and its name become recognition hints. */ readonly projectId?: ProjectId | null | undefined; readonly projectName?: string | null | undefined; - /** The active thread: used on the server to enrich optional transcript cleanup with live context. */ - readonly threadId?: ThreadId | null | undefined; readonly ownerKey: string; readonly disabled?: boolean | undefined; /** @@ -314,7 +311,6 @@ export function useEnvironmentSpeechInput(input: HookInput) { const current = latestRef.current; return { environmentId: current.input.environmentId, - threadId: current.input.threadId ?? null, projectName: current.input.projectName ?? null, projectWords: current.projectWords, clientSettings: current.clientSettings, diff --git a/apps/web/src/speech/voiceInputSession.ts b/apps/web/src/speech/voiceInputSession.ts index 152c0fde71cb..577b26595efe 100644 --- a/apps/web/src/speech/voiceInputSession.ts +++ b/apps/web/src/speech/voiceInputSession.ts @@ -18,7 +18,6 @@ import type { SpeechPostProcessingOptions, SpeechStreamText, SpeechTranscriptionOptions, - ThreadId, } from "@t3tools/contracts"; import { DEFAULT_CLIENT_SETTINGS, EnvironmentInternalError } from "@t3tools/contracts"; import { resolveSpeechVocabulary } from "@t3tools/shared/speech"; @@ -48,7 +47,6 @@ type DraftInput = { /** What a recording needs from its editor, read once when it starts. */ export type VoiceRecordingContext = { readonly environmentId: EnvironmentId; - readonly threadId?: ThreadId | null | undefined; readonly projectName: string | null; readonly projectWords: SpeechCustomWords; readonly clientSettings: ClientSettings; @@ -134,7 +132,6 @@ export class VoiceInputSession { readonly cleanup: SpeechPostProcessingOptions | null; readonly cleanupGrant: string | null; readonly cleanupPrepared: PreparedConnection | null; - readonly threadId: ThreadId | null; } | undefined; const platformInput = { @@ -158,7 +155,6 @@ export class VoiceInputSession { recordingPreferences = { cleanupGrant, cleanupPrepared: context.cleanupPrepared, - threadId: context.threadId ?? null, cleanup: cleanupEnabled ? { speechCustomWords, @@ -218,7 +214,6 @@ export class VoiceInputSession { cleanupContext(options.draft), preferences.cleanup, () => hasAudioConsent() && preferences.cleanupGrant === readCleanupGrant(), - preferences.threadId, ), options, ).then((result) => result.text); From df6a8b2b8805f5735b705483d6425d6b1edfca1a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 21:18:35 +0000 Subject: [PATCH 3/4] fix(web): send detached dictation without a load-balancing refresh The refresh gives up once the draft is no longer displayed, which is the only time a detached send runs, so a queued send from a load-balanced draft was dropped. Co-Authored-By: Claude Opus 5.5 --- .../src/components/chat/useComposerSend.ts | 19 +++---------------- 1 file changed, 3 insertions(+), 16 deletions(-) diff --git a/apps/web/src/components/chat/useComposerSend.ts b/apps/web/src/components/chat/useComposerSend.ts index c1f72d0a5f05..d89a9d79febc 100644 --- a/apps/web/src/components/chat/useComposerSend.ts +++ b/apps/web/src/components/chat/useComposerSend.ts @@ -1741,21 +1741,8 @@ export function useComposerSend(input: ComposerSendInput) { }); if (ready) return onSendLatest(...args); }; - const captureDetachedSend = useStableCallback( - () => - async (...args: Parameters) => { - args[0]?.preventDefault(); - const refresh = - args[3] || sendInFlightRef.current || readPendingEnvironmentChange() !== null - ? null - : refreshBeforeSend(); - if (refresh === null) return onSend(...args); - sendInFlightRef.current = true; - const ready = await refresh.finally(() => { - sendInFlightRef.current = false; - }); - if (ready) return onSend(...args); - }, - ); + // No load-balancing refresh: it bails once the draft is no longer displayed, which is the + // only time a detached send runs, so the draft keeps the environment it was dictated for. + const captureDetachedSend = useStableCallback(() => onSend); return { onSend: onSendWithRouting, captureDetachedSend }; } From 503e0fc99aaac16001c66ee054e6017c651ba938 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 21:26:41 +0000 Subject: [PATCH 4/4] fix(web): multi-model sends leave another thread's composer alone A queued dictation send can fan out after the user switched threads; the shared prompt ref and editor then belong to the displayed thread, so only reset them when it is still the sending one. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/components/chat/useMultipleModelSend.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/chat/useMultipleModelSend.ts b/apps/web/src/components/chat/useMultipleModelSend.ts index 25f07b6eb079..cbfcac768656 100644 --- a/apps/web/src/components/chat/useMultipleModelSend.ts +++ b/apps/web/src/components/chat/useMultipleModelSend.ts @@ -144,9 +144,11 @@ export function useMultipleModelSend(input: MultipleModelSendInput) { { text: messageText, attachments: attachmentsSnapshot }, m, ); - promptRef.current = ""; clearComposerDraftContent(composerDraftTarget); - composerRef.current?.resetCursorState(); + if (currentRouteThreadKeyRef.current === routeThreadKey) { + promptRef.current = ""; + composerRef.current?.resetCursorState(); + } clearedDraft = true; const clearedDraftSnapshot = useComposerDraftStore .getState()