Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

fix(audio): re-acquire the mic when it goes silent after idle (#922)

Alcaheste822188de463
diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.js
index 28d0e2370..4c88b514e 100644
--- a/src/helpers/audioManager.js
+++ b/src/helpers/audioManager.js
@@ -10,6 +10,7 @@ import {
getLocalSpeechGateDecision,
recordLocalSpeechWindow,
} from "./localSpeechGate";
+import { reacquireIfDead } from "./micTrackHealth";
import { getSettings, getEffectiveCleanupModel, isCloudCleanupMode } from "../stores/settingsStore";
import { shouldSkipTranscriptionApiKey } from "./transcriptionAuth";
import { detectAgentName } from "../config/agentDetection";
@@ -129,6 +130,14 @@ class AudioManager {
this.cachedApiKeyProvider = null;
};
window.addEventListener("api-key-changed", this._onApiKeyChanged);
+
+ // Invalidate the pinned mic device when the OS adds/removes/suspends inputs.
+ // Otherwise wake-after-idle keeps requesting a stale deviceId that yields silence.
+ this._onDeviceChange = () => {
+ this.cachedMicDeviceId = null;
+ this.micDriverWarmedUp = false;
+ };
+ navigator.mediaDevices?.addEventListener?.("devicechange", this._onDeviceChange);
this.cachedTranscriptionEndpoint = null;
this.cachedEndpointProvider = null;
this.cachedEndpointBaseUrl = null;
@@ -333,9 +342,16 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
}
const constraints = await this.getAudioConstraints();
- const micStream = await navigator.mediaDevices.getUserMedia(constraints);
-
+ const micStream = await reacquireIfDead(
+ await navigator.mediaDevices.getUserMedia(constraints),
+ () => {
+ this.cachedMicDeviceId = null;
+ return this.getAudioConstraints();
+ },
+ logger
+ );
const audioTrack = micStream.getAudioTracks()[0];
+
if (audioTrack) {
const settings = audioTrack.getSettings();
logger.info(
@@ -345,6 +361,8 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
deviceId: settings.deviceId?.slice(0, 20) + "...",
sampleRate: settings.sampleRate,
channelCount: settings.channelCount,
+ muted: audioTrack.muted,
+ readyState: audioTrack.readyState,
},
"audio"
);
@@ -2180,10 +2198,19 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
const tConstraints = performance.now();
// 1. Get mic stream (can take 10-15s on cold macOS mic driver)
- const stream = await navigator.mediaDevices.getUserMedia(constraints);
+ const rawStream = await navigator.mediaDevices.getUserMedia(constraints);
const tMedia = performance.now();
+ const stream = await reacquireIfDead(
+ rawStream,
+ () => {
+ this.cachedMicDeviceId = null;
+ return this.getAudioConstraints();
+ },
+ logger
+ );
const audioTrack = stream.getAudioTracks()[0];
+
if (audioTrack) {
const settings = audioTrack.getSettings();
logger.info(
@@ -2193,6 +2220,8 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
deviceId: settings.deviceId?.slice(0, 20) + "...",
sampleRate: settings.sampleRate,
usedCachedId: !!this.cachedMicDeviceId,
+ muted: audioTrack.muted,
+ readyState: audioTrack.readyState,
},
"audio"
);
@@ -2824,6 +2853,9 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
if (this._onApiKeyChanged) {
window.removeEventListener("api-key-changed", this._onApiKeyChanged);
}
+ if (this._onDeviceChange) {
+ navigator.mediaDevices?.removeEventListener?.("devicechange", this._onDeviceChange);
+ }
}
}
diff --git a/src/helpers/micTrackHealth.js b/src/helpers/micTrackHealth.js
new file mode 100644
index 000000000..401cddaef
--- /dev/null
+++ b/src/helpers/micTrackHealth.js
@@ -0,0 +1,79 @@
+const TRACK_READY_TIMEOUT_MS = 600;
+
+// Waits until a capture track is actually delivering audio (wake-after-idle re-acquire).
+// After the OS suspends the input during idle, getUserMedia can hand back a track that
+// stays muted/ended and yields silence; callers use this to detect that and re-acquire.
+export const waitForTrackReady = (track, timeoutMs) =>
+ new Promise((resolve) => {
+ // Dead track will never deliver audio — fail fast so the caller re-acquires.
+ if (!track || track.readyState === "ended") {
+ resolve(false);
+ return;
+ }
+
+ // Common warm-device case: already unmuted, resolve with zero latency.
+ if (!track.muted) {
+ resolve(true);
+ return;
+ }
+
+ let settled = false;
+ let timer = null;
+
+ // Clear timer and detach both listeners on every exit path (no leaks).
+ const cleanup = () => {
+ if (timer !== null) {
+ clearTimeout(timer);
+ timer = null;
+ }
+ track.removeEventListener("unmute", onUnmute);
+ track.removeEventListener("ended", onEnded);
+ };
+
+ const settle = (value) => {
+ if (settled) return;
+ settled = true;
+ cleanup();
+ resolve(value);
+ };
+
+ function onUnmute() {
+ settle(true);
+ }
+
+ function onEnded() {
+ settle(false);
+ }
+
+ track.addEventListener("unmute", onUnmute);
+ track.addEventListener("ended", onEnded);
+
+ // Fallback: if neither event fires, treat a still-live unmuted track as ready.
+ timer = setTimeout(() => {
+ settle(!track.muted && track.readyState !== "ended");
+ }, timeoutMs);
+ });
+
+// Re-acquires the mic once if the first track never delivers audio (dead/muted after idle).
+// getFreshConstraints must drop any pinned device id so the retry re-resolves the device.
+// Returns a live stream — the original when it was healthy or the retry failed.
+export const reacquireIfDead = async (stream, getFreshConstraints, logger) => {
+ const track = stream.getAudioTracks()[0];
+ if (!track || (await waitForTrackReady(track, TRACK_READY_TIMEOUT_MS))) {
+ return stream;
+ }
+
+ try {
+ const retryStream = await navigator.mediaDevices.getUserMedia(await getFreshConstraints());
+ stream.getTracks().forEach((t) => t.stop());
+ logger.info("Re-acquired microphone after dead/muted track", {}, "audio");
+ return retryStream;
+ } catch (error) {
+ logger.warn(
+ "Microphone re-acquire failed, using original stream",
+ { error: error.message },
+ "audio"
+ );
+ return stream;
+ }
+};
diff --git a/test/helpers/micTrackHealth.test.js b/test/helpers/micTrackHealth.test.js
new file mode 100644
index 000000000..17d665efb
--- /dev/null
+++ b/test/helpers/micTrackHealth.test.js
@@ -0,0 +1,188 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+// Fake MediaStreamTrack: real EventTarget so add/removeEventListener behave normally.
+class FakeTrack extends EventTarget {
+ constructor({ muted = false, readyState = "live" } = {}) {
+ super();
+ this.muted = muted;
+ this.readyState = readyState;
+ this._listenerCount = 0;
+ }
+
+ addEventListener(type, cb) {
+ this._listenerCount += 1;
+ super.addEventListener(type, cb);
+ }
+
+ removeEventListener(type, cb) {
+ this._listenerCount -= 1;
+ super.removeEventListener(type, cb);
+ }
+
+ fire(type) {
+ this.dispatchEvent(new Event(type));
+ }
+}
+
+test("resolves false immediately for an ended track", async () => {
+ const { waitForTrackReady } = await import("../../src/helpers/micTrackHealth.js");
+ const track = new FakeTrack({ readyState: "ended" });
+ assert.equal(await waitForTrackReady(track, 600), false);
+ assert.equal(track._listenerCount, 0);
+});
+
+test("resolves false immediately for a null track", async () => {
+ const { waitForTrackReady } = await import("../../src/helpers/micTrackHealth.js");
+ assert.equal(await waitForTrackReady(null, 600), false);
+});
+
+test("resolves true immediately for an unmuted live track", async () => {
+ const { waitForTrackReady } = await import("../../src/helpers/micTrackHealth.js");
+ const track = new FakeTrack({ muted: false });
+ assert.equal(await waitForTrackReady(track, 600), true);
+ assert.equal(track._listenerCount, 0);
+});
+
+test("resolves true when a muted track fires unmute, with no listener leak", async () => {
+ const { waitForTrackReady } = await import("../../src/helpers/micTrackHealth.js");
+ const track = new FakeTrack({ muted: true });
+ const pending = waitForTrackReady(track, 600);
+ track.muted = false;
+ track.fire("unmute");
+ assert.equal(await pending, true);
+ assert.equal(track._listenerCount, 0);
+});
+
+test("resolves false when a muted track fires ended, with no listener leak", async () => {
+ const { waitForTrackReady } = await import("../../src/helpers/micTrackHealth.js");
+ const track = new FakeTrack({ muted: true });
+ const pending = waitForTrackReady(track, 600);
+ track.readyState = "ended";
+ track.fire("ended");
+ assert.equal(await pending, false);
+ assert.equal(track._listenerCount, 0);
+});
+
+test("resolves false after timeout when a muted track never changes", async (t) => {
+ const { waitForTrackReady } = await import("../../src/helpers/micTrackHealth.js");
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const track = new FakeTrack({ muted: true });
+ const pending = waitForTrackReady(track, 600);
+ t.mock.timers.tick(600);
+ assert.equal(await pending, false);
+ assert.equal(track._listenerCount, 0);
+});
+
+test("resolves true after timeout if the track quietly unmuted without firing", async (t) => {
+ const { waitForTrackReady } = await import("../../src/helpers/micTrackHealth.js");
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const track = new FakeTrack({ muted: true });
+ const pending = waitForTrackReady(track, 600);
+ track.muted = false; // unmuted but no event dispatched
+ t.mock.timers.tick(600);
+ assert.equal(await pending, true);
+ assert.equal(track._listenerCount, 0);
+});
+
+// Fake MediaStream: one track plus a stop-tracking flag, matching the bits reacquireIfDead touches.
+class FakeStream {
+ constructor(track) {
+ this.track = track;
+ this.stopped = false;
+ }
+
+ getAudioTracks() {
+ return this.track ? [this.track] : [];
+ }
+
+ getTracks() {
+ return this.track ? [this.track] : [];
+ }
+}
+
+const noopLogger = { info() {}, warn() {} };
+
+function stubGetUserMedia(impl) {
+ const original = globalThis.navigator;
+ Object.defineProperty(globalThis, "navigator", {
+ value: { mediaDevices: { getUserMedia: impl } },
+ configurable: true,
+ });
+ return () =>
+ Object.defineProperty(globalThis, "navigator", { value: original, configurable: true });
+}
+
+test("reacquireIfDead returns the original stream and never retries a healthy track", async () => {
+ const { reacquireIfDead } = await import("../../src/helpers/micTrackHealth.js");
+ const stream = new FakeStream(new FakeTrack({ muted: false }));
+ let called = false;
+ const restore = stubGetUserMedia(async () => {
+ called = true;
+ });
+ try {
+ const result = await reacquireIfDead(stream, () => ({}), noopLogger);
+ assert.equal(result, stream);
+ assert.equal(called, false);
+ assert.equal(stream.stopped, false);
+ } finally {
+ restore();
+ }
+});
+
+test("reacquireIfDead returns the original stream for a trackless stream", async () => {
+ const { reacquireIfDead } = await import("../../src/helpers/micTrackHealth.js");
+ const stream = new FakeStream(null);
+ let called = false;
+ const restore = stubGetUserMedia(async () => {
+ called = true;
+ });
+ try {
+ assert.equal(await reacquireIfDead(stream, () => ({}), noopLogger), stream);
+ assert.equal(called, false);
+ } finally {
+ restore();
+ }
+});
+
+test("reacquireIfDead re-acquires once and stops the dead stream", async () => {
+ const { reacquireIfDead } = await import("../../src/helpers/micTrackHealth.js");
+ const deadTrack = new FakeTrack({ readyState: "ended" });
+ deadTrack.stop = () => {
+ deadTrack._stopped = true;
+ };
+ const stream = new FakeStream(deadTrack);
+ const fresh = new FakeStream(new FakeTrack({ muted: false }));
+ let constraintsCleared = false;
+ const restore = stubGetUserMedia(async () => fresh);
+ try {
+ const result = await reacquireIfDead(
+ stream,
+ () => {
+ constraintsCleared = true;
+ return {};
+ },
+ noopLogger
+ );
+ assert.equal(result, fresh);
+ assert.equal(constraintsCleared, true);
+ assert.equal(deadTrack._stopped, true);
+ } finally {
+ restore();
+ }
+});
+
+test("reacquireIfDead falls back to the original stream when the retry fails", async () => {
+ const { reacquireIfDead } = await import("../../src/helpers/micTrackHealth.js");
+ const deadTrack = new FakeTrack({ readyState: "ended" });
+ deadTrack.stop = () => {};
+ const stream = new FakeStream(deadTrack);
+ const restore = stubGetUserMedia(async () => {
+ throw new Error("device busy");
+ });
+ try {
+ assert.equal(await reacquireIfDead(stream, () => ({}), noopLogger), stream);
+ } finally {
+ restore();
+ }
+});