Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: dispose voice capture on owner unmount (#8028)

[._.]/ Adam Eivyb3b0a7468d4c
diff --git a/client/src/components/voice/VoiceWidget.jsx b/client/src/components/voice/VoiceWidget.jsx
index 6e64018ecd..f8ecc204ee 100644
--- a/client/src/components/voice/VoiceWidget.jsx
+++ b/client/src/components/voice/VoiceWidget.jsx
@@ -5,6 +5,7 @@ import {
startCapture, stopCapture, interrupt, resetConversation, sendText, onVoiceEvent, isCapturing,
startContinuous, stopContinuous, isContinuous, whenPlaybackDrained, getVadLevel,
webSpeechSupported, startWebSpeechCapture, stopWebSpeechCapture, isWebSpeechCapturing,
+ disposeCaptureOwner,
onProactiveSpeech, captureScreenForVision, sendScreenshotResult,
enableVisionCapture, disableVisionCapture, isVisionCaptureEnabled, onVisionCaptureEnded,
speakSynthesized, onVoiceOutputPrimary, claimVoiceOutput,
@@ -74,6 +75,7 @@ export default function VoiceWidget() {
const handleStartRef = useRef(null);
const handleStopRef = useRef(null);
const handleCancelRef = useRef(null);
+ const disposedRef = useRef(false);
// VoiceToggleButton fetches voice config independently, so it can show and
// dispatch ENGAGE_EVENT before this widget's own getVoiceConfig() resolves
// and `enabled` flips true. handleStart short-circuits while disabled, which
@@ -135,6 +137,7 @@ export default function VoiceWidget() {
useEffect(() => {
getVoiceConfig()
.then((cfg) => {
+ if (disposedRef.current) return;
setEnabled(!!cfg?.enabled);
setHotkey(cfg?.hotkey || 'Space');
if (cfg?.stt?.engine) setSttEngine(cfg.stt.engine);
@@ -236,15 +239,18 @@ export default function VoiceWidget() {
));
}),
onVoiceEvent('voice:idle', (d) => {
+ if (disposedRef.current) return;
// voice:idle fires when the server finishes *sending* TTS; local
// playback may still be running. Wait for drain so stage doesn't
// flip off 'speaking' while audio is still playing.
if (d?.reason === 'reset') setHistory([]);
whenPlaybackDrained().then(() => {
+ if (disposedRef.current) return;
setStage((current) => (ACTIVE_STAGES.has(current) ? current : restState()));
});
}),
onVoiceEvent('voice:error', (d) => {
+ if (disposedRef.current) return;
toast.error(`Voice: ${d.message}`);
setStage(restState());
}),
@@ -263,7 +269,9 @@ export default function VoiceWidget() {
if (next) {
// Defer to next tick so the local stage / dictation state has
// settled before handleStart reads it.
- setTimeout(() => { handleStartRef.current?.(); }, 0);
+ setTimeout(() => {
+ if (!disposedRef.current) handleStartRef.current?.();
+ }, 0);
} else if (isWebSpeechCapturing() || isCapturing() || isContinuous()) {
handleStopRef.current?.();
}
@@ -301,6 +309,7 @@ export default function VoiceWidget() {
// data URL, or null when no stream is authorized / a frame grab failed;
// always reply so the server-side waiter resolves rather than timing out.
onVoiceEvent('voice:screenshot:request', async (payload) => {
+ if (disposedRef.current) return;
const requestId = payload && typeof payload === 'object' ? payload.requestId : undefined;
if (!isVisionCaptureEnabled()) {
toast('Voice: click the screen button in the voice controls so I can see your screen.', { icon: '🖥️' });
@@ -309,6 +318,7 @@ export default function VoiceWidget() {
return;
}
const dataUrl = await captureScreenForVision();
+ if (disposedRef.current) return;
if (!dataUrl) {
toast('Voice: screen capture was unavailable.', { icon: '📷' });
setVisionEnabled(isVisionCaptureEnabled());
@@ -354,6 +364,7 @@ export default function VoiceWidget() {
// (navigate + speak, or speak). Returns true when handled; false means "send
// to the server pipeline as usual". Reads config via refs so it stays stable.
const runFastPath = useCallback(async (text) => {
+ if (disposedRef.current) return false;
const fp = fastPathRef.current;
if (!fp?.enabled) return false;
// Ensure the nav manifest is loaded (retries if an earlier fetch failed) so
@@ -371,19 +382,24 @@ export default function VoiceWidget() {
} catch {
return false;
}
+ if (disposedRef.current) return false;
if (decision.tier === TIER.SERVER) return false;
// A fast tier owns this turn. Stop any lingering playback, speak the reply
// through the same queue as server TTS, and settle the stage on drain.
const speak = (line) => {
+ if (disposedRef.current) return;
interrupt();
setHistory((h) => [...h, { role: 'assistant', text: line }].slice(-MAX_HISTORY));
setStage('speaking');
speakSynthesized(line, ttsRef.current)
.catch(() => {})
- .finally(() => whenPlaybackDrained().then(() => setStage((c) => (
- ACTIVE_STAGES.has(c) ? c : (isWebSpeechCapturing() ? 'listening' : 'idle')
- ))));
+ .finally(() => whenPlaybackDrained().then(() => {
+ if (disposedRef.current) return;
+ setStage((c) => (
+ ACTIVE_STAGES.has(c) ? c : (isWebSpeechCapturing() ? 'listening' : 'idle')
+ ));
+ }));
};
if (decision.tier === TIER.TRIGGER && decision.kind === 'navigate') {
@@ -406,6 +422,7 @@ export default function VoiceWidget() {
useEffect(() => {
if (!enabled) return undefined;
return onProactiveSpeech(({ sentence, priority }) => {
+ if (disposedRef.current) return;
setHistory((h) => [...h, { role: 'assistant', text: sentence, proactive: true }].slice(-MAX_HISTORY));
const icon = priority === 'high' ? '🔔' : '🤖';
toast(`${icon} ${sentence.length > 80 ? `${sentence.slice(0, 80)}…` : sentence}`);
@@ -413,7 +430,7 @@ export default function VoiceWidget() {
}, [enabled]);
const handleStart = useCallback(async () => {
- if (!enabled) return;
+ if (!enabled || disposedRef.current) return;
// Web Speech API mode — browser handles STT, sends text directly
if (useWebSpeech) {
@@ -422,8 +439,11 @@ export default function VoiceWidget() {
setInterimTranscript('');
startWebSpeechCapture({
language: sttLanguage,
- onInterim: (text) => setInterimTranscript(text),
+ onInterim: (text) => {
+ if (!disposedRef.current) setInterimTranscript(text);
+ },
onFinal: (text) => {
+ if (disposedRef.current) return;
setInterimTranscript('');
setHistory((h) => [...h, { role: 'user', text }].slice(-MAX_HISTORY));
setStage('thinking');
@@ -433,10 +453,12 @@ export default function VoiceWidget() {
// Gated on the live ref so toggling fast resolution in Settings takes
// effect on the next utterance without restarting the recognizer.
routeFinal: async (text) => {
+ if (disposedRef.current) return;
const handled = fastPathRef.current?.enabled ? await runFastPath(text) : false;
- if (!handled) sendText(text, 'voice');
+ if (!disposedRef.current && !handled) sendText(text, 'voice');
},
onError: (err) => {
+ if (disposedRef.current) return;
toast.error(`Mic: ${err}`);
setStage('idle');
},
@@ -448,9 +470,14 @@ export default function VoiceWidget() {
if (isContinuous()) return;
setStage('handsfree');
await startContinuous({
- onSpeechStart: () => setStage('capturing'),
- onSpeechEnd: () => setStage('thinking'),
+ onSpeechStart: () => {
+ if (!disposedRef.current) setStage('capturing');
+ },
+ onSpeechEnd: () => {
+ if (!disposedRef.current) setStage('thinking');
+ },
onSubmit: ({ submitted, peak }) => {
+ if (disposedRef.current) return;
if (!submitted) {
setStage('handsfree');
return;
@@ -458,6 +485,7 @@ export default function VoiceWidget() {
warnIfQuiet(peak);
},
}).catch((err) => {
+ if (disposedRef.current) return;
toast.error(`Mic: ${err.message}`);
setStage('idle');
});
@@ -466,12 +494,14 @@ export default function VoiceWidget() {
if (isCapturing()) return;
setStage('listening');
await startCapture().catch((err) => {
+ if (disposedRef.current) return;
toast.error(`Mic: ${err.message}`);
setStage('idle');
});
}, [enabled, handsFree, useWebSpeech, sttLanguage, runFastPath]);
const handleStop = useCallback(async () => {
+ if (disposedRef.current) return;
if (useWebSpeech) {
stopWebSpeechCapture();
setInterimTranscript('');
@@ -480,16 +510,19 @@ export default function VoiceWidget() {
}
if (handsFree && isContinuous()) {
await stopContinuous();
+ if (disposedRef.current) return;
setStage('idle');
return;
}
if (!isCapturing()) return;
setStage('thinking');
const r = await stopCapture().catch((err) => {
+ if (disposedRef.current) return null;
toast.error(`Mic: ${err.message}`);
setStage('idle');
return null;
});
+ if (disposedRef.current) return;
if (!r) {
setStage('idle');
return;
@@ -505,16 +538,17 @@ export default function VoiceWidget() {
// state, so a synchronous cancel followed by a quick re-engage can have
// the in-flight stop tear down the *new* capture's tracks. Awaiting the
// teardown serializes engage/disengage and prevents that race.
- const handleCancel = useCallback(async () => {
+ const handleCancel = useCallback(async ({ updateUi = true } = {}) => {
+ const canUpdateUi = updateUi && !disposedRef.current;
if (useWebSpeech) {
if (isWebSpeechCapturing()) stopWebSpeechCapture();
- setInterimTranscript('');
+ if (canUpdateUi) setInterimTranscript('');
} else {
if (isContinuous()) await stopContinuous().catch(() => {});
if (isCapturing()) await stopCapture({ submit: false }).catch(() => {});
}
interrupt();
- setStage('idle');
+ if (canUpdateUi) setStage('idle');
}, [useWebSpeech]);
// Keep the refs the dictation/engage/disengage listeners use pointed at the
@@ -526,6 +560,32 @@ export default function VoiceWidget() {
useLayoutEffect(() => { handleStopRef.current = handleStop; }, [handleStop]);
useLayoutEffect(() => { handleCancelRef.current = handleCancel; }, [handleCancel]);
+ // Route changes can unmount the widget without changing `enabled`, so the
+ // switchable-effect cleanup above is not enough. Invalidate module-level
+ // capture callbacks synchronously, then invoke the latest cancel closure for
+ // the awaited teardown/interrupt path. The cleanup never updates React state
+ // because the owner is already marked disposed.
+ useEffect(() => {
+ disposedRef.current = false;
+ return () => {
+ disposedRef.current = true;
+ pendingEngageRef.current = false;
+ disposeCaptureOwner();
+ const teardown = handleCancelRef.current?.({ updateUi: false });
+ if (teardown && typeof teardown.then === 'function') {
+ cancelInFlightRef.current = teardown;
+ teardown.then(
+ () => {
+ if (cancelInFlightRef.current === teardown) cancelInFlightRef.current = null;
+ },
+ () => {
+ if (cancelInFlightRef.current === teardown) cancelInFlightRef.current = null;
+ },
+ );
+ }
+ };
+ }, []);
+
const handleClear = () => {
resetConversation();
setHistory([]);
diff --git a/client/src/components/voice/VoiceWidget.lifecycle.test.jsx b/client/src/components/voice/VoiceWidget.lifecycle.test.jsx
new file mode 100644
index 0000000000..339eac11b0
--- /dev/null
+++ b/client/src/components/voice/VoiceWidget.lifecycle.test.jsx
@@ -0,0 +1,120 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { render } from '@testing-library/react';
+
+const mocks = vi.hoisted(() => {
+ const toast = vi.fn();
+ toast.error = vi.fn();
+ return {
+ toast,
+ disposeCaptureOwner: vi.fn(),
+ stopContinuous: vi.fn().mockResolvedValue(undefined),
+ stopCapture: vi.fn().mockResolvedValue(null),
+ stopWebSpeechCapture: vi.fn(),
+ isContinuous: vi.fn(() => false),
+ interrupt: vi.fn(),
+ getVoiceConfig: vi.fn(() => Promise.resolve({
+ enabled: true,
+ hotkey: 'Space',
+ stt: { engine: 'whisper', language: 'en' },
+ llm: { fastPath: null },
+ tts: { engine: 'piper', piper: { voice: 'example-voice' }, rate: 1 },
+ })),
+ };
+});
+
+vi.mock('../../services/voiceClient', () => ({
+ startCapture: vi.fn(),
+ stopCapture: mocks.stopCapture,
+ interrupt: mocks.interrupt,
+ resetConversation: vi.fn(),
+ sendText: vi.fn(),
+ onVoiceEvent: vi.fn(() => vi.fn()),
+ isCapturing: vi.fn(() => false),
+ startContinuous: vi.fn(),
+ stopContinuous: mocks.stopContinuous,
+ isContinuous: mocks.isContinuous,
+ whenPlaybackDrained: vi.fn(() => Promise.resolve(true)),
+ getVadLevel: vi.fn(() => 0),
+ webSpeechSupported: false,
+ startWebSpeechCapture: vi.fn(),
+ stopWebSpeechCapture: mocks.stopWebSpeechCapture,
+ isWebSpeechCapturing: vi.fn(() => false),
+ disposeCaptureOwner: mocks.disposeCaptureOwner,
+ onProactiveSpeech: vi.fn(() => vi.fn()),
+ captureScreenForVision: vi.fn(),
+ sendScreenshotResult: vi.fn(),
+ enableVisionCapture: vi.fn(),
+ disableVisionCapture: vi.fn(),
+ isVisionCaptureEnabled: vi.fn(() => false),
+ onVisionCaptureEnded: vi.fn(() => vi.fn()),
+ speakSynthesized: vi.fn(),
+ onVoiceOutputPrimary: vi.fn((handler) => { handler(false); return vi.fn(); }),
+ claimVoiceOutput: vi.fn(),
+}));
+
+vi.mock('../../services/voiceFastPath', () => ({
+ resolveTurn: vi.fn(),
+ buildRouterSystemPrompt: vi.fn(),
+ TIER: { SERVER: 'server', TRIGGER: 'trigger', NANO: 'nano' },
+}));
+
+vi.mock('../../services/browserLlm', () => ({ warmNano: vi.fn() }));
+vi.mock('../../services/apiPalette', () => ({ getPaletteManifest: vi.fn() }));
+vi.mock('../../services/apiVoice', () => ({ getVoiceConfig: mocks.getVoiceConfig }));
+vi.mock('../ui/Toast', () => ({ default: mocks.toast }));
+vi.mock('../../hooks/useVoiceUiSync', () => ({
+ useVoiceUiSync: vi.fn(),
+ pushUiIndexAfterAction: vi.fn(),
+}));
+vi.mock('../../services/uiInteract', () => ({
+ doClick: vi.fn(() => ({ ok: true })),
+ doFill: vi.fn(() => ({ ok: true })),
+ doSelect: vi.fn(() => ({ ok: true })),
+ doSetCheckbox: vi.fn(() => ({ ok: true })),
+}));
+vi.mock('../../services/voiceVisibility', () => ({
+ VISIBILITY_EVENT: 'voice-visibility',
+ ENGAGE_EVENT: 'voice-engage',
+ DISENGAGE_EVENT: 'voice-disengage',
+ readVoiceHidden: vi.fn(() => false),
+ writeVoiceHidden: vi.fn(),
+ isVoiceHiddenStorageEvent: vi.fn(() => false),
+}));
+vi.mock('../micrographics', () => ({ MicroGlyph: () => null }));
+vi.mock('../../lib/a11yKeyboard', () => ({ shouldIgnoreGlobalKey: vi.fn(() => false) }));
+vi.mock('../../lib/safeStorage', () => ({
+ safeReadStorage: vi.fn(() => null),
+ safeWriteStorage: vi.fn(),
+}));
+vi.mock('react-router', () => ({ useNavigate: () => vi.fn() }));
+
+import VoiceWidget from './VoiceWidget';
+
+describe('VoiceWidget owner lifecycle', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.stopContinuous.mockResolvedValue(undefined);
+ mocks.isContinuous.mockReturnValue(false);
+ mocks.getVoiceConfig.mockResolvedValue({
+ enabled: true,
+ hotkey: 'Space',
+ stt: { engine: 'whisper', language: 'en' },
+ llm: { fastPath: null },
+ tts: { engine: 'piper', piper: { voice: 'example-voice' }, rate: 1 },
+ });
+ });
+
+ it('invalidates capture before invoking the latest cancel handler on unmount', async () => {
+ const { unmount } = render(<VoiceWidget />);
+
+ mocks.isContinuous.mockReturnValue(true);
+ unmount();
+
+ expect(mocks.disposeCaptureOwner).toHaveBeenCalledOnce();
+ expect(mocks.stopContinuous).toHaveBeenCalledOnce();
+ expect(mocks.interrupt).toHaveBeenCalledOnce();
+ expect(mocks.disposeCaptureOwner.mock.invocationCallOrder[0])
+ .toBeLessThan(mocks.stopContinuous.mock.invocationCallOrder[0]);
+ expect(mocks.toast.error).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/services/voiceClient.js b/client/src/services/voiceClient.js
index f646ae4aca..33b664001a 100644
--- a/client/src/services/voiceClient.js
+++ b/client/src/services/voiceClient.js
@@ -26,7 +26,19 @@ let releaseWebSpeechSession = null;
let stream = null;
let recorder = null;
let chunks = [];
+let recorderGeneration = 0;
+let recorderStartPendingGeneration = null;
+let recorderSessionGeneration = null;
let audioCtx = null;
+
+// Capture engines are module-level because the widget can be hidden and shown
+// without recreating the browser resources. The widget itself is not immortal:
+// navigation can unmount it while a permission request, recorder event, VAD
+// conversion, or Web Speech restart is still pending. A new owner generation
+// makes those late continuations inert before the old owner starts teardown.
+let captureOwnerGeneration = 0;
+
+const isOwnerCurrent = (generation) => generation === captureOwnerGeneration;
// One owner for shared playback. Server-turn admission is independent of the
// two invalidation lifetimes: cancellation retires decode/queue work AND
// pending synthesis fetches; a new synthetic reply retires only older fetches.
@@ -407,7 +419,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
socket.on('voice:transcript', beginServerTurnAudio);
export const startCapture = async () => {
- if (recorder) return;
+ if (recorder || recorderStartPendingGeneration !== null) return;
+ const ownerGeneration = captureOwnerGeneration;
+ const generation = ++recorderGeneration;
+ recorderStartPendingGeneration = generation;
// Barge-in: abort any in-flight turn and silence current playback
socket.emit('voice:interrupt');
cancelVoicePlayback();
@@ -415,11 +430,13 @@ export const startCapture = async () => {
// Claimed BEFORE getUserMedia — an output-only session already in force would
// refuse the request outright.
releaseCaptureSession?.();
- releaseCaptureSession = acquireAudioSession('play-and-record');
+ const sessionRelease = acquireAudioSession('play-and-record');
+ releaseCaptureSession = sessionRelease;
+ recorderSessionGeneration = generation;
// autoGainControl is critical — without it, quiet mics record near-silent audio
// that whisper transcribes as [BLANK_AUDIO].
- stream = await navigator.mediaDevices.getUserMedia({
+ const nextStream = await navigator.mediaDevices.getUserMedia({
audio: {
echoCancellation: true,
noiseSuppression: true,
@@ -429,37 +446,81 @@ export const startCapture = async () => {
// A denied/failed mic never reaches stopCapture (`recorder` is still null),
// so the claim is handed back here or it pins the document record-capable
// for the rest of the session.
- releaseCaptureSession?.();
- releaseCaptureSession = null;
+ if (recorderSessionGeneration === generation) {
+ sessionRelease();
+ releaseCaptureSession = null;
+ recorderSessionGeneration = null;
+ }
+ recorderStartPendingGeneration = null;
throw err;
});
+ if (!isOwnerCurrent(ownerGeneration) || recorderGeneration !== generation) {
+ nextStream.getTracks().forEach((track) => track.stop());
+ if (recorderSessionGeneration === generation) {
+ sessionRelease();
+ releaseCaptureSession = null;
+ recorderSessionGeneration = null;
+ }
+ if (recorderStartPendingGeneration === generation) recorderStartPendingGeneration = null;
+ return null;
+ }
+ stream = nextStream;
// Run after permission is granted — `enumerateDevices` only returns
// device labels post-grant, and the headset heuristic relies on labels.
detectAudioRoute(stream).catch(() => {});
const mimeType = pickMime();
- chunks = [];
- recorder = new MediaRecorder(stream, { mimeType });
- recorder.addEventListener('dataavailable', (e) => { if (e.data.size > 0) chunks.push(e.data); });
- recorder.start(250);
+ const recordedChunks = [];
+ chunks = recordedChunks;
+ const nextRecorder = new MediaRecorder(stream, { mimeType });
+ recorder = nextRecorder;
+ recorderStartPendingGeneration = null;
+ nextRecorder.addEventListener('dataavailable', (e) => {
+ if (isOwnerCurrent(ownerGeneration) && recorderGeneration === generation && e.data.size > 0) {
+ recordedChunks.push(e.data);
+ }
+ });
+ nextRecorder.start(250);
return { mimeType };
};
export const stopCapture = async ({ submit = true } = {}) => {
- if (!recorder) return null;
+ const generation = recorderGeneration;
const rec = recorder;
+ const capturedStream = stream;
+ const recordedChunks = chunks;
+ if (!rec) {
+ if (recorderStartPendingGeneration === generation) recorderStartPendingGeneration = null;
+ recorderGeneration += 1;
+ chunks = [];
+ capturedStream?.getTracks().forEach((track) => track.stop());
+ stream = null;
+ if (recorderSessionGeneration === generation) {
+ releaseCaptureSession?.();
+ releaseCaptureSession = null;
+ recorderSessionGeneration = null;
+ }
+ return null;
+ }
recorder = null;
+ recorderStartPendingGeneration = null;
+ chunks = [];
+ // Stop the tracks before awaiting MediaRecorder's final event. Navigation
+ // teardown must release the microphone even if a browser delays that event.
+ capturedStream?.getTracks().forEach((track) => track.stop());
+ stream = null;
+ if (recorderSessionGeneration === generation) {
+ releaseCaptureSession?.();
+ releaseCaptureSession = null;
+ recorderSessionGeneration = null;
+ }
await new Promise((resolve) => {
rec.addEventListener('stop', resolve, { once: true });
rec.stop();
});
- stream?.getTracks().forEach((t) => t.stop());
- stream = null;
- releaseCaptureSession?.();
- releaseCaptureSession = null;
+ if (recorderGeneration === generation) recorderGeneration += 1;
- const blob = new Blob(chunks, { type: rec.mimeType });
- chunks = [];
+ const blob = new Blob(recordedChunks, { type: rec.mimeType });
// Mode-switch cancellation (e.g. user toggled hands-free mid-utterance):
// drop the buffered audio instead of submitting a partial sentence.
if (!submit) return null;
@@ -717,7 +778,10 @@ let continuousCtx = null;
let continuousStream = null;
let continuousWorkletNode = null;
let continuousSource = null;
-let continuousCallbacks = null;
+let continuousCapture = null;
+let continuousGeneration = 0;
+let continuousStartPendingGeneration = null;
+let continuousSessionGeneration = null;
let vadState = 'idle';
let speechChunks = [];
// Fixed-size ring buffer of the last `preRollLimit` frames; avoids the
@@ -741,7 +805,15 @@ class VADProcessor extends AudioWorkletProcessor {
registerProcessor('vad-processor', VADProcessor);
`;
-const submitUtterance = async () => {
+const isContinuousCaptureCurrent = (capture) => Boolean(
+ capture
+ && capture.ownerGeneration === captureOwnerGeneration
+ && capture.generation === continuousGeneration
+ && continuousCapture === capture,
+);
+
+const submitUtterance = async (capture) => {
+ if (!isContinuousCaptureCurrent(capture)) return;
if (!speechChunks.length) return;
const chunksToSubmit = speechChunks;
speechChunks = [];
@@ -751,14 +823,15 @@ const submitUtterance = async () => {
let off = 0;
for (const c of chunksToSubmit) { samples.set(c, off); off += c.length; }
- const rate = continuousCtx?.sampleRate || 48000;
+ const rate = capture.context?.sampleRate || 48000;
const { wav, peak } = await float32ToWav16k(samples, rate);
+ if (!isContinuousCaptureCurrent(capture)) return;
if (!wav || wav.byteLength < 800) {
- continuousCallbacks?.onSubmit?.({ submitted: false, peak });
+ capture.callbacks?.onSubmit?.({ submitted: false, peak });
return;
}
socket.emit('voice:turn', { audio: wav, mimeType: 'audio/wav' });
- continuousCallbacks?.onSubmit?.({ submitted: true, peak, size: wav.byteLength });
+ capture.callbacks?.onSubmit?.({ submitted: true, peak, size: wav.byteLength });
};
const finishCalibration = () => {
@@ -783,7 +856,8 @@ const snapshotPreRoll = () => {
return out;
};
-const handleFrame = (frame) => {
+const handleFrame = (frame, capture) => {
+ if (!isContinuousCaptureCurrent(capture)) return;
let sum = 0;
for (let i = 0; i < frame.length; i++) sum += frame[i] * frame[i];
const rms = Math.sqrt(sum / frame.length);
@@ -816,7 +890,7 @@ const handleFrame = (frame) => {
const effectiveConfirmMs = inEcho ? VAD.bargeInOnsetConfirmMs : VAD.onsetConfirmMs;
if (rms > effectiveOnRms) {
onsetFrames += 1;
- const frameMs = (frame.length / (continuousCtx?.sampleRate || 48000)) * 1000;
+ const frameMs = (frame.length / (capture.context?.sampleRate || 48000)) * 1000;
if (onsetFrames * frameMs >= effectiveConfirmMs) {
// Confirmed speech onset — barge-in + start capturing
vadState = 'speaking';
@@ -828,7 +902,7 @@ const handleFrame = (frame) => {
cancelVoicePlayback();
}
speechChunks = snapshotPreRoll();
- continuousCallbacks?.onSpeechStart?.();
+ capture.callbacks?.onSpeechStart?.();
}
} else {
onsetFrames = 0;
@@ -845,11 +919,11 @@ const handleFrame = (frame) => {
vadState = 'idle';
silenceStartedAt = 0;
onsetFrames = 0;
- continuousCallbacks?.onSpeechEnd?.();
+ capture.callbacks?.onSpeechEnd?.();
if (speechChunks.length) {
- submitUtterance().catch((err) => console.warn('[voice] watchdog submit failed:', err));
+ submitUtterance(capture).catch((err) => console.warn('[voice] watchdog submit failed:', err));
} else {
- continuousCallbacks?.onSubmit?.({ submitted: false, peak: 0, discarded: true });
+ capture.callbacks?.onSubmit?.({ submitted: false, peak: 0, discarded: true });
}
return;
}
@@ -861,14 +935,14 @@ const handleFrame = (frame) => {
vadState = 'idle';
silenceStartedAt = 0;
onsetFrames = 0;
- continuousCallbacks?.onSpeechEnd?.();
+ capture.callbacks?.onSpeechEnd?.();
if (speechMs >= VAD.minSpeechMs) {
- submitUtterance().catch((err) => console.warn('[voice] submit failed:', err));
+ submitUtterance(capture).catch((err) => console.warn('[voice] submit failed:', err));
} else {
// Too short to submit — notify the widget so it leaves 'thinking'
// instead of waiting for a server response that won't arrive.
speechChunks = [];
- continuousCallbacks?.onSubmit?.({ submitted: false, peak: 0, discarded: true });
+ capture.callbacks?.onSubmit?.({ submitted: false, peak: 0, discarded: true });
}
}
} else {
@@ -877,28 +951,47 @@ const handleFrame = (frame) => {
};
export const startContinuous = async (callbacks = {}) => {
- if (continuousCtx) return;
- continuousCallbacks = callbacks;
+ if (continuousCtx || continuousStartPendingGeneration !== null) return;
+ const ownerGeneration = captureOwnerGeneration;
+ const generation = ++continuousGeneration;
+ continuousStartPendingGeneration = generation;
// Claimed BEFORE getUserMedia — an output-only session already in force would
// refuse the request outright — and handed back on failure, since a denied mic
// never reaches stopContinuous (`continuousCtx` is still null).
releaseContinuousSession?.();
- releaseContinuousSession = acquireAudioSession('play-and-record');
+ const sessionRelease = acquireAudioSession('play-and-record');
+ releaseContinuousSession = sessionRelease;
+ continuousSessionGeneration = generation;
// AGC is intentionally OFF here — it boosts silence to maintain a target
// output level, which destroys the energy-difference signal the VAD needs.
- continuousStream = await navigator.mediaDevices.getUserMedia({
+ const nextStream = await navigator.mediaDevices.getUserMedia({
audio: {
echoCancellation: true,
noiseSuppression: true,
autoGainControl: false,
},
}).catch((err) => {
- releaseContinuousSession?.();
- releaseContinuousSession = null;
+ if (continuousSessionGeneration === generation) {
+ sessionRelease();
+ releaseContinuousSession = null;
+ continuousSessionGeneration = null;
+ }
+ continuousStartPendingGeneration = null;
throw err;
});
+ if (!isOwnerCurrent(ownerGeneration) || continuousGeneration !== generation) {
+ nextStream.getTracks().forEach((track) => track.stop());
+ if (continuousSessionGeneration === generation) {
+ sessionRelease();
+ releaseContinuousSession = null;
+ continuousSessionGeneration = null;
+ }
+ if (continuousStartPendingGeneration === generation) continuousStartPendingGeneration = null;
+ return null;
+ }
+ continuousStream = nextStream;
detectAudioRoute(continuousStream).catch(() => {});
// Everything from here on can reject — a refused resume, a worklet module that
@@ -914,12 +1007,20 @@ export const startContinuous = async (callbacks = {}) => {
const Ctor = window.AudioContext || window.webkitAudioContext;
continuousCtx = new Ctor();
await resumeAudioContext(continuousCtx).catch(unwindSetup);
+ if (!isOwnerCurrent(ownerGeneration) || continuousGeneration !== generation) {
+ await stopContinuous();
+ return null;
+ }
// Inline worklet module so we don't need a separate file in the build
const blobUrl = URL.createObjectURL(new Blob([WORKLET_SOURCE], { type: 'application/javascript' }));
await continuousCtx.audioWorklet.addModule(blobUrl)
.catch(async (err) => { URL.revokeObjectURL(blobUrl); await unwindSetup(err); });
URL.revokeObjectURL(blobUrl);
+ if (!isOwnerCurrent(ownerGeneration) || continuousGeneration !== generation) {
+ await stopContinuous();
+ return null;
+ }
continuousSource = continuousCtx.createMediaStreamSource(continuousStream);
continuousWorkletNode = new AudioWorkletNode(continuousCtx, 'vad-processor');
@@ -940,7 +1041,15 @@ export const startContinuous = async (callbacks = {}) => {
onRms = VAD.minOnRms;
offRms = VAD.minOffRms;
- continuousWorkletNode.port.onmessage = (e) => handleFrame(e.data);
+ const capture = {
+ ownerGeneration,
+ generation,
+ callbacks,
+ context: continuousCtx,
+ };
+ continuousCapture = capture;
+ continuousStartPendingGeneration = null;
+ continuousWorkletNode.port.onmessage = (e) => handleFrame(e.data, capture);
continuousSource.connect(continuousWorkletNode);
// Worklet output must be pulled by the graph or process() stops running;
// sinking through a zero-gain node keeps it alive without echoing the mic.
@@ -950,20 +1059,38 @@ export const startContinuous = async (callbacks = {}) => {
};
export const stopContinuous = async () => {
- if (!continuousCtx) return;
- try {
- continuousSource?.disconnect();
- continuousWorkletNode?.disconnect();
- continuousWorkletNode && (continuousWorkletNode.port.onmessage = null);
- } catch { /* ignore teardown errors */ }
- continuousStream?.getTracks().forEach((t) => t.stop());
- await continuousCtx.close().catch(() => {});
- releaseContinuousSession?.();
- releaseContinuousSession = null;
+ const generation = continuousGeneration;
+ continuousGeneration += 1;
+ continuousStartPendingGeneration = null;
+ const ctx = continuousCtx;
+ const captureStream = continuousStream;
+ const workletNode = continuousWorkletNode;
+ const source = continuousSource;
+ const release = continuousSessionGeneration === generation
+ ? releaseContinuousSession
+ : null;
continuousCtx = null;
continuousStream = null;
continuousWorkletNode = null;
continuousSource = null;
+ continuousCapture = null;
+ if (!ctx) {
+ captureStream?.getTracks().forEach((track) => track.stop());
+ if (release) release();
+ if (releaseContinuousSession === release) releaseContinuousSession = null;
+ if (continuousSessionGeneration === generation) continuousSessionGeneration = null;
+ return;
+ }
+ try {
+ source?.disconnect();
+ workletNode?.disconnect();
+ workletNode && (workletNode.port.onmessage = null);
+ } catch { /* ignore teardown errors */ }
+ captureStream?.getTracks().forEach((track) => track.stop());
+ await Promise.resolve(ctx.close?.()).catch(() => {});
+ if (release) release();
+ if (releaseContinuousSession === release) releaseContinuousSession = null;
+ if (continuousSessionGeneration === generation) continuousSessionGeneration = null;
speechChunks = [];
preRoll = null;
preRollIdx = 0;
@@ -972,7 +1099,6 @@ export const stopContinuous = async () => {
onsetFrames = 0;
calibrating = false;
calibrationSamples = [];
- continuousCallbacks = null;
};
export const isContinuous = () => continuousCtx !== null;
@@ -998,6 +1124,7 @@ const SpeechRecognition = typeof window !== 'undefined'
let webSpeechRecognition = null;
let webSpeechShouldListen = false;
+let webSpeechGeneration = 0;
// Chrome fires onend immediately when a mic error, OS permission flicker, or
// driver glitch prevents recognition from ever binding. Blindly calling
// start() from onend in that state hot-loops the CPU. Count consecutive
@@ -1023,6 +1150,8 @@ const resolveRecognitionLang = (configured) => {
export const startWebSpeechCapture = ({ language, ...callbacks } = {}) => {
if (!SpeechRecognition) return;
stopWebSpeechCapture();
+ const ownerGeneration = captureOwnerGeneration;
+ const generation = ++webSpeechGeneration;
// Barge-in: abort any in-flight turn and silence current playback
socket.emit('voice:interrupt');
@@ -1036,6 +1165,7 @@ export const startWebSpeechCapture = ({ language, ...callbacks } = {}) => {
recognition.lang = resolveRecognitionLang(language);
recognition.onresult = (event) => {
+ if (!isOwnerCurrent(ownerGeneration) || webSpeechGeneration !== generation || webSpeechRecognition !== recognition) return;
let interim = '';
let final = '';
for (let i = event.resultIndex; i < event.results.length; i++) {
@@ -1071,7 +1201,10 @@ export const startWebSpeechCapture = ({ language, ...callbacks } = {}) => {
};
recognition.onend = () => {
- if (!webSpeechShouldListen) return;
+ if (!webSpeechShouldListen
+ || !isOwnerCurrent(ownerGeneration)
+ || webSpeechGeneration !== generation
+ || webSpeechRecognition !== recognition) return;
webSpeechRestartFailures += 1;
if (webSpeechRestartFailures >= WEB_SPEECH_MAX_RESTART_FAILURES) {
// Full teardown, not a bare flag flip: every caller-side cleanup is gated
@@ -1087,13 +1220,17 @@ export const startWebSpeechCapture = ({ language, ...callbacks } = {}) => {
const delay = Math.min(50 * 2 ** (webSpeechRestartFailures - 1), 800);
clearTimeout(webSpeechRestartTimer);
webSpeechRestartTimer = setTimeout(() => {
- if (webSpeechShouldListen && webSpeechRecognition === recognition) {
+ if (webSpeechShouldListen
+ && isOwnerCurrent(ownerGeneration)
+ && webSpeechGeneration === generation
+ && webSpeechRecognition === recognition) {
recognition.start();
}
}, delay);
};
recognition.onerror = (event) => {
+ if (!isOwnerCurrent(ownerGeneration) || webSpeechGeneration !== generation || webSpeechRecognition !== recognition) return;
if (event.error === 'not-allowed' || event.error === 'service-not-allowed') {
// Same reason as onend's restart-cap branch: release the claim here or a
// denied mic leaves the session pinned record-capable forever.
@@ -1117,12 +1254,13 @@ export const startWebSpeechCapture = ({ language, ...callbacks } = {}) => {
};
export const stopWebSpeechCapture = () => {
+ webSpeechGeneration += 1;
webSpeechShouldListen = false;
clearTimeout(webSpeechRestartTimer);
webSpeechRestartTimer = null;
webSpeechRestartFailures = 0;
if (webSpeechRecognition) {
- webSpeechRecognition.stop();
+ try { webSpeechRecognition.stop(); } catch { /* already stopped */ }
webSpeechRecognition = null;
}
releaseWebSpeechSession?.();
@@ -1130,3 +1268,64 @@ export const stopWebSpeechCapture = () => {
};
export const isWebSpeechCapturing = () => webSpeechShouldListen;
+
+/**
+ * Invalidate the widget that currently owns capture before its React cleanup
+ * awaits the normal cancel path. This is intentionally synchronous: a late
+ * permission result, recorder event, VAD conversion, or Web Speech restart
+ * must be unable to emit a turn or call a dead widget during that gap.
+ */
+export const disposeCaptureOwner = () => {
+ captureOwnerGeneration += 1;
+
+ const activeRecorder = recorder;
+ recorder = null;
+ recorderGeneration += 1;
+ recorderStartPendingGeneration = null;
+ chunks = [];
+ stream?.getTracks().forEach((track) => track.stop());
+ stream = null;
+ releaseCaptureSession?.();
+ releaseCaptureSession = null;
+ recorderSessionGeneration = null;
+ try { activeRecorder?.stop(); } catch { /* already stopped */ }
+
+ const context = continuousCtx;
+ const captureStream = continuousStream;
+ const workletNode = continuousWorkletNode;
+ const source = continuousSource;
+ continuousGeneration += 1;
+ continuousStartPendingGeneration = null;
+ continuousCapture = null;
+ continuousCtx = null;
+ continuousStream = null;
+ continuousWorkletNode = null;
+ continuousSource = null;
+ try {
+ source?.disconnect();
+ workletNode?.disconnect();
+ workletNode && (workletNode.port.onmessage = null);
+ } catch { /* ignore teardown errors */ }
+ captureStream?.getTracks().forEach((track) => track.stop());
+ Promise.resolve(context?.close?.()).catch(() => {});
+ releaseContinuousSession?.();
+ releaseContinuousSession = null;
+ continuousSessionGeneration = null;
+ speechChunks = [];
+ preRoll = null;
+ preRollIdx = 0;
+ preRollFilled = 0;
+ vadState = 'idle';
+ calibrating = false;
+ calibrationSamples = [];
+
+ const recognition = webSpeechRecognition;
+ webSpeechRecognition = null;
+ webSpeechGeneration += 1;
+ webSpeechShouldListen = false;
+ clearTimeout(webSpeechRestartTimer);
+ webSpeechRestartTimer = null;
+ try { recognition?.stop(); } catch { /* already stopped */ }
+ releaseWebSpeechSession?.();
+ releaseWebSpeechSession = null;
+};
diff --git a/client/src/services/voiceClient.test.js b/client/src/services/voiceClient.test.js
index 5cd8d0cc66..9d2b124d59 100644
--- a/client/src/services/voiceClient.test.js
+++ b/client/src/services/voiceClient.test.js
@@ -25,6 +25,8 @@ const { socket, listeners, audio, FakeAudioContext } = vi.hoisted(() => {
constructor() {
this.destination = {};
this.state = 'running';
+ this.sampleRate = 48_000;
+ this.audioWorklet = { addModule: vi.fn(() => Promise.resolve()) };
}
resume() {
@@ -47,6 +49,19 @@ const { socket, listeners, audio, FakeAudioContext } = vi.hoisted(() => {
audio.sources.push(source);
return source;
}
+
+ createMediaStreamSource() {
+ return { connect: vi.fn((target) => target), disconnect: vi.fn() };
+ }
+
+ createGain() {
+ return { gain: { value: 1 }, connect: vi.fn((target) => target) };
+ }
+
+ close() {
+ this.state = 'closed';
+ return Promise.resolve();
+ }
}
return { socket, listeners, audio, FakeAudioContext };
});
@@ -56,10 +71,54 @@ vi.mock('./socket', () => ({ default: socket }));
let voiceClient;
let recognition;
class FakeSpeechRecognition {
- constructor() { recognition = this; }
- start() {}
- stop() {}
- abort() {}
+ constructor() {
+ recognition = this;
+ this.startCalls = 0;
+ this.stopCalls = 0;
+ }
+ start() { this.startCalls += 1; }
+ stop() { this.stopCalls += 1; }
+ abort() { this.stop(); }
+}
+
+class FakeAudioWorkletNode {
+ constructor() {
+ this.port = { onmessage: null };
+ this.disconnect = vi.fn();
+ FakeAudioWorkletNode.last = this;
+ }
+
+ connect(target) { return target; }
+}
+
+class FakeMediaRecorder {
+ static isTypeSupported() { return true; }
+
+ constructor(stream, { mimeType }) {
+ this.stream = stream;
+ this.mimeType = mimeType;
+ this.handlers = new Map();
+ this.state = 'inactive';
+ FakeMediaRecorder.last = this;
+ }
+
+ addEventListener(event, handler) {
+ const handlers = this.handlers.get(event) || [];
+ handlers.push(handler);
+ this.handlers.set(event, handlers);
+ }
+
+ dispatch(event, payload) {
+ for (const handler of this.handlers.get(event) || []) handler(payload);
+ }
+
+ start() { this.state = 'recording'; }
+
+ stop() {
+ this.state = 'inactive';
+ this.dispatch('dataavailable', { data: { size: 1_000 } });
+ this.dispatch('stop');
+ }
}
const recognizeFinal = (text) => recognition.onresult({
@@ -80,6 +139,9 @@ describe('voice playback cancellation', () => {
beforeAll(async () => {
vi.stubGlobal('AudioContext', FakeAudioContext);
vi.stubGlobal('SpeechRecognition', FakeSpeechRecognition);
+ vi.stubGlobal('AudioWorkletNode', FakeAudioWorkletNode);
+ window.AudioContext = FakeAudioContext;
+ window.SpeechRecognition = FakeSpeechRecognition;
voiceClient = await import('./voiceClient.js');
});
@@ -89,9 +151,11 @@ describe('voice playback cancellation', () => {
audio.decodeImpl = () => Promise.resolve({});
audio.sources.length = 0;
socket.emit.mockClear();
+ voiceClient.disposeCaptureOwner();
});
afterEach(() => {
+ voiceClient.disposeCaptureOwner();
voiceClient.stopWebSpeechCapture();
trigger('voice:output:detached');
vi.restoreAllMocks();
@@ -294,4 +358,81 @@ describe('voice playback cancellation', () => {
recognizeFinal('wait');
expect(routeFinal).toHaveBeenCalledWith('wait');
});
+
+ it('drops recorder callbacks and releases the mic when its owner is disposed', async () => {
+ const previousRecorder = window.MediaRecorder;
+ const previousGlobalRecorder = globalThis.MediaRecorder;
+ const previousMediaDevices = navigator.mediaDevices;
+ const track = { stop: vi.fn() };
+ const getUserMedia = vi.fn().mockResolvedValue({ getTracks: () => [track] });
+ window.MediaRecorder = FakeMediaRecorder;
+ globalThis.MediaRecorder = FakeMediaRecorder;
+ Object.defineProperty(navigator, 'mediaDevices', {
+ configurable: true,
+ value: { getUserMedia },
+ });
+
+ await voiceClient.startCapture();
+ const activeRecorder = FakeMediaRecorder.last;
+ voiceClient.disposeCaptureOwner();
+ activeRecorder.dispatch('dataavailable', { data: { size: 1_000 } });
+
+ expect(track.stop).toHaveBeenCalledOnce();
+ expect(voiceClient.isCapturing()).toBe(false);
+ expect(socket.emit).not.toHaveBeenCalledWith('voice:turn', expect.anything());
+
+ window.MediaRecorder = previousRecorder;
+ if (previousGlobalRecorder === undefined) delete globalThis.MediaRecorder;
+ else globalThis.MediaRecorder = previousGlobalRecorder;
+ Object.defineProperty(navigator, 'mediaDevices', {
+ configurable: true,
+ value: previousMediaDevices,
+ });
+ });
+
+ it('ignores VAD worklet frames and async submissions after owner disposal', async () => {
+ const previousMediaDevices = navigator.mediaDevices;
+ const track = { stop: vi.fn() };
+ Object.defineProperty(navigator, 'mediaDevices', {
+ configurable: true,
+ value: { getUserMedia: vi.fn().mockResolvedValue({ getTracks: () => [track] }) },
+ });
+ const onSpeechStart = vi.fn();
+ const onSubmit = vi.fn();
+
+ await voiceClient.startContinuous({ onSpeechStart, onSubmit });
+ const lateFrame = FakeAudioWorkletNode.last.port.onmessage;
+ voiceClient.disposeCaptureOwner();
+ lateFrame?.({ data: new Float32Array([1, 1, 1, 1]) });
+
+ expect(track.stop).toHaveBeenCalledOnce();
+ expect(voiceClient.isContinuous()).toBe(false);
+ expect(onSpeechStart).not.toHaveBeenCalled();
+ expect(onSubmit).not.toHaveBeenCalled();
+ expect(socket.emit).not.toHaveBeenCalledWith('voice:turn', expect.anything());
+
+ Object.defineProperty(navigator, 'mediaDevices', {
+ configurable: true,
+ value: previousMediaDevices,
+ });
+ });
+
+ it('ignores Web Speech results and restart errors after owner disposal', () => {
+ const routeFinal = vi.fn();
+ const onError = vi.fn();
+ voiceClient.startWebSpeechCapture({ routeFinal, onError });
+ const oldRecognition = recognition;
+ voiceClient.disposeCaptureOwner();
+
+ oldRecognition.onresult?.({
+ resultIndex: 0,
+ results: [Object.assign([{ transcript: 'late result' }], { isFinal: true })],
+ });
+ oldRecognition.onerror?.({ error: 'not-allowed' });
+
+ expect(oldRecognition.stopCalls).toBe(1);
+ expect(routeFinal).not.toHaveBeenCalled();
+ expect(onError).not.toHaveBeenCalled();
+ expect(voiceClient.isWebSpeechCapturing()).toBe(false);
+ });
});