The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): keep continuous voice working after a mic meter AudioContext error (#122278)
brooklyn!e417a096fd21
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-mic-recorder.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-mic-recorder.test.tsxnew file mode 100644index 00000000000..7e350a6d394--- /dev/null+++ b/apps/desktop/src/app/chat/composer/hooks/use-mic-recorder.test.tsx@@ -0,0 +1,190 @@+import { act, cleanup, renderHook } from '@testing-library/react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { type MicRecorderErrorCopy, useMicRecorder } from './use-mic-recorder'++// The level meter behind continuous voice mode is an AudioContext on the+// capture stream. #75329: a torn-down context was still closing when the next+// take opened another, the device errored, and the dead meter silently+// dropped every later utterance.++const copy: MicRecorderErrorCopy = {+ microphoneAccessDenied: 'denied',+ microphoneConstraintsUnsupported: 'constraints',+ microphoneInUse: 'in use',+ microphonePermissionDenied: 'permission',+ microphoneStartFailed: 'start failed',+ microphoneUnsupported: 'unsupported',+ noMicrophone: 'no mic'+}++function deferred() {+ let resolve!: () => void+ const promise = new Promise<void>(done => (resolve = done))++ return { promise, resolve }+}++class FakeAudioContext extends EventTarget {+ static instances: FakeAudioContext[] = []+ static throwOnConstruct = false+ state: AudioContextState = 'running'+ closing = deferred()++ constructor() {+ super()++ if (FakeAudioContext.throwOnConstruct) {+ throw new DOMException('too many contexts', 'NotSupportedError')+ }++ FakeAudioContext.instances.push(this)+ }++ createAnalyser() {+ return { fftSize: 0, getByteTimeDomainData: (data: Uint8Array) => data.fill(128) }+ }++ createMediaStreamSource() {+ return { connect: vi.fn() }+ }++ resume = vi.fn(async () => undefined)++ close() {+ return this.closing.promise.then(() => {+ this.state = 'closed'+ this.dispatchEvent(new Event('statechange'))+ })+ }+}++class FakeMediaRecorder {+ static isTypeSupported = () => true+ mimeType = 'audio/webm'+ state: RecordingState = 'inactive'+ ondataavailable: ((event: { data: Blob }) => void) | null = null+ onstop: (() => void) | null = null+ onerror: ((event: Event) => void) | null = null++ start() {+ this.state = 'recording'+ }++ stop() {+ this.state = 'inactive'+ this.ondataavailable?.({ data: new Blob(['clip'], { type: 'audio/webm' }) })+ this.onstop?.()+ }+}++const flush = () => act(async () => new Promise<void>(resolve => window.setTimeout(resolve, 0)))++beforeEach(() => {+ FakeAudioContext.instances = []+ FakeAudioContext.throwOnConstruct = false+ vi.stubGlobal('AudioContext', FakeAudioContext)+ vi.stubGlobal('MediaRecorder', FakeMediaRecorder)+ vi.stubGlobal(+ 'requestAnimationFrame',+ vi.fn(() => 1)+ )+ vi.stubGlobal('cancelAnimationFrame', vi.fn())+ Object.defineProperty(navigator, 'mediaDevices', {+ configurable: true,+ value: { getUserMedia: vi.fn(async () => ({ getTracks: () => [{ stop: vi.fn() }] })) }+ })+})++afterEach(() => {+ cleanup()+ FakeAudioContext.instances.forEach(context => context.closing.resolve())+ vi.unstubAllGlobals()+})++describe('useMicRecorder level meter', () => {+ it('waits for the previous take’s meter to finish closing before opening the next', async () => {+ const { result } = renderHook(() => useMicRecorder(copy))++ await act(async () => {+ await result.current.handle.start()+ })+ await act(async () => {+ await result.current.handle.stop()+ })++ const first = FakeAudioContext.instances[0]+ let secondStart: Promise<void> | undefined++ act(() => {+ secondStart = result.current.handle.start()+ })+ await flush()++ // Still closing: no second context on top of it.+ expect(FakeAudioContext.instances).toHaveLength(1)++ await act(async () => {+ first.closing.resolve()+ await secondStart+ })++ expect(FakeAudioContext.instances).toHaveLength(2)+ expect(first.state).toBe('closed')+ })++ it('reports a device error on the meter and marks the take meterFailed', async () => {+ const onMeterFailure = vi.fn()+ const { result } = renderHook(() => useMicRecorder(copy))++ await act(async () => {+ await result.current.handle.start({ onMeterFailure, onSilence: vi.fn(), silenceLevel: 0.075, silenceMs: 1_250 })+ })++ FakeAudioContext.instances[0].dispatchEvent(new Event('error'))+ await flush()++ expect(onMeterFailure).toHaveBeenCalledOnce()++ let recording: Awaited<ReturnType<typeof result.current.handle.stop>> = null++ await act(async () => {+ recording = await result.current.handle.stop()+ })++ expect(recording).toMatchObject({ heardSpeech: false, meterFailed: true })+ })++ it('treats a meter that cannot be built as failed instead of silently deaf', async () => {+ FakeAudioContext.throwOnConstruct = true+ const onMeterFailure = vi.fn()+ const { result } = renderHook(() => useMicRecorder(copy))++ await act(async () => {+ await result.current.handle.start({ onMeterFailure })+ })+ await flush()++ expect(onMeterFailure).toHaveBeenCalledOnce()+ })++ it('does not report its own close at the end of a take as a failure', async () => {+ const onMeterFailure = vi.fn()+ const { result } = renderHook(() => useMicRecorder(copy))++ await act(async () => {+ await result.current.handle.start({ onMeterFailure })+ })++ let recording: Awaited<ReturnType<typeof result.current.handle.stop>> = null++ await act(async () => {+ recording = await result.current.handle.stop()+ FakeAudioContext.instances[0].closing.resolve()+ })+ await flush()++ expect(onMeterFailure).not.toHaveBeenCalled()+ expect(recording).toMatchObject({ meterFailed: false })+ })+})diff --git a/apps/desktop/src/app/chat/composer/hooks/use-mic-recorder.ts b/apps/desktop/src/app/chat/composer/hooks/use-mic-recorder.tsindex c560ef9ad28..19d85469dbe 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-mic-recorder.ts+++ b/apps/desktop/src/app/chat/composer/hooks/use-mic-recorder.ts@@ -1,11 +1,16 @@import { useEffect, useRef, useState } from 'react'+import { closeMeterContext, meterContextsClosed } from '@/lib/mic-meter-context'+type BrowserAudioContext = typeof AudioContextexport interface MicRecorderOptions {onLevel?: (level: number) => voidonError?: (error: Error) => voidonSilence?: () => void+ /** The level meter died (AudioContext device/renderer error). Recording+ * goes on, but silence detection and `heardSpeech` are blind from here. */+ onMeterFailure?: () => voidsilenceLevel?: numbersilenceMs?: numberidleSilenceMs?: number@@ -15,6 +20,9 @@ export interface MicRecording {audio: BlobdurationMs: numberheardSpeech: boolean+ /** The level meter failed during this take, so `heardSpeech` is unknown+ * rather than false. */+ meterFailed?: boolean}export interface MicRecorderErrorCopy {@@ -82,6 +90,7 @@ export function useMicRecorder(copy: MicRecorderErrorCopy): {const animationRef = useRef<number | null>(null)const startedAtRef = useRef(0)const heardSpeechRef = useRef(false)+ const meterFailedRef = useRef(false)const silenceTriggeredRef = useRef(false)const silenceStartedAtRef = useRef<number | null>(null)const stopResolverRef = useRef<((recording: MicRecording | null) => void) | null>(null)@@ -92,8 +101,11 @@ export function useMicRecorder(copy: MicRecorderErrorCopy): {animationRef.current = null}- void audioContextRef.current?.close()+ // Null the ref before closing so the context's own 'closed' statechange+ // isn't mistaken for a meter failure.+ const audioContext = audioContextRef.currentaudioContextRef.current = null+ closeMeterContext(audioContext)streamRef.current?.getTracks().forEach(track => track.stop())streamRef.current = nullrecorderRef.current = null@@ -112,6 +124,28 @@ export function useMicRecorder(copy: MicRecorderErrorCopy): {return}+ const failMeter = () => {+ if (meterFailedRef.current || !recorderRef.current) {+ return+ }++ meterFailedRef.current = true++ if (animationRef.current) {+ window.cancelAnimationFrame(animationRef.current)+ animationRef.current = null+ }++ setLevel(0)+ // Deferred: a meter that fails while start() is still running must not+ // re-enter the caller before start() has resolved.+ window.setTimeout(() => {+ if (recorderRef.current) {+ options.onMeterFailure?.()+ }+ }, 0)+ }+try {const audioContext = new AudioContextCtor()const analyser = audioContext.createAnalyser()@@ -123,6 +157,25 @@ export function useMicRecorder(copy: MicRecorderErrorCopy): {source.connect(analyser)audioContextRef.current = audioContext+ // A device or renderer error kills the context without throwing+ // anywhere we'd see it; the analyser just goes flat. Watch for it.+ const failIfCurrent = () => {+ if (audioContextRef.current === audioContext) {+ failMeter()+ }+ }++ audioContext.addEventListener('error', failIfCurrent)+ audioContext.addEventListener('statechange', () => {+ if (audioContext.state === 'closed') {+ failIfCurrent()+ }+ })++ if (audioContext.state === 'suspended') {+ audioContext.resume().catch(failIfCurrent)+ }+const tick = () => {analyser.getByteTimeDomainData(data)@@ -170,7 +223,7 @@ export function useMicRecorder(copy: MicRecorderErrorCopy): {tick()} catch {- setLevel(0)+ failMeter()}}@@ -189,6 +242,11 @@ export function useMicRecorder(copy: MicRecorderErrorCopy): {throw new Error(copy.microphoneAccessDenied)}+ // The previous take's meter (or the barge monitor's) may still be+ // closing; opening another context on top of it is what trips the+ // AudioContext device error (#75329).+ await meterContextsClosed()+let stream: MediaStreamtry {@@ -217,6 +275,7 @@ export function useMicRecorder(copy: MicRecorderErrorCopy): {streamRef.current = streamrecorderRef.current = recorderheardSpeechRef.current = false+ meterFailedRef.current = falsesilenceTriggeredRef.current = falsesilenceStartedAtRef.current = nullstartedAtRef.current = Date.now()@@ -232,6 +291,7 @@ export function useMicRecorder(copy: MicRecorderErrorCopy): {const recordingType = recorder.mimeType || mimeType || 'audio/webm'const durationMs = Date.now() - startedAtRef.currentconst heardSpeech = heardSpeechRef.current+ const meterFailed = meterFailedRef.currentchunksRef.current = []cleanup()@@ -248,7 +308,8 @@ export function useMicRecorder(copy: MicRecorderErrorCopy): {resolver?.({audio: new Blob(chunks, { type: recordingType }),durationMs,- heardSpeech+ heardSpeech,+ meterFailed})}diff --git a/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation-meter.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation-meter.test.tsxnew file mode 100644index 00000000000..e881e117a46--- /dev/null+++ b/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation-meter.test.tsx@@ -0,0 +1,131 @@+import { act, cleanup, renderHook, waitFor } from '@testing-library/react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { notifyError } from '@/store/notifications'++import type { MicRecorderOptions, MicRecording } from './use-mic-recorder'+import { useVoiceConversation } from './use-voice-conversation'++// #75329: continuous voice decides "did the user speak?" from the WebAudio+// level meter alone. When that meter's AudioContext hits a device error the+// take reads heardSpeech=false, and every later utterance was dropped before+// STT with no error shown.++const mocks = vi.hoisted(() => ({+ handle: {+ cancel: vi.fn(),+ start: vi.fn(async (_options?: MicRecorderOptions) => undefined),+ stop: vi.fn<() => Promise<MicRecording | null>>(async () => null)+ }+}))++vi.mock('./use-mic-recorder', () => ({ useMicRecorder: () => ({ handle: mocks.handle, level: 0 }) }))+vi.mock('@/lib/voice-barge-in', () => ({ monitorSpeechDuringPlayback: () => vi.fn() }))+vi.mock('@/lib/thinking-sound', () => ({ startThinkingSound: vi.fn(), stopThinkingSound: vi.fn() }))+vi.mock('@/lib/voice-playback', () => ({+ markVoicePlaybackInterrupted: vi.fn(),+ playSpeechText: vi.fn(async () => true),+ startSpeechStream: vi.fn(async () => null),+ stopVoicePlayback: vi.fn()+}))+vi.mock('@/store/notifications', () => ({ notify: vi.fn(), notifyError: vi.fn() }))+vi.mock('@/i18n', () => ({+ useI18n: () => ({+ t: {+ notifications: {+ voice: {+ couldNotStartSession: 'could not start',+ microphoneFailed: 'mic failed',+ recordingFailed: 'recording failed',+ transcriptionFailed: 'transcription failed'+ }+ }+ }+ })+}))++function deadMeterTake(durationMs: number): MicRecording {+ return { audio: new Blob(['voice'], { type: 'audio/webm' }), durationMs, heardSpeech: false, meterFailed: true }+}++/** The options the hook handed to the most recent mic start. */+function lastStartOptions(): MicRecorderOptions {+ return mocks.handle.start.mock.calls.at(-1)?.[0] ?? {}+}++function renderConversation() {+ const onFatalError = vi.fn()+ const onSubmit = vi.fn()+ const onTranscribeAudio = vi.fn(async () => 'what time is it')++ const hook = renderHook(() =>+ useVoiceConversation({+ busy: false,+ consumePendingResponse: vi.fn(),+ enabled: true,+ onFatalError,+ onSubmit,+ onTranscribeAudio,+ pendingResponse: () => null+ })+ )++ return { hook, onFatalError, onSubmit, onTranscribeAudio }+}++describe('useVoiceConversation with a failed level meter', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ afterEach(cleanup)++ it('sends the take to STT instead of dropping it when the meter dies mid-utterance', async () => {+ const { hook, onSubmit, onTranscribeAudio } = renderConversation()++ await act(async () => {+ await hook.result.current.start()+ })+ await waitFor(() => expect(hook.result.current.status).toBe('listening'))++ const take = deadMeterTake(2_400)+ mocks.handle.stop.mockResolvedValueOnce(take)++ await act(async () => {+ lastStartOptions().onMeterFailure?.()+ })++ await waitFor(() => expect(onTranscribeAudio).toHaveBeenCalledWith(take.audio))+ await waitFor(() => expect(onSubmit).toHaveBeenCalledWith('what time is it'))+ })++ it('re-arms on a too-short dead-meter take, then stops with an error when the meter dies again', async () => {+ const { hook, onFatalError, onTranscribeAudio } = renderConversation()++ await act(async () => {+ await hook.result.current.start()+ })+ await waitFor(() => expect(hook.result.current.status).toBe('listening'))++ mocks.handle.stop.mockResolvedValueOnce(deadMeterTake(120))++ await act(async () => {+ lastStartOptions().onMeterFailure?.()+ })++ // Too short to hold speech: not sent to STT, and the loop listens again.+ await waitFor(() => expect(mocks.handle.start).toHaveBeenCalledTimes(2))+ expect(onTranscribeAudio).not.toHaveBeenCalled()+ expect(onFatalError).not.toHaveBeenCalled()++ mocks.handle.stop.mockResolvedValueOnce(deadMeterTake(120))++ await act(async () => {+ lastStartOptions().onMeterFailure?.()+ })++ await waitFor(() => expect(onFatalError).toHaveBeenCalledOnce())+ expect(notifyError).toHaveBeenCalledWith(expect.objectContaining({ message: 'recording failed' }), 'mic failed')+ expect(mocks.handle.start).toHaveBeenCalledTimes(2)+ })+})diff --git a/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation.ts b/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation.tsindex 4169b3a7a11..dab7405e9c7 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation.ts+++ b/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation.ts@@ -49,6 +49,14 @@ interface VoiceConversationOptions {* the captured utterance anyway. */const INTERRUPT_SETTLE_TIMEOUT_MS = 5_000+/** A take whose level meter died is sent to STT (the meter can't say whether+ * it heard speech) unless it is shorter than this. */+const METER_FAILURE_MIN_CLIP_MS = 750++/** Back-to-back takes with a dead meter mean the device isn't recovering;+ * stop and say so rather than re-arm forever. */+const METER_FAILURE_LIMIT = 2+export function useVoiceConversation({busy,enabled,@@ -75,6 +83,7 @@ export function useVoiceConversation({const turnTimeoutRef = useRef<number | null>(null)const pendingStartRef = useRef(false)const turnClosingRef = useRef(false)+ const meterFailuresRef = useRef(0)const awaitingSpokenResponseRef = useRef(false)const responseIdRef = useRef<string | null>(null)const spokenSourceLengthRef = useRef(0)@@ -166,8 +175,29 @@ export function useVoiceConversation({try {const result = await handle.stop()+ const meterFailed = Boolean(result?.meterFailed)++ meterFailuresRef.current = meterFailed ? meterFailuresRef.current + 1 : 0++ if (meterFailuresRef.current >= METER_FAILURE_LIMIT) {+ meterFailuresRef.current = 0+ notifyError(new Error(voiceCopy.recordingFailed), voiceCopy.microphoneFailed)+ pendingStartRef.current = false+ setStatus('idle')+ onFatalError?.()++ return+ }++ // `heardSpeech` comes from the level meter alone. When the meter died+ // (AudioContext device error) it is unknown, not false — let STT judge+ // the clip instead of silently dropping the turn (#75329).+ const transcribable =+ result?.heardSpeech ||+ forceTranscribe ||+ (meterFailed && (result?.durationMs ?? 0) >= METER_FAILURE_MIN_CLIP_MS)- if (!result || (!result.heardSpeech && !forceTranscribe) || !onTranscribeAudio) {+ if (!result || !transcribable || !onTranscribeAudio) {if (enabledRef.current && !mutedRef.current && !busyRef.current && statusRef.current !== 'speaking') {pendingStartRef.current = true}@@ -219,7 +249,15 @@ export function useVoiceConversation({turnClosingRef.current = false}},- [handle, onSubmit, onTranscribeAudio, voiceCopy.transcriptionFailed]+ [+ handle,+ onFatalError,+ onSubmit,+ onTranscribeAudio,+ voiceCopy.microphoneFailed,+ voiceCopy.recordingFailed,+ voiceCopy.transcriptionFailed+ ])const startListening = useCallback(async () => {@@ -262,6 +300,7 @@ export function useVoiceConversation({pendingStartRef.current = falseonFatalError?.()},+ onMeterFailure: () => void handleTurn(),onSilence: () => void handleTurn()})setStatus('listening')diff --git a/apps/desktop/src/lib/mic-meter-context.ts b/apps/desktop/src/lib/mic-meter-context.tsnew file mode 100644index 00000000000..87417e3b18f--- /dev/null+++ b/apps/desktop/src/lib/mic-meter-context.ts@@ -0,0 +1,33 @@+// The mic level meters (the recorder's VAD and the barge-in monitor) each open+// an AudioContext on the capture stream. close() is async, so a context torn+// down at the end of one turn can still hold the device when the next turn+// opens its own. Overlapping capture contexts are what make Chromium raise+// "The AudioContext encountered an error from the audio device" (#75329), so+// closes go through here and a new meter waits for them first.++// A close() on a wedged device must not hold the next turn forever.+const CLOSE_WAIT_CAP_MS = 1_000++let pendingClose: Promise<void> = Promise.resolve()++export function closeMeterContext(context: AudioContext | null | undefined) {+ if (!context || context.state === 'closed') {+ return+ }++ let closing: Promise<void>++ try {+ closing = context.close().catch(() => undefined)+ } catch {+ return+ }++ const previous = pendingClose+ pendingClose = Promise.all([previous, closing]).then(() => undefined)+}++/** Resolves once every meter context closed so far has finished closing. */+export function meterContextsClosed(): Promise<void> {+ return Promise.race([pendingClose, new Promise<void>(resolve => window.setTimeout(resolve, CLOSE_WAIT_CAP_MS))])+}diff --git a/apps/desktop/src/lib/voice-barge-in.ts b/apps/desktop/src/lib/voice-barge-in.tsindex 1c3685f7881..179163e937e 100644--- a/apps/desktop/src/lib/voice-barge-in.ts+++ b/apps/desktop/src/lib/voice-barge-in.ts@@ -23,6 +23,8 @@// - Detection is a windowed majority (>=80% of the last SUSTAINED_MS above// trigger) so intra-word energy dips don't reset progress.+import { closeMeterContext, meterContextsClosed } from '@/lib/mic-meter-context'+const CALIBRATION_MS = 400const SUSTAINED_MS = 300const SUSTAINED_MAJORITY = 0.8@@ -113,7 +115,7 @@ export function monitorSpeechDuringPlayback(callbacks: BargeMonitorCallbacks): (recorder = nullchunks = []- void context?.close().catch(() => undefined)+ closeMeterContext(context)context = nullstream?.getTracks().forEach(track => track.stop())stream = null@@ -188,6 +190,14 @@ export function monitorSpeechDuringPlayback(callbacks: BargeMonitorCallbacks): (}void (async () => {try {+ // Don't open a second capture context while the recorder's is still+ // closing (#75329).+ await meterContextsClosed()++ if (disposed) {+ return+ }+stream = await navigator.mediaDevices.getUserMedia({audio: { echoCancellation: true, noiseSuppression: true }})