Skip to content

The agent that grows with you

fix(desktop): surface dead client wake capture instead of staying deaf forever

finn763e801147cc2c7
diff --git a/apps/desktop/src/lib/wake-client-capture.test.ts b/apps/desktop/src/lib/wake-client-capture.test.ts
new file mode 100644
index 00000000000..4f672b9b4ec
--- /dev/null
+++ b/apps/desktop/src/lib/wake-client-capture.test.ts
@@ -0,0 +1,239 @@
+// Regression test for #119089: macOS Desktop remote-gateway client capture
+// went permanently deaf (platform capture error kills the continuous PCM
+// chain) while the ear still showed "listening" and no error ever surfaced.
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { type ClientWakeCaptureHandle, startClientWakeCapture } from './wake-client-capture'
+
+class FakeTrack {
+ readyState = 'live'
+ stop = vi.fn()
+ onended: (() => void) | null = null
+ onmute: (() => void) | null = null
+}
+
+class FakeStream {
+ constructor(public tracks: FakeTrack[]) {}
+
+ getAudioTracks(): FakeTrack[] {
+ return this.tracks
+ }
+
+ getTracks(): FakeTrack[] {
+ return this.tracks
+ }
+}
+
+class FakeProcessor {
+ onaudioprocess: ((event: { inputBuffer: { getChannelData: () => Float32Array } }) => void) | null = null
+ connect = vi.fn()
+ disconnect = vi.fn()
+ constructor(public bufferSize: number) {}
+
+ emit(input: Float32Array): void {
+ this.onaudioprocess?.({ inputBuffer: { getChannelData: () => input } })
+ }
+}
+
+class FakeSource {
+ connect = vi.fn()
+ disconnect = vi.fn()
+}
+
+class FakeGain {
+ gain = { value: 1 }
+ connect = vi.fn()
+ disconnect = vi.fn()
+}
+
+const instances: FakeAudioContext[] = []
+
+class FakeAudioContext {
+ sampleRate = 48_000
+ state = 'running'
+ destination = {}
+ processors: FakeProcessor[] = []
+ resume = vi.fn().mockResolvedValue(undefined)
+ close = vi.fn().mockResolvedValue(undefined)
+
+ constructor() {
+ instances.push(this)
+ }
+
+ createMediaStreamSource(_stream: unknown): FakeSource {
+ return new FakeSource()
+ }
+
+ createScriptProcessor(bufferSize: number): FakeProcessor {
+ const processor = new FakeProcessor(bufferSize)
+ this.processors.push(processor)
+
+ return processor
+ }
+
+ createGain(): FakeGain {
+ return new FakeGain()
+ }
+}
+
+const TONE = 0.2 // comfortably above any silence floor
+const toneFrame = () => new Float32Array(4096).fill(TONE)
+const silentFrame = () => new Float32Array(4096) // digital zeros, like a dead capture chain
+
+const flush = () => new Promise<void>(resolve => setTimeout(resolve, 0))
+
+describe('startClientWakeCapture (issue #119089)', () => {
+ let tracks: FakeTrack[]
+ let getUserMedia: ReturnType<typeof vi.fn>
+ let handles: ClientWakeCaptureHandle[]
+
+ const processor = () => instances[instances.length - 1].processors[0]
+
+ const start = (overrides: Record<string, unknown> = {}) =>
+ startClientWakeCapture({
+ frameLength: 1280,
+ request: async () => ({ fed: true }),
+ ...overrides
+ })
+
+ beforeEach(() => {
+ instances.length = 0
+ handles = []
+ tracks = [new FakeTrack()]
+ getUserMedia = vi.fn().mockResolvedValue(new FakeStream(tracks))
+ vi.stubGlobal('AudioContext', FakeAudioContext)
+ Object.defineProperty(window.navigator, 'mediaDevices', {
+ value: { getUserMedia },
+ configurable: true
+ })
+ })
+
+ afterEach(() => {
+ for (const handle of handles) {
+ handle.stop()
+ }
+
+ vi.unstubAllGlobals()
+ vi.useRealTimers()
+ })
+
+ it('streams resampled 16 kHz PCM frames to wake.feed', async () => {
+ const request = vi.fn(async () => ({ fed: true }))
+ const handle = await start({ request })
+ handles.push(handle)
+
+ processor().emit(toneFrame())
+ await flush()
+
+ expect(request).toHaveBeenCalled()
+ const [method, params] = request.mock.calls[0] as unknown as [string, { pcm: string; sample_rate: number }]
+ expect(method).toBe('wake.feed')
+ expect(params.sample_rate).toBe(16_000)
+ // 48 kHz -> 16 kHz: 4096 input samples become 1365, so one 80 ms frame ships.
+ expect(Buffer.from(params.pcm, 'base64')).toHaveLength(1280 * 2)
+ expect(handle.active).toBe(true)
+ })
+
+ it('reports sustained digital silence instead of staying deaf forever', async () => {
+ const onError = vi.fn()
+ const handle = await start({ onError, silenceFramesThreshold: 10 })
+ handles.push(handle)
+
+ for (let i = 0; i < 10; i++) {
+ processor().emit(silentFrame())
+ }
+
+ expect(onError).toHaveBeenCalledTimes(1)
+ expect(String(onError.mock.calls[0]?.[0])).toMatch(/silence/i)
+ expect(handle.active).toBe(false)
+ })
+
+ it('keeps listening through real audio with a quiet floor', async () => {
+ const onError = vi.fn()
+ const request = vi.fn(async () => ({ fed: true }))
+ const handle = await start({ onError, request })
+ handles.push(handle)
+
+ for (let i = 0; i < 30; i++) {
+ processor().emit(toneFrame())
+ }
+
+ await flush()
+ expect(onError).not.toHaveBeenCalled()
+ expect(handle.active).toBe(true)
+ expect(request).toHaveBeenCalled()
+ })
+
+ it('reports a dead microphone track instead of feeding zeros', async () => {
+ const onError = vi.fn()
+ const handle = await start({ onError })
+ handles.push(handle)
+
+ tracks[0].onended?.()
+
+ expect(onError).toHaveBeenCalledTimes(1)
+ expect(String(onError.mock.calls[0]?.[0])).toMatch(/track ended/i)
+ expect(handle.active).toBe(false)
+ })
+
+ it('throws when getUserMedia yields no live audio track', async () => {
+ getUserMedia.mockResolvedValue(new FakeStream([]))
+
+ await expect(start()).rejects.toThrow(/microphone track/i)
+ })
+
+ it('reports a stalled audio graph with no callbacks', async () => {
+ vi.useFakeTimers()
+ const onError = vi.fn()
+ const handle = await start({ onError, stallTimeoutMs: 1000 })
+ handles.push(handle)
+
+ await vi.advanceTimersByTimeAsync(1500)
+
+ expect(onError).toHaveBeenCalledTimes(1)
+ expect(String(onError.mock.calls[0]?.[0])).toMatch(/stall/i)
+ expect(handle.active).toBe(false)
+ })
+
+ it('escalates consecutive refused wake.feed frames', async () => {
+ const onError = vi.fn()
+ const request = vi.fn(async () => ({ fed: false, reason: 'not_owner' }))
+ const handle = await start({ onError, request, maxConsecutiveFeedFailures: 3 })
+ handles.push(handle)
+
+ for (let i = 0; i < 6; i++) {
+ processor().emit(toneFrame())
+ }
+
+ await flush()
+ expect(onError).toHaveBeenCalledTimes(1)
+ expect(String(onError.mock.calls[0]?.[0])).toMatch(/wake\.feed refused/i)
+ expect(handle.active).toBe(false)
+ })
+
+ it('tolerates an isolated wake.feed failure without killing the ear', async () => {
+ const onError = vi.fn()
+ let calls = 0
+
+ const request = vi.fn(async () => {
+ calls += 1
+
+ if (calls === 1) {
+ throw new Error('transient network blip')
+ }
+
+ return { fed: true }
+ })
+
+ const handle = await start({ onError, request, maxConsecutiveFeedFailures: 3 })
+ handles.push(handle)
+
+ for (let i = 0; i < 6; i++) {
+ processor().emit(toneFrame())
+ }
+
+ await flush()
+ expect(onError).not.toHaveBeenCalled()
+ expect(handle.active).toBe(true)
+ })
+})
diff --git a/apps/desktop/src/lib/wake-client-capture.ts b/apps/desktop/src/lib/wake-client-capture.ts
index cabcee90386..2ecab5d6220 100644
--- a/apps/desktop/src/lib/wake-client-capture.ts
+++ b/apps/desktop/src/lib/wake-client-capture.ts
@@ -10,13 +10,36 @@
const TARGET_RATE = 16_000
const DEFAULT_FRAME = 1280 // 80 ms @ 16 kHz — matches tools/wake_word.py
+// Health-monitor tuning for the continuous capture chain. A platform capture
+// failure (macOS PLAS IPC delegate error → StopSourceOnError, #119089) leaves
+// getUserMedia resolved but the PCM dead: ended track, halted callbacks, or
+// endless digital zeros. Without a watchdog the ear shows "listening" forever
+// and the gateway detector can never fire.
+/** -60 dBFS: live mic noise floors sit well above this; exact zeros do not. */
+const SILENCE_PEAK = 0.001
+/** ~8 s of digital zeros at 80 ms/frame before the ear is declared deaf. */
+const DEFAULT_SILENCE_FRAMES = 100
+const DEFAULT_STALL_TIMEOUT_MS = 3000
+const DEFAULT_MAX_FEED_FAILURES = 5
+
export type WakeFeedRequester = (method: string, params?: Record<string, unknown>) => Promise<unknown>
export interface ClientWakeCaptureOptions {
/** Samples per frame at 16 kHz (from wake.start response). */
frameLength?: number
request: WakeFeedRequester
+ /**
+ * Fatal capture-chain failures only (dead track, stalled graph, sustained
+ * silence, refused feeds). Isolated feed RPC blips are retried silently —
+ * reporting every one would flap the ear on ordinary network jitter.
+ */
onError?: (error: Error) => void
+ /** Consecutive near-silent 16 kHz frames before the ear is declared deaf. */
+ silenceFramesThreshold?: number
+ /** ms without an onaudioprocess callback before the graph is declared stalled. */
+ stallTimeoutMs?: number
+ /** Consecutive rejected/failed wake.feed calls before escalating. */
+ maxConsecutiveFeedFailures?: number
}
export interface ClientWakeCaptureHandle {
@@ -105,6 +128,21 @@ export async function startClientWakeCapture(options: ClientWakeCaptureOptions):
video: false
})
+ // getUserMedia can resolve with a stillborn stream (no audio track, or an
+ // already-ended one after a platform capture error). Starting the graph on
+ // that feeds the detector silence forever — fail loudly instead (#119089).
+ const audioTracks = stream.getAudioTracks()
+
+ if (audioTracks.length === 0 || audioTracks.every(track => track.readyState === 'ended')) {
+ stream.getTracks().forEach(track => track.stop())
+
+ throw new Error('microphone track unavailable for client wake capture')
+ }
+
+ const silenceFramesThreshold = Math.max(1, Math.trunc(options.silenceFramesThreshold ?? DEFAULT_SILENCE_FRAMES))
+ const stallTimeoutMs = Math.max(250, options.stallTimeoutMs ?? DEFAULT_STALL_TIMEOUT_MS)
+ const maxFeedFailures = Math.max(1, Math.trunc(options.maxConsecutiveFeedFailures ?? DEFAULT_MAX_FEED_FAILURES))
+
const context = new AudioContextCtor()
const source = context.createMediaStreamSource(stream)
// ScriptProcessor is deprecated but widely available and simple for PCM export.
@@ -115,6 +153,75 @@ export async function startClientWakeCapture(options: ClientWakeCaptureOptions):
let pending = new Float32Array(0)
let stopped = false
+ let failed = false
+ let silentFrames = 0
+ let feedFailures = 0
+ let stallTimer: ReturnType<typeof setTimeout> | undefined
+
+ const handle: ClientWakeCaptureHandle = {
+ get active() {
+ return !stopped
+ },
+ stop() {
+ if (stopped) {
+ return
+ }
+
+ stopped = true
+ queue.length = 0
+
+ if (stallTimer !== undefined) {
+ clearTimeout(stallTimer)
+ stallTimer = undefined
+ }
+
+ try {
+ processor.disconnect()
+ source.disconnect()
+ mute.disconnect()
+ } catch {
+ // ignore
+ }
+
+ void context.close().catch(() => undefined)
+ stream.getTracks().forEach(t => t.stop())
+ }
+ }
+
+ // Fatal capture-chain failure: tear the graph down exactly once and report.
+ // stop() is idempotent, so late track-ended events after a manual stop stay silent.
+ const fail = (error: Error) => {
+ if (failed || stopped) {
+ return
+ }
+
+ failed = true
+ handle.stop()
+ options.onError?.(error)
+ }
+
+ const armStallTimer = () => {
+ if (stopped || failed) {
+ return
+ }
+
+ if (stallTimer !== undefined) {
+ clearTimeout(stallTimer)
+ }
+
+ stallTimer = setTimeout(() => {
+ fail(new Error('client wake capture stalled: no microphone audio callbacks — the OS capture chain may have died'))
+ }, stallTimeoutMs)
+ }
+
+ // A platform capture error (macOS StopSourceOnError) ends the track after a
+ // successful getUserMedia. Without this the graph feeds zeros forever.
+ for (const track of audioTracks) {
+ track.onended = () => {
+ fail(new Error('microphone track ended during client wake capture — the OS capture chain may have died'))
+ }
+ }
+
// Bounded ordered queue of 16 kHz frames. We never drop the frame that is
// currently being sent; under remote latency we drop the oldest queued
// frames so the detector still sees contiguous recent PCM rather than gaps
@@ -126,6 +233,33 @@ export async function startClientWakeCapture(options: ClientWakeCaptureOptions):
const queue: Float32Array[] = []
let draining = false
+ const noteFeedResult = (accepted: boolean, reason: string | null) => {
+ if (stopped || failed) {
+ return
+ }
+
+ if (accepted) {
+ feedFailures = 0
+
+ return
+ }
+
+ // The server dropped our PCM (lease lost, wrong owner, detector gone).
+ // One blip is ordinary network jitter; a run of them means the ear is
+ // armed but permanently deaf — escalate instead of staying "listening".
+ feedFailures += 1
+
+ if (feedFailures >= maxFeedFailures) {
+ fail(
+ new Error(
+ `client wake capture deaf: wake.feed refused ${feedFailures} consecutive frames` +
+ (reason ? ` (${reason})` : '') +
+ ' — re-toggle the ear to re-arm'
+ )
+ )
+ }
+ }
+
const drainQueue = async () => {
if (draining) {
return
@@ -134,7 +268,7 @@ export async function startClientWakeCapture(options: ClientWakeCaptureOptions):
draining = true
try {
- while (!stopped && queue.length > 0) {
+ while (!stopped && !failed && queue.length > 0) {
const batch = queue.splice(0, MAX_FRAMES_PER_FEED)
if (batch.length === 0) {
@@ -145,19 +279,24 @@ export async function startClientWakeCapture(options: ClientWakeCaptureOptions):
const merged = new Float32Array(batch.length * frameLength)
batch.forEach((frame, i) => merged.set(frame, i * frameLength))
const pcm = floatToInt16LE(merged)
- await options.request('wake.feed', {
+
+ const result = (await options.request('wake.feed', {
pcm: bytesToBase64(pcm),
sample_rate: TARGET_RATE
- })
- } catch (error) {
- options.onError?.(error instanceof Error ? error : new Error(String(error)))
+ })) as { fed?: boolean; reason?: string | null } | null | undefined
+
+ // Absent on older backends that predate the {fed} envelope — only an
+ // explicit fed:false counts as a refusal. Thrown RPC errors land below.
+ noteFeedResult(!result || result.fed !== false, result?.reason ?? null)
+ } catch {
// Keep draining later frames; one failed RPC should not freeze the ear.
+ noteFeedResult(false, null)
}
}
} finally {
draining = false
- if (!stopped && queue.length > 0) {
+ if (!stopped && !failed && queue.length > 0) {
void drainQueue()
}
}
@@ -178,10 +317,12 @@ export async function startClientWakeCapture(options: ClientWakeCaptureOptions):
}
processor.onaudioprocess = event => {
- if (stopped) {
+ if (stopped || failed) {
return
}
+ armStallTimer()
+
const input = event.inputBuffer.getChannelData(0)
const at16k = downsampleTo16k(input, context.sampleRate)
// Append to pending and emit full frames
@@ -193,6 +334,37 @@ export async function startClientWakeCapture(options: ClientWakeCaptureOptions):
while (offset + frameLength <= merged.length) {
const frame = merged.subarray(offset, offset + frameLength)
offset += frameLength
+
+ // A dead capture chain delivers endless digital zeros. Live mics never
+ // do — their noise floor sits far above SILENCE_PEAK — so a long run of
+ // zeros means the detector is being fed silence, not speech (#119089).
+ let peak = 0
+
+ for (let i = 0; i < frame.length; i++) {
+ const abs = Math.abs(frame[i] ?? 0)
+
+ if (abs > peak) {
+ peak = abs
+ }
+ }
+
+ if (peak < SILENCE_PEAK) {
+ silentFrames += 1
+
+ if (silentFrames >= silenceFramesThreshold) {
+ fail(
+ new Error(
+ 'client wake capture hears only silence — the microphone delivers no audio; check OS mic access and re-toggle the ear'
+ )
+ )
+
+ return
+ }
+
+ continue
+ }
+
+ silentFrames = 0
enqueueFrame(new Float32Array(frame))
}
@@ -207,28 +379,7 @@ export async function startClientWakeCapture(options: ClientWakeCaptureOptions):
await context.resume().catch(() => undefined)
}
- return {
- get active() {
- return !stopped
- },
- stop() {
- if (stopped) {
- return
- }
-
- stopped = true
- queue.length = 0
-
- try {
- processor.disconnect()
- source.disconnect()
- mute.disconnect()
- } catch {
- // ignore
- }
+ armStallTimer()
- void context.close().catch(() => undefined)
- stream.getTracks().forEach(t => t.stop())
- }
- }
+ return handle
}
diff --git a/apps/desktop/src/store/wake-word-client-capture.test.ts b/apps/desktop/src/store/wake-word-client-capture.test.ts
new file mode 100644
index 00000000000..69bab894d12
--- /dev/null
+++ b/apps/desktop/src/store/wake-word-client-capture.test.ts
@@ -0,0 +1,47 @@
+// Issue #119089: a dead client PCM chain must land the ear in an honest off
+// state with the reason visible — not a "listening" toggle that can never fire.
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const capture = vi.hoisted(() => ({
+ options: null as {
+ frameLength?: number
+ onError?: (error: Error) => void
+ } | null,
+ stop: vi.fn()
+}))
+
+vi.mock('@/lib/wake-client-capture', () => ({
+ startClientWakeCapture: vi.fn(async (options: typeof capture.options) => {
+ capture.options = options
+
+ return { active: true, stop: capture.stop }
+ })
+}))
+
+import { $wakeWord, applyWakeStartResult, resetWakeWordState } from './wake-word'
+
+const flush = () => new Promise<void>(resolve => setTimeout(resolve, 0))
+
+beforeEach(() => {
+ capture.options = null
+ capture.stop.mockClear()
+ resetWakeWordState()
+})
+
+describe('client capture failure surfacing (issue #119089)', () => {
+ it('lands the ear off with the reason when the PCM chain dies after arming', async () => {
+ applyWakeStartResult({ capture: 'client', frame_length: 1280, phrase: 'hey hermes', started: true })
+ await flush()
+
+ expect($wakeWord.get()).toMatchObject({ listening: true, notice: '' })
+ expect(capture.options?.onError).toBeTypeOf('function')
+
+ capture.options?.onError?.(new Error('client wake capture hears only silence'))
+
+ expect(capture.stop).toHaveBeenCalled()
+ expect($wakeWord.get()).toMatchObject({
+ listening: false,
+ notice: 'client wake capture hears only silence'
+ })
+ })
+})
diff --git a/apps/desktop/src/store/wake-word.ts b/apps/desktop/src/store/wake-word.ts
index 13ed1f098ae..98dbcfe8a2c 100644
--- a/apps/desktop/src/store/wake-word.ts
+++ b/apps/desktop/src/store/wake-word.ts
@@ -59,7 +59,24 @@ async function maybeStartClientCapture(result: WakeStartResponse | null | undefi
try {
clientCapture = await startClientWakeCapture({
frameLength: result.frame_length,
- request: gatewayRequester
+ request: gatewayRequester,
+ // The continuous PCM chain can die after arming (dead track, stalled
+ // graph, sustained silence, refused feeds — #119089). A "listening" ear
+ // that can never fire is worse than an honest off state, so mirror the
+ // start-failure path: drop the capture, show the reason, release the lease.
+ onError: error => {
+ stopClientCapture()
+ const failed = $wakeWord.get()
+ $wakeWord.set({
+ ...failed,
+ listening: false,
+ notice: error.message,
+ pending: false
+ })
+
+ // Best-effort: release server lease if client mic failed.
+ void gatewayRequester('wake.stop', {}).catch(() => undefined)
+ }
})
} catch (error) {
const current = $wakeWord.get()