From 4dab8cbc291f24c2461a56fda80913e5ee59326e Mon Sep 17 00:00:00 2001 From: alpha Date: Wed, 2 Dec 2026 12:28:28 -0600 Subject: [PATCH 1/6] fix(transcription): keep capturing when another app takes the audio device Each channel's capture graph ended at the default context's destination, which tied capture to the system output device. When another app took the speakers in WASAPI exclusive mode, Chromium suspended both capture contexts at once and they never came back, while both sockets stayed open and the backend's keepalive hid the silence for the rest of the interview. - Capture contexts now render to a `none` sink, so they are clocked internally and survive the output device being taken. - A per-channel watchdog resumes a suspended context, rebuilds the graph when frames stop, and re-acquires the source when its track ends or the microphone goes digitally silent (an exclusive grab of the mic). The socket is kept throughout. - Loopback is re-acquired acquire-swap-release, like the microphone path. Refs #164 Co-Authored-By: Claude Opus 5.5 --- .../services/live-transcription.service.ts | 336 +++++++++++++++--- 1 file changed, 278 insertions(+), 58 deletions(-) diff --git a/src/renderer/services/live-transcription.service.ts b/src/renderer/services/live-transcription.service.ts index d3919c96..078ddb38 100644 --- a/src/renderer/services/live-transcription.service.ts +++ b/src/renderer/services/live-transcription.service.ts @@ -9,6 +9,17 @@ const WS_RETRY_MAX_ATTEMPTS = 5; const WS_RETRY_BASE_DELAY_MS = 1000; const WS_RETRY_MAX_DELAY_MS = 8000; const GET_DISPLAY_MEDIA_TIMEOUT_MS = 20000; + +// Capture health, checked once a second per channel while a session runs. See `checkCapture`. +const CAPTURE_CHECK_INTERVAL_MS = 1000; +// No worklet frames for this long means the AudioContext stopped rendering. +const CAPTURE_FRAME_STALL_MS = 3000; +// A live microphone never delivers exact zeros: its noise floor alone is nonzero. Sustained +// digital silence is what Windows hands a shared-mode stream whose device another app has taken +// in exclusive mode. Mic only - loopback is legitimately all zeros while nothing plays. +const CAPTURE_DIGITAL_SILENCE_MS = 5000; +// Between recovery attempts, so a device that stays taken is retried without spinning. +const CAPTURE_RECOVER_RETRY_MS = 5000; const BACKEND_BASE_URL = import.meta.env.DEV ? 'http://localhost:8080' : 'https://api.powerinterviewai.com'; @@ -78,6 +89,32 @@ export interface AudioWsStreamOptions { * called for a socket refused while `start()` is still running: `start()` throws instead. */ onOutOfCredits?: () => void; + /** + * Re-acquire this channel's source after its track ended or went digitally silent, and hand it + * back through `setStream`. Without one, a lost source can only be reported, not recovered. + */ + onCaptureLost?: () => Promise; + /** Treat sustained exact-zero audio as a lost source. For the microphone only. */ + detectDigitalSilence?: boolean; +} + +/** + * A capture context that renders to no output device. + * + * The graph has to end at `destination` for the worklet to be pulled at all, and a default + * context's destination is the system output device. That tied capture to playback: when another + * app took the speakers in WASAPI exclusive mode, Chromium suspended every such context at once - + * both channels stopped within milliseconds and stayed stopped after the device was released, + * with the sockets still open (#164). A `none` sink is clocked internally, so capture no longer + * depends on what the speakers are doing. Falls back to the old construction where the option is + * not supported; the watchdog in `AudioWsStream` still covers that case. + */ +function createCaptureContext(): AudioContext { + try { + return new AudioContext({ sinkId: { type: 'none' } } as AudioContextOptions); + } catch { + return new AudioContext(); + } } /** @@ -194,6 +231,18 @@ export class AudioWsStream { private readonly kind: SessionKind; private readonly clientSessionId: string | undefined; private readonly onOutOfCredits: (() => void) | undefined; + private readonly onCaptureLost: (() => Promise) | undefined; + private readonly detectDigitalSilence: boolean; + + // Capture health. The socket staying open says nothing about whether audio is reaching it: the + // backend keeps an audio-less stream alive indefinitely, so a dead source used to look exactly + // like a quiet interview for the rest of the session (#164). + private captureTimer: number | null = null; + private lastFrameAt = 0; + private zeroSince: number | null = null; + private recovering = false; + private lastRecoverAt = 0; + private captureLost = false; constructor( private readonly channel: Channel, @@ -210,6 +259,13 @@ export class AudioWsStream { this.kind = options.kind ?? 'live'; this.clientSessionId = options.clientSessionId; this.onOutOfCredits = options.onOutOfCredits; + this.onCaptureLost = options.onCaptureLost; + this.detectDigitalSilence = options.detectDigitalSilence ?? false; + } + + /** Whether this channel's audio source is currently lost. Polled by the control bar. */ + get stalled(): boolean { + return this.active && this.captureLost; } get replaced(): boolean { @@ -227,62 +283,83 @@ export class AudioWsStream { this.replacedByNewer = false; await this.connectWithRetry(); - this.ctx = new AudioContext(); - this.source = this.ctx.createMediaStreamSource(this.stream); + await this.buildGraph(); + + // Refused for credits while the graph above was being built: the socket opened (the backend + // accepts before it checks) and was closed straight after. Thrown rather than reported + // through `onOutOfCredits`, because the caller is still inside its start sequence and that is + // where a start that cannot happen belongs. + if (this.outOfCredits) throw new OutOfCreditsError(this.replacedByNewer); + + this.active = true; + this.lastFrameAt = Date.now(); + this.zeroSince = null; + this.captureLost = false; + this.captureTimer = window.setInterval(() => this.checkCapture(), CAPTURE_CHECK_INTERVAL_MS); + } + + /** + * Build the capture graph on `this.stream`: context, source, worklet, a muted gain to the + * context's destination. Shared by `start()` and by the watchdog's rebuild. + */ + private async buildGraph(): Promise { + const ctx = createCaptureContext(); + this.ctx = ctx; + this.source = ctx.createMediaStreamSource(this.stream); // 1. Load the AudioWorklet (required once per AudioContext) const workletBlob = new Blob([AUDIO_WORKLET_CODE], { type: 'application/javascript' }); const workletUrl = URL.createObjectURL(workletBlob); try { - await this.ctx.audioWorklet.addModule(workletUrl); + await ctx.audioWorklet.addModule(workletUrl); } finally { URL.revokeObjectURL(workletUrl); // clean up immediately } // 2. Create the worklet node (replaces ScriptProcessorNode) - this.workletNode = new AudioWorkletNode(this.ctx, 'audio-sender-worklet', { + const workletNode = new AudioWorkletNode(ctx, 'audio-sender-worklet', { numberOfInputs: 1, numberOfOutputs: 1, }); + this.workletNode = workletNode; - this.monitorGain = this.ctx.createGain(); + this.monitorGain = ctx.createGain(); this.monitorGain.gain.value = 0; // Receive raw Float32 audio buffers from the worklet (off-main-thread) - this.workletNode.port.onmessage = (event) => { + workletNode.port.onmessage = (event) => { + const float32 = event.data as Float32Array; + // Counted before the socket check: a reconnect is not a capture failure. + this.noteFrame(float32); + if (!this.active || this.ws?.readyState !== WebSocket.OPEN) return; if ((this.ws?.bufferedAmount ?? 0) > MAX_WS_BUFFERED_BYTES) { console.log(`[AudioWsStream] ws buffer full of ${this.channel} channel, dropping data`); return; } - const float32 = event.data as Float32Array; const pcm16 = this.convertTo16kPcm(float32, this.ctx?.sampleRate ?? SAMPLE_RATE); this.ws?.send(pcm16.buffer as ArrayBuffer); }; - // Wire up the audio graph exactly like the old ScriptProcessor version - this.source.connect(this.workletNode); - this.workletNode.connect(this.monitorGain); - this.monitorGain.connect(this.ctx.destination); - - // Refused for credits while the graph above was being built: the socket opened (the backend - // accepts before it checks) and was closed straight after. Thrown rather than reported - // through `onOutOfCredits`, because the caller is still inside its start sequence and that is - // where a start that cannot happen belongs. - if (this.outOfCredits) throw new OutOfCreditsError(this.replacedByNewer); + // A context Chromium suspends on its own - the output device was taken, an OS audio session + // was interrupted - is asked to resume straight away; the watchdog rebuilds it if that fails. + ctx.onstatechange = () => { + if (this.active && this.ctx === ctx && ctx.state === 'suspended') { + console.warn(`[AudioWsStream] ${this.channel} capture context suspended, resuming`); + ctx.resume().catch(() => {}); + } + }; - this.active = true; + // Wire up the audio graph exactly like the old ScriptProcessor version. `start()` may have + // been handed a new stream by `setStream` while the worklet module loaded; `this.source` is + // whichever source is current. + this.source.connect(workletNode); + workletNode.connect(this.monitorGain); + this.monitorGain.connect(ctx.destination); } - async stop() { - this.active = false; - this.stopping = true; - if (this.reconnectTimer !== null) { - window.clearTimeout(this.reconnectTimer); - this.reconnectTimer = null; - } - + private async teardownGraph(): Promise { this.workletNode?.disconnect(); this.source?.disconnect(); this.monitorGain?.disconnect(); @@ -291,10 +368,100 @@ export class AudioWsStream { this.source = null; this.monitorGain = null; - if (this.ctx && this.ctx.state !== 'closed') { - await this.ctx.close(); - } + const ctx = this.ctx; this.ctx = null; + if (ctx && ctx.state !== 'closed') { + await ctx.close().catch(() => {}); + } + } + + private noteFrame(frame: Float32Array): void { + const now = Date.now(); + this.lastFrameAt = now; + if (!this.detectDigitalSilence) return; + let silent = true; + for (let i = 0; i < frame.length; i++) { + if (frame[i] !== 0) { + silent = false; + break; + } + } + if (!silent) this.zeroSince = null; + else if (this.zeroSince === null) this.zeroSince = now; + } + + /** + * Whether audio is still reaching this channel, and recovery when it is not. + * + * Three ways capture dies with the socket still open, all reproduced on Windows (#164): + * the context stops rendering (frames stop), the source track ends, or the track keeps + * delivering frames that are exact digital silence. The first is fixed in place by rebuilding + * the graph on the same stream; the other two need a new source, which only the owner can get. + */ + private checkCapture(): void { + if (!this.active || this.stopping) return; + const now = Date.now(); + + const trackEnded = this.stream.getAudioTracks().every((track) => track.readyState === 'ended'); + const framesStalled = now - this.lastFrameAt > CAPTURE_FRAME_STALL_MS; + const digitallySilent = + this.zeroSince !== null && now - this.zeroSince > CAPTURE_DIGITAL_SILENCE_MS; + + const lost = trackEnded || framesStalled || digitallySilent; + if (lost !== this.captureLost) { + console.warn( + `[AudioWsStream] ${this.channel} capture ${lost ? 'LOST' : 'restored'}` + + (lost + ? ` (trackEnded=${trackEnded} framesStalled=${framesStalled} silent=${digitallySilent})` + : '') + ); + this.captureLost = lost; + } + if (!lost || this.recovering || now - this.lastRecoverAt < CAPTURE_RECOVER_RETRY_MS) return; + + this.recovering = true; + this.lastRecoverAt = now; + void this.recoverCapture(trackEnded || digitallySilent).finally(() => { + this.recovering = false; + }); + } + + private async recoverCapture(needsNewSource: boolean): Promise { + try { + if (needsNewSource && this.onCaptureLost) { + // The owner acquires a new source and hands it back through `setStream`. + await this.onCaptureLost(); + } + if (!this.active || this.stopping) return; + // A context that is not rendering is rebuilt whatever happened to the source: resuming a + // context the OS suspended does not reliably bring it back. + if (needsNewSource ? this.ctx?.state !== 'running' : true) { + await this.teardownGraph(); + if (!this.active || this.stopping) return; + await this.buildGraph(); + } + this.lastFrameAt = Date.now(); + this.zeroSince = null; + console.info(`[AudioWsStream] ${this.channel} capture recovery attempted`); + } catch (error) { + console.error(`[AudioWsStream] ${this.channel} capture recovery failed:`, error); + } + } + + async stop() { + this.active = false; + this.stopping = true; + this.captureLost = false; + if (this.captureTimer !== null) { + window.clearInterval(this.captureTimer); + this.captureTimer = null; + } + if (this.reconnectTimer !== null) { + window.clearTimeout(this.reconnectTimer); + this.reconnectTimer = null; + } + + await this.teardownGraph(); if (this.ws && this.ws.readyState < WebSocket.CLOSING) { this.ws.close(); @@ -315,6 +482,9 @@ export class AudioWsStream { */ async setStream(stream: MediaStream): Promise { this.stream = stream; + // A new source starts with a clean bill of health; the watchdog judges it from here. + this.lastFrameAt = Date.now(); + this.zeroSince = null; // No context yet: start() has not reached one, or stop() tore it down. The field above is // enough, because start() builds its source from it. @@ -640,6 +810,9 @@ class LiveTranscriptionService { // Held separately from `channels` because the microphone is the only one a device change can // move: ch_0 is loopback, captured from the call rather than from a device the user picks. private micChannel: AudioWsStream | null = null; + private loopbackChannel: AudioWsStream | null = null; + // The device the microphone was opened on, for re-acquiring it after it is lost. + private micDeviceName = ''; // Bumped per device change, so a swap can tell it has been superseded while it was awaiting. // Two changes in flight resolve in completion order, not request order, so without this the @@ -675,6 +848,11 @@ class LiveTranscriptionService { return this.running && this.channels.length > 0 && this.channels.every((c) => c.connected); } + /** Whether either channel has lost its audio source and is recovering it. */ + isCaptureStalled(): boolean { + return this.running && this.channels.some((c) => c.stalled); + } + /** Whether the session ended because a newer interview on this account replaced it. */ wasReplaced(): boolean { return this.channels.some((channel) => channel.replaced); @@ -695,33 +873,14 @@ class LiveTranscriptionService { if (!electron) throw new Error('Electron API not available'); await electron.transcription.setSessionToken(sessionToken); + this.micDeviceName = audioInputDeviceName; const micDeviceId = await resolveMicDeviceId(audioInputDeviceName); this.micStream = await navigator.mediaDevices.getUserMedia({ audio: micDeviceId ? { deviceId: { exact: micDeviceId } } : true, video: false, }); - let displayStream: MediaStream; - try { - await electron.transcription.enableLoopbackAudio(); - displayStream = await Promise.race([ - navigator.mediaDevices.getDisplayMedia({ audio: true, video: true }), - new Promise((_, reject) => - window.setTimeout( - () => reject(new Error(currentTranslation().assistant.screenCaptureTimedOut)), - GET_DISPLAY_MEDIA_TIMEOUT_MS - ) - ), - ]); - } finally { - await electron.transcription.disableLoopbackAudio().catch(() => {}); - } - - displayStream.getVideoTracks().forEach((track) => { - track.stop(); - displayStream.removeTrack(track); - }); - this.loopbackStream = displayStream; + this.loopbackStream = await this.acquireLoopbackStream(); const onTranscript = async (payload: { channel: Channel; @@ -738,14 +897,16 @@ class LiveTranscriptionService { clientSessionId: crypto.randomUUID(), onOutOfCredits: () => this.reportOutOfCredits(), }; - const micChannel = new AudioWsStream('ch_1', this.micStream, language, onTranscript, options); - const loopbackChannel = new AudioWsStream( - 'ch_0', - this.loopbackStream, - language, - onTranscript, - options - ); + const micChannel = new AudioWsStream('ch_1', this.micStream, language, onTranscript, { + ...options, + detectDigitalSilence: true, + onCaptureLost: () => this.setAudioInputDevice(this.micDeviceName), + }); + const loopbackChannel = new AudioWsStream('ch_0', this.loopbackStream, language, onTranscript, { + ...options, + onCaptureLost: () => this.reacquireLoopback(), + }); + this.loopbackChannel = loopbackChannel; this.micChannel = micChannel; this.channels = [micChannel, loopbackChannel]; await Promise.all(this.channels.map((channel) => channel.start())); @@ -782,9 +943,67 @@ class LiveTranscriptionService { * therefore leaves the session running on the microphone it already had, which is the whole * reason this is not a stop-and-start. Only ch_1 moves; ch_0 is loopback audio from the call. */ + /** + * The system-audio stream ch_0 transcribes: loopback through `getDisplayMedia`, video dropped. + */ + private async acquireLoopbackStream(): Promise { + const electron = getElectron(); + if (!electron) throw new Error('Electron API not available'); + + let displayStream: MediaStream; + try { + await electron.transcription.enableLoopbackAudio(); + displayStream = await Promise.race([ + navigator.mediaDevices.getDisplayMedia({ audio: true, video: true }), + new Promise((_, reject) => + window.setTimeout( + () => reject(new Error(currentTranslation().assistant.screenCaptureTimedOut)), + GET_DISPLAY_MEDIA_TIMEOUT_MS + ) + ), + ]); + } finally { + await electron.transcription.disableLoopbackAudio().catch(() => {}); + } + + displayStream.getVideoTracks().forEach((track) => { + track.stop(); + displayStream.removeTrack(track); + }); + return displayStream; + } + + /** + * Replace a loopback stream whose track ended - which is what Windows does to it when another + * app takes the output device in exclusive mode (#164). Acquire first, swap, then release, the + * same order the microphone path keeps. + */ + private async reacquireLoopback(): Promise { + const channel = this.loopbackChannel; + if (!channel) return; + + const nextStream = await this.acquireLoopbackStream(); + if (this.loopbackChannel !== channel) { + nextStream.getTracks().forEach((track) => track.stop()); + return; + } + + const previous = this.loopbackStream; + try { + await channel.setStream(nextStream); + } catch (error) { + nextStream.getTracks().forEach((track) => track.stop()); + throw error; + } + this.loopbackStream = nextStream; + previous?.getTracks().forEach((track) => track.stop()); + } + async setAudioInputDevice(deviceName: string): Promise { const channel = this.micChannel; if (!channel) return; + // Remembered so a lost microphone is re-acquired on the device the user picked. + this.micDeviceName = deviceName; const seq = ++this.micSwitchSeq; @@ -819,6 +1038,7 @@ class LiveTranscriptionService { await Promise.all(this.channels.map((channel) => channel.stop())); this.channels = []; this.micChannel = null; + this.loopbackChannel = null; this.micStream?.getTracks().forEach((track) => track.stop()); this.loopbackStream?.getTracks().forEach((track) => track.stop()); From 4b97eb5280b794c63e06f3aa9eefbd3ecefd4e58 Mon Sep 17 00:00:00 2001 From: alpha Date: Wed, 2 Dec 2026 12:28:41 -0600 Subject: [PATCH 2/6] feat(control-bar): say when audio stops reaching transcription The live signal now has a third state beside Listening and Reconnecting: "Audio lost - recovering", shown while either channel's capture watchdog reports its source lost. Before this, a dead capture with an open socket looked exactly like a quiet interview. Strings added for all nine interface languages. Refs #164 Co-Authored-By: Claude Opus 5.5 --- .../custom/control-panel/live-signal.tsx | 25 +++++++++++++------ src/renderer/i18n/locales/de.ts | 3 +++ src/renderer/i18n/locales/en.ts | 3 +++ src/renderer/i18n/locales/es.ts | 3 +++ src/renderer/i18n/locales/fr.ts | 3 +++ src/renderer/i18n/locales/ja.ts | 3 +++ src/renderer/i18n/locales/ko.ts | 3 +++ src/renderer/i18n/locales/pt.ts | 3 +++ src/renderer/i18n/locales/ru.ts | 3 +++ src/renderer/i18n/locales/zh.ts | 2 ++ 10 files changed, 43 insertions(+), 8 deletions(-) diff --git a/src/renderer/components/custom/control-panel/live-signal.tsx b/src/renderer/components/custom/control-panel/live-signal.tsx index 8436731b..c7b8fca4 100644 --- a/src/renderer/components/custom/control-panel/live-signal.tsx +++ b/src/renderer/components/custom/control-panel/live-signal.tsx @@ -31,16 +31,20 @@ export function LiveSignal() { const [stream, setStream] = useState(null); const [connected, setConnected] = useState(true); + // Socket up but no audio reaching it - another app took the microphone or speakers (#164). + const [audioLost, setAudioLost] = useState(false); useEffect(() => { if (!running) { setStream(null); setConnected(true); + setAudioLost(false); return; } const poll = () => { setStream(liveTranscriptionService.getMicStream()); setConnected(liveTranscriptionService.isConnected()); + setAudioLost(liveTranscriptionService.isCaptureStalled()); }; poll(); const id = window.setInterval(poll, POLL_MS); @@ -71,10 +75,15 @@ export function LiveSignal() { if (!running) return null; - const label = connected ? t.controlPanel.signal.listening : t.controlPanel.signal.reconnecting; - const hint = connected - ? t.controlPanel.signal.listeningHint - : t.controlPanel.signal.reconnectingHint; + const signal = t.controlPanel.signal; + // A dropped socket is reported first: it is what any audio fix would be waiting on. + const healthy = connected && !audioLost; + const label = !connected ? signal.reconnecting : audioLost ? signal.audioLost : signal.listening; + const hint = !connected + ? signal.reconnectingHint + : audioLost + ? signal.audioLostHint + : signal.listeningHint; return ( @@ -84,7 +93,7 @@ export function LiveSignal() { aria-label={`${label}. ${hint}`} className={cn( 'flex h-8 items-center gap-2 rounded-lg border px-2.5 text-xs font-medium', - connected + healthy ? 'border-border text-muted-foreground' : 'border-destructive/40 bg-destructive/10 text-destructive' )} @@ -93,16 +102,16 @@ export function LiveSignal() { aria-hidden="true" className={cn( 'h-2 w-2 shrink-0 rounded-full', - connected ? 'bg-emerald-500' : 'animate-pulse bg-destructive' + healthy ? 'bg-emerald-500' : 'animate-pulse bg-destructive' )} /> {/* The bar is full at the 840px minimum width, so "Listening" - the state nobody needs to read - is dropped there and the dot and meter carry it, with the tooltip and the aria-label holding the words. "Reconnecting" always shows: it is the one to notice. */} - + {label} - {connected && ( + {healthy && (