From 73af7aec893dab14a6f414b44f8febacbcfef835 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Thu, 22 Oct 2026 20:36:01 -0400 Subject: [PATCH] fix(frontend): address CodeRabbit review findings on voice conversation mode Report STT start and capture failures instead of staying on Listening, treat a failed reading as an error, skip replies with no readable text, stop auto-play replaying a reply voice mode already read, focus the text box after Edit in text box, and strip think blocks before text reaches TTS. --- .../message/PromptInput.stt.test.tsx | 20 ++++ .../src/components/message/PromptInput.tsx | 8 +- .../useAutoPlayLastResponse.test.tsx | 110 +++++++++++++++++- frontend/src/hooks/useAutoPlayLastResponse.ts | 15 ++- .../src/hooks/useVoiceConversation.test.tsx | 79 ++++++++++++- frontend/src/hooks/useVoiceConversation.ts | 82 +++++++------ frontend/src/lib/voiceConversation.test.ts | 21 ++++ shared/src/opencode/voiceConversation.ts | 2 +- 8 files changed, 292 insertions(+), 45 deletions(-) diff --git a/frontend/src/components/message/PromptInput.stt.test.tsx b/frontend/src/components/message/PromptInput.stt.test.tsx index 537797e2..80d50b3e 100644 --- a/frontend/src/components/message/PromptInput.stt.test.tsx +++ b/frontend/src/components/message/PromptInput.stt.test.tsx @@ -298,6 +298,26 @@ describe('PromptInput voice conversation', () => { expect(promptInput()).toHaveValue('draft dictated words') }) + + it('focuses the text box with the cursor after the transcript once the conversation closes', async () => { + const view = renderComponent({ onVoiceConversationActiveChange: vi.fn() }) + + fireEvent.change(promptInput(), { target: { value: 'draft' } }) + + setVoiceController({ isActive: true, phase: 'listening', canEditInTextBox: true }, 'dictated words') + view.rerenderWith({ messages: [] }) + fireEvent.click(screen.getByRole('button', { name: 'Edit in text box' })) + + setVoiceController() + view.rerenderWith({ messages: [] }) + + await waitFor(() => { + const input = promptInput() as HTMLTextAreaElement + expect(input).toHaveFocus() + expect(input.selectionStart).toBe('draft dictated words'.length) + expect(input.selectionEnd).toBe('draft dictated words'.length) + }) + }) }) describe('sending a voice turn', () => { diff --git a/frontend/src/components/message/PromptInput.tsx b/frontend/src/components/message/PromptInput.tsx index 9ccf6b5f..78e8a075 100644 --- a/frontend/src/components/message/PromptInput.tsx +++ b/frontend/src/components/message/PromptInput.tsx @@ -1112,9 +1112,11 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read) const handleVoiceEditInTextBox = useCallback((text: string) => { const dictated = text.trim() if (!dictated) return - setPrompt((current) => (current.trim() ? `${current} ${dictated}` : dictated)) - textareaRef.current?.focus() - }, []) + const current = promptRef.current + const next = current.trim() ? `${current} ${dictated}` : dictated + setPrompt(next) + focusPromptAt(next.length) + }, [focusPromptAt]) const voiceConversation = useVoiceConversation({ sessionID, diff --git a/frontend/src/hooks/__tests__/useAutoPlayLastResponse.test.tsx b/frontend/src/hooks/__tests__/useAutoPlayLastResponse.test.tsx index 8754d877..fd6d2be1 100644 --- a/frontend/src/hooks/__tests__/useAutoPlayLastResponse.test.tsx +++ b/frontend/src/hooks/__tests__/useAutoPlayLastResponse.test.tsx @@ -27,7 +27,7 @@ interface MockTTSReturn { activeMessageId: string | null } -import { getLatestPlayableAssistantMessage, useAutoPlayLastResponse } from '../useAutoPlayLastResponse' +import { getAssistantText, getLatestPlayableAssistantMessage, useAutoPlayLastResponse } from '../useAutoPlayLastResponse' const createMessage = ( id: string, @@ -172,6 +172,114 @@ describe('useAutoPlayLastResponse', () => { expect(mockQueueMessage).not.toHaveBeenCalled() }) + it('does NOT queue a reply that completed while voice mode owned playback when enabled turns back on', () => { + setup() + + const baselineMessage = createMessage('0', Date.now()) + const streamingMessage = createMessage('1') + const completedMessage = createMessage('1', Date.now()) + const { rerender } = renderHook( + (props) => useAutoPlayLastResponse(props), + { + initialProps: { + sessionId: 'test-session', + lastAssistantMessage: baselineMessage, + lastAssistantText: 'Earlier reply', + enabled: true, + }, + }, + ) + + expect(mockQueueMessage).not.toHaveBeenCalled() + + rerender({ + sessionId: 'test-session', + lastAssistantMessage: streamingMessage, + lastAssistantText: 'Read by voice mode', + enabled: false, + }) + + rerender({ + sessionId: 'test-session', + lastAssistantMessage: completedMessage, + lastAssistantText: 'Read by voice mode', + enabled: false, + }) + + expect(mockQueueMessage).not.toHaveBeenCalled() + + rerender({ + sessionId: 'test-session', + lastAssistantMessage: completedMessage, + lastAssistantText: 'Read by voice mode', + enabled: true, + }) + + expect(mockQueueMessage).not.toHaveBeenCalled() + }) + + it('queues a reply that was still streaming when voice mode handed playback back, once it completes', () => { + setup() + + const streamingMessage = createMessage('1') + const { rerender } = renderHook( + (props) => useAutoPlayLastResponse(props), + { + initialProps: { + sessionId: 'test-session', + lastAssistantMessage: streamingMessage, + lastAssistantText: 'Test text', + enabled: false, + }, + }, + ) + + rerender({ + sessionId: 'test-session', + lastAssistantMessage: streamingMessage, + lastAssistantText: 'Test text', + enabled: true, + }) + + expect(mockQueueMessage).not.toHaveBeenCalled() + + rerender({ + sessionId: 'test-session', + lastAssistantMessage: createMessage('1', Date.now()), + lastAssistantText: 'Test text', + enabled: true, + }) + + expect(mockQueueMessage).toHaveBeenCalledTimes(1) + expect(mockQueueMessage).toHaveBeenCalledWith('1', 'Test text') + }) + + it('queues a reply with its inline think block stripped', () => { + setup() + + const streamingMessage = createMessage('1', undefined, 'The answer is ready hidden reasoning and verified') + const { rerender } = renderHook( + (props) => useAutoPlayLastResponse(props), + { + initialProps: { + sessionId: 'test-session', + lastAssistantMessage: streamingMessage, + lastAssistantText: getAssistantText(streamingMessage), + }, + }, + ) + + const completedMessage = createMessage('1', Date.now(), 'The answer is ready hidden reasoning and verified') + rerender({ + sessionId: 'test-session', + lastAssistantMessage: completedMessage, + lastAssistantText: getAssistantText(completedMessage), + }) + + expect(mockQueueMessage).toHaveBeenCalledTimes(1) + expect(mockQueueMessage).toHaveBeenCalledWith('1', 'The answer is ready and verified') + }) + it('does NOT call queueMessage on mount when last message was already time.completed', () => { setup() diff --git a/frontend/src/hooks/useAutoPlayLastResponse.ts b/frontend/src/hooks/useAutoPlayLastResponse.ts index 04b94ae8..f761061a 100644 --- a/frontend/src/hooks/useAutoPlayLastResponse.ts +++ b/frontend/src/hooks/useAutoPlayLastResponse.ts @@ -17,7 +17,7 @@ interface PlayableAssistantMessage { } export function getAssistantText(message: SessionMessageInfo | undefined): string { - return message?.type === 'assistant' ? assistantText(message.content) : '' + return message?.type === 'assistant' ? assistantText(message.content, { stripThink: true }) : '' } export function getLatestPlayableAssistantMessage(messages: SessionMessageInfo[] | undefined): PlayableAssistantMessage | undefined { @@ -73,10 +73,19 @@ export function useAutoPlayLastResponse({ }, [sessionId]) useEffect(() => { - if (!enabled || !ttsEnabled || !autoPlayEnabled) { + if (!enabled) { + if (lastAssistantMessage && isMessageCompleted(lastAssistantMessage)) { + hasInitializedRef.current = true + lastSpokenIdRef.current = lastAssistantMessage.id + lastKnownCompletedRef.current[lastAssistantMessage.id] = true + } return } - + + if (!ttsEnabled || !autoPlayEnabled) { + return + } + if (!lastAssistantMessage) { return } diff --git a/frontend/src/hooks/useVoiceConversation.test.tsx b/frontend/src/hooks/useVoiceConversation.test.tsx index ff32927b..a70b0c90 100644 --- a/frontend/src/hooks/useVoiceConversation.test.tsx +++ b/frontend/src/hooks/useVoiceConversation.test.tsx @@ -3,6 +3,7 @@ import { act, renderHook, waitFor } from '@testing-library/react' import { useReducer, useEffect } from 'react' import { VOICE_MODE_INSTRUCTION_KEY } from '@opencode-manager/shared/opencode' import type { SessionMessageAssistant } from '@opencode-manager/shared/opencode' +import type { TTSEndReason } from '@/contexts/tts-context' import type { SttEndOfSpeechReason } from '@/lib/webSpeechRecognizer' import { useVoiceConversation } from './useVoiceConversation' import type { UseVoiceConversationInput } from './useVoiceConversation' @@ -113,6 +114,14 @@ async function endOfSpeech(reason: SttEndOfSpeechReason, finalText: string) { }) } +function speechEndHandler(callIndex = 0): (reason: TTSEndReason) => void { + const options = harness.speakMessage.mock.calls[callIndex]?.[2] as + | { onEnd?: (reason: TTSEndReason) => void } + | undefined + if (!options?.onEnd) throw new Error('speakMessage was not called with an onEnd handler') + return options.onEnd +} + function assistantMessage(id: string, text: string): SessionMessageAssistant { return { id, @@ -171,6 +180,7 @@ describe('useVoiceConversation', () => { harness.listSessionInstructionKeys.mockResolvedValue([]) harness.sendTurn.mockResolvedValue(undefined) harness.interrupt.mockResolvedValue(undefined) + harness.startRecording.mockResolvedValue(true) }) it('starts listening and opens capture with the pause budget when idle', async () => { @@ -226,8 +236,7 @@ describe('useVoiceConversation', () => { expect(result.current.label).toBe('Speaking') expect(result.current.canStopAgent).toBe(false) - const options = harness.speakMessage.mock.calls[0]?.[2] as { onEnd: () => void } - act(() => options.onEnd()) + act(() => speechEndHandler(0)('completed')) await waitFor(() => expect(result.current.phase).toBe('listening')) expect(harness.startRecording).toHaveBeenCalledTimes(2) @@ -374,4 +383,70 @@ describe('useVoiceConversation', () => { expect(result.current.hint).toBe('Tap to talk') expect(result.current.orbLabel).toBe('Resume voice conversation') }) + + it('pauses with an error when capture cannot start', async () => { + harness.startRecording.mockResolvedValue(false) + const { result } = renderHook((props: UseVoiceConversationInput) => useVoiceConversation(props), { + initialProps: createProps(), + }) + + act(() => result.current.start()) + + await waitFor(() => expect(result.current.phase).toBe('paused')) + expect(result.current.label).toBe('Something went wrong') + expect(result.current.hint).toBe('Tap to retry') + }) + + it('pauses when speech recognition reports an error while listening', async () => { + const { result } = renderHook((props: UseVoiceConversationInput) => useVoiceConversation(props), { + initialProps: createProps(), + }) + + act(() => result.current.start()) + await waitFor(() => expect(result.current.phase).toBe('listening')) + + updateStt({ isError: true, error: 'Microphone access denied' }) + + await waitFor(() => expect(result.current.phase).toBe('paused')) + expect(result.current.label).toBe('Something went wrong') + }) + + it('pauses instead of finishing the turn when reading the reply fails', async () => { + const { result, rerender } = renderHook( + (props: UseVoiceConversationInput) => useVoiceConversation(props), + { initialProps: createProps() }, + ) + + act(() => result.current.start()) + await waitFor(() => expect(result.current.phase).toBe('listening')) + await endOfSpeech('pause', 'hello there') + await waitFor(() => expect(result.current.phase).toBe('working')) + + rerender(createProps({ messages: [assistantMessage('msg_1', 'Done')] })) + await waitFor(() => expect(result.current.phase).toBe('speaking')) + + act(() => speechEndHandler(0)('error')) + + expect(result.current.phase).toBe('paused') + expect(result.current.label).toBe('Something went wrong') + expect(harness.startRecording).toHaveBeenCalledTimes(1) + }) + + it('marks a reply with nothing to read as heard and listens again', async () => { + const { result, rerender } = renderHook( + (props: UseVoiceConversationInput) => useVoiceConversation(props), + { initialProps: createProps() }, + ) + + act(() => result.current.start()) + await waitFor(() => expect(result.current.phase).toBe('listening')) + await endOfSpeech('pause', 'hello there') + await waitFor(() => expect(result.current.phase).toBe('working')) + + rerender(createProps({ messages: [assistantMessage('msg_1', '```ts\nconst answer = 42\n```')] })) + + await waitFor(() => expect(result.current.phase).toBe('listening')) + expect(harness.speakMessage).not.toHaveBeenCalled() + expect(harness.startRecording).toHaveBeenCalledTimes(2) + }) }) diff --git a/frontend/src/hooks/useVoiceConversation.ts b/frontend/src/hooks/useVoiceConversation.ts index deba94a6..3d9b4793 100644 --- a/frontend/src/hooks/useVoiceConversation.ts +++ b/frontend/src/hooks/useVoiceConversation.ts @@ -29,6 +29,7 @@ import { } from '@/api/opencode' import { useSTT } from '@/hooks/useSTT' import { useTTS } from '@/hooks/useTTS' +import { sanitizeForTTS } from '@/lib/utils' import type { SttEndOfSpeechReason } from '@/lib/webSpeechRecognizer' /** Everything the voice conversation loop needs from the view that owns it. */ @@ -128,6 +129,10 @@ const SPEAKING_WATCHDOG_MAX_MS = 180_000 const SPEAKING_STALLED_MESSAGE = 'Reading the reply stopped responding' +const REPLY_READ_FAILED_MESSAGE = 'Reading the reply failed' + +const STT_FAILED_MESSAGE = 'Speech recognition failed' + const LISTENING_MAX_TURN_MS = 120_000 const STT_STOP_TIMEOUT_MS = 10_000 @@ -300,7 +305,7 @@ export function useVoiceConversation( const phaseRef = useRef(state.phase) const baselineIdRef = useRef(state.baselineId) const previousPhaseRef = useRef('off') - const captureEntryRef = useRef(false) + const previousSttErrorRef = useRef(false) const activeSessionIDRef = useRef(null) const endTurnInFlightRef = useRef(false) const turnGenerationRef = useRef(0) @@ -312,7 +317,6 @@ export function useVoiceConversation( const speakingTextRef = useRef('') const speakingIdRef = useRef(null) const spokenIdsRef = useRef>(new Set()) - const observedTtsErrorRef = useRef(null) const noSpeechTimerRef = useRef | null>(null) const maxTurnTimerRef = useRef | null>(null) const pendingTurnBaselineRef = useRef(null) @@ -417,14 +421,27 @@ export function useVoiceConversation( [], ) + const failCapture = useCallback((message: string) => { + const phase = phaseRef.current + if (phase !== 'listening' && phase !== 'recording') return + phaseRef.current = 'paused' + dispatch({ type: 'error', message }) + }, []) + const startCapture = useCallback(async () => { const current = sttRef.current if (!current || !current.isEnabled || !current.isSupported) return - await current.startRecording({ + const generation = turnGenerationRef.current + const phase = phaseRef.current + const started = await current.startRecording({ endpointing: { pauseMs, noSpeechTimeoutMs: VOICE_NO_SPEECH_TIMEOUT_MS }, onEndOfSpeech: handleEndOfSpeech, }) - }, [pauseMs, handleEndOfSpeech]) + if (started) return + if (turnGenerationRef.current !== generation) return + if (phaseRef.current !== phase) return + failCapture(sttRef.current?.error ?? STT_FAILED_MESSAGE) + }, [pauseMs, handleEndOfSpeech, failCapture]) const endTurn = useCallback( async (finalText?: string) => { @@ -500,9 +517,8 @@ export function useVoiceConversation( previousPhaseRef.current = state.phase if (state.phase !== 'listening' && state.phase !== 'recording') return if (previousPhase === state.phase) return - if (state.phase === 'listening') captureEntryRef.current = true const current = sttRef.current - if (current?.state === 'error') current.abortRecording() + if (current?.isError) current.abortRecording() void startCapture() }, [state.phase, startCapture]) @@ -527,8 +543,14 @@ export function useVoiceConversation( speakingIdRef.current = message.id spokenIdsRef.current.add(message.id) void latestRef.current.tts.speakMessage(message.id, message.text, { - onEnd: () => { + onEnd: (reason) => { if (speakTokenRef.current !== token) return + if (reason === 'error') { + speakTokenRef.current += 1 + speakingIdRef.current = null + dispatch({ type: 'error', message: REPLY_READ_FAILED_MESSAGE }) + return + } speakingIdRef.current = null if (playbackHeldRef.current) { setHeldPlayback(false) @@ -541,17 +563,6 @@ export function useVoiceConversation( [setHeldPlayback], ) - useEffect(() => { - const previousError = observedTtsErrorRef.current - observedTtsErrorRef.current = tts.error - if (state.phase !== 'speaking') return - if (tts.error === null || tts.error === previousError) return - speakTokenRef.current += 1 - speakingIdRef.current = null - latestRef.current.tts.stop() - dispatch({ type: 'error', message: tts.error }) - }, [state.phase, tts.error]) - useEffect(() => { if (state.phase !== 'speaking') return const estimated = @@ -613,17 +624,19 @@ export function useVoiceConversation( return } const spokenIds = spokenIdsRef.current - const next = findNextUnspokenMessage(messages, state.baselineId, spokenIds) - if (next) { + const unspoken = listUnspokenMessages(messages, state.baselineId, spokenIds) + const readable = latestRef.current.tts.isEnabled + ? unspoken.find((message) => sanitizeForTTS(message.text).trim() !== '') + : undefined + if (readable) { clearWorkingTimers() - if (latestRef.current.tts.isEnabled) { - dispatch({ type: 'speak-start' }) - speakMessage(next) - return - } - for (const message of listUnspokenMessages(messages, state.baselineId, spokenIds)) { - spokenIds.add(message.id) - } + dispatch({ type: 'speak-start' }) + speakMessage(readable) + return + } + if (unspoken.length > 0) { + clearWorkingTimers() + for (const message of unspoken) spokenIds.add(message.id) } if (pendingPromptCount > 0) clearTimeoutRef(noDeliveryTimerRef) if (status !== 'idle') { @@ -890,6 +903,7 @@ export function useVoiceConversation( dispatch({ type: 'exit' }) sttRef.current?.abortRecording() const { tts: capturedTts, serverId: capturedServerId } = latestRef.current + speakTokenRef.current += 1 capturedTts.stop() const pendingPut = instructionPutRef.current instructionPutRef.current = null @@ -933,13 +947,11 @@ export function useVoiceConversation( }, [requestPause]) useEffect(() => { - const enteredCapture = captureEntryRef.current - captureEntryRef.current = false - if (state.phase !== 'listening' && state.phase !== 'recording') return - if (stt.state !== 'error') return - if (enteredCapture) return - dispatch({ type: 'error', message: stt.error ?? 'Speech recognition failed' }) - }, [state.phase, stt.state, stt.error]) + const wasError = previousSttErrorRef.current + previousSttErrorRef.current = stt.isError + if (!stt.isError || wasError) return + failCapture(stt.error ?? STT_FAILED_MESSAGE) + }, [stt.isError, stt.error, failCapture]) const hasHeldReading = state.phase === 'paused' && playbackHeld const textInput = { diff --git a/frontend/src/lib/voiceConversation.test.ts b/frontend/src/lib/voiceConversation.test.ts index 7710794c..0477258f 100644 --- a/frontend/src/lib/voiceConversation.test.ts +++ b/frontend/src/lib/voiceConversation.test.ts @@ -520,6 +520,27 @@ describe('listUnspokenMessages', () => { expect(listUnspokenMessages(messages, null, new Set())).toEqual([{ id: 'a2', text: 'Spoken' }]) }) + it('excludes an inline think block from the spoken text', () => { + const messages = [ + user('u1', 'hi', 1), + assistant('a1', 2, 3, ['The answer is ready hidden reasoning and verified']), + ] + + expect(listUnspokenMessages(messages, null, new Set())).toEqual([ + { id: 'a1', text: 'The answer is ready and verified' }, + ]) + }) + + it('skips a completed reply that only contains a think block', () => { + const messages = [ + user('u1', 'hi', 1), + assistant('a1', 2, 3, ['hidden reasoning']), + assistant('a2', 4, 5, ['Spoken']), + ] + + expect(listUnspokenMessages(messages, null, new Set())).toEqual([{ id: 'a2', text: 'Spoken' }]) + }) + it('considers the whole transcript when the baseline is null', () => { const messages = [user('u1', 'only turn', 1), assistant('a1', 2, 3, ['The answer'])] diff --git a/shared/src/opencode/voiceConversation.ts b/shared/src/opencode/voiceConversation.ts index 58c5e619..4a8bbcdd 100644 --- a/shared/src/opencode/voiceConversation.ts +++ b/shared/src/opencode/voiceConversation.ts @@ -260,7 +260,7 @@ export function listUnspokenMessages( if (message === undefined || message.type !== 'assistant') continue if (message.time.completed === undefined) continue if (spokenIds.has(message.id)) continue - const text = assistantText(message.content).trim() + const text = assistantText(message.content, { stripThink: true }).trim() if (!text) continue unspoken.push({ id: message.id, text }) }