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(audio): eliminate first-words loss from cold mic opens (#845) (#1493)
Chad Piha28cb7f82094c
diff --git a/main.js b/main.jsindex 5e36f2c2c..fbe921fd3 100644--- a/main.js+++ b/main.js@@ -1229,6 +1229,7 @@ async function startApp() {return;}windowManager.showDictationPanel();+ windowManager.sendPrepareDictation();const pressTime = now;globeKeyDownTime = pressTime;globeKeyIsRecording = false;@@ -1286,6 +1287,9 @@ async function startApp() {globeKeyIsRecording = false;debugLogger?.debug("[Globe] Stopping dictation (push release)");windowManager.sendStopDictation();+ } else {+ windowManager.sendCancelDictationPreparation();+ windowManager.hideDictationPanel();}}}@@ -1311,6 +1315,7 @@ async function startApp() {if (wasRecording) {windowManager.sendCancelDictation();} else {+ windowManager.sendCancelDictationPreparation();windowManager.hideDictationPanel();}});@@ -1349,6 +1354,7 @@ async function startApp() {const now = Date.now();if (now - rightModLastStopTime < POST_STOP_COOLDOWN_MS) return;windowManager.showDictationPanel();+ windowManager.sendPrepareDictation();const pressTime = now;rightModActiveKey = modifier;rightModDownTime = pressTime;@@ -1377,6 +1383,7 @@ async function startApp() {rightModIsRecording = false;windowManager.sendStopDictation();} else {+ windowManager.sendCancelDictationPreparation();windowManager.hideDictationPanel();}}@@ -1435,6 +1442,7 @@ async function startApp() {const now = Date.now();if (now - mouseButtonLastStopTime < POST_STOP_COOLDOWN_MS) return;windowManager.showDictationPanel();+ windowManager.sendPrepareDictation();const pressTime = now;mouseButtonActiveButton = button;mouseButtonDownTime = pressTime;@@ -1469,6 +1477,7 @@ async function startApp() {mouseButtonIsRecording = false;windowManager.sendStopDictation();} else {+ windowManager.sendCancelDictationPreparation();windowManager.hideDictationPanel();}}diff --git a/preload.js b/preload.jsindex cfbdff8d5..4e4125228 100644--- a/preload.js+++ b/preload.js@@ -56,6 +56,12 @@ contextBridge.exposeInMainWorld("electronAPI", {onToggleTranslation: registerListener("toggle-translation", (callback) => () => callback()),onStartDictation: registerListener("start-dictation", (callback) => () => callback()),onStopDictation: registerListener("stop-dictation", (callback) => () => callback()),+ onPrepareDictation: registerListener("prepare-dictation", (callback) => () => callback()),+ onCancelDictationPreparation: registerListener(+ "cancel-dictation-preparation",+ (callback) => () => callback()+ ),+ micWarmHoldChanged: (active) => ipcRenderer.send("mic-warm-hold-changed", active),// Database functionssaveTranscription: (text, rawText, options) =>diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsxindex 7980661be..12b0c90a0 100644--- a/src/components/SettingsPage.tsx+++ b/src/components/SettingsPage.tsx@@ -767,8 +767,10 @@ export default function SettingsPage({preferBuiltInMic,selectedMicDeviceId,selectedMicDeviceLabel,+ micWarmHoldSeconds,setPreferBuiltInMic,setSelectedMicDevice,+ setMicWarmHoldSeconds,setUseLocalWhisper,setUiLanguage,setWhisperModel,@@ -2818,8 +2820,10 @@ export default function SettingsPage({preferBuiltInMic={preferBuiltInMic}selectedMicDeviceId={selectedMicDeviceId}selectedMicDeviceLabel={selectedMicDeviceLabel}+ micWarmHoldSeconds={micWarmHoldSeconds}onPreferBuiltInChange={setPreferBuiltInMic}onDeviceSelect={setSelectedMicDevice}+ onMicWarmHoldSecondsChange={setMicWarmHoldSeconds}/></SettingsPanelRow></SettingsPanel>diff --git a/src/components/ui/MicrophoneSettings.tsx b/src/components/ui/MicrophoneSettings.tsxindex 93b405e3f..465c7370e 100644--- a/src/components/ui/MicrophoneSettings.tsx+++ b/src/components/ui/MicrophoneSettings.tsx@@ -7,6 +7,7 @@ import { Button } from "./button";import { RefreshCw, Mic } from "lucide-react";import { isBuiltInMicrophone } from "../../utils/audioDeviceUtils";import { resolveMicDeviceSelection } from "../../helpers/micDeviceSelection";+import { MIC_WARM_HOLD_CHOICES } from "../../stores/settingsStore";interface AudioDevice {deviceId: string;@@ -18,16 +19,20 @@ interface MicrophoneSettingsProps {preferBuiltInMic: boolean;selectedMicDeviceId: string;selectedMicDeviceLabel: string;+ micWarmHoldSeconds: number;onPreferBuiltInChange: (value: boolean) => void;onDeviceSelect: (deviceId: string, label: string) => void;+ onMicWarmHoldSecondsChange: (seconds: number) => void;}export const MicrophoneSettings: React.FC<MicrophoneSettingsProps> = ({preferBuiltInMic,selectedMicDeviceId,selectedMicDeviceLabel,+ micWarmHoldSeconds,onPreferBuiltInChange,onDeviceSelect,+ onMicWarmHoldSecondsChange,}) => {const { t } = useTranslation();const [devices, setDevices] = useState<AudioDevice[]>([]);@@ -198,6 +203,34 @@ export const MicrophoneSettings: React.FC<MicrophoneSettingsProps> = ({<p className="text-xs text-muted-foreground">{t("microphoneSettings.helpText")}</p></div>)}++ <SettingsRow+ label={t("microphoneSettings.warmHold.label")}+ description={t("microphoneSettings.warmHold.description")}+ >+ <Select+ value={String(micWarmHoldSeconds)}+ onValueChange={(value) => onMicWarmHoldSecondsChange(Number(value))}+ >+ <SelectTrigger className="w-40">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {/* Derived from the store's whitelist so a new option can't silently+ snap to 0 in the setter; its label key is the value itself. */}+ {MIC_WARM_HOLD_CHOICES.map((seconds) => (+ <SelectItem key={seconds} value={String(seconds)}>+ {t(`microphoneSettings.warmHold.options.${seconds}`)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </SettingsRow>+ {micWarmHoldSeconds > 0 && (+ <p className="text-xs text-muted-foreground">+ {t("microphoneSettings.warmHold.privacyNote")}+ </p>+ )}</div>);};diff --git a/src/helpers/audioActivityDetector.js b/src/helpers/audioActivityDetector.jsindex 91704e1a5..1e1f9fa1e 100644--- a/src/helpers/audioActivityDetector.js+++ b/src/helpers/audioActivityDetector.js@@ -31,6 +31,7 @@ class AudioActivityDetector extends EventEmitter {this._eventDriven = false;this._resetTimer = null;this._startGeneration = 0;+ this._micWarmHold = false;}setUserRecording(active) {@@ -43,6 +44,19 @@ class AudioActivityDetector extends EventEmitter {debugLogger.debug("User recording state changed", { active }, "meeting");}+ // Our own idle-hold keeps the device "in use" after a dictation ends, and the+ // macOS/Linux mic signals are device-global — they cannot tell us apart from+ // a meeting app. Mic evidence during the hold is dropped outright (never+ // queued: it is not a meeting). Sustained state resets on both transitions so+ // a half-armed detection from before the hold cannot fire after it.+ setMicWarmHold(active) {+ this._micWarmHold = active;+ this.consecutiveChecks = 0;+ this.audioActiveStart = null;+ this._clearSustainedTimer();+ debugLogger.debug("Mic warm-hold state changed", { active }, "meeting");+ }+async start() {if (this._running) return;this._running = true;@@ -339,6 +353,10 @@ class AudioActivityDetector extends EventEmitter {debugLogger.debug("Mic state changed but user recording, ignoring", { active }, "meeting");return;}+ if (this._micWarmHold) {+ debugLogger.debug("Mic state changed during warm-hold, ignoring", { active }, "meeting");+ return;+ }if (this.lastDismissedAt && Date.now() - this.lastDismissedAt < COOLDOWN_MS) {debugLogger.debug("Mic state changed but in cooldown",@@ -368,7 +386,7 @@ class AudioActivityDetector extends EventEmitter {if (!this._sustainedTimer) {this._sustainedTimer = setTimeout(() => {this._sustainedTimer = null;- if (this._userRecording || this.hasPrompted) return;+ if (this._userRecording || this._micWarmHold || this.hasPrompted) return;if (this.lastDismissedAt && Date.now() - this.lastDismissedAt < COOLDOWN_MS) return;this.hasPrompted = true;@@ -402,6 +420,7 @@ class AudioActivityDetector extends EventEmitter {if (this._checking) return;if (this.lastDismissedAt && Date.now() - this.lastDismissedAt < COOLDOWN_MS) return;if (this._userRecording) return;+ if (this._micWarmHold) return;this._checking = true;try {diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.jsindex eb8d321a9..de95efde4 100644--- a/src/helpers/audioManager.js+++ b/src/helpers/audioManager.js@@ -21,12 +21,21 @@ import {recordLocalSpeechWindow,} from "./localSpeechGate";import { reacquireIfDead } from "./micTrackHealth";+import { isMicWarm, WARMUP_ACQUIRE_TIMEOUT_MS } from "./micWarmState";+import {+ PreparedMicCapture,+ disposePreparedCapture,+ discardPreRoll,+ PRE_ROLL_MAX_AGE_MS,+} from "./preparedMicCapture";+import { MicStreamHold } from "./micStreamHold";import { ActiveMicRecoveryController } from "./activeMicRecovery";import { followsSystemDefaultMic, reconcileSavedMicSelection } from "./micSelectionRecovery";import { isStaleDeviceError } from "./staleMicDevice";import { shouldSaveDiscardedRecording } from "./discardedRecording";import {getSettings,+ useSettingsStore,getEffectiveCleanupModel,isCloudCleanupMode,isCloudDictationAgentMode,@@ -83,6 +92,8 @@ const RECORDING_TIMESLICE_MS = 250; // flush chunks periodically so short recordconst PREVIEW_FLUSH_WATCHDOG_MS = 1000;const REALTIME_MODELS = new Set(["gpt-4o-mini-transcribe", "gpt-4o-transcribe"]);+const micDeviceKey = (settings) => `${settings.preferBuiltInMic}|${settings.selectedMicDeviceId}`;+function getEffectiveRetentionPreferences() {const settings = getSettings();const policyState = usePolicyStore.getState();@@ -300,6 +311,40 @@ class AudioManager {this.micCaptureStatus = "inactive";this.cachedApiKey = null;this.cachedApiKeyProvider = null;+ this._micWarmedAt = 0;+ this._startInProgress = false;+ this._micOpenReported = false;+ this.preparedMicCapture = new PreparedMicCapture({+ dispose: (prepared) => this._disposePrepared(prepared),+ onActiveChange: () => this._syncMicOpenGate(),+ });+ const micSettings = getSettings();+ this._micHoldSeconds = Number(micSettings.micWarmHoldSeconds) || 0;+ this._micDeviceKey = micDeviceKey(micSettings);+ this.micStreamHold = new MicStreamHold({+ holdSeconds: this._micHoldSeconds,+ onHoldChange: () => this._syncMicOpenGate(),+ isBusy: () =>+ this.isRecording ||+ this.isStreaming ||+ this.mediaRecorder?.state === "recording" ||+ this.preparedMicCapture.active,+ });++ // Every window owns an AudioManager (dictation and the agent overlay), so+ // the hold has to follow the setting here rather than in one window's hook.+ this._unsubscribeSettings = useSettingsStore.subscribe((state) => {+ const holdSeconds = Number(state.micWarmHoldSeconds) || 0;+ if (holdSeconds !== this._micHoldSeconds) {+ this._micHoldSeconds = holdSeconds;+ this.micStreamHold.setHoldSeconds(holdSeconds);+ }+ const deviceKey = micDeviceKey(state);+ if (deviceKey !== this._micDeviceKey) {+ this._micDeviceKey = deviceKey;+ this.micStreamHold.drop();+ }+ });this._onApiKeyChanged = () => {this.cachedApiKey = null;@@ -312,8 +357,10 @@ class AudioManager {this._onDeviceChange = () => {this.cachedMicDeviceId = null;this.validatedSelectedMicDeviceId = null;- this.micDriverWarmedUp = false;+ this._micWarmedAt = 0;this.rejectedMicDeviceId = null;+ this.cancelPreparedMicCapture();+ this.micStreamHold.drop();};navigator.mediaDevices?.addEventListener?.("devicechange", this._onDeviceChange);this.cachedTranscriptionEndpoint = null;@@ -772,20 +819,151 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);}}- // Briefly acquire and release the mic so the OS audio driver is warm before- // the first real recording, reducing cold-start empty captures. See #871.- async warmupMicDriver() {- if (this.micDriverWarmedUp) return;- // Skip while a recording is active so we don't double-acquire the mic. See #871.- if (this.isRecording || this.isProcessing || this.mediaRecorder?.state === "recording") return;+ // Open the mic the moment a dictation is likely (push-to-talk key-down,+ // toggle press) and hand the same stream — plus everything its pre-roll+ // recorder already captured — to the real recording. Replaces the one-shot+ // warmupMicDriver (#845): a raced warm-up never resolved before the+ // recording's own open, so it only ever added a concurrent double open.+ async prepareMicCapture() {+ // Preparing opens the device, so it answers to the same policy as the+ // recording it anticipates — otherwise a blocked user's key-down would+ // still light the mic and buffer pre-roll.+ if (!this.isRecordingAllowedByPolicy()) return null;+ // A start already awaiting the mic open leaves isRecording false for as long+ // as that open takes, so without this guard a second prepare would open the+ // device again and buffer a pre-roll no recording ever answers.+ if (+ this._startInProgress ||+ this.isRecording ||+ this.isProcessing ||+ this.mediaRecorder?.state === "recording"+ ) {+ return null;+ }+ try {+ const prepared = await this.preparedMicCapture.prepare(async () => {+ const constraints = await this.getAudioConstraints();+ const stream = await this._acquireCaptureStream(constraints);+ const value = { stream, constraints, recorder: null, chunks: [], startedAt: Date.now() };+ if (!this.shouldUseStreaming()) this._startPreRollRecorder(value);+ return value;+ });+ if (prepared) {+ logger.debug("Microphone capture prepared", { preRoll: !!prepared.recorder }, "audio");+ }+ return prepared;+ } catch (e) {+ logger.debug("Mic capture preparation failed (non-critical)", { error: e.message }, "audio");+ return null;+ }+ }++ cancelPreparedMicCapture() {+ this.preparedMicCapture.cancel();+ }++ // Tells the main process whether this renderer is holding the mic open outside+ // a recording — an idle hold or a prepared capture. Recordings are gated by+ // setUserRecording instead. Without this the device-global macOS/Linux mic+ // signal reports our own capture as a meeting.+ _syncMicOpenGate() {+ const open = this.micStreamHold.active || this.preparedMicCapture.active;+ if (open === this._micOpenReported) return;+ this._micOpenReported = open;+ window.electronAPI?.micWarmHoldChanged?.(open);+ }++ _disposePrepared(prepared) {+ if (!prepared) return;+ disposePreparedCapture(prepared);+ this._markCaptureStreamReleased();+ }++ // Record from the instant the prepared stream delivers frames. If the hold+ // guard confirms a real dictation these chunks become the recording's opening;+ // a cancel discards them without the audio ever leaving the renderer.+ _startPreRollRecorder(prepared) {+ try {+ const recorder = new MediaRecorder(prepared.stream);+ recorder.ondataavailable = (event) => {+ if (event.data && event.data.size > 0) prepared.chunks.push(event.data);+ };+ recorder.start(RECORDING_TIMESLICE_MS);+ prepared.recorder = recorder;+ } catch (e) {+ logger.debug("Pre-roll recorder unavailable", { error: e.message }, "audio");+ }+ }++ _constraintsKey(constraints) {+ return JSON.stringify(constraints?.audio ?? constraints ?? {});+ }++ _stampMicWarm() {+ this._micWarmedAt = Date.now();+ }++ // Every capture-stream release funnels through here: the driver was+ // demonstrably open, so stamp warmth (a free warm window for the next open,+ // replacing #1284's post-transcription re-warm and its extra device open)+ // and restart the idle-hold countdown.+ _markCaptureStreamReleased() {+ this._stampMicWarm();+ this.micStreamHold.touch();+ }++ async _acquireCaptureStream(constraints) {+ const key = this._constraintsKey(constraints);+ const held = this.micStreamHold.acquireClone(key);+ if (held) {+ this._stampMicWarm();+ return held;+ }+ const stream = await this.acquireHealthyMicStream(+ await navigator.mediaDevices.getUserMedia(constraints),+ constraints+ );+ this._stampMicWarm();+ return this.micStreamHold.adoptAndClone(stream, key);+ }++ // TTL-gated warm-up used only by the streaming-connection warm-up. The+ // recording paths never warm-then-discard — they open once via+ // prepareMicCapture and keep the stream. A stream resolving past the deadline+ // still stamps warmth: the driver did come up, which is exactly what the+ // slowest machines need recorded (#845).+ async _warmMicDriverIfCold(logCategory) {+ // A held master already has the driver up; opening a second device to prove+ // it is the concurrent double open this replaced.+ if (this.micStreamHold.active) {+ this._stampMicWarm();+ return;+ }+ if (isMicWarm(this._micWarmedAt, Date.now())) return;try {const constraints = await this.getAudioConstraints();- const tempStream = await navigator.mediaDevices.getUserMedia(constraints);- tempStream.getTracks().forEach((track) => track.stop());- this.micDriverWarmedUp = true;- logger.debug("Microphone driver pre-warmed", {}, "audio");+ const streamPromise = navigator.mediaDevices.getUserMedia(constraints);+ streamPromise+ .then((stream) => {+ stream.getTracks().forEach((track) => track.stop());+ this._stampMicWarm();+ })+ .catch(() => {});+ let timer = null;+ const deadline = new Promise((_, reject) => {+ timer = setTimeout(+ () => reject(new Error("mic warmup timed out")),+ WARMUP_ACQUIRE_TIMEOUT_MS+ );+ });+ try {+ await Promise.race([streamPromise, deadline]);+ } finally {+ if (timer !== null) clearTimeout(timer);+ }+ logger.debug("Microphone driver pre-warmed", {}, logCategory);} catch (e) {- logger.debug("Mic driver warmup failed (non-critical)", { error: e.message }, "audio");+ logger.debug("Mic driver warmup failed (non-critical)", { error: e.message }, logCategory);}}@@ -828,6 +1006,9 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);}async startRecording(forceDefaultMic = false) {+ let prepared = null;+ let preparedAdopted = false;+ this._startInProgress = true;try {if (!this.isRecordingAllowedByPolicy()) {logger.warn("Recording blocked by workspace policy", { context: this.context }, "audio");@@ -837,11 +1018,12 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);return false;}- const constraints = await this.getAudioConstraints(forceDefaultMic);- const micStream = await this.acquireHealthyMicStream(- await navigator.mediaDevices.getUserMedia(constraints),- constraints- );+ const startRequestedAt = performance.now();+ prepared = forceDefaultMic ? null : await this.preparedMicCapture.take();+ const constraints =+ prepared?.constraints ?? (await this.getAudioConstraints(forceDefaultMic));+ const micStream = prepared?.stream ?? (await this._acquireCaptureStream(constraints));+ const micReadyAt = performance.now();const audioTrack = micStream.getAudioTracks()[0];@@ -898,14 +1080,36 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);this._stopRequestedDuringMicRecovery = false;this._cancelRequestedDuringMicRecovery = false;this._receivedAudioData = false;- this.recordingStartTime = Date.now();- this.createBatchRecorder(micStream);+ if (prepared && Date.now() - prepared.startedAt > PRE_ROLL_MAX_AGE_MS) {+ discardPreRoll(prepared);+ }+ const preRoll =+ prepared?.recorder && prepared.recorder.state === "recording"+ ? { recorder: prepared.recorder, chunks: prepared.chunks }+ : null;+ // Pre-roll audio is part of the recording, so the reported duration+ // starts when the prepared stream started — but only when its recorder+ // was adopted; a prepared stream without pre-roll contributes no audio+ // before this point, and back-dating would inflate durationSeconds.+ this.recordingStartTime = preRoll ? prepared.startedAt : Date.now();+ this.createBatchRecorder(micStream, preRoll);+ preparedAdopted = true;this.isRecording = true;this.onStateChange?.({isRecording: true,isProcessing: false,micCaptureStatus: "active",});+ logger.info(+ "Recording start timing",+ {+ micReadyMs: Math.round(micReadyAt - startRequestedAt),+ totalMs: Math.round(performance.now() - startRequestedAt),+ usedPreparedCapture: !!prepared,+ preparedAgeMs: prepared?.startedAt ? Date.now() - prepared.startedAt : 0,+ },+ "audio"+ );const {showTranscriptionPreview,@@ -956,6 +1160,9 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);return true;} catch (error) {+ // A prepared value the recording never adopted still owns a live stream+ // (and possibly a pre-roll recorder); release it before any retry.+ if (prepared && !preparedAdopted) this._disposePrepared(prepared);if (isStaleDeviceError(error) && !forceDefaultMic) {// Pinned mic is gone (Chromium rotates IDs / device unplugged). Retry once on the default mic. See #900.logger.warn("Pinned microphone unavailable, retrying on default mic", {}, "audio");@@ -988,12 +1195,24 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);description: errorDescription,});return false;+ } finally {+ this._startInProgress = false;}}- createBatchRecorder(micStream) {- const recorder = new MediaRecorder(micStream);- const segmentChunks = [];+ createBatchRecorder(micStream, adoption = null) {+ // Adopting the pre-roll recorder keeps every chunk captured since key-down:+ // rebinding the handlers below transfers ownership with no gap and no+ // re-encode, and the seeded chunks become the recording's opening.+ const recorder = adoption?.recorder ?? new MediaRecorder(micStream);+ const segmentChunks = adoption ? [...adoption.chunks] : [];+ if (segmentChunks.length > 0) {+ this._receivedAudioData = true;+ // The speech-gate analyser only attaches at recording start, so it never+ // measured these frames. Fail the gate open rather than let it discard a+ // short utterance spoken entirely in pre-roll (#845).+ this._localSpeechGateState = null;+ }this.mediaRecorder = recorder;this.audioChunks = segmentChunks;this.recordingMimeType = recorder.mimeType || "audio/webm";@@ -1015,6 +1234,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);if (rotating || this.micRecovery.started) {if (segment.size > 0) this._batchSegments.push(segment);micStream.getTracks().forEach((track) => track.stop());+ this._markCaptureStreamReleased();if (rotating) {this._rotatingBatchRecorder = null;this._rotationResolve?.();@@ -1026,10 +1246,11 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);}micStream.getTracks().forEach((track) => track.stop());+ this._markCaptureStreamReleased();await this.finalizeBatchRecording(segment);};- recorder.start(RECORDING_TIMESLICE_MS);+ if (!adoption) recorder.start(RECORDING_TIMESLICE_MS);return recorder;}@@ -1199,6 +1420,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);if (recorder.stream) {recorder.stream.getTracks().forEach((track) => track.stop());+ this._markCaptureStreamReleased();}return true;@@ -3509,24 +3731,10 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor););}- // Warm up the OS audio driver by briefly acquiring the mic, then releasing.- // This forces macOS to initialize the audio subsystem so subsequent- // getUserMedia calls resolve in ~100-200ms instead of ~500-1000ms.- if (!this.micDriverWarmedUp) {- try {- const constraints = await this.getAudioConstraints();- const tempStream = await navigator.mediaDevices.getUserMedia(constraints);- tempStream.getTracks().forEach((track) => track.stop());- this.micDriverWarmedUp = true;- logger.debug("Microphone driver pre-warmed", {}, "streaming");- } catch (e) {- logger.debug(- "Mic driver warmup failed (non-critical)",- { error: e.message },- "streaming"- );- }- }+ // Warm up the OS audio driver by briefly acquiring the mic, then+ // releasing. TTL-gated: drivers go cold again after idle, so this must+ // re-fire once the warm window lapses (#845).+ await this._warmMicDriverIfCold("streaming");logger.info("Streaming connection warmed up",@@ -3627,6 +3835,9 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);}async startStreamingRecording(forceDefaultMic = false) {+ let acquiredStream = null;+ let usedPreparedCapture = false;+ this._startInProgress = true;try {if (!this.isRecordingAllowedByPolicy()) {logger.warn(@@ -3649,15 +3860,21 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);this.stopRequestedDuringStreamingStart = false;const t0 = performance.now();- const constraints = await this.getAudioConstraints(forceDefaultMic);+ const prepared = forceDefaultMic ? null : await this.preparedMicCapture.take();+ // Prepared while batch mode was expected; keep the stream, drop the pre-roll+ // (the streaming transcript comes from the PCM worklet, not these chunks).+ discardPreRoll(prepared);+ usedPreparedCapture = !!prepared;+ const constraints =+ prepared?.constraints ?? (await this.getAudioConstraints(forceDefaultMic));const tConstraints = performance.now();- // 1. Get mic stream (can take 10-15s on cold macOS mic driver)- const rawStream = await navigator.mediaDevices.getUserMedia(constraints);+ // 1. Get mic stream (can take 10-15s on a cold driver — unless a prepared+ // capture or a held master stream already opened the device).+ const stream = prepared?.stream ?? (await this._acquireCaptureStream(constraints));+ acquiredStream = stream;const tMedia = performance.now();- const stream = await this.acquireHealthyMicStream(rawStream, constraints);-const audioTrack = stream.getAudioTracks()[0];if (audioTrack) {@@ -3830,7 +4047,8 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);wsConnectMs: Math.round(tWs - tPipeline),totalMs: Math.round(tWs - t0),usedWarmConnection: result.usedWarmConnection,- micDriverWarmedUp: !!this.micDriverWarmedUp,+ usedPreparedCapture,+ micWarm: isMicWarm(this._micWarmedAt, Date.now()),},"streaming");@@ -3847,6 +4065,13 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);this.streamingStartInProgress = false;this.stopRequestedDuringStreamingStart = false;+ // A stream the pipeline never took ownership of would leak the device+ // (and, when prepared, keep the mic indicator lit) — release it here.+ if (acquiredStream && this.streamingStream !== acquiredStream) {+ acquiredStream.getTracks().forEach((track) => track.stop());+ this._markCaptureStreamReleased();+ }+if (isStaleDeviceError(error) && !forceDefaultMic && !stopRequested) {// Pinned mic is gone (Chromium rotates IDs / device unplugged). Retry once on the default mic. See #900.logger.warn(@@ -3896,6 +4121,8 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);this.recordingStartTime = null;this.onStateChange?.({ isRecording: false, isProcessing: false, isStreaming: false });return false;+ } finally {+ this._startInProgress = false;}}@@ -3968,6 +4195,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);if (this.streamingStream) {this.streamingStream.getTracks().forEach((track) => track.stop());this.streamingStream = null;+ this._markCaptureStreamReleased();}const tAudioCleanup = performance.now();@@ -4373,6 +4601,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);if (this.streamingStream) {this.streamingStream.getTracks().forEach((track) => track.stop());this.streamingStream = null;+ this._markCaptureStreamReleased();}this.isStreaming = false;@@ -4402,6 +4631,9 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);cleanup() {this.micRecovery.stop();+ this._unsubscribeSettings?.();+ this.preparedMicCapture.cancel();+ this.micStreamHold.drop();this.lastAudioBlob = null;this.lastAudioMetadata = null;if (this.isStreaming) {diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex d44809de6..05f2b9b51 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -509,6 +509,8 @@ class IPCHandlers {// requestId -> AbortController for in-flight audio-upload transcriptions,// so a cancel can abort the exact job.this._uploadTranscriptionControllers = new Map();+ // webContents id -> its release listener, for renderers holding the mic open.+ this._micHoldSenders = new Map();this.assemblyAiStreaming = null;this.deepgramStreaming = null;this.cortiStreaming = null;@@ -559,6 +561,15 @@ class IPCHandlers {}}+ _releaseMicHold(sender) {+ const release = this._micHoldSenders.get(sender.id);+ if (!release) return;+ this._micHoldSenders.delete(sender.id);+ sender.off("destroyed", release);+ sender.off("did-finish-load", release);+ this.meetingDetectionEngine?.setMicWarmHold(this._micHoldSenders.size > 0);+ }+_getWhisperVadSettings() {const current = this.whisperVadSettings || {};return {@@ -1205,6 +1216,23 @@ class IPCHandlers {return this.databaseManager.getTranscriptionById(id);});+ // Every window's AudioManager can hold the mic open outside a recording, so+ // gate the audio-evidence meeting detector until they all release. A+ // renderer that reloads or goes away releases implicitly — otherwise a+ // crash mid-hold would gate detection for the rest of the session.+ ipcMain.on("mic-warm-hold-changed", (event, active) => {+ if (!active) {+ this._releaseMicHold(event.sender);+ return;+ }+ if (this._micHoldSenders.has(event.sender.id)) return;+ const release = () => this._releaseMicHold(event.sender);+ this._micHoldSenders.set(event.sender.id, release);+ event.sender.on("destroyed", release);+ event.sender.on("did-finish-load", release);+ this.meetingDetectionEngine?.setMicWarmHold(true);+ });+// Dictionary handlersipcMain.on("auto-learn-changed", (_event, enabled) => {// Both renderer windows re-sync this on mount — ignore same-value updates (#1080).diff --git a/src/helpers/meetingDetectionEngine.js b/src/helpers/meetingDetectionEngine.jsindex 829d30c71..0d3406ba7 100644--- a/src/helpers/meetingDetectionEngine.js+++ b/src/helpers/meetingDetectionEngine.js@@ -411,6 +411,13 @@ class MeetingDetectionEngine {}}+ // Forward-only: unlike setUserRecording there is no cooldown or queue flush —+ // that machinery exists for real recordings, while a warm-hold merely means+ // our own renderer still has the device open.+ setMicWarmHold(active) {+ this.audioActivityDetector.setMicWarmHold(active);+ }+setPreferences(prefs) {debugLogger.info("Updating detection preferences", prefs, "meeting");Object.assign(this.preferences, prefs);diff --git a/src/helpers/micStreamHold.js b/src/helpers/micStreamHold.jsnew file mode 100644index 000000000..7dec11554--- /dev/null+++ b/src/helpers/micStreamHold.js@@ -0,0 +1,104 @@+// Opt-in idle-hold: keep one "master" mic stream open after a dictation so the+// next one re-acquires in ~0.1ms (track.clone) instead of paying a cold driver+// open. Recordings only ever own clones, so every existing teardown path keeps+// stopping the stream it was given, and releasing the master never interrupts a+// live recording (clones are independent of their source track).+export class MicStreamHold {+ constructor({+ holdSeconds = 0,+ setTimer = (fn, ms) => setTimeout(fn, ms),+ clearTimer = (id) => clearTimeout(id),+ onHoldChange = null,+ makeStream = (track) => new MediaStream([track]),+ isBusy = () => false,+ } = {}) {+ this.holdSeconds = holdSeconds > 0 ? holdSeconds : 0;+ this.setTimer = setTimer;+ this.clearTimer = clearTimer;+ this.onHoldChange = onHoldChange;+ this.makeStream = makeStream;+ this.isBusy = isBusy;+ this.master = null;+ this.masterKey = null;+ this.releaseTimer = null;+ }++ get active() {+ return this.master !== null;+ }++ setHoldSeconds(seconds) {+ this.holdSeconds = seconds > 0 ? seconds : 0;+ if (this.holdSeconds === 0) this.drop();+ else if (this.master) this.touch();+ }++ // Returns a clone of the held master, or null when the caller must open the+ // device itself (hold disabled, no master, device changed, or master died).+ acquireClone(constraintsKey) {+ if (this.holdSeconds === 0 || !this.master) return null;+ const track = this._masterTrack();+ if (this.masterKey !== constraintsKey || !this._isLive(track)) {+ this.drop();+ return null;+ }+ this.touch();+ return this.makeStream(track.clone());+ }++ // Keeps a freshly opened stream as the master and returns a clone for the+ // recording — one getUserMedia serves both roles. Pass-through when disabled.+ adoptAndClone(stream, constraintsKey) {+ if (this.holdSeconds === 0) return stream;+ const wasActive = this.active;+ // Replacing a master is a swap, not a release+acquire: stop the old tracks+ // silently so observers see one continuous hold, not a false→true blip.+ this._clearReleaseTimer();+ this.master?.getAudioTracks().forEach((track) => track.stop());+ this.master = stream;+ this.masterKey = constraintsKey;+ if (!wasActive) this.onHoldChange?.(true);+ this.touch();+ return this.makeStream(this._masterTrack().clone());+ }++ touch() {+ this._clearReleaseTimer();+ if (this.holdSeconds > 0 && this.master) {+ this.releaseTimer = this.setTimer(() => {+ this.releaseTimer = null;+ // A recording longer than the hold window must not lose its master —+ // the countdown belongs after the dictation ends, so defer instead.+ if (this.isBusy()) {+ this.touch();+ return;+ }+ this.drop();+ }, this.holdSeconds * 1000);+ }+ }++ drop() {+ this._clearReleaseTimer();+ if (!this.master) return;+ this.master.getAudioTracks().forEach((track) => track.stop());+ this.master = null;+ this.masterKey = null;+ this.onHoldChange?.(false);+ }++ _masterTrack() {+ return this.master?.getAudioTracks()[0] ?? null;+ }++ _isLive(track) {+ return !!track && track.readyState === "live" && !track.muted;+ }++ _clearReleaseTimer() {+ if (this.releaseTimer !== null) {+ this.clearTimer(this.releaseTimer);+ this.releaseTimer = null;+ }+ }+}diff --git a/src/helpers/micWarmState.js b/src/helpers/micWarmState.jsnew file mode 100644index 000000000..c1a36fea6--- /dev/null+++ b/src/helpers/micWarmState.js@@ -0,0 +1,16 @@+// Warm state is a timestamp, not a latch: mic drivers go cold again after idle,+// so a permanent "warmed" flag would never re-warm a driver that has since slept.+export const MIC_WARM_TTL_MS = 5000;++// Deadline for a warm-up acquisition, deliberately independent of the TTL: the+// cold-open worst case documented in audioManager is 10-15s, and a machine that+// slow is exactly the one whose eventual success must still be recorded as warm.+export const WARMUP_ACQUIRE_TIMEOUT_MS = 15000;++// True only when the mic was warmed within the TTL. A negative elapsed (clock+// jumped backwards) returns false so we err on the side of re-warming.+export const isMicWarm = (lastWarmedAt, now, ttlMs = MIC_WARM_TTL_MS) => {+ if (typeof lastWarmedAt !== "number" || lastWarmedAt <= 0) return false;+ const elapsed = now - lastWarmedAt;+ return elapsed >= 0 && elapsed < ttlMs;+};diff --git a/src/helpers/preparedMicCapture.js b/src/helpers/preparedMicCapture.jsnew file mode 100644index 000000000..163498549--- /dev/null+++ b/src/helpers/preparedMicCapture.js@@ -0,0 +1,135 @@+// A prepared value not taken within this window is disposed: prepare fires on+// main-process guesses (toggle key-down) that the renderer may decline, and a+// forgotten prepared stream would otherwise hold the mic open indefinitely.+export const PREPARED_MAX_AGE_MS = 10000;++// Pre-roll older than a normal key-down-to-start gap was buffered by a prepare+// the recording never answered, so it holds audio from before the user meant to+// dictate. The stream is still reusable; only the buffered chunks are not.+export const PRE_ROLL_MAX_AGE_MS = 2000;++export const discardPreRoll = (prepared) => {+ const recorder = prepared?.recorder;+ if (recorder) {+ try {+ // Detach before stop: the recorder's final dataavailable fires async and+ // would otherwise repopulate the chunks array after it is cleared.+ recorder.ondataavailable = null;+ if (recorder.state !== "inactive") recorder.stop();+ } catch {+ // Recorder already torn down by the browser.+ }+ prepared.recorder = null;+ }+ if (prepared?.chunks) prepared.chunks.length = 0;+};++export const disposePreparedCapture = (prepared) => {+ if (!prepared) return;+ discardPreRoll(prepared);+ prepared.stream?.getTracks?.().forEach((track) => track.stop());+};++export class PreparedMicCapture {+ constructor({+ dispose = disposePreparedCapture,+ maxAgeMs = PREPARED_MAX_AGE_MS,+ setTimer = (fn, ms) => setTimeout(fn, ms),+ clearTimer = (id) => clearTimeout(id),+ onActiveChange = null,+ } = {}) {+ this.dispose = dispose;+ this.maxAgeMs = maxAgeMs;+ this.setTimer = setTimer;+ this.clearTimer = clearTimer;+ this.onActiveChange = onActiveChange;+ this.generation = 0;+ this.prepared = null;+ this.pending = null;+ this.inFlight = 0;+ this.expiryTimer = null;+ this._reportedActive = false;+ }++ // The window in which the device is open (or opening) for this capture. A+ // cancel clears `pending` so the next prepare can start, but the acquisition+ // it abandoned still owns the mic until it settles — hence the in-flight+ // count rather than a `pending` check.+ get active() {+ return this.prepared !== null || this.inFlight > 0;+ }++ prepare(acquire) {+ if (this.prepared) return Promise.resolve(this.prepared);+ if (this.pending) return this.pending;++ const generation = this.generation;+ this.inFlight += 1;+ const pending = Promise.resolve()+ .then(acquire)+ .then((prepared) => {+ if (generation !== this.generation) {+ this.dispose(prepared);+ return null;+ }+ this.prepared = prepared;+ this._armExpiry();+ return prepared;+ })+ .finally(() => {+ this.inFlight -= 1;+ if (this.pending === pending) this.pending = null;+ this._notifyActive();+ });++ this.pending = pending;+ this._notifyActive();+ return pending;+ }++ async take() {+ if (this.pending) {+ try {+ await this.pending;+ } catch {+ // The caller can fall back to a normal acquisition.+ }+ }+ const prepared = this.prepared;+ this.prepared = null;+ this.generation += 1;+ this._clearExpiry();+ this._notifyActive();+ return prepared;+ }++ cancel() {+ this.generation += 1;+ this._clearExpiry();+ this.dispose(this.prepared);+ this.prepared = null;+ this.pending = null;+ this._notifyActive();+ }++ _notifyActive() {+ if (this.active === this._reportedActive) return;+ this._reportedActive = this.active;+ this.onActiveChange?.(this._reportedActive);+ }++ _armExpiry() {+ this._clearExpiry();+ this.expiryTimer = this.setTimer(() => {+ this.expiryTimer = null;+ this.cancel();+ }, this.maxAgeMs);+ }++ _clearExpiry() {+ if (this.expiryTimer !== null) {+ this.clearTimer(this.expiryTimer);+ this.expiryTimer = null;+ }+ }+}diff --git a/src/helpers/windowManager.js b/src/helpers/windowManager.jsindex cc8897edf..549030244 100644--- a/src/helpers/windowManager.js+++ b/src/helpers/windowManager.js@@ -278,6 +278,7 @@ class WindowManager {if (this.textEditMonitor) this.textEditMonitor.captureTargetPid();this.showDictationPanel();+ this.sendPrepareDictation();const safetyTimeoutId = setTimeout(() => {if (this.macCompoundPushState?.active) {@@ -325,6 +326,7 @@ class WindowManager {if (wasRecording) {this.sendStopDictation();} else {+ this.sendCancelDictationPreparation();this.hideDictationPanel();}}@@ -343,6 +345,8 @@ class WindowManager {if (wasRecording) {this.sendStopDictation();+ } else {+ this.sendCancelDictationPreparation();}this.hideDictationPanel();@@ -402,6 +406,7 @@ class WindowManager {const downTime = Date.now();this.showDictationPanel();+ this.sendPrepareDictation();this.winPushState = {active: true,@@ -438,6 +443,7 @@ class WindowManager {if (wasRecording) {this.sendStopDictation();} else {+ this.sendCancelDictationPreparation();this.hideDictationPanel();}}@@ -466,6 +472,10 @@ class WindowManager {if (this.textEditMonitor) this.textEditMonitor.captureTargetPid();void this.selectionManager?.captureTarget?.();this.showDictationPanel();+ // About-to-start guess: open the mic one IPC message ahead of the toggle.+ // A wrong guess (renderer declines) is bounded by the prepared capture's+ // max-age expiry, and the renderer dedups its own prepare call.+ if (!this._isDictatingToggle) this.sendPrepareDictation();this.mainWindow.webContents.send(channel);this._isDictatingToggle = !this._isDictatingToggle;this.meetingDetectionEngine?.setUserRecording(this._isDictatingToggle);@@ -511,11 +521,27 @@ class WindowManager {}}+ sendPrepareDictation() {+ if (this.hotkeyManager.isInListeningMode()) {+ return;+ }+ if (this.mainWindow && !this.mainWindow.isDestroyed()) {+ this.mainWindow.webContents.send("prepare-dictation");+ }+ }++ sendCancelDictationPreparation() {+ if (this.mainWindow && !this.mainWindow.isDestroyed()) {+ this.mainWindow.webContents.send("cancel-dictation-preparation");+ }+ }+sendCancelDictation() {if (this.hotkeyManager.isInListeningMode()) {return;}if (this.mainWindow && !this.mainWindow.isDestroyed()) {+ this.mainWindow.webContents.send("cancel-dictation-preparation");this.mainWindow.webContents.send("cancel-hotkey-pressed");this._isDictatingToggle = false;this.meetingDetectionEngine?.setUserRecording(false);diff --git a/src/hooks/useAudioRecording.js b/src/hooks/useAudioRecording.jsindex 5449562e7..72145f04c 100644--- a/src/hooks/useAudioRecording.js+++ b/src/hooks/useAudioRecording.js@@ -29,6 +29,7 @@ export const useAudioRecording = (toast, options = {}) => {const [partialTranscript, setPartialTranscript] = useState("");const audioManagerRef = useRef(null);const startLockRef = useRef(false);+ const stopRequestedDuringStartRef = useRef(false);const stopLockRef = useRef(false);const wasRecordingRef = useRef(false);const wasMicUnavailableRef = useRef(false);@@ -38,6 +39,7 @@ export const useAudioRecording = (toast, options = {}) => {async ({ voiceAgentRequested = false, translationRequested = false } = {}) => {if (startLockRef.current) return false;startLockRef.current = true;+ stopRequestedDuringStartRef.current = false;try {if (!audioManagerRef.current) return false;const policyState = usePolicyStore.getState();@@ -77,6 +79,22 @@ export const useAudioRecording = (toast, options = {}) => {? await audioManagerRef.current.startStreamingRecording(): await audioManagerRef.current.startRecording();+ // A stop that landed while the start was still awaiting the mic open was+ // dropped (isRecording was still false), leaving a runaway recording+ // until the next hotkey press. Honor it now that we started.+ if (didStart && stopRequestedDuringStartRef.current) {+ window.electronAPI?.unregisterCancelHotkey?.();+ // Cue semantics mirror performStopRecording: unconditional for+ // streaming, gated on the stop landing for batch.+ if (audioManagerRef.current.getState().isStreaming) {+ void playStopCue();+ await audioManagerRef.current.stopStreamingRecording();+ } else if (audioManagerRef.current.stopRecording()) {+ void playStopCue();+ }+ return didStart;+ }+// A quick tap can end the recording inside the start call itself (deferred// streaming stop) — don't pause media for a recording that already ended. See #1060.if (didStart && audioManagerRef.current.getState().isRecording) {@@ -90,12 +108,17 @@ export const useAudioRecording = (toast, options = {}) => {return didStart;} finally {startLockRef.current = false;+ stopRequestedDuringStartRef.current = false;}},[t, toast]);const performStopRecording = useCallback(async () => {+ if (startLockRef.current) {+ stopRequestedDuringStartRef.current = true;+ return true;+ }if (stopLockRef.current) return false;stopLockRef.current = true;try {@@ -325,19 +348,22 @@ export const useAudioRecording = (toast, options = {}) => {translationRequested = false,} = {}) => {if (!audioManagerRef.current) return;- // Lazily warm the mic driver on first dictation use, not at launch. See #871.- audioManagerRef.current.warmupMicDriver?.();const currentState = audioManagerRef.current.getState();- if (!currentState.isRecording && !currentState.isProcessing) {- await performStartRecording({ voiceAgentRequested, translationRequested });- } else if (currentState.isRecording) {+ // A start still awaiting the mic open leaves isRecording false, so without+ // the lock check this toggle-off would take the start branch and be lost.+ if (startLockRef.current || currentState.isRecording) {await performStopRecording();+ } else if (!currentState.isProcessing) {+ // Fire-and-forget: startRecording's take() joins this same acquisition,+ // so the device is opened exactly once. See #845.+ audioManagerRef.current.prepareMicCapture?.();+ await performStartRecording({ voiceAgentRequested, translationRequested });}};const handleStart = async () => {- audioManagerRef.current?.warmupMicDriver?.();+ audioManagerRef.current?.prepareMicCapture?.();await performStartRecording();};@@ -365,6 +391,14 @@ export const useAudioRecording = (toast, options = {}) => {onToggle?.();});+ const disposePrepare = window.electronAPI.onPrepareDictation?.(() => {+ audioManagerRef.current?.prepareMicCapture?.();+ });++ const disposeCancelPreparation = window.electronAPI.onCancelDictationPreparation?.(() => {+ audioManagerRef.current?.cancelPreparedMicCapture?.();+ });+const disposeStop = window.electronAPI.onStopDictation?.(() => {handleStop();onToggle?.();@@ -389,6 +423,8 @@ export const useAudioRecording = (toast, options = {}) => {disposeVoiceAgentToggle?.();disposeTranslationToggle?.();disposeStart?.();+ disposePrepare?.();+ disposeCancelPreparation?.();disposeStop?.();disposeNoAudio?.();if (audioManagerRef.current) {diff --git a/src/hooks/useSettings.ts b/src/hooks/useSettings.tsindex e5d0d24ef..755095b63 100644--- a/src/hooks/useSettings.ts+++ b/src/hooks/useSettings.ts@@ -70,6 +70,7 @@ export interface MicrophoneSettings {preferBuiltInMic: boolean;selectedMicDeviceId: string;selectedMicDeviceLabel: string;+ micWarmHoldSeconds: number;}export interface ApiKeySettings {@@ -356,8 +357,10 @@ function useSettingsInternal() {preferBuiltInMic: store.preferBuiltInMic,selectedMicDeviceId: store.selectedMicDeviceId,selectedMicDeviceLabel: store.selectedMicDeviceLabel,+ micWarmHoldSeconds: store.micWarmHoldSeconds,setPreferBuiltInMic: store.setPreferBuiltInMic,setSelectedMicDevice: store.setSelectedMicDevice,+ setMicWarmHoldSeconds: store.setMicWarmHoldSeconds,autoLearnCorrections,setAutoLearnCorrections,showTranscriptionPreview: store.showTranscriptionPreview,diff --git a/src/locales/de/translation.json b/src/locales/de/translation.jsonindex 622d50e1c..2d586916b 100644--- a/src/locales/de/translation.json+++ b/src/locales/de/translation.json@@ -1084,7 +1084,18 @@"selectPlaceholder": "Mikrofon auswählen","systemDefault": "Systemstandard","unknownDevice": "Unbekanntes Gerät",- "using": "Verwendet: {{device}}"+ "using": "Verwendet: {{device}}",+ "warmHold": {+ "label": "Mikrofon warmhalten",+ "description": "Nach einem Diktat das Mikrofon kurz geöffnet lassen, damit das nächste sofort und ohne abgeschnittene Wörter startet",+ "privacyNote": "Solange das Mikrofon gehalten wird, bleibt die Mikrofonanzeige des Systems aktiv. Zwischen den Diktaten wird nichts aufgezeichnet.",+ "options": {+ "0": "Aus",+ "10": "10 Sekunden",+ "60": "1 Minute",+ "900": "15 Minuten"+ }+ }},"pasteToolsInfo": {"checking": "Systemfähigkeiten werden geprüft...",diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex 5d2ed2418..da7ccaabf 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -1084,7 +1084,18 @@"selectPlaceholder": "Select a microphone","systemDefault": "System Default","unknownDevice": "Unknown Device",- "using": "Using: {{device}}"+ "using": "Using: {{device}}",+ "warmHold": {+ "label": "Keep Microphone Warm",+ "description": "After a dictation ends, keep the microphone open briefly so the next one starts instantly with nothing clipped",+ "privacyNote": "While the microphone is held, your system's mic-in-use indicator stays on. Nothing is recorded between dictations.",+ "options": {+ "0": "Off",+ "10": "10 seconds",+ "60": "1 minute",+ "900": "15 minutes"+ }+ }},"pasteToolsInfo": {"checking": "Checking system capabilities...",diff --git a/src/locales/es/translation.json b/src/locales/es/translation.jsonindex bdf27c2d4..3e4e8a275 100644--- a/src/locales/es/translation.json+++ b/src/locales/es/translation.json@@ -1044,7 +1044,18 @@"selectPlaceholder": "Selecciona un micrófono","systemDefault": "Predeterminado del sistema","unknownDevice": "Dispositivo desconocido",- "using": "Usando: {{device}}"+ "using": "Usando: {{device}}",+ "warmHold": {+ "label": "Mantener el micrófono activo",+ "description": "Después de un dictado, mantén el micrófono abierto brevemente para que el siguiente empiece al instante y sin palabras cortadas",+ "privacyNote": "Mientras el micrófono se mantiene abierto, el indicador de micrófono en uso del sistema permanece encendido. No se graba nada entre dictados.",+ "options": {+ "0": "Desactivado",+ "10": "10 segundos",+ "60": "1 minuto",+ "900": "15 minutos"+ }+ }},"pasteToolsInfo": {"checking": "Verificando capacidades del sistema...",diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.jsonindex 46b19970b..c4e7d5d5f 100644--- a/src/locales/fr/translation.json+++ b/src/locales/fr/translation.json@@ -1084,7 +1084,18 @@"selectPlaceholder": "Sélectionnez un microphone","systemDefault": "Par défaut du système","unknownDevice": "Appareil inconnu",- "using": "Utilisation : {{device}}"+ "using": "Utilisation : {{device}}",+ "warmHold": {+ "label": "Garder le microphone actif",+ "description": "Après une dictée, garder le microphone ouvert brièvement pour que la suivante démarre instantanément, sans mots coupés",+ "privacyNote": "Tant que le microphone est maintenu ouvert, l'indicateur d'utilisation du micro du système reste allumé. Rien n'est enregistré entre les dictées.",+ "options": {+ "0": "Désactivé",+ "10": "10 secondes",+ "60": "1 minute",+ "900": "15 minutes"+ }+ }},"pasteToolsInfo": {"checking": "Vérification des capacités du système...",diff --git a/src/locales/it/translation.json b/src/locales/it/translation.jsonindex b2ebcfed0..c51a6e51a 100644--- a/src/locales/it/translation.json+++ b/src/locales/it/translation.json@@ -996,7 +996,18 @@"selectPlaceholder": "Seleziona un microfono","systemDefault": "Predefinito di sistema","unknownDevice": "Dispositivo sconosciuto",- "using": "In uso: {{device}}"+ "using": "In uso: {{device}}",+ "warmHold": {+ "label": "Mantieni il microfono attivo",+ "description": "Dopo una dettatura, mantieni il microfono aperto brevemente così la successiva parte all'istante senza parole tagliate",+ "privacyNote": "Finché il microfono resta aperto, l'indicatore di microfono in uso del sistema rimane acceso. Non viene registrato nulla tra le dettature.",+ "options": {+ "0": "Disattivato",+ "10": "10 secondi",+ "60": "1 minuto",+ "900": "15 minuti"+ }+ }},"pasteToolsInfo": {"checking": "Verifica delle funzionalità di sistema...",diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.jsonindex 403f8736f..53cb259fc 100644--- a/src/locales/ja/translation.json+++ b/src/locales/ja/translation.json@@ -996,7 +996,18 @@"selectPlaceholder": "マイクを選択","systemDefault": "システムデフォルト","unknownDevice": "不明なデバイス",- "using": "使用中: {{device}}"+ "using": "使用中: {{device}}",+ "warmHold": {+ "label": "マイクをウォーム状態に保つ",+ "description": "ディクテーション終了後もマイクを短時間開いたままにし、次回を冒頭の欠落なくすぐに開始できるようにします",+ "privacyNote": "マイクを保持している間は、システムのマイク使用中インジケーターが点灯したままになります。ディクテーションの合間に録音は行われません。",+ "options": {+ "0": "オフ",+ "10": "10秒",+ "60": "1分",+ "900": "15分"+ }+ }},"pasteToolsInfo": {"checking": "システム機能を確認中...",diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.jsonindex a85cc9b87..94c0c7c25 100644--- a/src/locales/pt/translation.json+++ b/src/locales/pt/translation.json@@ -975,7 +975,18 @@"selectPlaceholder": "Selecione um microfone","systemDefault": "Padrão do sistema","unknownDevice": "Dispositivo desconhecido",- "using": "Usando: {{device}}"+ "using": "Usando: {{device}}",+ "warmHold": {+ "label": "Manter o microfone ativo",+ "description": "Após um ditado, mantenha o microfone aberto por um breve período para que o próximo comece na hora, sem palavras cortadas",+ "privacyNote": "Enquanto o microfone estiver aberto, o indicador de microfone em uso do sistema permanece aceso. Nada é gravado entre os ditados.",+ "options": {+ "0": "Desativado",+ "10": "10 segundos",+ "60": "1 minuto",+ "900": "15 minutos"+ }+ }},"pasteToolsInfo": {"checking": "Verificando capacidades do sistema...",diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.jsonindex 575c8187b..7466b0a3f 100644--- a/src/locales/ru/translation.json+++ b/src/locales/ru/translation.json@@ -996,7 +996,18 @@"selectPlaceholder": "Выберите микрофон","systemDefault": "Системный по умолчанию","unknownDevice": "Неизвестное устройство",- "using": "Используется: {{device}}"+ "using": "Используется: {{device}}",+ "warmHold": {+ "label": "Держать микрофон готовым",+ "description": "После диктовки ненадолго оставлять микрофон открытым, чтобы следующая начиналась мгновенно и без обрезанных слов",+ "privacyNote": "Пока микрофон удерживается открытым, системный индикатор использования микрофона остаётся включённым. Между диктовками ничего не записывается.",+ "options": {+ "0": "Выключено",+ "10": "10 секунд",+ "60": "1 минута",+ "900": "15 минут"+ }+ }},"pasteToolsInfo": {"checking": "Проверка системных возможностей...",diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.jsonindex 372750244..b6c71a0a1 100644--- a/src/locales/zh-CN/translation.json+++ b/src/locales/zh-CN/translation.json@@ -996,7 +996,18 @@"selectPlaceholder": "选择麦克风","systemDefault": "系统默认","unknownDevice": "未知设备",- "using": "当前使用:{{device}}"+ "using": "当前使用:{{device}}",+ "warmHold": {+ "label": "保持麦克风预热",+ "description": "听写结束后短暂保持麦克风开启,让下一次听写即刻开始且不丢字",+ "privacyNote": "麦克风保持开启期间,系统的麦克风使用指示灯会一直亮起。听写之间不会录制任何内容。",+ "options": {+ "0": "关闭",+ "10": "10 秒",+ "60": "1 分钟",+ "900": "15 分钟"+ }+ }},"pasteToolsInfo": {"checking": "正在检查系统功能...",diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.jsonindex ee672ad5d..cf85d62ec 100644--- a/src/locales/zh-TW/translation.json+++ b/src/locales/zh-TW/translation.json@@ -996,7 +996,18 @@"selectPlaceholder": "選擇麥克風","systemDefault": "系統預設","unknownDevice": "未知裝置",- "using": "使用中:{{device}}"+ "using": "使用中:{{device}}",+ "warmHold": {+ "label": "保持麥克風預熱",+ "description": "聽寫結束後短暫保持麥克風開啟,讓下一次聽寫立即開始且不漏字",+ "privacyNote": "麥克風保持開啟期間,系統的麥克風使用指示燈會持續亮起。聽寫之間不會錄製任何內容。",+ "options": {+ "0": "關閉",+ "10": "10 秒",+ "60": "1 分鐘",+ "900": "15 分鐘"+ }+ }},"pasteToolsInfo": {"checking": "正在檢查系統功能...",diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.tsindex beb2f36d1..59e00ca43 100644--- a/src/stores/settingsStore.ts+++ b/src/stores/settingsStore.ts@@ -63,6 +63,14 @@ function readNumber(key: string, fallback: number): number {return isNaN(parsed) ? fallback : parsed;}+// Durations offered by the mic warm-hold select; unknown values snap to 0 (off)+// so a hand-edited localStorage entry can never hold the mic open indefinitely.+export const MIC_WARM_HOLD_CHOICES = [0, 10, 60, 900] as const;++function snapMicWarmHold(value: number): number {+ return (MIC_WARM_HOLD_CHOICES as readonly number[]).includes(value) ? value : 0;+}+function readStringArray(key: string, fallback: string[]): string[] {if (!isBrowser) return fallback;const stored = localStorage.getItem(key);@@ -174,6 +182,7 @@ const ARRAY_SETTINGS = new Set([]);const NUMERIC_SETTINGS = new Set([+ "micWarmHoldSeconds","audioRetentionDays","transcriptRetentionDays","whisperVadThreshold",@@ -678,6 +687,7 @@ export interface SettingsStatesetPreferBuiltInMic: (value: boolean) => void;setSelectedMicDevice: (deviceId: string, label: string) => void;+ setMicWarmHoldSeconds: (seconds: number) => void;setTheme: (value: "light" | "dark" | "auto") => void;setCloudBackupEnabled: (value: boolean) => void;@@ -1031,6 +1041,7 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({preferBuiltInMic: readBoolean("preferBuiltInMic", true),selectedMicDeviceId: readString("selectedMicDeviceId", ""),selectedMicDeviceLabel: readString("selectedMicDeviceLabel", ""),+ micWarmHoldSeconds: snapMicWarmHold(readNumber("micWarmHoldSeconds", 0)),theme: (() => {const v = readString("theme", "auto");@@ -1647,6 +1658,11 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({setCloudBackupEnabled: createBooleanSetter("cloudBackupEnabled"),setTelemetryEnabled: createBooleanSetter("telemetryEnabled"),+ setMicWarmHoldSeconds: (value: number) => {+ const snapped = snapMicWarmHold(value);+ if (isBrowser) localStorage.setItem("micWarmHoldSeconds", String(snapped));+ set({ micWarmHoldSeconds: snapped });+ },setAudioRetentionDays: createNumberSetter("audioRetentionDays"),setTranscriptRetentionDays: createNumberSetter("transcriptRetentionDays"),setDataRetentionEnabled: (value: boolean) => {@@ -2629,8 +2645,14 @@ export async function initializeSettings(): Promise<void> {if (Number.isNaN(parsed)) {value =key === "audioRetentionDays" ? 30 : (state as unknown as Record<string, unknown>)[key];+ } else if (key === "audioRetentionDays") {+ value = Math.round(parsed);+ } else if (key === "micWarmHoldSeconds") {+ // Same whitelist as the setter — a hand-edited localStorage value+ // synced from another window must not exceed the offered durations.+ value = snapMicWarmHold(parsed);} else {- value = key === "audioRetentionDays" ? Math.round(parsed) : parsed;+ value = parsed;}} else {value = newValue;diff --git a/src/types/electron.ts b/src/types/electron.tsindex c598b92f0..5b230c404 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -787,6 +787,9 @@ declare global {onToggleTranslation?: (callback: () => void) => () => void;onStartDictation?: (callback: () => void) => () => void;onStopDictation?: (callback: () => void) => () => void;+ onPrepareDictation?: (callback: () => void) => () => void;+ onCancelDictationPreparation?: (callback: () => void) => () => void;+ micWarmHoldChanged?: (active: boolean) => void;// STT configgetSttConfig?: () => Promise<diff --git a/test/helpers/micStreamHold.test.js b/test/helpers/micStreamHold.test.jsnew file mode 100644index 000000000..9a32ef90c--- /dev/null+++ b/test/helpers/micStreamHold.test.js@@ -0,0 +1,170 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const load = () => import("../../src/helpers/micStreamHold.js");++const fakeTrack = ({ live = true, muted = false } = {}) => {+ const track = {+ readyState: live ? "live" : "ended",+ muted,+ stopped: 0,+ clones: 0,+ stop() {+ this.stopped += 1;+ this.readyState = "ended";+ },+ clone() {+ this.clones += 1;+ return { cloneOf: track };+ },+ };+ return track;+};++const fakeStream = (track) => ({ getAudioTracks: () => [track] });++const makeHold = async (options = {}) => {+ const { MicStreamHold } = await load();+ const timers = { armed: [], cleared: [] };+ const events = [];+ const hold = new MicStreamHold({+ holdSeconds: 10,+ setTimer: (fn, ms) => {+ const id = timers.armed.push({ fn, ms });+ return id;+ },+ clearTimer: (id) => timers.cleared.push(id),+ onHoldChange: (active) => events.push(active),+ makeStream: (track) => ({ wrapped: track }),+ ...options,+ });+ return { hold, timers, events };+};++test("disabled hold passes the stream through and keeps nothing", async () => {+ const { hold, events } = await makeHold({ holdSeconds: 0 });+ const track = fakeTrack();+ const stream = fakeStream(track);++ assert.equal(hold.adoptAndClone(stream, "key"), stream);+ assert.equal(hold.active, false);+ assert.equal(hold.acquireClone("key"), null);+ assert.equal(track.clones, 0);+ assert.deepEqual(events, []);+});++test("adoptAndClone stores the master and returns a clone", async () => {+ const { hold, events } = await makeHold();+ const track = fakeTrack();++ const clone = hold.adoptAndClone(fakeStream(track), "key");++ assert.equal(track.clones, 1);+ assert.equal(clone.wrapped.cloneOf, track);+ assert.equal(hold.active, true);+ assert.deepEqual(events, [true]);+});++test("replacing the master is a silent swap, not a release+acquire", async () => {+ const { hold, events } = await makeHold();+ const first = fakeTrack();+ const second = fakeTrack();++ hold.adoptAndClone(fakeStream(first), "key");+ const clone = hold.adoptAndClone(fakeStream(second), "key2");++ assert.equal(first.stopped, 1);+ assert.equal(clone.wrapped.cloneOf, second);+ assert.equal(hold.active, true);+ // One continuous hold: no false→true blip from the swap.+ assert.deepEqual(events, [true]);+});++test("acquireClone returns fresh clones while the master is live", async () => {+ const { hold } = await makeHold();+ const track = fakeTrack();+ hold.adoptAndClone(fakeStream(track), "key");++ const clone = hold.acquireClone("key");++ assert.equal(track.clones, 2);+ assert.equal(clone.wrapped.cloneOf, track);+});++test("acquireClone drops the master on constraints mismatch", async () => {+ const { hold, events } = await makeHold();+ const track = fakeTrack();+ hold.adoptAndClone(fakeStream(track), "key");++ assert.equal(hold.acquireClone("other"), null);+ assert.equal(track.stopped, 1);+ assert.equal(hold.active, false);+ assert.deepEqual(events, [true, false]);+});++test("acquireClone drops a dead or muted master", async () => {+ for (const state of [{ live: false }, { muted: true }]) {+ const { hold } = await makeHold();+ const track = fakeTrack(state);+ hold.adoptAndClone(fakeStream(track), "key");++ assert.equal(hold.acquireClone("key"), null);+ assert.equal(hold.active, false);+ }+});++test("the release timer stops the master and can be re-armed by touch", async () => {+ const { hold, timers, events } = await makeHold();+ const track = fakeTrack();+ hold.adoptAndClone(fakeStream(track), "key");++ assert.equal(timers.armed.length, 1);+ assert.equal(timers.armed[0].ms, 10000);++ hold.touch();+ assert.equal(timers.cleared.length, 1);+ assert.equal(timers.armed.length, 2);++ timers.armed[1].fn();+ assert.equal(track.stopped, 1);+ assert.equal(hold.active, false);+ assert.deepEqual(events, [true, false]);+});++test("a release firing mid-recording defers instead of dropping the master", async () => {+ let busy = true;+ const { hold, timers, events } = await makeHold({ isBusy: () => busy });+ const track = fakeTrack();+ hold.adoptAndClone(fakeStream(track), "key");++ timers.armed[0].fn();+ assert.equal(track.stopped, 0);+ assert.equal(hold.active, true);+ assert.equal(timers.armed.length, 2);++ busy = false;+ timers.armed[1].fn();+ assert.equal(track.stopped, 1);+ assert.equal(hold.active, false);+ assert.deepEqual(events, [true, false]);+});++test("setHoldSeconds(0) drops a live master immediately", async () => {+ const { hold, events } = await makeHold();+ const track = fakeTrack();+ hold.adoptAndClone(fakeStream(track), "key");++ hold.setHoldSeconds(0);++ assert.equal(track.stopped, 1);+ assert.equal(hold.active, false);+ assert.deepEqual(events, [true, false]);+});++test("drop is idempotent and silent when nothing is held", async () => {+ const { hold, events } = await makeHold();+ hold.drop();+ hold.drop();++ assert.deepEqual(events, []);+});diff --git a/test/helpers/micWarmState.test.js b/test/helpers/micWarmState.test.jsnew file mode 100644index 000000000..d579f6800--- /dev/null+++ b/test/helpers/micWarmState.test.js@@ -0,0 +1,56 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const {+ isMicWarm,+ MIC_WARM_TTL_MS,+ WARMUP_ACQUIRE_TIMEOUT_MS,+} = require("../../src/helpers/micWarmState");++test("MIC_WARM_TTL_MS is 5000", () => {+ assert.equal(MIC_WARM_TTL_MS, 5000);+});++test("acquire timeout is decoupled from the warm TTL", () => {+ assert.equal(WARMUP_ACQUIRE_TIMEOUT_MS, 15000);+ assert.notEqual(WARMUP_ACQUIRE_TIMEOUT_MS, MIC_WARM_TTL_MS);+});++test("is not warm for a zero timestamp", () => {+ assert.equal(isMicWarm(0, 1000), false);+});++test("is not warm for a missing timestamp", () => {+ assert.equal(isMicWarm(undefined, 1000), false);+ assert.equal(isMicWarm(null, 1000), false);+});++test("is not warm for a non-number timestamp", () => {+ assert.equal(isMicWarm("1000", 2000), false);+ assert.equal(isMicWarm(NaN, 2000), false);+});++test("is warm when the elapsed time is below the TTL", () => {+ assert.equal(isMicWarm(1000, 1000 + MIC_WARM_TTL_MS - 1), true);+ // Zero elapsed still counts as warm.+ assert.equal(isMicWarm(1000, 1000), true);+});++test("is not warm at exactly the TTL", () => {+ assert.equal(isMicWarm(1000, 1000 + MIC_WARM_TTL_MS), false);+});++test("is not warm beyond the TTL", () => {+ assert.equal(isMicWarm(1000, 1000 + MIC_WARM_TTL_MS + 1), false);+});++test("is not warm when the clock jumped backwards", () => {+ assert.equal(isMicWarm(5000, 4000), false);+});++test("honors a custom ttlMs argument", () => {+ assert.equal(isMicWarm(1000, 1500, 1000), true);+ // Exactly the custom TTL is not warm.+ assert.equal(isMicWarm(1000, 2000, 1000), false);+ assert.equal(isMicWarm(1000, 2001, 1000), false);+});diff --git a/test/helpers/preparedMicCapture.test.js b/test/helpers/preparedMicCapture.test.jsnew file mode 100644index 000000000..0a19433f3--- /dev/null+++ b/test/helpers/preparedMicCapture.test.js@@ -0,0 +1,210 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const load = () => import("../../src/helpers/preparedMicCapture.js");++const fakeStream = (onStop) => ({+ getTracks: () => [{ stop: () => onStop?.() }],+});++test("take reuses the in-flight prepared capture", async () => {+ const { PreparedMicCapture } = await load();+ let resolveAcquire;+ let acquisitions = 0;+ const capture = new PreparedMicCapture();+ const stream = fakeStream();++ capture.prepare(+ () =>+ new Promise((resolve) => {+ acquisitions += 1;+ resolveAcquire = resolve;+ })+ );+ const taken = capture.take();+ await Promise.resolve();+ resolveAcquire({ stream, constraints: { audio: true }, chunks: [] });++ assert.equal((await taken).stream, stream);+ assert.equal(acquisitions, 1);+});++test("cancel disposes a prepared value (stream and recorder stopped)", async () => {+ const { PreparedMicCapture } = await load();+ let streamStops = 0;+ let recorderStops = 0;+ const capture = new PreparedMicCapture();++ const recorder = {+ state: "recording",+ ondataavailable: () => {},+ stop: () => (recorderStops += 1),+ };+ await capture.prepare(async () => ({+ stream: fakeStream(() => (streamStops += 1)),+ recorder,+ chunks: [],+ constraints: { audio: true },+ }));+ capture.cancel();++ assert.equal(streamStops, 1);+ assert.equal(recorderStops, 1);+ // Detached before stop, so the final async dataavailable can't repopulate.+ assert.equal(recorder.ondataavailable, null);+ assert.equal(await capture.take(), null);+});++test("cancel during acquisition disposes the value when it arrives", async () => {+ const { PreparedMicCapture } = await load();+ let resolveAcquire;+ let streamStops = 0;+ const capture = new PreparedMicCapture();++ const preparation = capture.prepare(+ () =>+ new Promise((resolve) => {+ resolveAcquire = resolve;+ })+ );+ await Promise.resolve();+ capture.cancel();+ resolveAcquire({ stream: fakeStream(() => (streamStops += 1)), chunks: [] });++ assert.equal(await preparation, null);+ assert.equal(streamStops, 1);+ assert.equal(await capture.take(), null);+});++test("take falls back cleanly when preparation fails", async () => {+ const { PreparedMicCapture } = await load();+ const capture = new PreparedMicCapture();+ const preparation = capture.prepare(async () => {+ throw new Error("device busy");+ });++ await assert.rejects(preparation, /device busy/);+ assert.equal(await capture.take(), null);+});++test("expires an untaken prepared value after maxAgeMs", async () => {+ const { PreparedMicCapture } = await load();+ const disposed = [];+ let expire;+ const capture = new PreparedMicCapture({+ dispose: (prepared) => disposed.push(prepared),+ maxAgeMs: 1000,+ setTimer: (fn) => {+ expire = fn;+ return 1;+ },+ clearTimer: () => {},+ });+ const value = { stream: fakeStream(), chunks: [] };+ await capture.prepare(async () => value);+ expire();++ assert.deepEqual(disposed, [value]);+ assert.equal(await capture.take(), null);+});++test("take before expiry cancels the expiry timer", async () => {+ const { PreparedMicCapture } = await load();+ const cleared = [];+ const capture = new PreparedMicCapture({+ dispose: () => {},+ maxAgeMs: 1000,+ setTimer: () => 42,+ clearTimer: (id) => cleared.push(id),+ });+ await capture.prepare(async () => ({ stream: fakeStream(), chunks: [] }));++ assert.equal((await capture.take()).stream.getTracks().length, 1);+ assert.deepEqual(cleared, [42]);+});++test("a prepared value that expired is not handed to a later prepare", async () => {+ const { PreparedMicCapture } = await load();+ let expire;+ const capture = new PreparedMicCapture({+ dispose: () => {},+ maxAgeMs: 1000,+ setTimer: (fn) => {+ expire = fn;+ return 1;+ },+ clearTimer: () => {},+ });+ await capture.prepare(async () => ({ stream: fakeStream(), id: "first", chunks: [] }));+ expire();+ const second = await capture.prepare(async () => ({+ stream: fakeStream(),+ id: "second",+ chunks: [],+ }));++ assert.equal(second.id, "second");+ assert.equal((await capture.take()).id, "second");+});++test("discardPreRoll drops the recorder and chunks but keeps the stream", async () => {+ const { discardPreRoll } = await load();+ let streamStops = 0;+ let recorderStops = 0;+ const prepared = {+ stream: fakeStream(() => (streamStops += 1)),+ recorder: { state: "recording", ondataavailable: () => {}, stop: () => (recorderStops += 1) },+ chunks: ["a", "b"],+ };++ discardPreRoll(prepared);++ assert.equal(recorderStops, 1);+ assert.equal(prepared.recorder, null);+ assert.deepEqual(prepared.chunks, []);+ assert.equal(streamStops, 0);+});++test("stays active after a cancel until the abandoned acquisition settles", async () => {+ const { PreparedMicCapture } = await load();+ const events = [];+ let resolveAcquire;+ const capture = new PreparedMicCapture({+ dispose: () => {},+ onActiveChange: (active) => events.push(active),+ });++ capture.prepare(+ () =>+ new Promise((resolve) => {+ resolveAcquire = resolve;+ })+ );+ await Promise.resolve();+ assert.equal(capture.active, true);+ assert.deepEqual(events, [true]);++ // The cancel frees the slot for a new prepare, but the mic is still opening.+ capture.cancel();+ assert.equal(capture.active, true);+ assert.deepEqual(events, [true]);++ resolveAcquire({ stream: fakeStream(), chunks: [] });+ await new Promise((resolve) => setImmediate(resolve));+ assert.equal(capture.active, false);+ assert.deepEqual(events, [true, false]);+});++test("take reports the capture inactive once it is handed over", async () => {+ const { PreparedMicCapture } = await load();+ const events = [];+ const capture = new PreparedMicCapture({ onActiveChange: (active) => events.push(active) });++ await capture.prepare(async () => ({ stream: fakeStream(), chunks: [] }));+ assert.equal(capture.active, true);++ await capture.take();++ assert.equal(capture.active, false);+ assert.deepEqual(events, [true, false]);+});