Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
fix(mic): persist microphone selection across Chromium device ID change (#1172)
Chad Piha540a785026a4
diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsxindex 08edc340c..2400fb582 100644--- a/src/components/SettingsPage.tsx+++ b/src/components/SettingsPage.tsx@@ -707,8 +707,9 @@ export default function SettingsPage({setActivationMode,preferBuiltInMic,selectedMicDeviceId,+ selectedMicDeviceLabel,setPreferBuiltInMic,- setSelectedMicDeviceId,+ setSelectedMicDevice,setUseLocalWhisper,setUiLanguage,setWhisperModel,@@ -2703,8 +2704,9 @@ export default function SettingsPage({<MicrophoneSettingspreferBuiltInMic={preferBuiltInMic}selectedMicDeviceId={selectedMicDeviceId}+ selectedMicDeviceLabel={selectedMicDeviceLabel}onPreferBuiltInChange={setPreferBuiltInMic}- onDeviceSelect={setSelectedMicDeviceId}+ onDeviceSelect={setSelectedMicDevice}/></SettingsPanelRow></SettingsPanel>diff --git a/src/components/ui/MicrophoneSettings.tsx b/src/components/ui/MicrophoneSettings.tsxindex 215f5d3bc..93b405e3f 100644--- a/src/components/ui/MicrophoneSettings.tsx+++ b/src/components/ui/MicrophoneSettings.tsx@@ -6,6 +6,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from ".import { Button } from "./button";import { RefreshCw, Mic } from "lucide-react";import { isBuiltInMicrophone } from "../../utils/audioDeviceUtils";+import { resolveMicDeviceSelection } from "../../helpers/micDeviceSelection";interface AudioDevice {deviceId: string;@@ -16,13 +17,15 @@ interface AudioDevice {interface MicrophoneSettingsProps {preferBuiltInMic: boolean;selectedMicDeviceId: string;+ selectedMicDeviceLabel: string;onPreferBuiltInChange: (value: boolean) => void;- onDeviceSelect: (deviceId: string) => void;+ onDeviceSelect: (deviceId: string, label: string) => void;}export const MicrophoneSettings: React.FC<MicrophoneSettingsProps> = ({preferBuiltInMic,selectedMicDeviceId,+ selectedMicDeviceLabel,onPreferBuiltInChange,onDeviceSelect,}) => {@@ -34,14 +37,16 @@ export const MicrophoneSettings: React.FC<MicrophoneSettingsProps> = ({// Use refs to access current values without triggering re-rendersconst preferBuiltInRef = useRef(preferBuiltInMic);const selectedDeviceRef = useRef(selectedMicDeviceId);+ const selectedDeviceLabelRef = useRef(selectedMicDeviceLabel);const onDeviceSelectRef = useRef(onDeviceSelect);// Keep refs in syncuseEffect(() => {preferBuiltInRef.current = preferBuiltInMic;selectedDeviceRef.current = selectedMicDeviceId;+ selectedDeviceLabelRef.current = selectedMicDeviceLabel;onDeviceSelectRef.current = onDeviceSelect;- }, [preferBuiltInMic, selectedMicDeviceId, onDeviceSelect]);+ }, [preferBuiltInMic, selectedMicDeviceId, selectedMicDeviceLabel, onDeviceSelect]);const loadDevices = useCallback(async () => {setIsLoading(true);@@ -68,9 +73,24 @@ export const MicrophoneSettings: React.FC<MicrophoneSettingsProps> = ({setDevices(audioInputs);+ const resolvedSelection = resolveMicDeviceSelection(+ audioInputs,+ selectedDeviceRef.current,+ selectedDeviceLabelRef.current+ );+ if (+ resolvedSelection.device &&+ (resolvedSelection.status === "remapped" || !selectedDeviceLabelRef.current)+ ) {+ onDeviceSelectRef.current(+ resolvedSelection.device.deviceId,+ resolvedSelection.device.label+ );+ }+// If no device is selected and not preferring built-in, select the first deviceif (!preferBuiltInRef.current && !selectedDeviceRef.current && audioInputs.length > 0) {- onDeviceSelectRef.current(audioInputs[0].deviceId);+ onDeviceSelectRef.current(audioInputs[0].deviceId, audioInputs[0].label);}} catch {setError(t("microphoneSettings.errors.unableToAccess"));@@ -143,7 +163,14 @@ export const MicrophoneSettings: React.FC<MicrophoneSettingsProps> = ({) : (<Selectvalue={selectedMicDeviceId || "default"}- onValueChange={(value) => onDeviceSelect(value === "default" ? "" : value)}+ onValueChange={(value) => {+ if (value === "default") {+ onDeviceSelect("", "");+ return;+ }+ const device = devices.find((candidate) => candidate.deviceId === value);+ onDeviceSelect(value, device?.label || "");+ }}><SelectTrigger className="w-full"><SelectValue placeholder={t("microphoneSettings.selectPlaceholder")}>diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.jsindex 42b7d9d9c..3bf12d902 100644--- a/src/helpers/audioManager.js+++ b/src/helpers/audioManager.js@@ -15,6 +15,7 @@ import {recordLocalSpeechWindow,} from "./localSpeechGate";import { reacquireIfDead } from "./micTrackHealth";+import { reconcileSavedMicSelection } from "./micSelectionRecovery";import { isStaleDeviceError } from "./staleMicDevice";import { shouldSaveDiscardedRecording } from "./discardedRecording";import {@@ -212,6 +213,7 @@ class AudioManager {// Otherwise wake-after-idle keeps requesting a stale deviceId that yields silence.this._onDeviceChange = () => {this.cachedMicDeviceId = null;+ this.validatedSelectedMicDeviceId = null;this.micDriverWarmedUp = false;};navigator.mediaDevices?.addEventListener?.("devicechange", this._onDeviceChange);@@ -232,6 +234,7 @@ class AudioManager {this.streamingTextResolve = null;this.streamingTextDebounce = null;this.cachedMicDeviceId = null;+ this.validatedSelectedMicDeviceId = null;this.persistentAudioContext = null;this.workletModuleLoaded = false;this.workletBlobUrl = null;@@ -352,8 +355,11 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);}async getAudioConstraints(forceDefaultMic = false) {- const { preferBuiltInMic: preferBuiltIn, selectedMicDeviceId: selectedDeviceId } =- getSettings();+ const {+ preferBuiltInMic: preferBuiltIn,+ selectedMicDeviceId: selectedDeviceId,+ selectedMicDeviceLabel: selectedDeviceLabel,+ } = getSettings();// All browser audio processing disabled to avoid OS-level side-effects.// AGC off: Chromium's AGC on Windows mutates the system mic volume via WASAPI (#476).@@ -407,8 +413,37 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);}if (!preferBuiltIn && selectedDeviceId) {- logger.debug("Using selected microphone", { deviceId: selectedDeviceId }, "audio");- return { audio: { deviceId: { exact: selectedDeviceId }, ...noProcessing } };+ let resolvedDeviceId = selectedDeviceId;++ if (this.validatedSelectedMicDeviceId !== selectedDeviceId) {+ try {+ const reconciled = await reconcileSavedMicSelection(+ selectedDeviceId,+ selectedDeviceLabel,+ "audio"+ );+ resolvedDeviceId = reconciled.deviceId;++ if (reconciled.resolved) {+ this.validatedSelectedMicDeviceId = resolvedDeviceId;+ } else {+ // Avoid enumerating on every recording while the saved device is+ // unplugged. A devicechange event clears this cache when it returns.+ this.validatedSelectedMicDeviceId = reconciled.labelsAvailable+ ? selectedDeviceId+ : null;+ }+ } catch (error) {+ logger.debug(+ "Failed to reconcile selected microphone",+ { error: error.message },+ "audio"+ );+ }+ }++ logger.debug("Using selected microphone", { deviceId: resolvedDeviceId }, "audio");+ return { audio: { deviceId: { exact: resolvedDeviceId }, ...noProcessing } };}logger.debug("Using default microphone", {}, "audio");diff --git a/src/helpers/micDeviceSelection.js b/src/helpers/micDeviceSelection.jsnew file mode 100644index 000000000..7a3e71253--- /dev/null+++ b/src/helpers/micDeviceSelection.js@@ -0,0 +1,37 @@+/**+ * Reconcile a saved microphone preference with the devices Chromium currently+ * exposes. deviceId is preferred while it remains valid; the label is only a+ * recovery key when exactly one current input has that label.+ */+export function resolveMicDeviceSelection(devices, selectedDeviceId, selectedDeviceLabel) {+ if (!selectedDeviceId) {+ return { device: null, status: "default" };+ }++ // Callers pass raw MediaDeviceInfo lists or pre-filtered inputs without a kind.+ const audioInputs = devices.filter(+ (device) => device.kind === undefined || device.kind === "audioinput"+ );+ const exactMatch = audioInputs.find((device) => device.deviceId === selectedDeviceId);++ if (exactMatch) {+ return { device: exactMatch, status: "exact" };+ }++ if (!selectedDeviceLabel) {+ return { device: null, status: "missing" };+ }++ const labelMatches = audioInputs.filter(+ (device) => device.deviceId !== "default" && device.label === selectedDeviceLabel+ );++ if (labelMatches.length === 1) {+ return { device: labelMatches[0], status: "remapped" };+ }++ return {+ device: null,+ status: labelMatches.length > 1 ? "ambiguous" : "missing",+ };+}diff --git a/src/helpers/micSelectionRecovery.js b/src/helpers/micSelectionRecovery.jsnew file mode 100644index 000000000..25fb176dc--- /dev/null+++ b/src/helpers/micSelectionRecovery.js@@ -0,0 +1,43 @@+import { getSettings } from "../stores/settingsStore";+import logger from "../utils/logger";+import { resolveMicDeviceSelection } from "./micDeviceSelection";++/**+ * Resolve the saved mic selection against live devices, persisting a remap or+ * label backfill so the preference survives Chromium device-ID rotation.+ * `labelsAvailable` is false while device labels are hidden (no mic permission+ * yet), in which case a failed resolution should not be treated as final.+ */+export async function reconcileSavedMicSelection(+ selectedDeviceId,+ selectedDeviceLabel,+ logChannel+) {+ const devices = await navigator.mediaDevices.enumerateDevices();+ const { device, status } = resolveMicDeviceSelection(+ devices,+ selectedDeviceId,+ selectedDeviceLabel+ );++ if (!device) {+ return {+ deviceId: selectedDeviceId,+ resolved: false,+ labelsAvailable: devices.some((d) => d.kind === "audioinput" && d.label),+ };+ }++ if (status === "remapped" || (!selectedDeviceLabel && device.label)) {+ getSettings().setSelectedMicDevice(device.deviceId, device.label);+ logger.info(+ status === "remapped"+ ? "Restored selected microphone after its device ID changed"+ : "Saved selected microphone label for future recovery",+ { deviceId: device.deviceId, label: device.label },+ logChannel+ );+ }++ return { deviceId: device.deviceId, resolved: true, labelsAvailable: true };+}diff --git a/src/hooks/useSettings.ts b/src/hooks/useSettings.tsindex 87c58b50e..19530a65c 100644--- a/src/hooks/useSettings.ts+++ b/src/hooks/useSettings.ts@@ -60,6 +60,7 @@ export interface OnboardingSettings {export interface MicrophoneSettings {preferBuiltInMic: boolean;selectedMicDeviceId: string;+ selectedMicDeviceLabel: string;}export interface ApiKeySettings {@@ -324,8 +325,9 @@ function useSettingsInternal() {setPanelStartPosition: store.setPanelStartPosition,preferBuiltInMic: store.preferBuiltInMic,selectedMicDeviceId: store.selectedMicDeviceId,+ selectedMicDeviceLabel: store.selectedMicDeviceLabel,setPreferBuiltInMic: store.setPreferBuiltInMic,- setSelectedMicDeviceId: store.setSelectedMicDeviceId,+ setSelectedMicDevice: store.setSelectedMicDevice,autoLearnCorrections,setAutoLearnCorrections,showTranscriptionPreview: store.showTranscriptionPreview,diff --git a/src/stores/meetingRecordingStore.ts b/src/stores/meetingRecordingStore.tsindex 86238ee3f..c15dde9e3 100644--- a/src/stores/meetingRecordingStore.ts+++ b/src/stores/meetingRecordingStore.ts@@ -2,6 +2,7 @@ import { create } from "zustand";import { getSettings, selectResolvedMeetingTranscription } from "./settingsStore";import { useStreamingProvidersStore } from "./streamingProvidersStore";import { isBuiltInMicrophone } from "../utils/audioDeviceUtils";+import { reconcileSavedMicSelection } from "../helpers/micSelectionRecovery";import { getBaseLanguageCode } from "../utils/languageSupport";import type { SystemAudioAccessResult, SystemAudioStrategy } from "../types/electron";import {@@ -295,7 +296,7 @@ export const primeMeetingWorklet = () => {};const getMeetingMicConstraints = async (): Promise<MediaStreamConstraints> => {- const { preferBuiltInMic, selectedMicDeviceId } = getSettings();+ const { preferBuiltInMic, selectedMicDeviceId, selectedMicDeviceLabel } = getSettings();if (preferBuiltInMic) {try {@@ -322,9 +323,26 @@ const getMeetingMicConstraints = async (): Promise<MediaStreamConstraints> => {}if (selectedMicDeviceId && selectedMicDeviceId !== "default") {+ let resolvedDeviceId = selectedMicDeviceId;++ try {+ const reconciled = await reconcileSavedMicSelection(+ selectedMicDeviceId,+ selectedMicDeviceLabel,+ "meeting"+ );+ resolvedDeviceId = reconciled.deviceId;+ } catch (err) {+ logger.debug(+ "Failed to reconcile selected microphone for meeting transcription",+ { error: (err as Error).message },+ "meeting"+ );+ }+return {audio: {- deviceId: { exact: selectedMicDeviceId },+ deviceId: { exact: resolvedDeviceId },...MEETING_MIC_PRIMARY_AUDIO_CONSTRAINTS,},};diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.tsindex 11b02219b..f238d114a 100644--- a/src/stores/settingsStore.ts+++ b/src/stores/settingsStore.ts@@ -623,7 +623,7 @@ export interface SettingsStatesetActivationMode: (mode: "tap" | "push") => void;setPreferBuiltInMic: (value: boolean) => void;- setSelectedMicDeviceId: (value: string) => void;+ setSelectedMicDevice: (deviceId: string, label: string) => void;setTheme: (value: "light" | "dark" | "auto") => void;setCloudBackupEnabled: (value: boolean) => void;@@ -954,6 +954,7 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({preferBuiltInMic: readBoolean("preferBuiltInMic", true),selectedMicDeviceId: readString("selectedMicDeviceId", ""),+ selectedMicDeviceLabel: readString("selectedMicDeviceLabel", ""),theme: (() => {const v = readString("theme", "auto");@@ -1469,7 +1470,13 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({},setPreferBuiltInMic: createBooleanSetter("preferBuiltInMic"),- setSelectedMicDeviceId: createStringSetter("selectedMicDeviceId"),+ setSelectedMicDevice: (deviceId: string, label: string) => {+ if (isBrowser) {+ localStorage.setItem("selectedMicDeviceLabel", label);+ localStorage.setItem("selectedMicDeviceId", deviceId);+ }+ set({ selectedMicDeviceId: deviceId, selectedMicDeviceLabel: label });+ },setTheme: (value: "light" | "dark" | "auto") => {if (isBrowser) localStorage.setItem("theme", value);diff --git a/test/helpers/micDeviceSelection.test.js b/test/helpers/micDeviceSelection.test.jsnew file mode 100644index 000000000..0c7fa851c--- /dev/null+++ b/test/helpers/micDeviceSelection.test.js@@ -0,0 +1,76 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const load = () => import("../../src/helpers/micDeviceSelection.js");++const mic = (deviceId, label) => ({ kind: "audioinput", deviceId, label });++test("uses the saved device ID while it is still available", async () => {+ const { resolveMicDeviceSelection } = await load();+ const device = mic("saved-id", "Studio Mic");++ assert.deepEqual(resolveMicDeviceSelection([device], "saved-id", "Studio Mic"), {+ device,+ status: "exact",+ });+});++test("remaps a stale ID when exactly one microphone has the saved label", async () => {+ const { resolveMicDeviceSelection } = await load();+ const device = mic("new-id", "Studio Mic");++ assert.deepEqual(resolveMicDeviceSelection([device], "old-id", "Studio Mic"), {+ device,+ status: "remapped",+ });+});++test("does not guess when multiple microphones have the saved label", async () => {+ const { resolveMicDeviceSelection } = await load();++ assert.deepEqual(+ resolveMicDeviceSelection(+ [mic("first", "USB Audio"), mic("second", "USB Audio")],+ "old-id",+ "USB Audio"+ ),+ { device: null, status: "ambiguous" }+ );+});++test("keeps an unplugged microphone preference unresolved", async () => {+ const { resolveMicDeviceSelection } = await load();++ assert.deepEqual(resolveMicDeviceSelection([], "old-id", "Studio Mic"), {+ device: null,+ status: "missing",+ });+});++test("does not remap a stale ID without a saved label", async () => {+ const { resolveMicDeviceSelection } = await load();++ assert.deepEqual(resolveMicDeviceSelection([mic("new-id", "Studio Mic")], "old-id", ""), {+ device: null,+ status: "missing",+ });+});++test("ignores non-input devices when remapping", async () => {+ const { resolveMicDeviceSelection } = await load();+ const output = { kind: "audiooutput", deviceId: "speaker", label: "Studio Mic" };++ assert.deepEqual(resolveMicDeviceSelection([output], "old-id", "Studio Mic"), {+ device: null,+ status: "missing",+ });+});++test("treats an empty saved ID as the system default", async () => {+ const { resolveMicDeviceSelection } = await load();++ assert.deepEqual(resolveMicDeviceSelection([mic("mic", "Studio Mic")], "", ""), {+ device: null,+ status: "default",+ });+});