From 99b8d854d4e5db0dd580ad860058ebc1c9e267a4 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:49:47 -0500 Subject: [PATCH] Keep voice mode listening after empty sends and transcription errors, and let failed sends be resent --- .../message/VoiceConversationBar.test.tsx | 23 +- .../src/hooks/useVoiceConversation.test.tsx | 234 ++++++++++++++++-- frontend/src/hooks/useVoiceConversation.ts | 166 +++++++++++-- frontend/src/lib/voiceConversation.test.ts | 99 +++++++- shared/src/opencode/voiceConversation.ts | 40 ++- 5 files changed, 522 insertions(+), 40 deletions(-) diff --git a/frontend/src/components/message/VoiceConversationBar.test.tsx b/frontend/src/components/message/VoiceConversationBar.test.tsx index 884dfab6..80e226ab 100644 --- a/frontend/src/components/message/VoiceConversationBar.test.tsx +++ b/frontend/src/components/message/VoiceConversationBar.test.tsx @@ -223,18 +223,39 @@ describe('VoiceConversationBar', () => { renderBar( buildController({ phase: 'paused', - label: 'Microphone access denied. Please allow microphone permissions.', + label: 'Microphone problem', + notice: 'Microphone access denied. Please allow microphone permissions.', hint: 'Allow microphone access, then tap to retry', orbLabel: 'Resume voice conversation', }), ) + expect(screen.getByText('Microphone problem')).toBeInTheDocument() expect( screen.getByText('Microphone access denied. Please allow microphone permissions.'), ).toBeInTheDocument() expect(screen.getByText('Allow microphone access, then tap to retry')).toBeInTheDocument() }) + it('offers the edit control while paused with a failed message', async () => { + const user = userEvent.setup() + const controller = buildController({ + phase: 'paused', + label: "Couldn't send your message", + hint: 'Tap to resend', + notice: "Couldn't send: network down", + canEditInTextBox: true, + orbLabel: 'Resend message', + }) + renderBar(controller) + + expect(screen.queryByRole('button', { name: 'Exit voice conversation' })).toBeNull() + expect(screen.getByRole('button', { name: 'Resend message' })).toBeInTheDocument() + await user.click(screen.getByRole('button', { name: 'Edit in text box' })) + + expect(controller.editInTextBox).toHaveBeenCalledTimes(1) + }) + it('shows the notice when there is one and keeps the reserved hint line empty', () => { renderBar( buildController({ diff --git a/frontend/src/hooks/useVoiceConversation.test.tsx b/frontend/src/hooks/useVoiceConversation.test.tsx index da1f2454..1ad41c87 100644 --- a/frontend/src/hooks/useVoiceConversation.test.tsx +++ b/frontend/src/hooks/useVoiceConversation.test.tsx @@ -458,7 +458,61 @@ describe('useVoiceConversation', () => { expect(result.current.orbLabel).toBe('Resume voice conversation') }) - it('pauses with an error when capture cannot start', async () => { + it('keeps listening and restarts capture when a tap captures nothing', async () => { + const { result } = renderHook((props: UseVoiceConversationInput) => useVoiceConversation(props, collaborators), { + initialProps: createProps(), + }) + + act(() => result.current.start()) + await waitFor(() => expect(result.current.phase).toBe('listening')) + expect(harness.startRecording).toHaveBeenCalledTimes(1) + + act(() => result.current.tapOrb()) + + await waitFor(() => expect(harness.startRecording).toHaveBeenCalledTimes(2)) + expect(result.current.phase).toBe('listening') + expect(result.current.label).toBe('Listening') + expect(result.current.notice).toBe("Didn't hear anything, still listening") + expect(harness.sendTurn).not.toHaveBeenCalled() + }) + + it('clears the empty-tap notice once speech arrives', async () => { + const { result } = renderHook((props: UseVoiceConversationInput) => useVoiceConversation(props, collaborators), { + initialProps: createProps(), + }) + + act(() => result.current.start()) + await waitFor(() => expect(result.current.phase).toBe('listening')) + + act(() => result.current.tapOrb()) + await waitFor(() => + expect(result.current.notice).toBe("Didn't hear anything, still listening"), + ) + + updateStt({ interimTranscript: 'hello' }) + + await waitFor(() => expect(result.current.notice).toBeNull()) + }) + + it('keeps working with a notice when a queue tap captures nothing', async () => { + const { result } = renderHook((props: UseVoiceConversationInput) => useVoiceConversation(props, collaborators), { + initialProps: createProps({ status: 'busy' }), + }) + + act(() => result.current.start()) + await waitFor(() => expect(result.current.phase).toBe('working')) + + act(() => result.current.tapOrb()) + await waitFor(() => expect(result.current.phase).toBe('recording')) + + act(() => result.current.tapOrb()) + + await waitFor(() => expect(result.current.phase).toBe('working')) + expect(result.current.notice).toBe("Didn't hear anything") + expect(harness.sendTurn).not.toHaveBeenCalled() + }) + + it('pauses with a microphone label and the reason when capture cannot start', async () => { harness.startRecording.mockResolvedValue(false) const { result } = renderHook((props: UseVoiceConversationInput) => useVoiceConversation(props, collaborators), { initialProps: createProps(), @@ -467,31 +521,29 @@ describe('useVoiceConversation', () => { act(() => result.current.start()) await waitFor(() => expect(result.current.phase).toBe('paused')) - expect(result.current.label).toBe('Speech recognition failed') + expect(result.current.label).toBe('Microphone problem') + expect(result.current.notice).toBe('Speech recognition failed') expect(result.current.hint).toBe('Allow microphone access, then tap to retry') }) - it('shows the specific microphone failure and how to fix it', async () => { + it('shows the specific microphone failure in the notice and how to fix it', async () => { + harness.startRecording.mockResolvedValue(false) + updateStt({ error: 'Microphone access denied. Please allow microphone permissions.' }) const { result } = renderHook((props: UseVoiceConversationInput) => useVoiceConversation(props, collaborators), { initialProps: createProps(), }) act(() => result.current.start()) - await waitFor(() => expect(result.current.phase).toBe('listening')) - - updateStt({ - isError: true, - error: 'Microphone access denied. Please allow microphone permissions.', - }) await waitFor(() => expect(result.current.phase).toBe('paused')) - expect(result.current.label).toBe( + expect(result.current.label).toBe('Microphone problem') + expect(result.current.notice).toBe( 'Microphone access denied. Please allow microphone permissions.', ) expect(result.current.hint).toBe('Allow microphone access, then tap to retry') }) - it('keeps a plain retry for a failure that retrying can clear', async () => { + it('keeps the failed text and resends it from the orb', async () => { harness.sendTurn.mockRejectedValueOnce(new Error('network down')) const { result } = renderHook((props: UseVoiceConversationInput) => useVoiceConversation(props, collaborators), { initialProps: createProps(), @@ -502,8 +554,54 @@ describe('useVoiceConversation', () => { await endOfSpeech('pause', 'hello there') await waitFor(() => expect(result.current.phase).toBe('paused')) - expect(result.current.label).toBe('network down') - expect(result.current.hint).toBe('Tap to retry') + expect(result.current.label).toBe("Couldn't send your message") + expect(result.current.notice).toBe("Couldn't send: network down") + expect(result.current.hint).toBe('Tap to resend') + expect(result.current.orbLabel).toBe('Resend message') + expect(result.current.canEditInTextBox).toBe(true) + + act(() => result.current.tapOrb()) + + await waitFor(() => expect(result.current.phase).toBe('working')) + expect(harness.sendTurn).toHaveBeenCalledTimes(2) + expect(harness.sendTurn).toHaveBeenLastCalledWith('hello there', { busy: false }) + expect(result.current.notice).toBeNull() + expect(result.current.canEditInTextBox).toBe(false) + }) + + it('resends the failed text from the resume control', async () => { + harness.sendTurn.mockRejectedValueOnce(new Error('network down')) + const { result } = renderHook((props: UseVoiceConversationInput) => useVoiceConversation(props, collaborators), { + 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('paused')) + + act(() => result.current.resume()) + + await waitFor(() => expect(harness.sendTurn).toHaveBeenCalledTimes(2)) + expect(harness.sendTurn).toHaveBeenLastCalledWith('hello there', { busy: false }) + await waitFor(() => expect(result.current.phase).toBe('working')) + }) + + it('moves the failed text into the composer instead of resuming', async () => { + harness.sendTurn.mockRejectedValueOnce(new Error('network down')) + const { result } = renderHook((props: UseVoiceConversationInput) => useVoiceConversation(props, collaborators), { + 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('paused')) + + act(() => result.current.editInTextBox()) + + expect(harness.onEditInTextBox).toHaveBeenCalledWith('hello there') + expect(result.current.phase).toBe('off') }) it('reports that the microphone is starting until capture begins', async () => { @@ -525,7 +623,29 @@ describe('useVoiceConversation', () => { expect(result.current.hint).toBe('Tap to send') }) - it('pauses when speech recognition reports an error while listening', async () => { + it('keeps listening and restarts capture when a transcription fails', async () => { + const { result } = renderHook((props: UseVoiceConversationInput) => useVoiceConversation(props, collaborators), { + initialProps: createProps(), + }) + + act(() => result.current.start()) + await waitFor(() => expect(result.current.phase).toBe('listening')) + expect(harness.startRecording).toHaveBeenCalledTimes(1) + + updateStt({ isRecording: true }) + updateStt({ isError: true, error: 'STT API returned invalid response' }) + + await waitFor(() => expect(harness.startRecording).toHaveBeenCalledTimes(2)) + expect(harness.abortRecording).toHaveBeenCalledTimes(1) + expect(result.current.phase).toBe('listening') + expect(result.current.label).toBe('Listening') + expect(result.current.notice).toBe( + "Couldn't transcribe that: STT API returned invalid response. Still listening", + ) + expect(harness.sendTurn).not.toHaveBeenCalled() + }) + + it('pauses after three transcription failures in a row', async () => { const { result } = renderHook((props: UseVoiceConversationInput) => useVoiceConversation(props, collaborators), { initialProps: createProps(), }) @@ -533,10 +653,86 @@ describe('useVoiceConversation', () => { act(() => result.current.start()) await waitFor(() => expect(result.current.phase).toBe('listening')) - updateStt({ isError: true, error: 'Microphone access denied' }) + updateStt({ isError: true, error: 'STT API returned invalid response' }) + await waitFor(() => expect(harness.startRecording).toHaveBeenCalledTimes(2)) + updateStt({ isError: false, error: null }) + + updateStt({ isError: true, error: 'STT API returned invalid response' }) + await waitFor(() => expect(harness.startRecording).toHaveBeenCalledTimes(3)) + updateStt({ isError: false, error: null }) + + updateStt({ isError: true, error: 'STT API returned invalid response' }) await waitFor(() => expect(result.current.phase).toBe('paused')) - expect(result.current.label).toBe('Microphone access denied') + expect(result.current.label).toBe("Transcription isn't working") + expect(result.current.hint).toBe('Tap to try again') + expect(result.current.notice).toBe('STT API returned invalid response') + expect(harness.startRecording).toHaveBeenCalledTimes(3) + }) + + it('resets the transcription failure streak after a sent message', async () => { + const { result } = renderHook((props: UseVoiceConversationInput) => useVoiceConversation(props, collaborators), { + initialProps: createProps({ status: 'busy' }), + }) + + act(() => result.current.start()) + await waitFor(() => expect(result.current.phase).toBe('working')) + + act(() => result.current.tapOrb()) + await waitFor(() => expect(result.current.phase).toBe('recording')) + updateStt({ isError: true, error: 'first failure' }) + await waitFor(() => expect(result.current.phase).toBe('working')) + updateStt({ isError: false, error: null }) + + act(() => result.current.tapOrb()) + await waitFor(() => expect(result.current.phase).toBe('recording')) + updateStt({ isError: true, error: 'second failure' }) + await waitFor(() => expect(result.current.phase).toBe('working')) + updateStt({ isError: false, error: null }) + + act(() => result.current.tapOrb()) + await waitFor(() => expect(result.current.phase).toBe('recording')) + await endOfSpeech('pause', 'hello there') + await waitFor(() => + expect(harness.sendTurn).toHaveBeenCalledWith('hello there', { busy: true }), + ) + + for (const error of ['third failure', 'fourth failure']) { + act(() => result.current.tapOrb()) + await waitFor(() => expect(result.current.phase).toBe('recording')) + updateStt({ isError: true, error }) + await waitFor(() => expect(result.current.phase).toBe('working')) + updateStt({ isError: false, error: null }) + } + + expect(result.current.phase).toBe('working') + expect(harness.sendTurn).toHaveBeenCalledTimes(1) + }) + + it('restarts capture once when a transcription fails while a turn is finishing', async () => { + const { result } = renderHook((props: UseVoiceConversationInput) => useVoiceConversation(props, collaborators), { + initialProps: createProps(), + }) + + act(() => result.current.start()) + await waitFor(() => expect(result.current.phase).toBe('listening')) + expect(harness.startRecording).toHaveBeenCalledTimes(1) + + updateStt({ isRecording: true }) + act(() => result.current.tapOrb()) + updateStt({ isError: true, error: 'STT API returned invalid response' }) + + expect(harness.startRecording).toHaveBeenCalledTimes(1) + + updateStt({ isRecording: false, isProcessing: false, isError: true }) + + await waitFor(() => expect(harness.startRecording).toHaveBeenCalledTimes(2)) + expect(result.current.phase).toBe('listening') + expect(result.current.notice).toBe( + "Couldn't transcribe that: STT API returned invalid response. Still listening", + ) + expect(harness.sendTurn).not.toHaveBeenCalled() + expect(harness.startRecording).toHaveBeenCalledTimes(2) }) it('pauses instead of finishing the turn when reading the reply fails', async () => { @@ -556,7 +752,8 @@ describe('useVoiceConversation', () => { act(() => speechEndHandler(0)('error', 'Audio playback was blocked by the browser')) expect(result.current.phase).toBe('paused') - expect(result.current.label).toBe( + expect(result.current.label).toBe("Couldn't read the reply") + expect(result.current.notice).toBe( 'Reading the reply failed: Audio playback was blocked by the browser', ) expect(result.current.hint).toBe('Tap to retry') @@ -580,7 +777,8 @@ describe('useVoiceConversation', () => { act(() => speechEndHandler(0)('error')) expect(result.current.phase).toBe('paused') - expect(result.current.label).toBe('Reading the reply failed') + expect(result.current.label).toBe("Couldn't read the reply") + expect(result.current.notice).toBe('Reading the reply failed') }) it('marks replies as heard without speaking when read-back is turned off', async () => { diff --git a/frontend/src/hooks/useVoiceConversation.ts b/frontend/src/hooks/useVoiceConversation.ts index baf1b6b6..6b0ed364 100644 --- a/frontend/src/hooks/useVoiceConversation.ts +++ b/frontend/src/hooks/useVoiceConversation.ts @@ -17,6 +17,7 @@ import { import type { SessionInboxInfo, SessionMessageInfo, + VoiceFailureSource, VoicePauseReason, VoicePhase, VoiceSessionStatus, @@ -108,6 +109,12 @@ const REPLY_READ_FAILED_MESSAGE = 'Reading the reply failed' const STT_FAILED_MESSAGE = 'Speech recognition failed' +const EMPTY_TURN_NOTICE = "Didn't hear anything, still listening" + +const EMPTY_QUEUE_NOTICE = "Didn't hear anything" + +const TRANSCRIPTION_FAILURE_LIMIT = 3 + const LISTENING_MAX_TURN_MS = 120_000 const STT_STOP_TIMEOUT_MS = 10_000 @@ -130,6 +137,12 @@ function clearTimeoutRef(ref: TimeoutRef): void { ref.current = null } +function failureNotice(source: VoiceFailureSource | null, error: string | null): string | null { + const message = error?.trim() + if (!message) return null + return source === 'send' ? `Couldn't send: ${message}` : message +} + function latestMessageBaseline(messages: readonly SessionMessageInfo[]): string | null { return messages[messages.length - 1]?.id ?? null } @@ -177,9 +190,13 @@ function orbLabelFor( phase: VoicePhase, canStopAgent: boolean, hasHeldReading: boolean, + canResend: boolean, ): string { if (phase === 'speaking') return canStopAgent ? 'Add a message' : ORB_LABELS.speaking - if (phase === 'paused') return hasHeldReading ? 'Continue reading' : ORB_LABELS.paused + if (phase === 'paused') { + if (canResend) return 'Resend message' + return hasHeldReading ? 'Continue reading' : ORB_LABELS.paused + } return ORB_LABELS[phase] } @@ -253,6 +270,10 @@ export function useVoiceConversation( const playbackHeldRef = useRef(false) const endTurnRef = useRef<((finalText?: string) => Promise) | null>(null) const endRecordingRef = useRef<((finalText?: string) => Promise) | null>(null) + const failedTurnTextRef = useRef(null) + const transcriptionFailureCountRef = useRef(0) + const transcriptionFailedRef = useRef(false) + const captureStartingRef = useRef(false) const captureSettleRef = useRef void>>([]) const exitInFlightRef = useRef(false) const speakTokenRef = useRef(0) @@ -365,16 +386,45 @@ export function useVoiceConversation( if (!current || !current.isEnabled || !current.isSupported) return const generation = turnGenerationRef.current const phase = phaseRef.current - const started = await current.startRecording({ - endpointing: { pauseMs, noSpeechTimeoutMs: VOICE_NO_SPEECH_TIMEOUT_MS }, - onEndOfSpeech: handleEndOfSpeech, - }) + captureStartingRef.current = true + let started = false + try { + started = await current.startRecording({ + endpointing: { pauseMs, noSpeechTimeoutMs: VOICE_NO_SPEECH_TIMEOUT_MS }, + onEndOfSpeech: handleEndOfSpeech, + }) + } finally { + captureStartingRef.current = false + } if (started) return if (turnGenerationRef.current !== generation) return if (phaseRef.current !== phase) return failCapture(sttRef.current?.error ?? STT_FAILED_MESSAGE) }, [pauseMs, handleEndOfSpeech, failCapture]) + const handleTranscriptionFailure = useCallback(() => { + const phase = phaseRef.current + if (phase !== 'listening' && phase !== 'recording') return + transcriptionFailureCountRef.current += 1 + const message = sttRef.current?.error?.trim() || STT_FAILED_MESSAGE + const current = sttRef.current + if (current && (current.isRecording || current.isProcessing)) current.abortRecording() + if (transcriptionFailureCountRef.current >= TRANSCRIPTION_FAILURE_LIMIT) { + dispatch({ type: 'error', message, source: 'transcription' }) + return + } + setNotice(`Couldn't transcribe that: ${message}. Still listening`) + if (endTurnInFlightRef.current) { + transcriptionFailedRef.current = true + return + } + if (phase === 'recording') { + dispatch({ type: 'record-ended' }) + return + } + void startCapture() + }, [startCapture]) + const endTurn = useCallback( async (finalText?: string) => { if (exitInFlightRef.current) return @@ -386,8 +436,19 @@ export function useVoiceConversation( finalText === undefined ? await stopCapture() : capturedWords(finalText) if (turnGenerationRef.current !== generation) return if (phaseRef.current !== 'listening') return + if (!text) { + if (transcriptionFailedRef.current) { + transcriptionFailedRef.current = false + } else { + setNotice(EMPTY_TURN_NOTICE) + } + await startCapture() + return + } dispatch({ type: 'transcript', text }) - if (!text) return + failedTurnTextRef.current = null + transcriptionFailureCountRef.current = 0 + setNotice(null) const latest = latestRef.current const baselineId = latestMessageBaseline(latest.messages) fireImpactHaptic() @@ -395,6 +456,7 @@ export function useVoiceConversation( await latest.sendTurn(text, { busy: latest.status !== 'idle' }) } catch (error) { if (turnGenerationRef.current !== generation) return + failedTurnTextRef.current = text dispatch({ type: 'send-failed', message: errorMessage(error) }) return } @@ -406,7 +468,7 @@ export function useVoiceConversation( } } }, - [stopCapture], + [stopCapture, startCapture], ) const endRecording = useCallback( @@ -421,13 +483,24 @@ export function useVoiceConversation( if (turnGenerationRef.current !== generation) return if (phaseRef.current !== 'recording') return dispatch({ type: 'record-ended' }) - if (!text) return + if (!text) { + if (transcriptionFailedRef.current) { + transcriptionFailedRef.current = false + } else { + setNotice(EMPTY_QUEUE_NOTICE) + } + return + } + failedTurnTextRef.current = null + transcriptionFailureCountRef.current = 0 + setNotice(null) const latest = latestRef.current fireImpactHaptic() try { await latest.sendTurn(text, { busy: latest.status !== 'idle' }) } catch (error) { if (turnGenerationRef.current !== generation) return + failedTurnTextRef.current = text dispatch({ type: 'send-failed', message: errorMessage(error) }) } } finally { @@ -517,6 +590,11 @@ export function useVoiceConversation( const interimText = capturedWords(stt.interimTranscript) const turnTextValue = capturedWords(stt.transcript) + useEffect(() => { + if (!interimText && !turnTextValue) return + setNotice(null) + }, [interimText, turnTextValue]) + useEffect(() => { const isCapturing = state.phase === 'listening' || state.phase === 'recording' if (!isCapturing || !stt.isRecording || stt.isEndpointing) { @@ -649,6 +727,9 @@ export function useVoiceConversation( invalidateTurn() instructionEpochRef.current += 1 pendingTurnBaselineRef.current = null + failedTurnTextRef.current = null + transcriptionFailureCountRef.current = 0 + transcriptionFailedRef.current = false spokenIdsRef.current.clear() speakingIdRef.current = null activeSessionIDRef.current = latest.sessionID @@ -706,6 +787,9 @@ export function useVoiceConversation( const current = sttRef.current invalidateTurn() pendingTurnBaselineRef.current = null + failedTurnTextRef.current = null + transcriptionFailureCountRef.current = 0 + transcriptionFailedRef.current = false spokenIdsRef.current.clear() speakingIdRef.current = null if (current && (current.isRecording || current.isProcessing)) current.abortRecording() @@ -750,6 +834,11 @@ export function useVoiceConversation( const editInTextBox = useCallback(() => { const phase = phaseRef.current if (phase === 'off' || exitInFlightRef.current) return + const failedText = failedTurnTextRef.current + if (phase === 'paused' && failedText) { + performExit(failedText) + return + } const capturedText = readCapturedText() if ((phase !== 'listening' && phase !== 'recording') || !capturedText) { performExit('') @@ -763,8 +852,45 @@ export function useVoiceConversation( })() }, [invalidateTurn, performExit, readCapturedText, stopCapture]) + const resendFailedTurn = useCallback(async (text: string) => { + if (phaseRef.current !== 'paused' || failedTurnTextRef.current !== text) return + if (endTurnInFlightRef.current) return + const generation = turnGenerationRef.current + endTurnInFlightRef.current = true + const latest = latestRef.current + const busy = latest.status !== 'idle' + const baselineId = latestMessageBaseline(latest.messages) + pendingTurnBaselineRef.current = null + setNotice(null) + fireImpactHaptic() + dispatch({ type: 'resend', busy, baselineId }) + try { + await latest.sendTurn(text, { busy }) + } catch (error) { + if (turnGenerationRef.current !== generation) return + failedTurnTextRef.current = text + dispatch({ type: 'send-failed', message: errorMessage(error) }) + return + } finally { + if (turnGenerationRef.current === generation) { + endTurnInFlightRef.current = false + } + } + if (turnGenerationRef.current !== generation) return + failedTurnTextRef.current = null + dispatch({ type: 'turn-sent', baselineId }) + }, []) + const resumeConversation = useCallback(() => { if (phaseRef.current !== 'paused') return + transcriptionFailureCountRef.current = 0 + transcriptionFailedRef.current = false + const failedText = failedTurnTextRef.current + if (failedText) { + void resendFailedTurn(failedText) + return + } + setNotice(null) const latest = latestRef.current if (playbackHeldRef.current) { setHeldPlayback(false) @@ -786,7 +912,7 @@ export function useVoiceConversation( busy: latest.status !== 'idle' || pendingTurnBaseline !== null || hasUnspoken, baselineId: resumeBaseline ?? currentTurnBaseline(latest.messages), }) - }, [setHeldPlayback]) + }, [setHeldPlayback, resendFailedTurn]) const skipReading = useCallback(() => { const latest = latestRef.current @@ -864,6 +990,8 @@ export function useVoiceConversation( return () => { invalidateTurn() pendingTurnBaselineRef.current = null + transcriptionFailureCountRef.current = 0 + transcriptionFailedRef.current = false spokenIds.clear() speakingIdRef.current = null playbackHeldRef.current = false @@ -926,10 +1054,13 @@ export function useVoiceConversation( const wasError = previousSttErrorRef.current previousSttErrorRef.current = stt.isError if (!stt.isError || wasError) return - failCapture(stt.error ?? STT_FAILED_MESSAGE) - }, [stt.isError, stt.error, failCapture]) + if (captureStartingRef.current) return + handleTranscriptionFailure() + }, [stt.isError, stt.error, handleTranscriptionFailure]) const hasHeldReading = state.phase === 'paused' && playbackHeld + const hasFailedTurnText = + state.phase === 'paused' && state.failureSource === 'send' && failedTurnTextRef.current !== null const isCapturing = state.phase === 'listening' || state.phase === 'recording' const textInput = { phase: state.phase, @@ -941,19 +1072,26 @@ export function useVoiceConversation( error: state.error, failureSource: state.failureSource, isStartingCapture: isCapturing && stt.isStarting, + canResend: hasFailedTurnText, } const label = voiceConversationLabel(textInput) const hint = voiceConversationHint(textInput) const liveTranscript = isCapturing ? interimText || turnTextValue : '' - const canEditInTextBox = isCapturing && (interimText !== '' || turnTextValue !== '') + const canEditInTextBox = + hasFailedTurnText || (isCapturing && (interimText !== '' || turnTextValue !== '')) const canStopAgent = isActive && status !== 'idle' + const errorNotice = + state.phase === 'paused' && state.pauseReason === 'error' + ? failureNotice(state.failureSource, state.error) + : null + const shownNotice = errorNotice ?? notice return { isActive, phase: state.phase, label, hint, - orbLabel: orbLabelFor(state.phase, canStopAgent, hasHeldReading), + orbLabel: orbLabelFor(state.phase, canStopAgent, hasHeldReading, hasFailedTurnText), liveTranscript, canEditInTextBox, canStopAgent, @@ -961,7 +1099,7 @@ export function useVoiceConversation( isEndpointing: stt.isEndpointing, readRepliesAloud, canReadRepliesAloud: tts.isEnabled, - notice, + notice: shownNotice, start, exit, editInTextBox, diff --git a/frontend/src/lib/voiceConversation.test.ts b/frontend/src/lib/voiceConversation.test.ts index 385e149b..8f383004 100644 --- a/frontend/src/lib/voiceConversation.test.ts +++ b/frontend/src/lib/voiceConversation.test.ts @@ -87,6 +87,7 @@ function labelInput( error: null, failureSource: null, isStartingCapture: false, + canResend: false, ...overrides, } } @@ -205,6 +206,47 @@ describe('reduceVoiceConversation', () => { }) }) + describe('resend', () => { + it('returns to sending with a cleared failure when the session is idle', () => { + const state = conversation({ + phase: 'paused', + pauseReason: 'error', + error: 'network down', + failureSource: 'send', + baselineId: 'b2', + }) + expect( + reduceVoiceConversation(state, { type: 'resend', busy: false, baselineId: 'b3' }), + ).toEqual({ + ...state, + phase: 'sending', + pauseReason: null, + error: null, + failureSource: null, + }) + }) + + it('returns to working with the new baseline when the session is busy', () => { + const state = conversation({ + phase: 'paused', + pauseReason: 'error', + error: 'network down', + failureSource: 'send', + }) + expect( + reduceVoiceConversation(state, { type: 'resend', busy: true, baselineId: 'b3' }), + ).toEqual({ + ...state, + phase: 'working', + sawBusy: true, + baselineId: 'b3', + pauseReason: null, + error: null, + failureSource: null, + }) + }) + }) + describe('status', () => { it('records the first busy report after a turn is sent', () => { const state = conversation({ phase: 'working', baselineId: 'b2' }) @@ -463,6 +505,16 @@ describe('reduceVoiceConversation', () => { ], ['resume-speech while listening', conversation({ phase: 'listening' }), { type: 'resume-speech' }], ['resume-speech while speaking', conversation({ phase: 'speaking' }), { type: 'resume-speech' }], + [ + 'resend while listening', + conversation({ phase: 'listening' }), + { type: 'resend', busy: false, baselineId: null }, + ], + [ + 'resend while working', + conversation({ phase: 'working' }), + { type: 'resend', busy: true, baselineId: null }, + ], ])('ignores %s and returns the same state object', (_description, state, event) => { expect(reduceVoiceConversation(state, event)).toBe(state) }) @@ -716,7 +768,42 @@ describe('voiceConversationLabel', () => { error: 'Microphone access denied. Please allow microphone permissions.', failureSource: 'capture', }, - 'Microphone access denied. Please allow microphone permissions.', + 'Microphone problem', + ], + [ + 'paused after a capture failure without a reason', + { phase: 'paused', pauseReason: 'error', failureSource: 'capture' }, + 'Microphone problem', + ], + [ + 'paused after a send failure with a reason', + { + phase: 'paused', + pauseReason: 'error', + error: 'network down', + failureSource: 'send', + }, + "Couldn't send your message", + ], + [ + 'paused after a playback failure with a reason', + { + phase: 'paused', + pauseReason: 'error', + error: 'Audio playback was blocked by the browser', + failureSource: 'playback', + }, + "Couldn't read the reply", + ], + [ + 'paused after a transcription failure', + { + phase: 'paused', + pauseReason: 'error', + error: 'STT API returned invalid response', + failureSource: 'transcription', + }, + "Transcription isn't working", ], [ 'paused after a failure with a blank reason', @@ -783,11 +870,21 @@ describe('voiceConversationHint', () => { { phase: 'paused', pauseReason: 'error', failureSource: 'send' }, 'Tap to retry', ], + [ + 'paused after a send failure with the text kept', + { phase: 'paused', pauseReason: 'error', failureSource: 'send', canResend: true }, + 'Tap to resend', + ], [ 'paused after a playback failure', { phase: 'paused', pauseReason: 'error', failureSource: 'playback' }, 'Tap to retry', ], + [ + 'paused after a transcription failure', + { phase: 'paused', pauseReason: 'error', failureSource: 'transcription' }, + 'Tap to try again', + ], ['paused by the user', { phase: 'paused', pauseReason: 'user' }, 'Tap to talk'], [ 'paused by the user while a reply is held', diff --git a/shared/src/opencode/voiceConversation.ts b/shared/src/opencode/voiceConversation.ts index 697b2d76..f5a1722c 100644 --- a/shared/src/opencode/voiceConversation.ts +++ b/shared/src/opencode/voiceConversation.ts @@ -18,7 +18,7 @@ export type VoicePhase = export type VoicePauseReason = 'user' | 'background' | 'no-speech' | 'error' -export type VoiceFailureSource = 'capture' | 'send' | 'playback' +export type VoiceFailureSource = 'capture' | 'send' | 'playback' | 'transcription' export type VoiceSessionStatus = SessionStatus['type'] @@ -46,6 +46,7 @@ export type VoiceConversationEvent = | { type: 'turn-sent'; baselineId: string | null } | { type: 'turn-started'; baselineId: string | null } | { type: 'send-failed'; message: string } + | { type: 'resend'; busy: boolean; baselineId: string | null } | { type: 'status'; busy: boolean } | { type: 'speak-start' } | { type: 'speech-ended' } @@ -83,6 +84,7 @@ export interface VoiceConversationLabelInput { error?: string | null failureSource?: VoiceFailureSource | null isStartingCapture?: boolean + canResend?: boolean } export function reduceVoiceConversation( @@ -129,6 +131,25 @@ export function reduceVoiceConversation( error: event.message, failureSource: 'send', } + case 'resend': + if (state.phase !== 'paused') return state + return event.busy + ? { + ...state, + phase: 'working', + sawBusy: true, + baselineId: event.baselineId, + pauseReason: null, + error: null, + failureSource: null, + } + : { + ...state, + phase: 'sending', + pauseReason: null, + error: null, + failureSource: null, + } case 'status': if (state.phase !== 'working') return state if (!event.busy || state.sawBusy) return state @@ -267,7 +288,7 @@ export function isVoiceTurnComplete(input: VoiceTurnCompletionInput): boolean { } export function voiceConversationLabel(input: VoiceConversationLabelInput): string { - const { phase, pauseReason, pendingApproval, error, isStartingCapture } = input + const { phase, pauseReason, pendingApproval, error, failureSource, isStartingCapture } = input switch (phase) { case 'listening': @@ -282,7 +303,13 @@ export function voiceConversationLabel(input: VoiceConversationLabelInput): stri return isStartingCapture ? 'Starting…' : 'Adding to queue' case 'paused': if (pauseReason === 'no-speech') return "Didn't catch that" - if (pauseReason === 'error') return error?.trim() || 'Something went wrong' + if (pauseReason === 'error') { + if (failureSource === 'send') return "Couldn't send your message" + if (failureSource === 'capture') return 'Microphone problem' + if (failureSource === 'playback') return "Couldn't read the reply" + if (failureSource === 'transcription') return "Transcription isn't working" + return error?.trim() || 'Something went wrong' + } return 'Paused' case 'off': return '' @@ -318,9 +345,10 @@ export function voiceConversationHint(input: VoiceConversationLabelInput): strin case 'paused': if (pauseReason === 'no-speech') return 'Tap to talk' if (pauseReason === 'error') { - return failureSource === 'capture' - ? 'Allow microphone access, then tap to retry' - : 'Tap to retry' + if (failureSource === 'capture') return 'Allow microphone access, then tap to retry' + if (failureSource === 'send') return input.canResend ? 'Tap to resend' : 'Tap to retry' + if (failureSource === 'transcription') return 'Tap to try again' + return 'Tap to retry' } return isPlaybackPaused ? 'Tap to continue' : 'Tap to talk' case 'off':