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: release microphone after hands-free startup failures (#8029)

[._.]/ Adam Eivy7ad8cf6b0936
diff --git a/client/src/services/voiceClient.js b/client/src/services/voiceClient.js
index 33b664001a..9210707674 100644
--- a/client/src/services/voiceClient.js
+++ b/client/src/services/voiceClient.js
@@ -994,68 +994,62 @@ export const startContinuous = async (callbacks = {}) => {
continuousStream = nextStream;
detectAudioRoute(continuousStream).catch(() => {});
- // Everything from here on can reject — a refused resume, a worklet module that
- // fails to compile — and `continuousCtx` is already assigned by then, so an
- // unwound setup would leave the mic open, the claim held, AND every later
- // Start returning at the `if (continuousCtx) return` guard with no way back
- // short of a reload. Tear the whole partial setup down before rethrowing.
- const unwindSetup = async (err) => {
- await stopContinuous();
+ // Constructors and graph wiring can throw synchronously too. Roll back every
+ // partial setup, including one that acquired the mic but never got a context.
+ let blobUrl = null;
+ try {
+ const Ctor = window.AudioContext || window.webkitAudioContext;
+ continuousCtx = new Ctor();
+ await resumeAudioContext(continuousCtx);
+ if (!isOwnerCurrent(ownerGeneration) || continuousGeneration !== generation) return null;
+
+ // Inline worklet module so we don't need a separate file in the build.
+ blobUrl = URL.createObjectURL(new Blob([WORKLET_SOURCE], { type: 'application/javascript' }));
+ await continuousCtx.audioWorklet.addModule(blobUrl);
+ if (!isOwnerCurrent(ownerGeneration) || continuousGeneration !== generation) return null;
+
+ continuousSource = continuousCtx.createMediaStreamSource(continuousStream);
+ continuousWorkletNode = new AudioWorkletNode(continuousCtx, 'vad-processor');
+
+ const sampleRate = continuousCtx.sampleRate;
+ preRollLimit = Math.max(1, Math.ceil((VAD.preRollMs / 1000) * sampleRate / 128));
+ preRoll = new Array(preRollLimit);
+ preRollIdx = 0;
+ preRollFilled = 0;
+ speechChunks = [];
+ vadState = 'idle';
+ silenceStartedAt = 0;
+ speechStartedAt = 0;
+ onsetFrames = 0;
+ calibrating = true;
+ calibrationSamples = [];
+ calibrationUntil = performance.now() + VAD.calibrationMs;
+ onRms = VAD.minOnRms;
+ offRms = VAD.minOffRms;
+
+ const capture = {
+ ownerGeneration,
+ generation,
+ callbacks,
+ context: continuousCtx,
+ };
+ continuousCapture = capture;
+ 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.
+ const sink = continuousCtx.createGain();
+ sink.gain.value = 0;
+ continuousWorkletNode.connect(sink).connect(continuousCtx.destination);
+ continuousStartPendingGeneration = null;
+ } catch (err) {
+ // A disposed or stopped generation already released its resources. Its late
+ // rejection must not stop a newer capture that has since started.
+ if (continuousGeneration === generation) await stopContinuous();
throw err;
- };
-
- const Ctor = window.AudioContext || window.webkitAudioContext;
- continuousCtx = new Ctor();
- await resumeAudioContext(continuousCtx).catch(unwindSetup);
- if (!isOwnerCurrent(ownerGeneration) || continuousGeneration !== generation) {
- await stopContinuous();
- return null;
+ } finally {
+ if (blobUrl !== null) URL.revokeObjectURL(blobUrl);
}
-
- // 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');
-
- const sampleRate = continuousCtx.sampleRate;
- preRollLimit = Math.max(1, Math.ceil((VAD.preRollMs / 1000) * sampleRate / 128));
- preRoll = new Array(preRollLimit);
- preRollIdx = 0;
- preRollFilled = 0;
- speechChunks = [];
- vadState = 'idle';
- silenceStartedAt = 0;
- speechStartedAt = 0;
- onsetFrames = 0;
- calibrating = true;
- calibrationSamples = [];
- calibrationUntil = performance.now() + VAD.calibrationMs;
- onRms = VAD.minOnRms;
- offRms = VAD.minOffRms;
-
- 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.
- const sink = continuousCtx.createGain();
- sink.gain.value = 0;
- continuousWorkletNode.connect(sink).connect(continuousCtx.destination);
};
export const stopContinuous = async () => {
@@ -1074,20 +1068,12 @@ export const stopContinuous = async () => {
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;
@@ -1099,6 +1085,8 @@ export const stopContinuous = async () => {
onsetFrames = 0;
calibrating = false;
calibrationSamples = [];
+ // Reset shared state before awaiting close so a retry owns fresh VAD state.
+ await Promise.resolve().then(() => ctx?.close?.()).catch(() => {});
};
export const isContinuous = () => continuousCtx !== null;
diff --git a/client/src/services/voiceClient.test.js b/client/src/services/voiceClient.test.js
index 9d2b124d59..30eeb2c913 100644
--- a/client/src/services/voiceClient.test.js
+++ b/client/src/services/voiceClient.test.js
@@ -417,6 +417,113 @@ describe('voice playback cancellation', () => {
});
});
+ describe('continuous startup rollback', () => {
+ let previousMediaDevices;
+ let previousAudioSession;
+ let tracks;
+ let getUserMedia;
+
+ beforeEach(() => {
+ previousMediaDevices = Object.getOwnPropertyDescriptor(navigator, 'mediaDevices');
+ previousAudioSession = Object.getOwnPropertyDescriptor(navigator, 'audioSession');
+ tracks = [{ stop: vi.fn() }, { stop: vi.fn() }];
+ getUserMedia = vi.fn().mockResolvedValue({ getTracks: () => tracks });
+ Object.defineProperty(navigator, 'mediaDevices', {
+ configurable: true,
+ value: { getUserMedia },
+ });
+ Object.defineProperty(navigator, 'audioSession', {
+ configurable: true,
+ value: { type: 'auto' },
+ });
+ });
+
+ afterEach(async () => {
+ await voiceClient.stopContinuous();
+ if (previousMediaDevices) Object.defineProperty(navigator, 'mediaDevices', previousMediaDevices);
+ else delete navigator.mediaDevices;
+ if (previousAudioSession) Object.defineProperty(navigator, 'audioSession', previousAudioSession);
+ else delete navigator.audioSession;
+ });
+
+ // Each stage leaves a different set of acquired resources to unwind.
+ it.each(['constructor', 'source', 'worklet node', 'connection', 'resume', 'module'])(
+ 'releases the microphone and permits retry after a %s failure', async (stage) => {
+ const error = new Error(`${stage} failed`);
+ const fail = () => { throw error; };
+ const context = new FakeAudioContext();
+ const close = vi.spyOn(context, 'close');
+ vi.spyOn(window, 'AudioContext').mockImplementationOnce(function () {
+ if (stage === 'constructor') throw error;
+ return context;
+ });
+ if (stage === 'source') vi.spyOn(context, 'createMediaStreamSource').mockImplementationOnce(fail);
+ if (stage === 'worklet node') {
+ vi.spyOn(globalThis, 'AudioWorkletNode').mockImplementationOnce(function () { throw error; });
+ }
+ if (stage === 'connection') vi.spyOn(FakeAudioWorkletNode.prototype, 'connect').mockImplementationOnce(fail);
+ if (stage === 'resume') {
+ context.state = 'suspended';
+ vi.spyOn(context, 'resume').mockRejectedValueOnce(error);
+ }
+ if (stage === 'module') context.audioWorklet.addModule.mockRejectedValueOnce(error);
+ const createUrl = vi.spyOn(URL, 'createObjectURL');
+ const revokeUrl = vi.spyOn(URL, 'revokeObjectURL');
+
+ await expect(voiceClient.startContinuous()).rejects.toBe(error);
+
+ tracks.forEach((track) => expect(track.stop).toHaveBeenCalledOnce());
+ expect(navigator.audioSession.type).toBe('auto');
+ expect(voiceClient.isContinuous()).toBe(false);
+ expect(close).toHaveBeenCalledTimes(stage === 'constructor' ? 0 : 1);
+ createUrl.mock.results.forEach(({ value }) => expect(revokeUrl).toHaveBeenCalledWith(value));
+ await voiceClient.stopContinuous();
+ tracks.forEach((track) => expect(track.stop).toHaveBeenCalledOnce());
+
+ const retryTrack = { stop: vi.fn() };
+ getUserMedia.mockResolvedValueOnce({ getTracks: () => [retryTrack] });
+ await voiceClient.startContinuous();
+ expect(getUserMedia).toHaveBeenCalledTimes(2);
+ expect(voiceClient.isContinuous()).toBe(true);
+ expect(navigator.audioSession.type).toBe('play-and-record');
+ expect(retryTrack.stop).not.toHaveBeenCalled();
+ await voiceClient.stopContinuous();
+ expect(retryTrack.stop).toHaveBeenCalledOnce();
+ expect(navigator.audioSession.type).toBe('auto');
+ },
+ );
+
+ it.each(['resolve', 'reject'])('does not stop a retry when a disposed startup later %ss', async (outcome) => {
+ let resolveModule;
+ let rejectModule;
+ const context = new FakeAudioContext();
+ context.audioWorklet.addModule.mockImplementationOnce(() => new Promise((resolve, reject) => {
+ resolveModule = resolve;
+ rejectModule = reject;
+ }));
+ vi.spyOn(window, 'AudioContext').mockImplementationOnce(function () { return context; });
+ const pending = voiceClient.startContinuous();
+ await vi.waitFor(() => expect(context.audioWorklet.addModule).toHaveBeenCalledOnce());
+ voiceClient.disposeCaptureOwner();
+ const retryTrack = { stop: vi.fn() };
+ getUserMedia.mockResolvedValueOnce({ getTracks: () => [retryTrack] });
+ await voiceClient.startContinuous();
+
+ if (outcome === 'reject') {
+ const error = new Error('old module failed');
+ const rejection = expect(pending).rejects.toBe(error);
+ rejectModule(error);
+ await rejection;
+ } else {
+ resolveModule();
+ await expect(pending).resolves.toBeNull();
+ }
+ expect(voiceClient.isContinuous()).toBe(true);
+ expect(navigator.audioSession.type).toBe('play-and-record');
+ expect(retryTrack.stop).not.toHaveBeenCalled();
+ });
+ });
+
it('ignores Web Speech results and restart errors after owner disposal', () => {
const routeFinal = vi.fn();
const onError = vi.fn();