Skip to content

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

fix: recover recordings on microphone disconnects (#1261)

Chad Piha7c06935ac05f
diff --git a/preload.js b/preload.js
index 5b2039798..fd6f6192a 100644
--- a/preload.js
+++ b/preload.js
@@ -64,6 +64,7 @@ contextBridge.exposeInMainWorld("electronAPI", {
// Audio storage functions
saveTranscriptionAudio: (id, audioBuffer, metadata) =>
ipcRenderer.invoke("save-transcription-audio", id, audioBuffer, metadata),
+ mergeAudioSegments: (segments) => ipcRenderer.invoke("merge-audio-segments", segments),
getAudioPath: (id) => ipcRenderer.invoke("get-audio-path", id),
showAudioInFolder: (id) => ipcRenderer.invoke("show-audio-in-folder", id),
getAudioBuffer: (id) => ipcRenderer.invoke("get-audio-buffer", id),
diff --git a/src/App.jsx b/src/App.jsx
index a75345e1f..01fd16565 100644
--- a/src/App.jsx
+++ b/src/App.jsx
@@ -206,10 +206,16 @@ export default function App() {
setWindowInteractivity(false);
}, [setWindowInteractivity]);
- const { isRecording, isProcessing, toggleListening, cancelRecording, cancelProcessing } =
- useAudioRecording(toast, {
- onToggle: handleDictationToggle,
- });
+ const {
+ isRecording,
+ isProcessing,
+ micCaptureStatus,
+ toggleListening,
+ cancelRecording,
+ cancelProcessing,
+ } = useAudioRecording(toast, {
+ onToggle: handleDictationToggle,
+ });
// Sync auto-hide from main process — setState directly to avoid IPC echo
useEffect(() => {
@@ -291,6 +297,8 @@ export default function App() {
// Determine current mic state
const getMicState = () => {
+ if (isRecording && (micCaptureStatus === "reconnecting" || micCaptureStatus === "unavailable"))
+ return "unavailable";
if (isRecording) return "recording";
if (isProcessing) return "processing";
if (isHovered && !isRecording && !isProcessing) return "hover";
@@ -315,6 +323,11 @@ export default function App() {
className: `${baseClasses} bg-primary cursor-pointer`,
tooltip: t("app.mic.recording"),
};
+ case "unavailable":
+ return {
+ className: `${baseClasses} bg-amber-500 cursor-pointer`,
+ tooltip: t("app.mic.waitingForMicrophone"),
+ };
case "processing":
return {
className: `${baseClasses} bg-accent cursor-not-allowed`,
@@ -456,12 +469,17 @@ export default function App() {
<LoadingDots />
) : micState === "processing" ? (
<VoiceWaveIndicator isListening={true} />
+ ) : micState === "unavailable" ? (
+ <span className="text-white text-base font-bold">!</span>
) : null}
{/* State indicator ring for recording */}
{micState === "recording" && (
<div className="absolute inset-0 rounded-full border-2 border-primary/50 animate-pulse"></div>
)}
+ {micState === "unavailable" && (
+ <div className="absolute inset-0 rounded-full border-2 border-amber-200/70 animate-pulse"></div>
+ )}
{/* State indicator ring for processing */}
{micState === "processing" && (
diff --git a/src/components/MeetingRecordingMount.tsx b/src/components/MeetingRecordingMount.tsx
index 22cd3b246..c92c47db3 100644
--- a/src/components/MeetingRecordingMount.tsx
+++ b/src/components/MeetingRecordingMount.tsx
@@ -1,4 +1,4 @@
-import { useEffect } from "react";
+import { useEffect, useRef } from "react";
import { useTranslation } from "react-i18next";
import { useToast } from "./ui/useToast";
import {
@@ -15,6 +15,8 @@ export default function MeetingRecordingMount(): null {
const { toast } = useToast();
const isRecording = useMeetingRecordingStore((s) => s.isRecording);
const error = useMeetingRecordingStore((s) => s.error);
+ const micCaptureStatus = useMeetingRecordingStore((s) => s.micCaptureStatus);
+ const wasMicUnavailable = useRef(false);
useEffect(() => {
primeMeetingWorklet();
@@ -29,6 +31,26 @@ export default function MeetingRecordingMount(): null {
});
}, [error, toast, t]);
+ useEffect(() => {
+ if (micCaptureStatus === "unavailable" && !wasMicUnavailable.current) {
+ wasMicUnavailable.current = true;
+ toast({
+ title: t("hooks.audioRecording.micDisconnected.title"),
+ description: t("hooks.audioRecording.micDisconnected.meetingDescription"),
+ variant: "default",
+ });
+ } else if (micCaptureStatus === "active" && wasMicUnavailable.current) {
+ wasMicUnavailable.current = false;
+ toast({
+ title: t("hooks.audioRecording.micRestored.title"),
+ description: t("hooks.audioRecording.micRestored.description"),
+ variant: "default",
+ });
+ } else if (micCaptureStatus === "inactive") {
+ wasMicUnavailable.current = false;
+ }
+ }, [micCaptureStatus, toast, t]);
+
useEffect(() => {
if (!isRecording) return;
diff --git a/src/components/notes/MeetingRecordingPill.tsx b/src/components/notes/MeetingRecordingPill.tsx
index 3a01b2307..99455b8c6 100644
--- a/src/components/notes/MeetingRecordingPill.tsx
+++ b/src/components/notes/MeetingRecordingPill.tsx
@@ -37,6 +37,8 @@ export default function MeetingRecordingPill({
const recordingNoteId = useMeetingRecordingStore((s) => s.recordingNoteId);
const recordingNoteTitle = useMeetingRecordingStore((s) => s.recordingNoteTitle);
const micLevel = useMeetingRecordingStore((s) => s.currentMicLevel);
+ const micCaptureStatus = useMeetingRecordingStore((s) => s.micCaptureStatus);
+ const isWaitingForMic = micCaptureStatus === "reconnecting" || micCaptureStatus === "unavailable";
const [isStopping, setIsStopping] = useState(false);
const isViewingRecordingNote =
@@ -95,13 +97,16 @@ export default function MeetingRecordingPill({
{Array.from({ length: BAR_COUNT }, (_, i) => (
<div
key={i}
- className="w-0.75 rounded-full bg-primary/60 dark:bg-primary/70 origin-bottom"
+ className={cn(
+ "w-0.75 rounded-full origin-bottom",
+ isWaitingForMic ? "bg-amber-500" : "bg-primary/60 dark:bg-primary/70"
+ )}
style={{ height: computeBarHeight(micLevel, i) }}
/>
))}
</div>
<span className="text-xs font-medium text-foreground/80 truncate max-w-[12rem]">
- {title}
+ {isWaitingForMic ? t("notes.meetingPill.waitingForMicrophone") : title}
</span>
</button>
diff --git a/src/helpers/activeMicRecovery.js b/src/helpers/activeMicRecovery.js
new file mode 100644
index 000000000..5fcaf52f3
--- /dev/null
+++ b/src/helpers/activeMicRecovery.js
@@ -0,0 +1,211 @@
+const DEFAULT_DEBOUNCE_MS = 250;
+const DEFAULT_MUTE_GRACE_MS = 800;
+const DEFAULT_RETRY_MS = 2000;
+
+const deviceKey = (device) =>
+ [device?.deviceId || "", device?.groupId || "", device?.label || ""].join("\u0000");
+
+export const describeAudioInputs = (devices = []) => {
+ const inputs = devices.filter((device) => device.kind === "audioinput");
+ return {
+ defaultKey: inputs.length > 0 ? deviceKey(inputs[0]) : "",
+ keys: new Set(inputs.map(deviceKey)),
+ deviceIds: new Set(inputs.map((device) => device.deviceId).filter(Boolean)),
+ groupIds: new Set(inputs.map((device) => device.groupId).filter(Boolean)),
+ };
+};
+
+export const activeTrackIsAvailable = (track, inputs) => {
+ if (!track || track.readyState === "ended") return false;
+ const settings = track.getSettings?.() || {};
+ if (settings.deviceId && inputs.deviceIds.has(settings.deviceId)) return true;
+ if (settings.groupId && inputs.groupIds.has(settings.groupId)) return true;
+ // Device labels are not a stable identity, but a live track with no exposed IDs
+ // is healthier than guessing that a permission-redacted enumeration removed it.
+ return !settings.deviceId && !settings.groupId;
+};
+
+export class ActiveMicRecoveryController {
+ constructor({
+ mediaDevices,
+ acquire,
+ onRecovered,
+ onStatusChange,
+ debounceMs = DEFAULT_DEBOUNCE_MS,
+ muteGraceMs = DEFAULT_MUTE_GRACE_MS,
+ retryMs = DEFAULT_RETRY_MS,
+ }) {
+ this.mediaDevices = mediaDevices;
+ this.acquire = acquire;
+ this.onRecovered = onRecovered;
+ this.onStatusChange = onStatusChange;
+ this.debounceMs = debounceMs;
+ this.muteGraceMs = muteGraceMs;
+ this.retryMs = retryMs;
+ this.status = "inactive";
+ this.stream = null;
+ this.track = null;
+ this.followDefault = true;
+ this.inputs = describeAudioInputs();
+ this.generation = 0;
+ this.recoveryPromise = null;
+ this.debounceTimer = null;
+ this.muteTimer = null;
+ this.retryTimer = null;
+ this.started = false;
+ this.onDeviceChange = () => this.scheduleEvaluation();
+ this.onTrackEnded = () => this.recover("ended");
+ this.onTrackMute = () => {
+ clearTimeout(this.muteTimer);
+ this.muteTimer = setTimeout(() => {
+ if (this.track?.muted) this.recover("muted");
+ }, this.muteGraceMs);
+ };
+ this.onTrackUnmute = () => clearTimeout(this.muteTimer);
+ }
+
+ setStatus(status) {
+ if (this.status === status) return;
+ this.status = status;
+ this.onStatusChange?.(status);
+ }
+
+ async start(stream, { followDefault = true } = {}) {
+ this.stop();
+ this.started = true;
+ this.generation += 1;
+ this.followDefault = followDefault;
+ this.mediaDevices?.addEventListener?.("devicechange", this.onDeviceChange);
+ this.attachStream(stream);
+ await this.refreshInputs();
+ if (!this.started) return;
+ // The track may have died (or come up muted) before our listeners attached;
+ // those events won't replay, so evaluate the track's state directly.
+ const alive = this.track && this.track.readyState !== "ended";
+ this.setStatus(alive ? "active" : "unavailable");
+ if (!alive) {
+ this.recover("start");
+ } else if (this.track.muted) {
+ this.onTrackMute();
+ }
+ }
+
+ attachStream(stream) {
+ this.detachTrack();
+ this.stream = stream || null;
+ this.track = stream?.getAudioTracks?.()[0] || null;
+ this.track?.addEventListener?.("ended", this.onTrackEnded);
+ this.track?.addEventListener?.("mute", this.onTrackMute);
+ this.track?.addEventListener?.("unmute", this.onTrackUnmute);
+ }
+
+ detachTrack() {
+ this.track?.removeEventListener?.("ended", this.onTrackEnded);
+ this.track?.removeEventListener?.("mute", this.onTrackMute);
+ this.track?.removeEventListener?.("unmute", this.onTrackUnmute);
+ this.track = null;
+ clearTimeout(this.muteTimer);
+ this.muteTimer = null;
+ }
+
+ async refreshInputs() {
+ try {
+ this.inputs = describeAudioInputs(await this.mediaDevices.enumerateDevices());
+ return this.inputs;
+ } catch {
+ return null;
+ }
+ }
+
+ scheduleEvaluation() {
+ if (!this.started) return;
+ clearTimeout(this.debounceTimer);
+ this.debounceTimer = setTimeout(() => this.evaluateDeviceChange(), this.debounceMs);
+ }
+
+ async evaluateDeviceChange() {
+ if (!this.started) return;
+ const previous = this.inputs;
+ const current = await this.refreshInputs();
+ if (!this.started || !current) {
+ if (this.track?.readyState === "ended") this.recover("devicechange-ended");
+ return;
+ }
+
+ const defaultChanged = previous.defaultKey !== current.defaultKey;
+ const activeMissing = !activeTrackIsAvailable(this.track, current);
+ if ((this.followDefault && defaultChanged) || activeMissing || this.status === "unavailable") {
+ this.recover("devicechange");
+ }
+ }
+
+ recover(reason) {
+ if (!this.started) return Promise.resolve(false);
+ if (this.recoveryPromise) return this.recoveryPromise;
+
+ clearTimeout(this.retryTimer);
+ this.retryTimer = null;
+ const generation = this.generation;
+ const oldStream = this.stream;
+ this.setStatus("reconnecting");
+
+ const attempt = async () => {
+ let replacement = null;
+ try {
+ replacement = await this.acquire(reason);
+ if (!replacement?.getAudioTracks?.()[0]) throw new Error("No audio track returned");
+ if (!this.started || generation !== this.generation) {
+ replacement.getTracks?.().forEach((track) => track.stop());
+ return false;
+ }
+ await this.onRecovered(replacement, oldStream, reason);
+ if (!this.started || generation !== this.generation) {
+ replacement.getTracks?.().forEach((track) => track.stop());
+ return false;
+ }
+ this.attachStream(replacement);
+ await this.refreshInputs();
+ this.setStatus("active");
+ return true;
+ } catch {
+ if (replacement && replacement !== this.stream) {
+ replacement.getTracks?.().forEach((track) => track.stop());
+ }
+ if (this.started && generation === this.generation) {
+ this.setStatus("unavailable");
+ this.scheduleRetry();
+ }
+ return false;
+ }
+ };
+ // Only clear our own handle: a stale attempt settling after stop()+start()
+ // must not clobber a newer in-flight recovery's dedup handle.
+ const promise = attempt().finally(() => {
+ if (this.recoveryPromise === promise) this.recoveryPromise = null;
+ });
+ this.recoveryPromise = promise;
+ return promise;
+ }
+
+ scheduleRetry() {
+ if (!this.started || this.retryTimer) return;
+ this.retryTimer = setTimeout(() => {
+ this.retryTimer = null;
+ this.recover("retry");
+ }, this.retryMs);
+ }
+
+ stop() {
+ this.started = false;
+ this.generation += 1;
+ this.mediaDevices?.removeEventListener?.("devicechange", this.onDeviceChange);
+ this.detachTrack();
+ clearTimeout(this.debounceTimer);
+ clearTimeout(this.retryTimer);
+ this.debounceTimer = null;
+ this.retryTimer = null;
+ this.recoveryPromise = null;
+ this.stream = null;
+ this.setStatus("inactive");
+ }
+}
diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.js
index 013d7ae7d..b96816240 100644
--- a/src/helpers/audioManager.js
+++ b/src/helpers/audioManager.js
@@ -15,7 +15,8 @@ import {
recordLocalSpeechWindow,
} from "./localSpeechGate";
import { reacquireIfDead } from "./micTrackHealth";
-import { reconcileSavedMicSelection } from "./micSelectionRecovery";
+import { ActiveMicRecoveryController } from "./activeMicRecovery";
+import { followsSystemDefaultMic, reconcileSavedMicSelection } from "./micSelectionRecovery";
import { isStaleDeviceError } from "./staleMicDevice";
import { shouldSaveDiscardedRecording } from "./discardedRecording";
import {
@@ -47,6 +48,7 @@ import {
import { resolvePrompt } from "../config/prompts";
import { syncService } from "../services/SyncService.js";
import { evaluateFinishedRecording } from "./recordingValidation";
+import { isEmptyRecording } from "./recordingGuard";
import { matchesDictionaryPrompt } from "../utils/dictionaryEchoFilter.js";
import { getDictionaryHintWords } from "../utils/snippets";
@@ -282,6 +284,7 @@ class AudioManager {
this.onError = null;
this.onTranscriptionComplete = null;
this.onPartialTranscript = null;
+ this.micCaptureStatus = "inactive";
this.cachedApiKey = null;
this.cachedApiKeyProvider = null;
@@ -336,6 +339,32 @@ class AudioManager {
this._localSpeechGateState = null;
this._streamingCommitActive = false;
this._previewFlushResolve = null;
+ this._batchSegments = [];
+ this._rotatingBatchRecorder = null;
+ this._rotationResolve = null;
+ this._stopRequestedDuringMicRecovery = false;
+ this._cancelRequestedDuringMicRecovery = false;
+ this._streamingFallbackSegments = [];
+ this._streamingMicSwapPromise = null;
+ this.micRecovery = new ActiveMicRecoveryController({
+ mediaDevices: navigator.mediaDevices,
+ acquire: async () => {
+ try {
+ const constraints = await this.getAudioConstraints();
+ return await navigator.mediaDevices.getUserMedia(constraints);
+ } catch (error) {
+ logger.debug(
+ "Preferred mic unavailable during recovery, falling back to default",
+ { error: error.message },
+ "audio"
+ );
+ const fallback = await this.getAudioConstraints(true);
+ return navigator.mediaDevices.getUserMedia(fallback);
+ }
+ },
+ onRecovered: (replacement, previous) => this.replaceActiveMic(replacement, previous),
+ onStatusChange: (status) => this.setMicCaptureStatus(status),
+ });
}
getWorkletBlobUrl() {
@@ -413,6 +442,60 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
this.onTranslationFallback?.({ reason });
}
+ setMicCaptureStatus(status) {
+ if (this.micCaptureStatus === status) return;
+ this.micCaptureStatus = status;
+ this.onStateChange?.({
+ isRecording: this.isRecording,
+ isProcessing: this.isProcessing,
+ isStreaming: this.isStreaming,
+ micCaptureStatus: status,
+ });
+ }
+
+ async beginMicRecovery(stream) {
+ // A stop/cancel can land during the awaits between recorder start and this
+ // call; never arm recovery for a recording that already ended.
+ if (!this.isRecording) return;
+ await this.micRecovery.start(stream, {
+ followDefault: followsSystemDefaultMic(getSettings()),
+ });
+ }
+
+ async replaceActiveMic(replacement, previous) {
+ if (!this.isRecording) throw new Error("Recording is no longer active");
+ if (this.isStreaming) {
+ await this.replaceStreamingMic(replacement, previous);
+ } else {
+ await this.replaceBatchMic(replacement, previous);
+ }
+ }
+
+ async mergeRecordedSegments(segments) {
+ // Header-only segments carry no audio frames and crash FFmpeg's concat (#871).
+ const usable = segments.filter((segment) => segment && !isEmptyRecording(segment.size));
+ if (usable.length === 0) return null;
+ if (usable.length === 1) return usable[0];
+ const payload = await Promise.all(
+ usable.map(async (segment) => ({
+ buffer: await segment.arrayBuffer(),
+ mimeType: segment.type || "audio/webm",
+ }))
+ );
+ const result = await window.electronAPI.mergeAudioSegments(payload);
+ if (!result?.success) throw new Error(result?.error || "Failed to merge audio segments");
+ return new Blob([result.buffer], { type: result.mimeType });
+ }
+
+ getLargestRecordedSegment(segments) {
+ return segments
+ .filter((segment) => segment && !isEmptyRecording(segment.size))
+ .reduce(
+ (largest, segment) => (segment.size > (largest?.size || 0) ? segment : largest),
+ null
+ );
+ }
+
setSkipReasoning(skip) {
this.skipReasoning = skip;
}
@@ -698,8 +781,8 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
}
this._silenceAnalyser = this._silenceCtx.createAnalyser();
this._silenceAnalyser.fftSize = 2048;
- const sourceNode = this._silenceCtx.createMediaStreamSource(micStream);
- sourceNode.connect(this._silenceAnalyser);
+ this._silenceSource = this._silenceCtx.createMediaStreamSource(micStream);
+ this._silenceSource.connect(this._silenceAnalyser);
this._localSpeechGateState = createLocalSpeechGateState();
const dataArray = new Uint8Array(this._silenceAnalyser.fftSize);
this._silenceInterval = setInterval(() => {
@@ -722,86 +805,19 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
this._localSpeechGateState = null;
}
- this.mediaRecorder = new MediaRecorder(micStream);
this.audioChunks = [];
+ this._batchSegments = [];
+ this._stopRequestedDuringMicRecovery = false;
+ this._cancelRequestedDuringMicRecovery = false;
this._receivedAudioData = false;
this.recordingStartTime = Date.now();
- this.recordingMimeType = this.mediaRecorder.mimeType || "audio/webm";
-
- this.mediaRecorder.ondataavailable = (event) => {
- if (event.data && event.data.size > 0) {
- this._receivedAudioData = true;
- this.audioChunks.push(event.data);
- }
- };
-
- this.mediaRecorder.onstop = async () => {
- this.teardownSpeechGate();
-
- const previewStopPromise = this.cleanupPreview({
- showCleanup: this.shouldShowPreviewCleanupState(),
- });
-
- this.isRecording = false;
- this.isProcessing = true;
- this.onStateChange?.({ isRecording: false, isProcessing: true });
-
- const audioBlob = new Blob(this.audioChunks, { type: this.recordingMimeType });
- this.lastAudioBlob = audioBlob;
-
- logger.info(
- "Recording stopped",
- {
- blobSize: audioBlob.size,
- blobType: audioBlob.type,
- chunksCount: this.audioChunks.length,
- },
- "audio"
- );
-
- const durationSeconds = this.recordingStartTime
- ? (Date.now() - this.recordingStartTime) / 1000
- : null;
- this.recordingStartTime = null;
-
- // Drop header-only / no-frame recordings before they crash FFmpeg. See #871.
- const recordingCheck = evaluateFinishedRecording({
- blobSize: audioBlob.size,
- receivedAudioData: this._receivedAudioData,
- });
- if (!recordingCheck.usable) {
- logger.info(
- "Dropping degenerate recording before transcription",
- {
- blobSize: audioBlob.size,
- reason: recordingCheck.reason,
- receivedAudioData: this._receivedAudioData,
- },
- "audio"
- );
- this.isProcessing = false;
- this._localSpeechGateState = null;
- this.onStateChange?.({ isRecording: false, isProcessing: false });
- this.onTranscriptionComplete?.({ success: true, text: "" });
- micStream.getTracks().forEach((track) => track.stop());
- return;
- }
-
- // Non-commit sessions stop concurrently with the decode below.
- const previewStop = this._streamingCommitActive ? await previewStopPromise : null;
- this._streamingCommitActive = false;
-
- await this.processAudio(audioBlob, {
- durationSeconds,
- ...(previewStop?.streamed ? { streamedText: previewStop.text } : {}),
- });
-
- micStream.getTracks().forEach((track) => track.stop());
- };
-
- this.mediaRecorder.start(RECORDING_TIMESLICE_MS);
+ this.createBatchRecorder(micStream);
this.isRecording = true;
- this.onStateChange?.({ isRecording: true, isProcessing: false });
+ this.onStateChange?.({
+ isRecording: true,
+ isProcessing: false,
+ micCaptureStatus: "active",
+ });
const {
showTranscriptionPreview,
@@ -848,6 +864,8 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
}
}
+ await this.beginMicRecovery(micStream);
+
return true;
} catch (error) {
if (isStaleDeviceError(error) && !forceDefaultMic) {
@@ -885,11 +903,174 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
}
}
+ createBatchRecorder(micStream) {
+ const recorder = new MediaRecorder(micStream);
+ const segmentChunks = [];
+ this.mediaRecorder = recorder;
+ this.audioChunks = segmentChunks;
+ this.recordingMimeType = recorder.mimeType || "audio/webm";
+
+ recorder.ondataavailable = (event) => {
+ if (event.data && event.data.size > 0) {
+ this._receivedAudioData = true;
+ segmentChunks.push(event.data);
+ }
+ };
+
+ recorder.onstop = async () => {
+ const segment = new Blob(segmentChunks, { type: recorder.mimeType || "audio/webm" });
+ segmentChunks.length = 0;
+ const rotating = this._rotatingBatchRecorder === recorder;
+ // The recorder also stops on its own when its mic track dies (the stream
+ // goes inactive). While recovery is armed, treat that like a rotation:
+ // bank the segment and keep the recording alive for the replacement mic.
+ if (rotating || this.micRecovery.started) {
+ if (segment.size > 0) this._batchSegments.push(segment);
+ micStream.getTracks().forEach((track) => track.stop());
+ if (rotating) {
+ this._rotatingBatchRecorder = null;
+ this._rotationResolve?.();
+ this._rotationResolve = null;
+ } else {
+ void this.micRecovery.recover("recorder-stopped");
+ }
+ return;
+ }
+
+ micStream.getTracks().forEach((track) => track.stop());
+ await this.finalizeBatchRecording(segment);
+ };
+
+ recorder.start(RECORDING_TIMESLICE_MS);
+ return recorder;
+ }
+
+ async finalizeBatchRecording(finalSegment) {
+ this.micRecovery.stop();
+ this.teardownSpeechGate();
+ const previewStopPromise = this.cleanupPreview({
+ showCleanup: this.shouldShowPreviewCleanupState(),
+ });
+ this.isRecording = false;
+ this.isProcessing = true;
+ this.onStateChange?.({
+ isRecording: false,
+ isProcessing: true,
+ micCaptureStatus: "inactive",
+ });
+
+ const segments = finalSegment ? [...this._batchSegments, finalSegment] : this._batchSegments;
+ this._batchSegments = [];
+ const segmentsCount = segments.filter((segment) => segment?.size > 0).length;
+ let audioBlob = null;
+ try {
+ audioBlob = await this.mergeRecordedSegments(segments);
+ } catch (error) {
+ logger.error("Failed to assemble recovered recording", { error: error.message }, "audio");
+ // Salvage the largest segment rather than dropping the whole recording.
+ audioBlob = this.getLargestRecordedSegment(segments);
+ }
+ audioBlob = audioBlob || new Blob([], { type: this.recordingMimeType || "audio/webm" });
+ this.lastAudioBlob = audioBlob;
+
+ logger.info(
+ "Recording stopped",
+ {
+ blobSize: audioBlob.size,
+ blobType: audioBlob.type,
+ segmentsCount,
+ },
+ "audio"
+ );
+
+ const durationSeconds = this.recordingStartTime
+ ? (Date.now() - this.recordingStartTime) / 1000
+ : null;
+ this.recordingStartTime = null;
+ const recordingCheck = evaluateFinishedRecording({
+ blobSize: audioBlob.size,
+ receivedAudioData: this._receivedAudioData,
+ });
+ if (!recordingCheck.usable) {
+ logger.info(
+ "Dropping degenerate recording before transcription",
+ {
+ blobSize: audioBlob.size,
+ reason: recordingCheck.reason,
+ receivedAudioData: this._receivedAudioData,
+ },
+ "audio"
+ );
+ this.isProcessing = false;
+ this._localSpeechGateState = null;
+ this.onStateChange?.({ isRecording: false, isProcessing: false });
+ this.onTranscriptionComplete?.({ success: true, text: "" });
+ return;
+ }
+ // Non-commit sessions stop concurrently with the decode below.
+ const previewStop = this._streamingCommitActive ? await previewStopPromise : null;
+ this._streamingCommitActive = false;
+
+ await this.processAudio(audioBlob, {
+ durationSeconds,
+ ...(previewStop?.streamed ? { streamedText: previewStop.text } : {}),
+ });
+ }
+
+ async replaceBatchMic(replacement) {
+ try {
+ const recorder = this.mediaRecorder;
+ if (!recorder) throw new Error("Batch recorder is no longer active");
+ // An auto-stopped recorder (mic track died) already banked its segment in
+ // onstop; only a live recorder needs the explicit rotation handshake.
+ if (recorder.state === "recording") {
+ await new Promise((resolve) => {
+ this._rotatingBatchRecorder = recorder;
+ this._rotationResolve = resolve;
+ recorder.stop();
+ });
+ }
+ if (!this.isRecording) throw new Error("Recording stopped during microphone recovery");
+
+ this._silenceSource?.disconnect();
+ if (this._silenceCtx && this._silenceAnalyser) {
+ this._silenceSource = this._silenceCtx.createMediaStreamSource(replacement);
+ this._silenceSource.connect(this._silenceAnalyser);
+ }
+ this._previewSource?.disconnect();
+ if (this._previewAudioContext && this._previewProcessor) {
+ this._previewSource = this._previewAudioContext.createMediaStreamSource(replacement);
+ this._previewSource.connect(this._previewProcessor);
+ }
+ this.createBatchRecorder(replacement);
+ } finally {
+ // Honor a stop/cancel that arrived mid-rotation even when the swap failed —
+ // dropping it would leave an unstoppable recording (isRecording stuck true).
+ const cancelRequested = this._cancelRequestedDuringMicRecovery;
+ const stopRequested = this._stopRequestedDuringMicRecovery;
+ this._cancelRequestedDuringMicRecovery = false;
+ this._stopRequestedDuringMicRecovery = false;
+ if (cancelRequested) this.cancelRecording();
+ else if (stopRequested) this.stopRecording();
+ }
+ }
+
stopRecording() {
+ this.micRecovery.stop();
+ if (this._rotatingBatchRecorder) {
+ this._stopRequestedDuringMicRecovery = true;
+ return true;
+ }
if (this.mediaRecorder?.state === "recording") {
this.mediaRecorder.stop();
return true;
}
+ if (this.isRecording && !this.isStreaming) {
+ // The mic died mid-recovery, so no live recorder exists; finalize what
+ // was captured instead of leaving the recording unstoppable.
+ void this.finalizeBatchRecording(null);
+ return true;
+ }
return false;
}
@@ -901,49 +1082,114 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
this._silenceCtx?.close().catch(() => {});
this._silenceCtx = null;
this._silenceAnalyser = null;
+ this._silenceSource = null;
}
cancelRecording() {
+ this.micRecovery.stop();
+ if (this._rotatingBatchRecorder) {
+ this._cancelRequestedDuringMicRecovery = true;
+ return true;
+ }
if (this.mediaRecorder && this.mediaRecorder.state === "recording") {
+ const recorder = this.mediaRecorder;
+ const discarded = this.takeDiscardedBatchSnapshot();
this.mediaRecorder.onstop = () => {
- this.teardownSpeechGate();
- this._localSpeechGateState = null;
-
- const durationSeconds = this.recordingStartTime
- ? (Date.now() - this.recordingStartTime) / 1000
- : null;
- const shouldSave =
- shouldSaveDiscardedRecording(getSettings(), durationSeconds) &&
- this.audioChunks.length > 0;
- const blob = shouldSave
- ? new Blob(this.audioChunks, { type: this.recordingMimeType })
- : null;
-
- this.cleanupPreview({ dismiss: true });
- this.isRecording = false;
- this.isProcessing = false;
- this.audioChunks = [];
- this.recordingStartTime = null;
- this.onStateChange?.({ isRecording: false, isProcessing: false });
-
- if (blob) {
- this.saveDiscardedTranscription(blob, durationSeconds).catch((err) => {
- logger.warn("Failed to save discarded transcription", { error: err.message }, "audio");
- });
- }
+ recorder.stream?.getTracks().forEach((track) => track.stop());
+ this.persistDiscardedBatchRecording(discarded);
};
- this.mediaRecorder.stop();
+ // Detach from manager state before recorder.stop(): its final
+ // dataavailable/onstop land async and must not block or observe the
+ // next recording.
+ this.resetDiscardedBatchRecordingState();
+
+ recorder.stop();
- if (this.mediaRecorder.stream) {
- this.mediaRecorder.stream.getTracks().forEach((track) => track.stop());
+ if (recorder.stream) {
+ recorder.stream.getTracks().forEach((track) => track.stop());
}
return true;
}
+ if (this.isRecording && !this.isStreaming) {
+ // The mic died mid-recovery, so no live recorder exists; discard what was
+ // captured instead of leaving the recording uncancelable.
+ this.discardBatchRecording();
+ return true;
+ }
return false;
}
+ discardBatchRecording() {
+ const discarded = this.takeDiscardedBatchSnapshot();
+ this.resetDiscardedBatchRecordingState();
+ this.persistDiscardedBatchRecording(discarded);
+ }
+
+ takeDiscardedBatchSnapshot() {
+ return {
+ durationSeconds: this.recordingStartTime
+ ? (Date.now() - this.recordingStartTime) / 1000
+ : null,
+ chunks: this.audioChunks,
+ segments: this._batchSegments,
+ mimeType: this.recordingMimeType,
+ };
+ }
+
+ resetDiscardedBatchRecordingState() {
+ this.teardownSpeechGate();
+ this._localSpeechGateState = null;
+
+ this.cleanupPreview({ dismiss: true });
+ this.isRecording = false;
+ this.isProcessing = false;
+ this.mediaRecorder = null;
+ this.audioChunks = [];
+ this._batchSegments = [];
+ this.recordingStartTime = null;
+ this.onStateChange?.({ isRecording: false, isProcessing: false });
+ }
+
+ persistDiscardedBatchRecording({ durationSeconds, chunks, segments, mimeType }) {
+ // This must run after MediaRecorder's final dataavailable event, so decide
+ // whether to retain the discarded audio from the snapshot rather than live
+ // manager state (which may already belong to a new recording).
+ const shouldSave =
+ shouldSaveDiscardedRecording(getSettings(), durationSeconds) &&
+ (chunks.length > 0 || segments.length > 0);
+ if (shouldSave) {
+ // Assemble and save in the background — the merge crosses IPC into FFmpeg
+ // and must not delay the recorder becoming available again.
+ void (async () => {
+ try {
+ const current = new Blob(chunks, { type: mimeType });
+ const blob = await this.mergeRecordedSegments([...segments, current]);
+ if (blob) await this.saveDiscardedTranscription(blob, durationSeconds);
+ } catch (error) {
+ const fallback = this.getLargestRecordedSegment([
+ ...segments,
+ new Blob(chunks, { type: mimeType }),
+ ]);
+ if (fallback) {
+ try {
+ await this.saveDiscardedTranscription(fallback, durationSeconds);
+ } catch (fallbackError) {
+ logger.warn(
+ "Failed to save discarded recording fallback",
+ { error: fallbackError.message },
+ "audio"
+ );
+ }
+ return;
+ }
+ logger.warn("Failed to save discarded recording", { error: error.message }, "audio");
+ }
+ })();
+ }
+ }
+
cancelProcessing() {
if (this.isProcessing) {
this.isProcessing = false;
@@ -2903,6 +3149,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
isProcessing: this.isProcessing,
isStreaming: this.isStreaming,
isStreamingStartInProgress: this.streamingStartInProgress,
+ micCaptureStatus: this.micCaptureStatus,
};
}
@@ -3053,6 +3300,73 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
return this.persistentAudioContext;
}
+ startStreamingFallbackRecorder(stream) {
+ try {
+ const chunks = [];
+ const recorder = new MediaRecorder(stream);
+ recorder.ondataavailable = (event) => {
+ if (event.data?.size > 0) chunks.push(event.data);
+ };
+ recorder.start(RECORDING_TIMESLICE_MS);
+ this.streamingFallbackRecorder = recorder;
+ this.streamingFallbackChunks = chunks;
+ return recorder;
+ } catch (error) {
+ logger.debug("Fallback recorder failed to start", { error: error.message }, "streaming");
+ this.streamingFallbackRecorder = null;
+ return null;
+ }
+ }
+
+ async finishStreamingFallbackSegment() {
+ const recorder = this.streamingFallbackRecorder;
+ if (!recorder) return null;
+ const chunks = this.streamingFallbackChunks;
+ const collect = () => new Blob(chunks, { type: recorder.mimeType || "audio/webm" });
+ let blob;
+ if (recorder.state === "recording") {
+ blob = await new Promise((resolve) => {
+ recorder.onstop = () => resolve(collect());
+ recorder.stop();
+ });
+ } else {
+ // The recorder auto-stops when its track dies; its chunks still hold the
+ // audio captured up to that point.
+ blob = collect();
+ }
+ this.streamingFallbackRecorder = null;
+ this.streamingFallbackChunks = [];
+ if (blob?.size > 0) this._streamingFallbackSegments.push(blob);
+ return blob;
+ }
+
+ async replaceStreamingMic(replacement, previous) {
+ if (!this.streamingProcessor || !this.streamingAudioContext) {
+ throw new Error("Streaming audio pipeline is unavailable");
+ }
+ const swap = (async () => {
+ const nextSource = this.streamingAudioContext.createMediaStreamSource(replacement);
+ nextSource.connect(this.streamingProcessor);
+ this.streamingSource?.disconnect();
+ this.streamingSource = nextSource;
+ await this.finishStreamingFallbackSegment();
+ if (!this.isStreaming || !this.isRecording) {
+ throw new Error("Streaming stopped during microphone recovery");
+ }
+ this.startStreamingFallbackRecorder(replacement);
+ previous?.getTracks().forEach((track) => track.stop());
+ this.streamingStream = replacement;
+ })();
+ // Expose the swap so stopStreamingRecording can wait for it instead of
+ // racing it (losing the newest fallback segment / orphaning a recorder).
+ this._streamingMicSwapPromise = swap.catch(() => {});
+ try {
+ await swap;
+ } finally {
+ this._streamingMicSwapPromise = null;
+ }
+ }
+
async startStreamingRecording(forceDefaultMic = false) {
try {
if (this.streamingStartInProgress) {
@@ -3095,18 +3409,9 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
);
}
- // Start fallback recorder in case streaming produces no results
- try {
- this.streamingFallbackChunks = [];
- this.streamingFallbackRecorder = new MediaRecorder(stream);
- this.streamingFallbackRecorder.ondataavailable = (e) => {
- if (e.data.size > 0) this.streamingFallbackChunks.push(e.data);
- };
- this.streamingFallbackRecorder.start();
- } catch (e) {
- logger.debug("Fallback recorder failed to start", { error: e.message }, "streaming");
- this.streamingFallbackRecorder = null;
- }
+ // Start fallback recorder in case streaming produces no results.
+ this._streamingFallbackSegments = [];
+ this.startStreamingFallbackRecorder(stream);
// 2. Set up audio pipeline so frames flow the instant WebSocket is ready.
// Frames sent before the connection is open are buffered (bounded) by
@@ -3187,6 +3492,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
this.isRecording = true;
this.recordingStartTime = Date.now();
this.onStateChange?.({ isRecording: true, isProcessing: false, isStreaming: true });
+ await this.beginMicRecovery(stream);
// 4. Connect WebSocket — audio is already flowing from the pipeline above,
// so Deepgram receives data immediately (no idle timeout).
@@ -3334,6 +3640,10 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
}
if (!this.isStreaming) return false;
+ this.micRecovery.stop();
+ // Let an in-flight mic swap settle so its fallback segment isn't lost and
+ // its replacement recorder doesn't outlive this stop.
+ if (this._streamingMicSwapPromise) await this._streamingMicSwapPromise;
const durationSeconds = this.recordingStartTime
? (Date.now() - this.recordingStartTime) / 1000
@@ -3370,20 +3680,23 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
// Stop fallback recorder before stopping media tracks
let fallbackBlob = null;
- if (this.streamingFallbackRecorder?.state === "recording") {
- fallbackBlob = await new Promise((resolve) => {
- this.streamingFallbackRecorder.onstop = () => {
- const mimeType = this.streamingFallbackRecorder.mimeType || "audio/webm";
- resolve(new Blob(this.streamingFallbackChunks, { type: mimeType }));
- };
- this.streamingFallbackRecorder.stop();
- });
+ await this.finishStreamingFallbackSegment();
+ try {
+ fallbackBlob = await this.mergeRecordedSegments(this._streamingFallbackSegments);
+ } catch (error) {
+ logger.warn(
+ "Failed to merge streaming fallback audio",
+ { error: error.message },
+ "streaming"
+ );
+ fallbackBlob = this.getLargestRecordedSegment(this._streamingFallbackSegments);
}
if (fallbackBlob) {
this.lastAudioBlob = fallbackBlob;
}
this.streamingFallbackRecorder = null;
this.streamingFallbackChunks = [];
+ this._streamingFallbackSegments = [];
if (this.streamingStream) {
this.streamingStream.getTracks().forEach((track) => track.stop());
@@ -3788,11 +4101,13 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
}
async cleanupStreaming() {
+ this.micRecovery.stop();
this.cleanupStreamingAudio();
this.cleanupStreamingListeners();
}
cleanup() {
+ this.micRecovery.stop();
this.lastAudioBlob = null;
this.lastAudioMetadata = null;
if (this.isStreaming) {
diff --git a/src/helpers/ffmpegUtils.js b/src/helpers/ffmpegUtils.js
index f2a8d4e7a..04cd0f050 100644
--- a/src/helpers/ffmpegUtils.js
+++ b/src/helpers/ffmpegUtils.js
@@ -1,5 +1,6 @@
const { spawn } = require("child_process");
const fs = require("fs");
+const os = require("os");
const path = require("path");
const debugLogger = require("./debugLogger");
@@ -346,6 +347,79 @@ function splitAudioFile(inputPath, outputDir, options = {}) {
});
}
+async function mergeAudioSegments(segments) {
+ if (!Array.isArray(segments) || segments.length === 0) {
+ throw new Error("At least one audio segment is required");
+ }
+ if (segments.length === 1) return Buffer.from(segments[0].buffer);
+
+ const ffmpegPath = getFFmpegPath();
+ if (!ffmpegPath) throw new Error("FFmpeg not found - required for audio segment recovery");
+
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-audio-merge-"));
+ const outputPath = path.join(tempDir, "merged.webm");
+ try {
+ const inputPaths = segments.map((segment, index) => {
+ const mimeType = segment.mimeType || "audio/webm";
+ const extension = mimeType.includes("ogg")
+ ? "ogg"
+ : mimeType.includes("mp4")
+ ? "m4a"
+ : "webm";
+ const inputPath = path.join(tempDir, `segment-${index}.${extension}`);
+ fs.writeFileSync(inputPath, Buffer.from(segment.buffer));
+ return inputPath;
+ });
+
+ const filters = inputPaths.map(
+ (_, index) =>
+ `[${index}:a]aresample=16000,aformat=sample_fmts=fltp:channel_layouts=mono[s${index}]`
+ );
+ filters.push(
+ `${inputPaths.map((_, index) => `[s${index}]`).join("")}concat=n=${inputPaths.length}:v=0:a=1[out]`
+ );
+
+ await new Promise((resolve, reject) => {
+ const args = inputPaths.flatMap((inputPath) => ["-i", inputPath]);
+ args.push(
+ "-filter_complex",
+ filters.join(";"),
+ "-map",
+ "[out]",
+ "-c:a",
+ "libopus",
+ "-b:a",
+ "64k",
+ "-y",
+ outputPath
+ );
+ const proc = spawn(ffmpegPath, args, {
+ stdio: ["ignore", "pipe", "pipe"],
+ windowsHide: true,
+ });
+ let stderr = "";
+ proc.stderr.on("data", (data) => {
+ stderr += data.toString();
+ });
+ proc.on("error", (error) => reject(new Error(`FFmpeg process error: ${error.message}`)));
+ proc.on("close", (code) => {
+ if (code !== 0) {
+ const preview = stderr.slice(-500).trim();
+ reject(
+ new Error(`FFmpeg audio merge exited with code ${code}${preview ? `: ${preview}` : ""}`)
+ );
+ return;
+ }
+ resolve();
+ });
+ });
+
+ return fs.readFileSync(outputPath);
+ } finally {
+ fs.rmSync(tempDir, { recursive: true, force: true });
+ }
+}
+
function clearCache() {
cachedFFmpegPath = null;
}
@@ -358,5 +432,6 @@ module.exports = {
splitAudioFile,
wavToFloat32Samples,
computeFloat32RMS,
+ mergeAudioSegments,
clearCache,
};
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index e38555de7..2fd7afcfc 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -966,6 +966,32 @@ class IPCHandlers {
return result;
});
+ ipcMain.handle("merge-audio-segments", async (_event, segments) => {
+ try {
+ if (!Array.isArray(segments) || segments.length < 2 || segments.length > 100) {
+ throw new Error("Invalid audio segment count");
+ }
+ const normalized = segments.map((segment) => {
+ if (!segment?.buffer || typeof segment.mimeType !== "string") {
+ throw new Error("Invalid audio segment");
+ }
+ return { buffer: Buffer.from(segment.buffer), mimeType: segment.mimeType };
+ });
+ const { mergeAudioSegments } = require("./ffmpegUtils");
+ const buffer = await mergeAudioSegments(normalized);
+ // Slice to a real ArrayBuffer: Buffers sent over IPC arrive as Uint8Array,
+ // and pooled Buffers share a larger underlying allocation.
+ return {
+ success: true,
+ buffer: buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength),
+ mimeType: "audio/webm",
+ };
+ } catch (error) {
+ debugLogger.error("Failed to merge recovered audio segments", { error: error.message });
+ return { success: false, error: error.message };
+ }
+ });
+
ipcMain.handle("get-audio-path", async (event, id) => {
return this.audioStorageManager.getAudioPath(id);
});
diff --git a/src/helpers/micSelectionRecovery.js b/src/helpers/micSelectionRecovery.js
index 25fb176dc..9537c07a1 100644
--- a/src/helpers/micSelectionRecovery.js
+++ b/src/helpers/micSelectionRecovery.js
@@ -2,6 +2,11 @@ import { getSettings } from "../stores/settingsStore";
import logger from "../utils/logger";
import { resolveMicDeviceSelection } from "./micDeviceSelection";
+// Chromium's "default" pseudo-device is a follow-the-OS-default selection, not a pin.
+export function followsSystemDefaultMic({ preferBuiltInMic, selectedMicDeviceId }) {
+ return !preferBuiltInMic && (!selectedMicDeviceId || selectedMicDeviceId === "default");
+}
+
/**
* Resolve the saved mic selection against live devices, persisting a remap or
* label backfill so the preference survives Chromium device-ID rotation.
diff --git a/src/hooks/useAudioRecording.js b/src/hooks/useAudioRecording.js
index 4e4e2240c..0f43acfc6 100644
--- a/src/hooks/useAudioRecording.js
+++ b/src/hooks/useAudioRecording.js
@@ -13,12 +13,14 @@ export const useAudioRecording = (toast, options = {}) => {
const [isRecording, setIsRecording] = useState(false);
const [isProcessing, setIsProcessing] = useState(false);
const [isStreaming, setIsStreaming] = useState(false);
+ const [micCaptureStatus, setMicCaptureStatus] = useState("inactive");
const [transcript, setTranscript] = useState("");
const [partialTranscript, setPartialTranscript] = useState("");
const audioManagerRef = useRef(null);
const startLockRef = useRef(false);
const stopLockRef = useRef(false);
const wasRecordingRef = useRef(false);
+ const wasMicUnavailableRef = useRef(false);
const { onToggle } = options;
const performStartRecording = useCallback(
@@ -96,7 +98,7 @@ export const useAudioRecording = (toast, options = {}) => {
audioManagerRef.current = new AudioManager();
audioManagerRef.current.setCallbacks({
- onStateChange: ({ isRecording, isProcessing, isStreaming }) => {
+ onStateChange: ({ isRecording, isProcessing, isStreaming, micCaptureStatus }) => {
if (!isRecording) {
window.electronAPI?.unregisterCancelHotkey?.();
// Resume media the instant recording ends, not after transcription.
@@ -108,6 +110,27 @@ export const useAudioRecording = (toast, options = {}) => {
setIsRecording(isRecording);
setIsProcessing(isProcessing);
setIsStreaming(isStreaming ?? false);
+ if (micCaptureStatus) {
+ setMicCaptureStatus(micCaptureStatus);
+ const unavailable = micCaptureStatus === "unavailable";
+ if (unavailable && !wasMicUnavailableRef.current) {
+ wasMicUnavailableRef.current = true;
+ toast({
+ title: t("hooks.audioRecording.micDisconnected.title"),
+ description: t("hooks.audioRecording.micDisconnected.description"),
+ variant: "default",
+ });
+ } else if (micCaptureStatus === "active" && wasMicUnavailableRef.current) {
+ wasMicUnavailableRef.current = false;
+ toast({
+ title: t("hooks.audioRecording.micRestored.title"),
+ description: t("hooks.audioRecording.micRestored.description"),
+ variant: "default",
+ });
+ } else if (micCaptureStatus === "inactive") {
+ wasMicUnavailableRef.current = false;
+ }
+ }
if (!isStreaming) {
setPartialTranscript("");
}
@@ -347,6 +370,7 @@ export const useAudioRecording = (toast, options = {}) => {
isRecording,
isProcessing,
isStreaming,
+ micCaptureStatus,
transcript,
partialTranscript,
startRecording: performStartRecording,
diff --git a/src/locales/de/translation.json b/src/locales/de/translation.json
index 29aa542ef..000b49d35 100644
--- a/src/locales/de/translation.json
+++ b/src/locales/de/translation.json
@@ -571,6 +571,15 @@
"title": "Kein Audio erkannt",
"description": "Die Aufnahme enthielt kein erkennbares Audio. Bitte versuchen Sie es erneut."
},
+ "micDisconnected": {
+ "title": "Mikrofon getrennt",
+ "description": "Die Aufnahme ist weiterhin aktiv und wird fortgesetzt, sobald ein Mikrofon verfügbar ist.",
+ "meetingDescription": "Das Meeting zeichnet weiterhin Systemaudio auf und setzt die Mikrofonaufnahme automatisch fort."
+ },
+ "micRestored": {
+ "title": "Mikrofon wiederhergestellt",
+ "description": "Die Audioaufnahme wurde fortgesetzt."
+ },
"partialTranscription": {
"title": "Unvollständige Transkription",
"description": "Ein Teil der Aufnahme konnte nicht transkribiert werden."
@@ -2227,7 +2236,8 @@
"back": "Zurück"
},
"meetingPill": {
- "returnToNote": "Zurück zur Aufnahme"
+ "returnToNote": "Zurück zur Aufnahme",
+ "waitingForMicrophone": "Warte auf Mikrofon"
},
"context": {
"moveToFolder": "In Ordner verschieben",
@@ -2541,7 +2551,8 @@
"hotkeyToSpeak": "{{hotkey}} zum Sprechen",
"recording": "Aufnahme...",
"processing": "Verarbeitung...",
- "clickToSpeak": "Klicken zum Sprechen"
+ "clickToSpeak": "Klicken zum Sprechen",
+ "waitingForMicrophone": "Warte auf Mikrofon…"
},
"buttons": {
"cancelRecording": "Aufnahme abbrechen",
diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json
index 6c2ce61c6..f15c9f9e3 100644
--- a/src/locales/en/translation.json
+++ b/src/locales/en/translation.json
@@ -571,6 +571,15 @@
"title": "No Audio Detected",
"description": "The recording contained no detectable audio. Please try again."
},
+ "micDisconnected": {
+ "title": "Microphone disconnected",
+ "description": "Recording is still active and will resume when a microphone is available.",
+ "meetingDescription": "The meeting is still recording system audio and will resume microphone capture automatically."
+ },
+ "micRestored": {
+ "title": "Microphone restored",
+ "description": "Audio capture has resumed."
+ },
"partialTranscription": {
"title": "Partial Transcription",
"description": "Part of the recording couldn't be transcribed."
@@ -2428,7 +2437,8 @@
"back": "Back"
},
"meetingPill": {
- "returnToNote": "Return to recording"
+ "returnToNote": "Return to recording",
+ "waitingForMicrophone": "Waiting for microphone"
},
"empty": {
"title": "No notes here yet",
@@ -2677,7 +2687,8 @@
"hotkeyToSpeak": "{{hotkey}} to talk",
"recording": "Recording...",
"processing": "Processing...",
- "clickToSpeak": "Click to speak"
+ "clickToSpeak": "Click to speak",
+ "waitingForMicrophone": "Waiting for microphone…"
},
"buttons": {
"cancelRecording": "Cancel recording",
diff --git a/src/locales/es/translation.json b/src/locales/es/translation.json
index 3a53b2cf8..dae209f8f 100644
--- a/src/locales/es/translation.json
+++ b/src/locales/es/translation.json
@@ -571,6 +571,15 @@
"title": "No se detectó audio",
"description": "La grabación no contiene audio detectable. Inténtalo de nuevo."
},
+ "micDisconnected": {
+ "title": "Micrófono desconectado",
+ "description": "La grabación sigue activa y se reanudará cuando haya un micrófono disponible.",
+ "meetingDescription": "La reunión sigue grabando el audio del sistema y reanudará la captura del micrófono automáticamente."
+ },
+ "micRestored": {
+ "title": "Micrófono restaurado",
+ "description": "La captura de audio se ha reanudado."
+ },
"partialTranscription": {
"title": "Transcripción parcial",
"description": "No se pudo transcribir una parte de la grabación."
@@ -2275,7 +2284,8 @@
"back": "Atrás"
},
"meetingPill": {
- "returnToNote": "Volver a la grabación"
+ "returnToNote": "Volver a la grabación",
+ "waitingForMicrophone": "Esperando el micrófono"
},
"context": {
"moveToFolder": "Mover a carpeta",
@@ -2589,7 +2599,8 @@
"hotkeyToSpeak": "{{hotkey}} para hablar",
"recording": "Grabando...",
"processing": "Procesando...",
- "clickToSpeak": "Haz clic para hablar"
+ "clickToSpeak": "Haz clic para hablar",
+ "waitingForMicrophone": "Esperando el micrófono…"
},
"buttons": {
"cancelRecording": "Cancelar grabación",
diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.json
index 6d17bbb0e..a8c88a8a6 100644
--- a/src/locales/fr/translation.json
+++ b/src/locales/fr/translation.json
@@ -571,6 +571,15 @@
"title": "Aucun audio détecté",
"description": "L'enregistrement ne contient pas d'audio détectable. Réessayez."
},
+ "micDisconnected": {
+ "title": "Microphone déconnecté",
+ "description": "L'enregistrement est toujours actif et reprendra dès qu'un microphone sera disponible.",
+ "meetingDescription": "La réunion continue d'enregistrer l'audio système et reprendra automatiquement la capture du microphone."
+ },
+ "micRestored": {
+ "title": "Microphone rétabli",
+ "description": "La capture audio a repris."
+ },
"partialTranscription": {
"title": "Transcription partielle",
"description": "Une partie de l'enregistrement n'a pas pu être transcrite."
@@ -2340,7 +2349,8 @@
"back": "Retour"
},
"meetingPill": {
- "returnToNote": "Revenir à l'enregistrement"
+ "returnToNote": "Revenir à l'enregistrement",
+ "waitingForMicrophone": "En attente du microphone"
},
"empty": {
"title": "Aucune note ici pour l'instant",
@@ -2589,7 +2599,8 @@
"hotkeyToSpeak": "{{hotkey}} pour parler",
"recording": "Enregistrement...",
"processing": "Traitement...",
- "clickToSpeak": "Cliquez pour parler"
+ "clickToSpeak": "Cliquez pour parler",
+ "waitingForMicrophone": "En attente du microphone…"
},
"buttons": {
"cancelRecording": "Annuler l’enregistrement",
diff --git a/src/locales/it/translation.json b/src/locales/it/translation.json
index 69bcc1b9f..92b58a183 100644
--- a/src/locales/it/translation.json
+++ b/src/locales/it/translation.json
@@ -571,6 +571,15 @@
"title": "Nessun audio rilevato",
"description": "La registrazione non contiene audio rilevabile. Riprova."
},
+ "micDisconnected": {
+ "title": "Microfono disconnesso",
+ "description": "La registrazione è ancora attiva e riprenderà quando sarà disponibile un microfono.",
+ "meetingDescription": "La riunione continua a registrare l'audio di sistema e riprenderà automaticamente l'acquisizione dal microfono."
+ },
+ "micRestored": {
+ "title": "Microfono ripristinato",
+ "description": "L'acquisizione audio è ripresa."
+ },
"partialTranscription": {
"title": "Trascrizione parziale",
"description": "Non è stato possibile trascrivere una parte della registrazione."
@@ -2227,7 +2236,8 @@
"back": "Indietro"
},
"meetingPill": {
- "returnToNote": "Torna alla registrazione"
+ "returnToNote": "Torna alla registrazione",
+ "waitingForMicrophone": "In attesa del microfono"
},
"context": {
"moveToFolder": "Sposta nella cartella",
@@ -2541,7 +2551,8 @@
"hotkeyToSpeak": "{{hotkey}} per parlare",
"recording": "Registrazione...",
"processing": "Elaborazione...",
- "clickToSpeak": "Clicca per parlare"
+ "clickToSpeak": "Clicca per parlare",
+ "waitingForMicrophone": "In attesa del microfono…"
},
"buttons": {
"cancelRecording": "Annulla registrazione",
diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.json
index ec71459d8..c7e6972c0 100644
--- a/src/locales/ja/translation.json
+++ b/src/locales/ja/translation.json
@@ -571,6 +571,15 @@
"title": "音声が検出されませんでした",
"description": "録音に音声が含まれていませんでした。もう一度お試しください。"
},
+ "micDisconnected": {
+ "title": "マイクが切断されました",
+ "description": "録音は継続中です。マイクが利用可能になると自動的に再開されます。",
+ "meetingDescription": "ミーティングはシステム音声の録音を継続しており、マイクの録音は自動的に再開されます。"
+ },
+ "micRestored": {
+ "title": "マイクが復旧しました",
+ "description": "音声の録音を再開しました。"
+ },
"partialTranscription": {
"title": "部分的な文字起こし",
"description": "録音の一部を文字起こしできませんでした。"
@@ -2211,7 +2220,8 @@
"back": "戻る"
},
"meetingPill": {
- "returnToNote": "録音に戻る"
+ "returnToNote": "録音に戻る",
+ "waitingForMicrophone": "マイクを待っています"
},
"onboarding": {
"llm": {
@@ -2541,7 +2551,8 @@
"hotkeyToSpeak": "{{hotkey}} で話す",
"recording": "録音中...",
"processing": "処理中...",
- "clickToSpeak": "クリックして話す"
+ "clickToSpeak": "クリックして話す",
+ "waitingForMicrophone": "マイクを待っています…"
},
"buttons": {
"cancelRecording": "録音をキャンセル",
diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.json
index 44757a301..0329a6bdf 100644
--- a/src/locales/pt/translation.json
+++ b/src/locales/pt/translation.json
@@ -550,6 +550,15 @@
"title": "Nenhum áudio detectado",
"description": "A gravação não contém áudio detectável. Tente novamente."
},
+ "micDisconnected": {
+ "title": "Microfone desconectado",
+ "description": "A gravação continua ativa e será retomada quando um microfone estiver disponível.",
+ "meetingDescription": "A reunião continua gravando o áudio do sistema e retomará a captura do microfone automaticamente."
+ },
+ "micRestored": {
+ "title": "Microfone restaurado",
+ "description": "A captura de áudio foi retomada."
+ },
"partialTranscription": {
"title": "Transcrição parcial",
"description": "Não foi possível transcrever parte da gravação."
@@ -2227,7 +2236,8 @@
"back": "Voltar"
},
"meetingPill": {
- "returnToNote": "Voltar à gravação"
+ "returnToNote": "Voltar à gravação",
+ "waitingForMicrophone": "Aguardando microfone"
},
"context": {
"moveToFolder": "Mover para pasta",
@@ -2541,7 +2551,8 @@
"hotkeyToSpeak": "{{hotkey}} para falar",
"recording": "Gravando...",
"processing": "Processando...",
- "clickToSpeak": "Clique para falar"
+ "clickToSpeak": "Clique para falar",
+ "waitingForMicrophone": "Aguardando microfone…"
},
"buttons": {
"cancelRecording": "Cancelar gravação",
diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.json
index e6100b76a..cce1cd683 100644
--- a/src/locales/ru/translation.json
+++ b/src/locales/ru/translation.json
@@ -571,6 +571,15 @@
"title": "Звук не обнаружен",
"description": "В записи не обнаружен звук. Попробуйте ещё раз."
},
+ "micDisconnected": {
+ "title": "Микрофон отключён",
+ "description": "Запись всё ещё активна и возобновится, когда микрофон станет доступен.",
+ "meetingDescription": "Встреча продолжает запись системного звука; запись с микрофона возобновится автоматически."
+ },
+ "micRestored": {
+ "title": "Микрофон восстановлен",
+ "description": "Захват звука возобновлён."
+ },
"partialTranscription": {
"title": "Частичная транскрипция",
"description": "Не удалось транскрибировать часть записи."
@@ -2227,7 +2236,8 @@
"back": "Назад"
},
"meetingPill": {
- "returnToNote": "Вернуться к записи"
+ "returnToNote": "Вернуться к записи",
+ "waitingForMicrophone": "Ожидание микрофона"
},
"context": {
"moveToFolder": "Переместить в папку",
@@ -2545,7 +2555,8 @@
"hotkeyToSpeak": "{{hotkey}} для записи",
"recording": "Запись...",
"processing": "Обработка...",
- "clickToSpeak": "Нажмите для записи"
+ "clickToSpeak": "Нажмите для записи",
+ "waitingForMicrophone": "Ожидание микрофона…"
},
"buttons": {
"cancelRecording": "Отменить запись",
diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.json
index e860d4352..9216d642c 100644
--- a/src/locales/zh-CN/translation.json
+++ b/src/locales/zh-CN/translation.json
@@ -571,6 +571,15 @@
"title": "未检测到音频",
"description": "录音中未检测到音频,请重试。"
},
+ "micDisconnected": {
+ "title": "麦克风已断开",
+ "description": "录音仍在进行中,麦克风可用后将自动恢复。",
+ "meetingDescription": "会议仍在录制系统音频,麦克风录制将自动恢复。"
+ },
+ "micRestored": {
+ "title": "麦克风已恢复",
+ "description": "音频采集已恢复。"
+ },
"partialTranscription": {
"title": "部分转录",
"description": "部分录音内容无法转录。"
@@ -2227,7 +2236,8 @@
"back": "返回"
},
"meetingPill": {
- "returnToNote": "返回到录音"
+ "returnToNote": "返回到录音",
+ "waitingForMicrophone": "等待麦克风"
},
"context": {
"moveToFolder": "移动到文件夹",
@@ -2541,7 +2551,8 @@
"hotkeyToSpeak": "{{hotkey}} 说话",
"recording": "录音中...",
"processing": "处理中...",
- "clickToSpeak": "点击开始说话"
+ "clickToSpeak": "点击开始说话",
+ "waitingForMicrophone": "等待麦克风…"
},
"buttons": {
"cancelRecording": "取消录音",
diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.json
index caa2a2599..5c120286f 100644
--- a/src/locales/zh-TW/translation.json
+++ b/src/locales/zh-TW/translation.json
@@ -571,6 +571,15 @@
"title": "未偵測到音訊",
"description": "錄音中未偵測到聲音。請再試一次。"
},
+ "micDisconnected": {
+ "title": "麥克風已中斷",
+ "description": "錄音仍在進行中,麥克風可用後將自動恢復。",
+ "meetingDescription": "會議仍在錄製系統音訊,麥克風錄製將自動恢復。"
+ },
+ "micRestored": {
+ "title": "麥克風已恢復",
+ "description": "音訊擷取已恢復。"
+ },
"partialTranscription": {
"title": "部分轉錄",
"description": "部分錄音內容無法轉錄。"
@@ -2227,7 +2236,8 @@
"back": "返回"
},
"meetingPill": {
- "returnToNote": "返回到錄音"
+ "returnToNote": "返回到錄音",
+ "waitingForMicrophone": "等待麥克風"
},
"context": {
"moveToFolder": "移動到資料夾",
@@ -2541,7 +2551,8 @@
"hotkeyToSpeak": "{{hotkey}} 說話",
"recording": "錄音中...",
"processing": "處理中...",
- "clickToSpeak": "點擊開始說話"
+ "clickToSpeak": "點擊開始說話",
+ "waitingForMicrophone": "等待麥克風…"
},
"buttons": {
"cancelRecording": "取消錄音",
diff --git a/src/stores/meetingRecordingStore.ts b/src/stores/meetingRecordingStore.ts
index c15dde9e3..22b95c02a 100644
--- a/src/stores/meetingRecordingStore.ts
+++ b/src/stores/meetingRecordingStore.ts
@@ -2,7 +2,11 @@ import { create } from "zustand";
import { getSettings, selectResolvedMeetingTranscription } from "./settingsStore";
import { useStreamingProvidersStore } from "./streamingProvidersStore";
import { isBuiltInMicrophone } from "../utils/audioDeviceUtils";
-import { reconcileSavedMicSelection } from "../helpers/micSelectionRecovery";
+import {
+ followsSystemDefaultMic,
+ reconcileSavedMicSelection,
+} from "../helpers/micSelectionRecovery";
+import { ActiveMicRecoveryController } from "../helpers/activeMicRecovery";
import { getBaseLanguageCode } from "../utils/languageSupport";
import type { SystemAudioAccessResult, SystemAudioStrategy } from "../types/electron";
import {
@@ -72,6 +76,7 @@ interface MeetingRecordingState {
userTouchedStepper: boolean;
error: string | null;
currentMicLevel: number;
+ micCaptureStatus: "inactive" | "active" | "reconnecting" | "unavailable";
windowWidth: number;
}
@@ -419,6 +424,7 @@ let micSource: MediaStreamAudioSourceNode | null = null;
let micProcessor: AudioWorkletNode | null = null;
let micStream: MediaStream | null = null;
let micAnalyser: AnalyserNode | null = null;
+let micRecovery: ActiveMicRecoveryController | null = null;
let systemContext: AudioContext | null = null;
let systemSource: MediaStreamAudioSourceNode | null = null;
let systemProcessor: AudioWorkletNode | null = null;
@@ -455,6 +461,7 @@ export const useMeetingRecordingStore = create<MeetingRecordingState>()(() => ({
userTouchedStepper: false,
error: null,
currentMicLevel: 0,
+ micCaptureStatus: "inactive",
windowWidth: typeof window !== "undefined" ? window.innerWidth : SIDE_PANEL_BREAKPOINT_PX,
}));
@@ -623,6 +630,8 @@ function assignProvisionalSpeaker(segment: TranscriptSegment): TranscriptSegment
}
async function cleanup(): Promise<void> {
+ micRecovery?.stop();
+ micRecovery = null;
await flushAndDisconnectProcessor(micProcessor);
micProcessor = null;
@@ -761,6 +770,7 @@ export async function startRecording(args: StartRecordingArgs): Promise<void> {
systemPartialSpeakerName: null,
diarizationSessionId: null,
error: null,
+ micCaptureStatus: "inactive",
});
isRecordingFlag = true;
@@ -1106,6 +1116,40 @@ export async function startRecording(args: StartRecordingArgs): Promise<void> {
if (micPipelinePromise) {
await micPipelinePromise;
+ micRecovery = new ActiveMicRecoveryController({
+ mediaDevices: navigator.mediaDevices,
+ acquire: async () => {
+ try {
+ return await navigator.mediaDevices.getUserMedia(await getMeetingMicConstraints());
+ } catch {
+ return navigator.mediaDevices.getUserMedia({
+ audio: MEETING_MIC_PRIMARY_AUDIO_CONSTRAINTS,
+ });
+ }
+ },
+ onStatusChange: (status) => {
+ useMeetingRecordingStore.setState({
+ micCaptureStatus: status,
+ ...(status === "active" ? {} : { currentMicLevel: 0 }),
+ });
+ },
+ onRecovered: async (replacement, previous) => {
+ if (!isRecordingFlag || !micContext || !micProcessor) {
+ throw new Error("Meeting recording is no longer active");
+ }
+ const nextSource = micContext.createMediaStreamSource(replacement);
+ nextSource.connect(micProcessor);
+ if (micAnalyser) nextSource.connect(micAnalyser);
+ micSource?.disconnect();
+ previous?.getTracks().forEach((track) => track.stop());
+ micSource = nextSource;
+ micStream = replacement;
+ logger.info("Meeting microphone capture recovered", {}, "meeting");
+ },
+ });
+ await micRecovery.start(micStream, {
+ followDefault: followsSystemDefaultMic(getSettings()),
+ });
}
if (systemCaptureResult.stream) {
diff --git a/src/types/electron.ts b/src/types/electron.ts
index ca978ac5b..bf743c87a 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -603,6 +603,12 @@ declare global {
audioBuffer: ArrayBuffer,
metadata?: { durationMs?: number; provider?: string; model?: string }
) => Promise<{ success: boolean; path?: string }>;
+ mergeAudioSegments: (
+ segments: Array<{ buffer: ArrayBuffer; mimeType: string }>
+ ) => Promise<
+ | { success: true; buffer: ArrayBuffer; mimeType: "audio/webm" }
+ | { success: false; error: string }
+ >;
getAudioPath: (id: number) => Promise<string | null>;
showAudioInFolder: (id: number) => Promise<{ success: boolean }>;
getAudioBuffer: (id: number) => Promise<ArrayBuffer | null>;
diff --git a/test/helpers/activeMicRecovery.test.js b/test/helpers/activeMicRecovery.test.js
new file mode 100644
index 000000000..acc3570fb
--- /dev/null
+++ b/test/helpers/activeMicRecovery.test.js
@@ -0,0 +1,240 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+class FakeTrack extends EventTarget {
+ constructor({ deviceId = "mic-1", groupId = "group-1", muted = false } = {}) {
+ super();
+ this.readyState = "live";
+ this.muted = muted;
+ this.settings = { deviceId, groupId };
+ this.stopped = false;
+ }
+
+ getSettings() {
+ return this.settings;
+ }
+
+ stop() {
+ this.stopped = true;
+ this.readyState = "ended";
+ }
+}
+
+class FakeStream {
+ constructor(track) {
+ this.track = track;
+ }
+
+ getAudioTracks() {
+ return this.track ? [this.track] : [];
+ }
+
+ getTracks() {
+ return this.getAudioTracks();
+ }
+}
+
+class FakeMediaDevices extends EventTarget {
+ constructor(devices) {
+ super();
+ this.devices = devices;
+ }
+
+ async enumerateDevices() {
+ return this.devices;
+ }
+
+ change(devices) {
+ this.devices = devices;
+ this.dispatchEvent(new Event("devicechange"));
+ }
+}
+
+const mic = (deviceId, groupId = deviceId, label = deviceId) => ({
+ kind: "audioinput",
+ deviceId,
+ groupId,
+ label,
+});
+
+const speaker = (deviceId) => ({
+ kind: "audiooutput",
+ deviceId,
+ groupId: deviceId,
+ label: deviceId,
+});
+const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
+
+test("filters output-only changes and keeps a healthy pinned microphone", async () => {
+ const { ActiveMicRecoveryController } = await import("../../src/helpers/activeMicRecovery.js");
+ const mediaDevices = new FakeMediaDevices([mic("mic-1")]);
+ const original = new FakeStream(new FakeTrack());
+ let acquired = 0;
+ const controller = new ActiveMicRecoveryController({
+ mediaDevices,
+ acquire: async () => {
+ acquired += 1;
+ return new FakeStream(new FakeTrack({ deviceId: "mic-2" }));
+ },
+ onRecovered: async () => {},
+ debounceMs: 1,
+ });
+ await controller.start(original, { followDefault: false });
+ mediaDevices.change([mic("mic-1"), speaker("speaker-2")]);
+ await delay(10);
+ assert.equal(acquired, 0);
+ controller.stop();
+});
+
+test("recovers when the system default input changes", async () => {
+ const { ActiveMicRecoveryController } = await import("../../src/helpers/activeMicRecovery.js");
+ const mediaDevices = new FakeMediaDevices([mic("default", "group-1", "Mic One")]);
+ const original = new FakeStream(new FakeTrack());
+ const replacement = new FakeStream(new FakeTrack({ deviceId: "mic-2", groupId: "group-2" }));
+ let recovered = null;
+ const statuses = [];
+ const controller = new ActiveMicRecoveryController({
+ mediaDevices,
+ acquire: async () => replacement,
+ onRecovered: async (stream) => {
+ recovered = stream;
+ },
+ onStatusChange: (status) => statuses.push(status),
+ debounceMs: 1,
+ });
+ await controller.start(original, { followDefault: true });
+ mediaDevices.change([mic("default", "group-2", "Mic Two")]);
+ await delay(10);
+ assert.equal(recovered, replacement);
+ assert.deepEqual(statuses.slice(-2), ["reconnecting", "active"]);
+ controller.stop();
+});
+
+test("track ended triggers recovery without waiting for devicechange", async () => {
+ const { ActiveMicRecoveryController } = await import("../../src/helpers/activeMicRecovery.js");
+ const mediaDevices = new FakeMediaDevices([mic("mic-1")]);
+ const track = new FakeTrack();
+ let acquired = 0;
+ const controller = new ActiveMicRecoveryController({
+ mediaDevices,
+ acquire: async () => {
+ acquired += 1;
+ return new FakeStream(new FakeTrack({ deviceId: "mic-2" }));
+ },
+ onRecovered: async () => {},
+ });
+ await controller.start(new FakeStream(track));
+ track.readyState = "ended";
+ track.dispatchEvent(new Event("ended"));
+ await delay(1);
+ assert.equal(acquired, 1);
+ controller.stop();
+});
+
+test("an unavailable microphone retries and later recovers", async () => {
+ const { ActiveMicRecoveryController } = await import("../../src/helpers/activeMicRecovery.js");
+ const mediaDevices = new FakeMediaDevices([mic("mic-1")]);
+ const track = new FakeTrack();
+ let attempts = 0;
+ const statuses = [];
+ const controller = new ActiveMicRecoveryController({
+ mediaDevices,
+ acquire: async () => {
+ attempts += 1;
+ if (attempts === 1) throw new Error("no mic");
+ return new FakeStream(new FakeTrack({ deviceId: "mic-2" }));
+ },
+ onRecovered: async () => {},
+ onStatusChange: (status) => statuses.push(status),
+ retryMs: 5,
+ });
+ await controller.start(new FakeStream(track));
+ track.readyState = "ended";
+ track.dispatchEvent(new Event("ended"));
+ await delay(20);
+ assert.equal(attempts, 2);
+ assert.ok(statuses.includes("unavailable"));
+ assert.equal(statuses.at(-1), "active");
+ controller.stop();
+});
+
+test("start() with an already-ended track recovers instead of reporting active", async () => {
+ const { ActiveMicRecoveryController } = await import("../../src/helpers/activeMicRecovery.js");
+ const mediaDevices = new FakeMediaDevices([mic("mic-1")]);
+ const track = new FakeTrack();
+ track.readyState = "ended";
+ let acquired = 0;
+ const statuses = [];
+ const controller = new ActiveMicRecoveryController({
+ mediaDevices,
+ acquire: async () => {
+ acquired += 1;
+ return new FakeStream(new FakeTrack({ deviceId: "mic-2" }));
+ },
+ onRecovered: async () => {},
+ onStatusChange: (status) => statuses.push(status),
+ });
+ await controller.start(new FakeStream(track));
+ await delay(5);
+ assert.equal(acquired, 1);
+ assert.equal(statuses.at(-1), "active");
+ controller.stop();
+});
+
+test("a stale recovery settling late cannot clobber a newer in-flight recovery", async () => {
+ const { ActiveMicRecoveryController } = await import("../../src/helpers/activeMicRecovery.js");
+ const mediaDevices = new FakeMediaDevices([mic("mic-1")]);
+ const track1 = new FakeTrack();
+ const track2 = new FakeTrack({ deviceId: "mic-2" });
+ const pendingAcquires = [];
+ const controller = new ActiveMicRecoveryController({
+ mediaDevices,
+ acquire: () => new Promise((resolve) => pendingAcquires.push(resolve)),
+ onRecovered: async () => {},
+ });
+ await controller.start(new FakeStream(track1));
+ track1.readyState = "ended";
+ track1.dispatchEvent(new Event("ended"));
+ assert.equal(pendingAcquires.length, 1);
+
+ controller.stop();
+ await controller.start(new FakeStream(track2));
+ track2.readyState = "ended";
+ track2.dispatchEvent(new Event("ended"));
+ assert.equal(pendingAcquires.length, 2);
+
+ pendingAcquires[0](new FakeStream(new FakeTrack({ deviceId: "stale" })));
+ await delay(1);
+ // The newer recovery is still in flight; another trigger must dedupe onto it.
+ track2.dispatchEvent(new Event("ended"));
+ await delay(1);
+ assert.equal(pendingAcquires.length, 2);
+
+ pendingAcquires[1](new FakeStream(new FakeTrack({ deviceId: "mic-3" })));
+ await delay(1);
+ controller.stop();
+});
+
+test("stop invalidates an in-flight acquisition and stops its late stream", async () => {
+ const { ActiveMicRecoveryController } = await import("../../src/helpers/activeMicRecovery.js");
+ const mediaDevices = new FakeMediaDevices([mic("mic-1")]);
+ const track = new FakeTrack();
+ const replacementTrack = new FakeTrack({ deviceId: "mic-2" });
+ let resolveAcquire;
+ let recovered = false;
+ const controller = new ActiveMicRecoveryController({
+ mediaDevices,
+ acquire: () => new Promise((resolve) => (resolveAcquire = resolve)),
+ onRecovered: async () => {
+ recovered = true;
+ },
+ });
+ await controller.start(new FakeStream(track));
+ track.readyState = "ended";
+ track.dispatchEvent(new Event("ended"));
+ controller.stop();
+ resolveAcquire(new FakeStream(replacementTrack));
+ await delay(1);
+ assert.equal(recovered, false);
+ assert.equal(replacementTrack.stopped, true);
+});
diff --git a/test/helpers/audioSegmentMerge.test.js b/test/helpers/audioSegmentMerge.test.js
new file mode 100644
index 000000000..5850000fc
--- /dev/null
+++ b/test/helpers/audioSegmentMerge.test.js
@@ -0,0 +1,65 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const Module = require("node:module");
+const fs = require("node:fs");
+const os = require("node:os");
+const path = require("node:path");
+const { spawnSync } = require("node:child_process");
+
+test("merges independent WebM recorder segments into one decodable timeline", async (t) => {
+ const originalLoad = Module._load;
+ Module._load = function loadWithElectronStub(request, parent, isMain) {
+ if (request === "electron") return { app: { isReady: () => false } };
+ return originalLoad.call(this, request, parent, isMain);
+ };
+
+ let ffmpeg;
+ try {
+ ffmpeg = require("../../src/helpers/ffmpegUtils");
+ } finally {
+ Module._load = originalLoad;
+ }
+ const ffmpegPath = ffmpeg.getFFmpegPath();
+ if (!ffmpegPath) {
+ t.skip("FFmpeg is not available");
+ return;
+ }
+
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-merge-test-"));
+ try {
+ const segments = [];
+ for (let index = 0; index < 2; index += 1) {
+ const segmentPath = path.join(tempDir, `segment-${index}.webm`);
+ const generated = spawnSync(
+ ffmpegPath,
+ [
+ "-f",
+ "lavfi",
+ "-i",
+ `sine=frequency=${440 + index * 220}:sample_rate=16000`,
+ "-t",
+ "0.25",
+ "-c:a",
+ "libopus",
+ "-y",
+ segmentPath,
+ ],
+ { windowsHide: true }
+ );
+ assert.equal(generated.status, 0, generated.stderr?.toString());
+ segments.push({ buffer: fs.readFileSync(segmentPath), mimeType: "audio/webm" });
+ }
+
+ const merged = await ffmpeg.mergeAudioSegments(segments);
+ const mergedPath = path.join(tempDir, "merged.webm");
+ const wavPath = path.join(tempDir, "merged.wav");
+ fs.writeFileSync(mergedPath, merged);
+ await ffmpeg.convertToWav(mergedPath, wavPath);
+ const samples = ffmpeg.wavToFloat32Samples(fs.readFileSync(wavPath));
+ const durationSeconds = samples.length / 4 / 16000;
+ assert.ok(durationSeconds > 0.4, `duration was ${durationSeconds}`);
+ assert.ok(durationSeconds < 0.7, `duration was ${durationSeconds}`);
+ } finally {
+ fs.rmSync(tempDir, { recursive: true, force: true });
+ }
+});