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(meeting): recover system audio capture when the macOS tap is stranded (#2040)
Alexander Chernov26ddb0995021
diff --git a/preload.js b/preload.jsindex 95157ad1e..c1c3973ea 100644--- a/preload.js+++ b/preload.js@@ -893,6 +893,14 @@ contextBridge.exposeInMainWorld("electronAPI", {"meeting-system-audio-degraded",(callback) => () => callback()),+ onMeetingSystemAudioInterrupted: registerListener(+ "meeting-system-audio-interrupted",+ (callback) => (_event, data) => callback(data)+ ),+ onMeetingSystemAudioResumed: registerListener(+ "meeting-system-audio-resumed",+ (callback) => () => callback()+ ),// Dictation realtime streamingdictationRealtimeWarmup: (options) => ipcRenderer.invoke("dictation-realtime-warmup", options),diff --git a/resources/macos-audio-tap.swift b/resources/macos-audio-tap.swiftindex c525ce388..bc0202355 100644--- a/resources/macos-audio-tap.swift+++ b/resources/macos-audio-tap.swift@@ -15,6 +15,7 @@ final class AudioTapCapture {private let targetFormat: AVAudioFormatprivate let chunkBytes: Intprivate let ioQueue = DispatchQueue(label: "com.openwhispr.audio-tap")+ private let listenerQueue = DispatchQueue(label: "com.openwhispr.audio-tap.listeners")private var tapID: AudioObjectID = 0private var aggregateDeviceID: AudioObjectID = 0@@ -24,6 +25,15 @@ final class AudioTapCapture {private var pendingPCM = Data()private var stopping = false+ private typealias Listener = (+ object: AudioObjectID,+ address: AudioObjectPropertyAddress,+ block: AudioObjectPropertyListenerBlock+ )+ private var listeners: [Listener] = []+ private var invalidationWorkItem: DispatchWorkItem?+ private var invalidationReported = false+init(config: Config) {self.config = configself.targetFormat = AVAudioFormat(@@ -64,6 +74,8 @@ final class AudioTapCapture {throw makeError("Failed to start aggregate device", status: status, operation: "start_device")}+ installInvalidationListeners()+emit(event: ["type": "start","sampleRate": Int(config.sampleRate),@@ -77,6 +89,7 @@ final class AudioTapCapture {return}stopping = true+ removeInvalidationListeners()if aggregateDeviceID != 0 {AudioDeviceStop(aggregateDeviceID, ioProcID)@@ -117,25 +130,32 @@ final class AudioTapCapture {aggregateDeviceID = deviceID}- private func waitForAggregateDeviceReady() throws {+ private func isAggregateDeviceAlive() -> Bool {+ guard aggregateDeviceID != 0 else {+ return false+ }+var address = AudioObjectPropertyAddress(mSelector: kAudioDevicePropertyDeviceIsAlive,mScope: kAudioObjectPropertyScopeGlobal,mElement: kAudioObjectPropertyElementMain)+ var isAlive: UInt32 = 0+ var dataSize = UInt32(MemoryLayout<UInt32>.size)+ let status = AudioObjectGetPropertyData(+ aggregateDeviceID,+ &address,+ 0,+ nil,+ &dataSize,+ &isAlive+ )+ return status == noErr && isAlive != 0+ }+ private func waitForAggregateDeviceReady() throws {for _ in 0..<20 {- var isAlive: UInt32 = 0- var dataSize = UInt32(MemoryLayout<UInt32>.size)- let status = AudioObjectGetPropertyData(- aggregateDeviceID,- &address,- 0,- nil,- &dataSize,- &isAlive- )- if status == noErr, isAlive != 0 {+ if isAggregateDeviceAlive() {return}Thread.sleep(forTimeInterval: 0.1)@@ -144,6 +164,101 @@ final class AudioTapCapture {throw makeError("Aggregate device did not become ready", operation: "wait_for_device")}+ // The tap is built once and never follows the system afterwards, so a route+ // change or a disappearing device can stop delivery with the process still+ // healthy. These listeners turn that into a warning the host can act on.+ private func installInvalidationListeners() {+ addInvalidationListener(+ object: AudioObjectID(kAudioObjectSystemObject),+ selector: kAudioHardwarePropertyDefaultOutputDevice,+ reason: "default_output_changed"+ )+ // kAudioHardwarePropertyDevices is deliberately not observed. Our+ // aggregate has an empty sub-device list, so it stays alive when a+ // physical device disappears and the report would always be suppressed;+ // meanwhile the notification fires on unrelated device churn from any+ // app, and sharing the coalescing window would cancel a pending+ // default_output_changed report that does matter.+ addInvalidationListener(+ object: aggregateDeviceID,+ selector: kAudioDevicePropertyDeviceIsAlive,+ reason: "device_not_alive"+ )+ }++ private func addInvalidationListener(+ object: AudioObjectID,+ selector: AudioObjectPropertySelector,+ reason: String+ ) {+ var address = AudioObjectPropertyAddress(+ mSelector: selector,+ mScope: kAudioObjectPropertyScopeGlobal,+ mElement: kAudioObjectPropertyElementMain+ )+ let block: AudioObjectPropertyListenerBlock = { [weak self] _, _ in+ self?.scheduleInvalidationReport(reason: reason)+ }++ let status = AudioObjectAddPropertyListenerBlock(object, &address, listenerQueue, block)+ guard status == noErr else {+ // Capture still works, it just loses this detection path, so report+ // and carry on rather than failing the whole session.+ emit(event: [+ "type": "warning",+ "code": "listener_unavailable",+ "reason": reason,+ "message": "Failed to observe \(reason): \(Int(status))",+ ])+ return+ }++ listeners.append((object: object, address: address, block: block))+ }++ private func removeInvalidationListeners() {+ listenerQueue.sync {+ invalidationWorkItem?.cancel()+ invalidationWorkItem = nil+ }++ for listener in listeners {+ var address = listener.address+ AudioObjectRemovePropertyListenerBlock(+ listener.object,+ &address,+ listenerQueue,+ listener.block+ )+ }+ listeners.removeAll()+ }++ // A route change fires several notifications in a burst, so coalesce them+ // into one report. Runs on listenerQueue, never on the IO thread.+ private func scheduleInvalidationReport(reason: String) {+ invalidationWorkItem?.cancel()+ let workItem = DispatchWorkItem { [weak self] in+ self?.reportInvalidation(reason: reason)+ }+ invalidationWorkItem = workItem+ listenerQueue.asyncAfter(deadline: .now() + 0.3, execute: workItem)+ }++ private func reportInvalidation(reason: String) {+ guard !invalidationReported, !stopping else {+ return+ }++ invalidationReported = true+ emit(event: [+ "type": "warning",+ "code": "device_invalidated",+ "reason": reason,+ "message": "System audio device changed (\(reason)); capture may have stopped.",+ ])+ }+private func configureConverter() throws {var asbd = AudioStreamBasicDescription()var dataSize = UInt32(MemoryLayout<AudioStreamBasicDescription>.size)@@ -329,6 +444,12 @@ func parseConfig() -> Config {return Config(sampleRate: sampleRate, chunkMilliseconds: chunkMilliseconds)}+// Events are emitted from the main thread and, since the invalidation+// listeners landed, from the listener queue too. The host parses stderr a line+// at a time, so two writers interleaving would produce a line it drops as+// malformed; serialising here keeps every event whole.+let emitQueue = DispatchQueue(label: "com.openwhispr.audio-tap.emit")+func emit(event: [String: Any]) {guard JSONSerialization.isValidJSONObject(event) else {return@@ -338,8 +459,10 @@ func emit(event: [String: Any]) {return}- FileHandle.standardError.write(data)- FileHandle.standardError.write(Data([0x0a]))+ emitQueue.sync {+ FileHandle.standardError.write(data)+ FileHandle.standardError.write(Data([0x0a]))+ }}func writeAll(fd: Int32, buffer: UnsafeRawPointer, count: Int) {diff --git a/src/components/MeetingRecordingMount.tsx b/src/components/MeetingRecordingMount.tsxindex 4a791365b..d0dfecf06 100644--- a/src/components/MeetingRecordingMount.tsx+++ b/src/components/MeetingRecordingMount.tsx@@ -1,4 +1,4 @@-import { useEffect, useRef } from "react";+import { createElement, useEffect, useRef } from "react";import { useTranslation } from "react-i18next";import { useToast } from "./ui/useToast";import {@@ -29,12 +29,16 @@ const MEETING_ERROR_KEYS: Record<string, string> = {export default function MeetingRecordingMount(): null {const { t } = useTranslation();- const { toast } = useToast();+ const { toast, dismiss } = useToast();const isRecording = useMeetingRecordingStore((s) => s.isRecording);const isTranscribing = useMeetingRecordingStore((s) => s.isTranscribing);const error = useMeetingRecordingStore((s) => s.error);const errorNonce = useMeetingRecordingStore((s) => s.errorNonce);const systemAudioSilentWarning = useMeetingRecordingStore((s) => s.systemAudioSilentWarning);+ const systemAudioInterrupted = useMeetingRecordingStore((s) => s.systemAudioInterrupted);+ const systemAudioInterruptedNonce = useMeetingRecordingStore(+ (s) => s.systemAudioInterruptedNonce+ );const micCaptureStatus = useMeetingRecordingStore((s) => s.micCaptureStatus);const wasMicUnavailable = useRef(false);const wasSystemAudioSilent = useRef(false);@@ -197,6 +201,73 @@ export default function MeetingRecordingMount(): null {});}, [systemAudioSilentWarning, toast, t]);+ useEffect(() => {+ const deliverInterruption = (): void => {+ const state = useMeetingRecordingStore.getState();+ if (!state.isRecording || !state.systemAudioInterrupted) {+ return;+ }+ if (+ document.visibilityState !== "visible" ||+ !document.hasFocus() ||+ state.systemAudioInterruptedDeliveredNonce === state.systemAudioInterruptedNonce+ )+ return;++ const interruption = state.systemAudioInterrupted;+ let key = "notes.meeting.systemAudioStopped";+ if (interruption.recovering) {+ key = "notes.meeting.systemAudioInterrupted";+ } else if (interruption.reason === "gone_quiet") {+ key = "notes.meeting.systemAudioQuiet";+ }+ const sessionId = getActiveRecordingSessionId();+ const toastId = toast({+ title: t(`${key}.title`),+ description: t(`${key}.description`),+ duration: interruption.recovering ? 8000 : 0,+ action:+ key === "notes.meeting.systemAudioStopped" && sessionId+ ? createElement(+ "button",+ {+ type: "button",+ className: "text-xs text-primary underline hover:text-primary/80",+ onClick: async (): Promise<void> => {+ await stopRecording(sessionId);+ },+ },+ t("notes.editor.stop")+ )+ : undefined,+ });+ // The provider survives route changes. Keep its warning until the+ // recording stops or a newer interruption supersedes it, even unmounted.+ const unsubscribe = useMeetingRecordingStore.subscribe((next) => {+ if (+ !next.isRecording ||+ !next.systemAudioInterrupted ||+ next.systemAudioInterruptedNonce !== state.systemAudioInterruptedNonce+ ) {+ dismiss(toastId);+ unsubscribe();+ }+ });+ // Keep delivery state outside this component: routes may unmount it+ // while the recording and interruption listener continue running.+ useMeetingRecordingStore.setState({+ systemAudioInterruptedDeliveredNonce: state.systemAudioInterruptedNonce,+ });+ };+ deliverInterruption();+ document.addEventListener("visibilitychange", deliverInterruption);+ window.addEventListener("focus", deliverInterruption);+ return (): void => {+ document.removeEventListener("visibilitychange", deliverInterruption);+ window.removeEventListener("focus", deliverInterruption);+ };+ }, [isRecording, systemAudioInterrupted, systemAudioInterruptedNonce, toast, dismiss, t]);+useEffect(() => {if (micCaptureStatus === "unavailable" && !wasMicUnavailable.current) {wasMicUnavailable.current = true;diff --git a/src/helpers/audioTapManager.js b/src/helpers/audioTapManager.jsindex 9b3b129e1..6cad42f20 100644--- a/src/helpers/audioTapManager.js+++ b/src/helpers/audioTapManager.js@@ -21,6 +21,7 @@ class AudioTapManager {this.stderrBuffer = "";this.onChunk = null;this.onError = null;+ this.onWarning = null;this.isStopping = false;this.permissionStatus = this._loadPermissionStatus();this._requestPromise = null;@@ -108,13 +109,14 @@ class AudioTapManager {return this._requestPromise;}- async start({ onChunk, onError } = {}) {+ async start({ onChunk, onError, onWarning } = {}) {if (!this.isSupported()) {throw new Error("macOS 14.2 or later is required for native system audio capture.");}if (this.process) {this.onChunk = onChunk || null;this.onError = onError || null;+ this.onWarning = onWarning || null;return;}if (this._requestPromise) {@@ -124,6 +126,7 @@ class AudioTapManager {const binaryPath = this._prepareBinary();this.onChunk = onChunk || null;this.onError = onError || null;+ this.onWarning = onWarning || null;this.isStopping = false;this.stderrBuffer = "";@@ -174,6 +177,11 @@ class AudioTapManager {return;}+ if (message.type === "warning") {+ this.onWarning?.(message);+ return;+ }+if (message.type === "error") {const error = this._buildProcessError(message);if (error.code === "permission_denied") {@@ -258,6 +266,7 @@ class AudioTapManager {this.stderrBuffer = "";this.onChunk = null;this.onError = null;+ this.onWarning = null;this.isStopping = false;}diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex fc90fc059..02f41c928 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -78,6 +78,7 @@ const { registerMeetingAutoEndLifecycleHandlers } = require("./meetingAutoEndLifconst liveSpeakerIdentifier = require("./liveSpeakerIdentifier");const { supportsLiveSpeakerIdentification } = require("./liveSpeakerIdPolicy");const MeetingEchoLeakDetector = require("./meetingEchoLeakDetector");+const createMeetingSystemAudioWatchdog = require("./meetingSystemAudioWatchdog");const {partitionPendingMicFinals,isRiskyMicDuplicateProfile,@@ -6730,24 +6731,42 @@ class IPCHandlers {meetingReconnectReplaySources = new Set();};- const queueMeetingReconnectAudio = (source, buffer) => {+ const sendMeetingStreamingAudio = (streaming, buffer, capturedAt = null) => {+ const firstSampleAt = streaming.audioBytesSent === 0 ? capturedAt : null;+ const sent = streaming.sendAudio(buffer);+ if (+ sent &&+ streaming.isConnected &&+ firstSampleAt !== null &&+ streaming.sessionStartedAt != null+ ) {+ // Deepgram/Corti time segments from the first PCM sample, which can+ // precede a replacement socket's creation when replaying recovery audio.+ streaming.sessionStartedAt = firstSampleAt;+ }+ return sent;+ };++ const queueMeetingReconnectAudio = (source, buffer, capturedAt = null) => {if (!meetingReconnectReplaySources.has(source)) return;const copy = Buffer.from(buffer);const queue = meetingReconnectAudioBuffers[source];- queue.push(copy);+ queue.push({ buffer: copy, capturedAt });meetingReconnectAudioBytes[source] += copy.length;while (meetingReconnectAudioBytes[source] > MEETING_RECONNECT_BUFFER_MAX_BYTES &&queue.length > 1) {- meetingReconnectAudioBytes[source] -= queue.shift().length;+ meetingReconnectAudioBytes[source] -= queue.shift().buffer.length;}};const replayMeetingReconnectAudio = (source, streaming) => {if (!meetingReconnectReplaySources.has(source)) return true;const queue = meetingReconnectAudioBuffers[source];- const replayed = queue.every((buffer) => streaming.sendAudio(buffer));+ const replayed = queue.every(({ buffer, capturedAt }) =>+ sendMeetingStreamingAudio(streaming, buffer, capturedAt)+ );debugLogger.info("Replayed meeting audio after reconnect", {source,chunks: queue.length,@@ -7082,8 +7101,34 @@ class IPCHandlers {const MEETING_MIC_BLEED_LOOKBACK_MS = 500;const MEETING_MIC_STATS_LOG_LIMIT = 200;const MEETING_SYSTEM_AUDIO_SILENCE_WARNING_MS = 45000;+ const MEETING_SYSTEM_AUDIO_TICK_MS = 2000;let meetingMicStatsLogCount = 0;let meetingSystemAudioSilenceTimer = null;+ let meetingSystemAudioTicker = null;+ let meetingSystemAudioWatchdogWin = null;++ const meetingSystemAudioWatchdog = createMeetingSystemAudioWatchdog({+ onResumed: () => {+ const win = meetingSystemAudioWatchdogWin;+ if (win && !win.isDestroyed()) {+ win.webContents.send("meeting-system-audio-resumed");+ }+ },+ onInterrupted: (payload) => {+ // debugLogger.error flattens its arguments into one string, dropping+ // both the meta and the scope, so the give-up event would vanish from a+ // log filtered on "meeting", the one filter used to triage this bug.+ if (payload.recovering) {+ debugLogger.warn("Meeting system audio interrupted, restarting", payload, "meeting");+ } else {+ debugLogger.warn("Meeting system audio capture gave up", payload, "meeting");+ }+ const win = meetingSystemAudioWatchdogWin;+ if (win && !win.isDestroyed()) {+ win.webContents.send("meeting-system-audio-interrupted", payload);+ }+ },+ });let meetingStartedAt = null;let meetingSendCounts = { mic: 0, system: 0 };const meetingEchoLeakDetector = new MeetingEchoLeakDetector();@@ -7194,8 +7239,11 @@ class IPCHandlers {}};- const dispatchMeetingAudioBuffer = (buffer, source) => {+ const dispatchMeetingAudioBuffer = (buffer, source, synthetic = false, capturedAt = null) => {if (meetingLocalMode) {+ // Local STT timestamps each batch with wall time, not a sample cursor.+ // Large synthetic gaps would dilute speech and inflate the next batch.+ if (synthetic) return;meetingLocalBuffers[source].push(buffer);return;}@@ -7238,7 +7286,7 @@ class IPCHandlers {zeroed: outbound !== buffer,});}- } else if (source === "system" && buffer.length >= 2) {+ } else if (source === "system" && buffer.length >= 2 && !synthetic) {// System chunks stream verbatim (no gate), so a periodic level readout// is the only way field logs can tell real audio from capture silence.const chunkCount = meetingSendCounts.system + 1;@@ -7252,8 +7300,9 @@ class IPCHandlers {}}- queueMeetingReconnectAudio(source, outbound);- const sent = streaming.sendAudio(outbound);+ queueMeetingReconnectAudio(source, outbound, capturedAt);+ const sent = sendMeetingStreamingAudio(streaming, outbound, capturedAt);+ if (synthetic) return;meetingSendCounts[source]++;if (meetingSendCounts[source] <= 5 || meetingSendCounts[source] % 100 === 0) {debugLogger.debug("Meeting audio send", {@@ -7905,8 +7954,43 @@ class IPCHandlers {}, MEETING_SYSTEM_AUDIO_SILENCE_WARNING_MS);};+ const clearMeetingSystemAudioTicker = () => {+ if (meetingSystemAudioTicker) {+ clearInterval(meetingSystemAudioTicker);+ meetingSystemAudioTicker = null;+ }+ };++ const stopMeetingSystemAudioWatchdog = () => {+ clearMeetingSystemAudioTicker();+ // Detaches the capture too, which strands any restart still in flight.+ meetingSystemAudioWatchdog.stop();+ meetingSystemAudioWatchdogWin = null;+ };++ // Rolling counterpart to the one-shot warning above, which only covers a+ // session that never produced audio and stops watching once any arrives.+ const startMeetingSystemAudioWatchdog = (win, systemAudioStrategy) => {+ // Deliberately not stopMeetingSystemAudioWatchdog(): capture is already+ // running and attached by this point, and detaching it here would leave a+ // watchdog that reports stalls it cannot recover from.+ clearMeetingSystemAudioTicker();+ meetingSystemAudioWatchdogWin = win;+ meetingSystemAudioWatchdog.start({+ systemAudioStrategy,+ // Only the macOS tap delivers a chunk every period regardless of what+ // is playing; a gap from the loopback helpers proves nothing.+ watchesDelivery: systemAudioStrategy === "native",+ });+ meetingSystemAudioTicker = setInterval(+ () => meetingSystemAudioWatchdog.tick(),+ MEETING_SYSTEM_AUDIO_TICK_MS+ );+ };+const rollbackMeetingTranscriptionStart = async () => {clearMeetingSystemAudioSilenceTimer();+ stopMeetingSystemAudioWatchdog();if (this.audioTapManager) {await this.audioTapManager.stop().catch(() => {});}@@ -8136,6 +8220,7 @@ class IPCHandlers {// in-person recordings where a silent system tap is expected.if (result.systemAudioStrategy && result.systemAudioStrategy !== "unsupported") {armMeetingSystemAudioSilenceTimer(meetingConnectionWin, result.systemAudioStrategy);+ startMeetingSystemAudioWatchdog(meetingConnectionWin, result.systemAudioStrategy);}return { ...result, sessionId: recordingSessionId };};@@ -8253,19 +8338,25 @@ class IPCHandlers {}};- const sendMeetingAudio = (audioBuffer, source) => {+ const sendMeetingAudio = (audioBuffer, source, synthetic = false, capturedAt = null) => {const outboundBuffer = Buffer.isBuffer(audioBuffer) ? audioBuffer : Buffer.from(audioBuffer);// Auto-end judges "is anyone audible" from the raw chunk of either// channel, before AEC/holdback/muting can swallow it.- this.meetingDetectionEngine?.recordMeetingAudioChunk(source, outboundBuffer);+ if (!synthetic) {+ this.meetingDetectionEngine?.recordMeetingAudioChunk(source, outboundBuffer);+ }if (source === "system") {const receivedAt = Date.now();- meetingEchoLeakDetector.recordSystemChunk(outboundBuffer, receivedAt);- if (meetingAecEnabled && !this.meetingAecManager?.processSystemBuffer(outboundBuffer)) {- meetingAecEnabled = false;+ // Recovery silence repairs sample clocks, but is not current capture+ // evidence or an AEC reference for the mic arriving now.+ if (!synthetic) {+ meetingEchoLeakDetector.recordSystemChunk(outboundBuffer, receivedAt);+ if (meetingAecEnabled && !this.meetingAecManager?.processSystemBuffer(outboundBuffer)) {+ meetingAecEnabled = false;+ }+ flushPendingMeetingMicChunks();}- flushPendingMeetingMicChunks();if (meetingLiveSpeakerActive) {// identification.startTime counts samples from the first chunk the@@ -8286,17 +8377,19 @@ class IPCHandlers {}meetingDiarizationStream.write(outboundBuffer);- if (!meetingSystemAudioHeard) {+ if (!synthetic) {+ // Every real chunk feeds the watchdog, including actual silence.const { rms, peak } = computeChunkStats(outboundBuffer);- if (rms >= MEETING_MIC_SILENCE_RMS || peak >= MEETING_MIC_SILENCE_PEAK) {- // A call is audibly underway: diarization stays on the system- // channel, so stop paying the mic capture's disk cost.+ const audible = rms >= MEETING_MIC_SILENCE_RMS || peak >= MEETING_MIC_SILENCE_PEAK;+ meetingSystemAudioWatchdog.recordChunk(audible);+ if (audible && !meetingSystemAudioHeard) {+ // A call is audibly underway, so stop paying the mic capture's disk cost.meetingSystemAudioHeard = true;dropMeetingMicDiarizationCapture();}}- dispatchMeetingAudioBuffer(outboundBuffer, "system");+ dispatchMeetingAudioBuffer(outboundBuffer, "system", synthetic, capturedAt);return;}@@ -8365,24 +8458,46 @@ class IPCHandlers {const startManagedMeetingSystemAudio = (event, manager, warningLabel, onWarningCode) => {const win = BrowserWindow.fromWebContents(event.sender);- return manager.start({- onChunk: (chunk) => {- sendMeetingAudio(chunk, "system");- },- onError: (error) => {- if (win && !win.isDestroyed()) {- win.webContents.send("meeting-transcription-error", error.message);- }- },- onWarning: (warning) => {- debugLogger.warn(- warningLabel,- { code: warning.code, message: warning.message },- "meeting"- );- onWarningCode?.(warning.code);- },+ const timeline =+ manager === this.audioTapManager ? require("./meetingAudioTimeline")() : null;+ let captureStarted = false;+ const startCapture = () => {+ if (captureStarted) timeline?.markRestart();+ captureStarted = true;+ return manager.start({+ onChunk: (chunk) => {+ if (timeline) {+ timeline.write(chunk, (buffer, synthetic, capturedAt) =>+ sendMeetingAudio(buffer, "system", synthetic, capturedAt)+ );+ } else {+ sendMeetingAudio(chunk, "system");+ }+ },+ onError: (error) => {+ if (win && !win.isDestroyed()) {+ win.webContents.send("meeting-transcription-error", error.message);+ }+ },+ onWarning: (warning) => {+ debugLogger.warn(+ warningLabel,+ { code: warning.code, message: warning.message },+ "meeting"+ );+ onWarningCode?.(warning.code);+ },+ });+ };++ // Keep the native sample timeline through recovery, including the stall+ // before detection and the helper restart. New sessions get a new timeline.+ meetingSystemAudioWatchdog.attachCapture({+ stop: () => manager.stop(),+ start: startCapture,});++ return startCapture();};const fallBackToMicOnly = async (context) => {@@ -8396,6 +8511,8 @@ class IPCHandlers {});}this._meetingSystemStreaming = null;+ // No system capture left to recover, so drop the restart hook with it.+ stopMeetingSystemAudioWatchdog();await stopLiveSpeakerIdentification().catch(() => {});};@@ -8410,7 +8527,14 @@ class IPCHandlers {await startManagedMeetingSystemAudio(event,this.audioTapManager,- "macOS system audio tap warning"+ "macOS system audio tap warning",+ (code) => {+ // The tap is pinned to the devices it saw at creation, so a route+ // change can strand it. Restart before the stall window elapses.+ if (code === "device_invalidated") {+ meetingSystemAudioWatchdog.reportDeviceInvalidated();+ }+ });return { systemAudioMode, systemAudioStrategy };} catch (error) {@@ -8484,6 +8608,7 @@ class IPCHandlers {}this.meetingDetectionEngine?.setUserRecording(false);clearMeetingSystemAudioSilenceTimer();+ stopMeetingSystemAudioWatchdog();try {if (this.audioTapManager) {await this.audioTapManager.stop();diff --git a/src/helpers/meetingAudioTimeline.js b/src/helpers/meetingAudioTimeline.jsnew file mode 100644index 000000000..1b5ac97db--- /dev/null+++ b/src/helpers/meetingAudioTimeline.js@@ -0,0 +1,47 @@+// PCM16 mono at the native tap's 24kHz. Reuse bounded silence blocks even if+// recovery takes a long time; never allocate the entire missing interval.+const SAMPLE_RATE = 24000;+// Match normal 100ms tap delivery. Providers may prepend a pending partial+// packet, so a block at their maximum frame size would overflow that limit.+const SILENCE_SAMPLES = SAMPLE_RATE / 10;+const SILENCE = Buffer.alloc(SILENCE_SAMPLES * 2);++const createMeetingAudioTimeline = ({ now = () => performance.now(), wallNow = Date.now } = {}) => {+ let startedAt = null;+ let wallStartedAt = null;+ let samples = 0;+ let recovering = false;++ return {+ markRestart() {+ recovering = true;+ },+ write(buffer, emit) {+ const receivedAt = now();+ startedAt ??= receivedAt;+ wallStartedAt ??= wallNow();+ if (recovering) {+ // Repair only explicit capture restarts. Arrival jitter and buffered+ // delivery during normal capture must not manufacture gaps.+ const elapsedSamples = Math.round(((receivedAt - startedAt) * SAMPLE_RATE) / 1000);+ let missingSamples = Math.max(0, elapsedSamples - samples);+ while (missingSamples > 0) {+ const count = Math.min(missingSamples, SILENCE_SAMPLES);+ emit(+ SILENCE.subarray(0, count * 2),+ true,+ wallStartedAt + (samples * 1000) / SAMPLE_RATE+ );+ samples += count;+ missingSamples -= count;+ }+ recovering = false;+ }+ const capturedAt = wallStartedAt + (samples * 1000) / SAMPLE_RATE;+ samples += buffer.length / 2;+ emit(buffer, false, capturedAt);+ },+ };+};++module.exports = createMeetingAudioTimeline;diff --git a/src/helpers/meetingSystemAudioWatchdog.js b/src/helpers/meetingSystemAudioWatchdog.jsnew file mode 100644index 000000000..576cd8aaf--- /dev/null+++ b/src/helpers/meetingSystemAudioWatchdog.js@@ -0,0 +1,236 @@+// The macOS tap helper writes a chunk every period whatever the audio is, so a+// gap this long means delivery stopped rather than the call going quiet.+const STALL_MS = 6_000;+// Chunks still arriving but silent for this long, after the call was audible at+// least once. Warning only: a genuinely quiet call looks exactly the same.+const GONE_QUIET_MS = 180_000;+// Enough to ride out a route change and its aftershocks without looping if the+// device is simply gone.+const MAX_RESTARTS = 3;+// A tick gap longer than this means the machine slept or the main process+// blocked. Delivery evidence from before the gap says nothing about now, and+// node runs the timers phase before the poll phase, so the tick after a block+// lands before the stdout data it should have been judging.+const TICK_GAP_MS = 5_000;++// The system-audio tap is built once and never follows the machine afterwards,+// so a route change or a disappearing device can stop capture with the helper+// process still alive and the UI still showing a live recording. Nothing else+// notices: the helper does not exit, and silence is indistinguishable from a+// quiet call, which is what made openwhispr#1990 invisible mid-meeting.+//+// Two triggers are trusted enough to restart capture:+//+// delivery: no chunk at all for STALL_MS. Only meaningful where the platform+// guarantees a chunk per period (the macOS tap); the loopback helpers may+// legitimately go idle, so the caller opts in via watchesDelivery.+// device: the helper reported that the device it was pinned to changed or+// went away. Decisive, and faster than waiting for the stall window.+//+// Going quiet is reported but never restarts anything, because restarting a+// working capture costs real audio and a silent call is not a fault.+//+// Tick-driven like meetingAutoEndController: every input updates state and the+// owner calls tick() on an interval, so there is no timer to leak per session.+const createMeetingSystemAudioWatchdog = ({ now = Date.now, onInterrupted, onResumed }) => {+ let session = null;+ let capture = null;+ // Bumped on every attach and detach. A restart suspended between its two+ // halves compares against the value it started with, so a meeting that ends+ // mid-restart cannot leave an orphan helper holding a process tap.+ let generation = 0;+ let lastTickAt = null;++ const notify = (reason, recovering) => {+ onInterrupted?.({+ systemAudioStrategy: session.systemAudioStrategy,+ reason,+ recovering,+ });+ };++ // Capture is attached when it starts, which happens before the session is+ // armed. start() must therefore never drop it, and detaching is teardown's+ // job alone: an earlier draft cleared it from the arming path and shipped a+ // watchdog that warned about stalls it could not actually recover from.+ const attachCapture = ({ stop, start }) => {+ generation += 1;+ capture = { generation, stop, start };+ };++ const detachCapture = () => {+ generation += 1;+ capture = null;+ };++ const runRestart = async (active) => {+ if (!capture) {+ return;+ }+ const target = capture;+ await target.stop().catch(() => {});+ if (generation !== target.generation || session !== active) {+ return;+ }+ active.replacementStarting = true;+ await target.start();+ if (generation !== target.generation) {+ // The session ended while the helper was coming back up.+ await target.stop().catch(() => {});+ }+ };++ const requestRestart = (reason) => {+ if (!session || session.recoveryFailed) {+ return;+ }+ if (session.restartInFlight) {+ // Ignore the retiring helper, but retain a warning from its replacement:+ // its start acknowledgement and warning can share the same stderr read.+ if (reason === "device_invalidated" && session.replacementStarting) {+ session.pendingDeviceInvalidation = true;+ }+ return;+ }++ if (session.restarts >= MAX_RESTARTS) {+ // Latched, so a later device event cannot restart the count at zero and+ // hand out another three attempts. The give-up report supersedes the+ // quiet one, which would otherwise arrive later saying less.+ session.recoveryFailed = true;+ session.quietReported = true;+ notify(reason, false);+ return;+ }++ const active = session;+ active.restarts += 1;+ active.restartInFlight = true;+ notify(reason, true);++ Promise.resolve()+ .then(() => runRestart(active))+ .catch(() => {})+ .finally(() => {+ if (session !== active) {+ return;+ }+ active.restartInFlight = false;+ active.replacementStarting = false;+ // Give the fresh capture a clean window even if the restart threw; the+ // next tick judges it on its own evidence either way.+ const at = now();+ active.lastChunkAt = at;+ if (active.lastAudibleAt !== null) {+ active.lastAudibleAt = at;+ }+ if (active.pendingDeviceInvalidation) {+ active.pendingDeviceInvalidation = false;+ requestRestart("device_invalidated");+ }+ });+ };++ const start = ({ systemAudioStrategy, watchesDelivery = false } = {}) => {+ lastTickAt = null;+ session = {+ systemAudioStrategy: systemAudioStrategy ?? null,+ watchesDelivery: watchesDelivery === true,+ // Null until the first chunk: a stream that never delivered at all is the+ // one-shot silence warning's case, not this one. Seeding it with now()+ // would assert a delivery that has not happened and let the watchdog+ // restart during startup, before the renderer is even listening.+ lastChunkAt: null,+ lastAudibleAt: null,+ restarts: 0,+ restartInFlight: false,+ replacementStarting: false,+ pendingDeviceInvalidation: false,+ recoveryFailed: false,+ quietReported: false,+ };+ };++ const stop = () => {+ session = null;+ lastTickAt = null;+ detachCapture();+ };++ const recordChunk = (audible = false) => {+ if (!session) {+ return;+ }+ const at = now();+ session.lastChunkAt = at;+ if (audible) {+ session.lastAudibleAt = at;+ if (session.quietReported && !session.recoveryFailed) {+ session.quietReported = false;+ onResumed?.();+ }+ }+ };++ const reportDeviceInvalidated = () => {+ requestRestart("device_invalidated");+ };++ // Rebases the delivery evidence across a gap the session did not really live+ // through, so waking from sleep does not read as a dead tap.+ const observeClock = () => {+ const at = now();+ const gap = lastTickAt === null ? 0 : at - lastTickAt;+ lastTickAt = at;+ if (gap > TICK_GAP_MS && session) {+ if (session.lastChunkAt !== null) {+ session.lastChunkAt = at;+ }+ if (session.lastAudibleAt !== null) {+ session.lastAudibleAt = at;+ }+ }+ return at;+ };++ const tick = () => {+ const at = observeClock();+ if (!session || session.restartInFlight) {+ return;+ }++ if (+ session.watchesDelivery &&+ session.lastChunkAt !== null &&+ at - session.lastChunkAt > STALL_MS+ ) {+ requestRestart("no_audio_delivered");+ return;+ }++ if (+ !session.quietReported &&+ session.lastAudibleAt !== null &&+ at - session.lastAudibleAt > GONE_QUIET_MS+ ) {+ session.quietReported = true;+ notify("gone_quiet", false);+ }+ };++ return {+ start,+ stop,+ attachCapture,+ detachCapture,+ recordChunk,+ reportDeviceInvalidated,+ tick,+ };+};++module.exports = createMeetingSystemAudioWatchdog;+module.exports.STALL_MS = STALL_MS;+module.exports.GONE_QUIET_MS = GONE_QUIET_MS;+module.exports.MAX_RESTARTS = MAX_RESTARTS;+module.exports.TICK_GAP_MS = TICK_GAP_MS;diff --git a/src/locales/de/translation.json b/src/locales/de/translation.jsonindex 20159ab6b..184aca4ae 100644--- a/src/locales/de/translation.json+++ b/src/locales/de/translation.json@@ -3242,6 +3242,18 @@"systemAudioSilent": {"title": "Noch kein Meeting-Ton erkannt","description": "Bisher hat nur Ihr Mikrofon Ton aufgenommen. Sie sind in einem Videoanruf? Prüfen Sie, ob der Meeting-Ton auf diesem Computer wiedergegeben wird und nicht stummgeschaltet ist. Sie nehmen vor Ort auf? Dann können Sie diesen Hinweis ignorieren – Ihr Mikrofon nimmt den Raum auf."+ },+ "systemAudioInterrupted": {+ "title": "Meeting-Ton unterbrochen",+ "description": "Die Aufnahme des Systemtons wurde unterbrochen und startet neu. Einige Sekunden des Gesprächs können im Transkript fehlen."+ },+ "systemAudioStopped": {+ "title": "Meeting-Ton gestoppt",+ "description": "OpenWhispr nimmt die anderen Teilnehmer nicht mehr auf. Beenden Sie die Aufnahme und starten Sie sie erneut, oder prüfen Sie Ihr Audioausgabegerät."+ },+ "systemAudioQuiet": {+ "title": "Meeting-Audio ist verstummt",+ "description": "Seit einigen Minuten war niemand zu hören. Falls das Gespräch noch läuft, prüfen Sie Ihr Audioausgabegerät."}},"meetingPill": {diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex 2b5cbf11f..1954a47fa 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -3242,6 +3242,18 @@"systemAudioSilent": {"title": "No meeting audio detected yet","description": "Only your microphone has picked up sound so far. On a video call? Check that the meeting audio is playing on this computer and isn't muted. Recording in person? You can ignore this — your microphone captures the room."+ },+ "systemAudioInterrupted": {+ "title": "Meeting audio interrupted",+ "description": "System audio capture stopped and is restarting. A few seconds of the call may be missing from the transcript."+ },+ "systemAudioStopped": {+ "title": "Meeting audio stopped",+ "description": "OpenWhispr is no longer capturing the other participants. Stop and start the recording again, or check your sound output device."+ },+ "systemAudioQuiet": {+ "title": "Meeting audio has gone quiet",+ "description": "No one has been heard for a few minutes. If the call is still going, check your sound output device."}},"meetingPill": {diff --git a/src/locales/es/translation.json b/src/locales/es/translation.jsonindex 4a62971bf..f320d2659 100644--- a/src/locales/es/translation.json+++ b/src/locales/es/translation.json@@ -3039,6 +3039,18 @@"systemAudioSilent": {"title": "Aún no se detecta el audio de la reunión","description": "Hasta ahora solo tu micrófono ha captado sonido. ¿Estás en una videollamada? Comprueba que el audio de la reunión se reproduce en este equipo y no está silenciado. ¿Estás grabando en persona? Puedes ignorar este aviso: tu micrófono capta la sala."+ },+ "systemAudioInterrupted": {+ "title": "Audio de la reunión interrumpido",+ "description": "La captura del audio del sistema se detuvo y se está reiniciando. Puede que falten unos segundos de la llamada en la transcripción."+ },+ "systemAudioStopped": {+ "title": "El audio de la reunión se detuvo",+ "description": "OpenWhispr ya no está captando a los demás participantes. Detén la grabación y vuelve a iniciarla, o revisa tu dispositivo de salida de sonido."+ },+ "systemAudioQuiet": {+ "title": "El audio de la reunión se ha quedado en silencio",+ "description": "No se ha oído a nadie desde hace unos minutos. Si la llamada sigue en curso, revisa tu dispositivo de salida de sonido."}},"meetingPill": {diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.jsonindex b920cb89c..76298b1c7 100644--- a/src/locales/fr/translation.json+++ b/src/locales/fr/translation.json@@ -3242,6 +3242,18 @@"systemAudioSilent": {"title": "Aucun son de réunion détecté pour le moment","description": "Seul votre microphone a capté du son jusqu'à présent. Vous êtes en visioconférence ? Vérifiez que le son de la réunion est diffusé sur cet ordinateur et qu'il n'est pas coupé. Vous enregistrez en présentiel ? Vous pouvez ignorer ce message : votre microphone capte la salle."+ },+ "systemAudioInterrupted": {+ "title": "Son de la réunion interrompu",+ "description": "La capture du son système s'est arrêtée et redémarre. Quelques secondes de l'appel peuvent manquer dans la transcription."+ },+ "systemAudioStopped": {+ "title": "Son de la réunion arrêté",+ "description": "OpenWhispr ne capte plus les autres participants. Arrêtez l'enregistrement puis relancez-le, ou vérifiez votre périphérique de sortie audio."+ },+ "systemAudioQuiet": {+ "title": "L'audio de la réunion est devenu silencieux",+ "description": "Personne n'a été entendu depuis quelques minutes. Si l'appel est toujours en cours, vérifiez votre périphérique de sortie audio."}},"meetingPill": {diff --git a/src/locales/it/translation.json b/src/locales/it/translation.jsonindex 4e2a61b1a..64113c692 100644--- a/src/locales/it/translation.json+++ b/src/locales/it/translation.json@@ -2991,6 +2991,18 @@"systemAudioSilent": {"title": "Nessun audio della riunione rilevato finora","description": "Finora solo il tuo microfono ha captato suoni. Sei in una videochiamata? Verifica che l'audio della riunione venga riprodotto su questo computer e non sia disattivato. Stai registrando di persona? Puoi ignorare questo avviso: il tuo microfono cattura la stanza."+ },+ "systemAudioInterrupted": {+ "title": "Audio della riunione interrotto",+ "description": "L'acquisizione dell'audio di sistema si è interrotta e sta ripartendo. Alcuni secondi della chiamata potrebbero mancare nella trascrizione."+ },+ "systemAudioStopped": {+ "title": "Audio della riunione fermo",+ "description": "OpenWhispr non sta più captando gli altri partecipanti. Interrompi la registrazione e riavviala, oppure controlla il dispositivo di uscita audio."+ },+ "systemAudioQuiet": {+ "title": "L'audio della riunione è diventato silenzioso",+ "description": "Non si sente nessuno da qualche minuto. Se la chiamata è ancora in corso, controlla il dispositivo di uscita audio."}},"meetingPill": {diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.jsonindex f7156f8ca..68b96767e 100644--- a/src/locales/ja/translation.json+++ b/src/locales/ja/translation.json@@ -2975,6 +2975,18 @@"systemAudioSilent": {"title": "会議の音声がまだ検出されていません","description": "これまでのところ、音声を拾っているのはマイクのみです。ビデオ会議中の場合は、会議の音声がこのコンピューターで再生されており、ミュートになっていないことを確認してください。対面で録音している場合は、この通知は無視してかまいません。マイクが室内の音を拾います。"+ },+ "systemAudioInterrupted": {+ "title": "会議の音声が中断されました",+ "description": "システム音声の取り込みが停止し、再起動しています。通話の数秒間が文字起こしから欠落する可能性があります。"+ },+ "systemAudioStopped": {+ "title": "会議の音声が停止しました",+ "description": "OpenWhispr は他の参加者の音声を取り込めなくなりました。録音を停止してもう一度開始するか、音声出力デバイスを確認してください。"+ },+ "systemAudioQuiet": {+ "title": "会議の音声が無音になりました",+ "description": "数分間、誰の声も検出されていません。通話が続いている場合は、音声出力デバイスを確認してください。"}},"meetingPill": {diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.jsonindex d6574aa56..6db8e0eda 100644--- a/src/locales/pt/translation.json+++ b/src/locales/pt/translation.json@@ -2991,6 +2991,18 @@"systemAudioSilent": {"title": "Nenhum áudio da reunião detectado até agora","description": "Até agora, apenas o seu microfone captou som. Está em uma videochamada? Verifique se o áudio da reunião está sendo reproduzido neste computador e não está silenciado. Está gravando presencialmente? Você pode ignorar este aviso: seu microfone capta o ambiente."+ },+ "systemAudioInterrupted": {+ "title": "Áudio da reunião interrompido",+ "description": "A captura do áudio do sistema parou e está reiniciando. Alguns segundos da chamada podem faltar na transcrição."+ },+ "systemAudioStopped": {+ "title": "O áudio da reunião parou",+ "description": "O OpenWhispr não está mais captando os outros participantes. Pare a gravação e inicie novamente, ou verifique seu dispositivo de saída de som."+ },+ "systemAudioQuiet": {+ "title": "O áudio da reunião ficou silencioso",+ "description": "Ninguém foi ouvido nos últimos minutos. Se a chamada ainda estiver acontecendo, verifique seu dispositivo de saída de som."}},"meetingPill": {diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.jsonindex bb2f1baae..20373d5a7 100644--- a/src/locales/ru/translation.json+++ b/src/locales/ru/translation.json@@ -3013,6 +3013,18 @@"systemAudioSilent": {"title": "Звук встречи пока не обнаружен","description": "Пока звук поступает только с вашего микрофона. Вы на видеозвонке? Убедитесь, что звук встречи воспроизводится на этом компьютере и не отключён. Записываете встречу вживую? Это предупреждение можно игнорировать — ваш микрофон улавливает звук в помещении."+ },+ "systemAudioInterrupted": {+ "title": "Звук встречи прерван",+ "description": "Запись системного звука остановилась и перезапускается. Несколько секунд разговора могут отсутствовать в расшифровке."+ },+ "systemAudioStopped": {+ "title": "Звук встречи остановлен",+ "description": "OpenWhispr больше не записывает других участников. Остановите запись и запустите её заново или проверьте устройство вывода звука."+ },+ "systemAudioQuiet": {+ "title": "Звук встречи стал тихим",+ "description": "Уже несколько минут никого не слышно. Если звонок продолжается, проверьте устройство вывода звука."}},"meetingPill": {diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.jsonindex 83ade7134..47435ffd5 100644--- a/src/locales/zh-CN/translation.json+++ b/src/locales/zh-CN/translation.json@@ -2991,6 +2991,18 @@"systemAudioSilent": {"title": "尚未检测到会议音频","description": "到目前为止,只有您的麦克风采集到声音。正在进行视频通话?请检查会议音频是否正在此电脑上播放且未被静音。正在进行现场录音?您可以忽略此提示——您的麦克风会采集房间内的声音。"+ },+ "systemAudioInterrupted": {+ "title": "会议音频已中断",+ "description": "系统音频采集已停止,正在重新启动。转录中可能会缺少几秒钟的通话内容。"+ },+ "systemAudioStopped": {+ "title": "会议音频已停止",+ "description": "OpenWhispr 已无法采集其他参会者的声音。请停止录制后重新开始,或检查您的音频输出设备。"+ },+ "systemAudioQuiet": {+ "title": "会议音频已静默",+ "description": "已有几分钟未检测到任何人声。如果通话仍在进行,请检查您的声音输出设备。"}},"meetingPill": {diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.jsonindex 2afe742d6..1f64b427b 100644--- a/src/locales/zh-TW/translation.json+++ b/src/locales/zh-TW/translation.json@@ -2991,6 +2991,18 @@"systemAudioSilent": {"title": "尚未偵測到會議音訊","description": "到目前為止,只有您的麥克風收到聲音。正在進行視訊通話?請檢查會議音訊是否正在此電腦上播放且未被靜音。正在進行現場錄音?您可以忽略此提示——您的麥克風會收錄房間內的聲音。"+ },+ "systemAudioInterrupted": {+ "title": "會議音訊已中斷",+ "description": "系統音訊擷取已停止,正在重新啟動。逐字稿中可能會缺少幾秒鐘的通話內容。"+ },+ "systemAudioStopped": {+ "title": "會議音訊已停止",+ "description": "OpenWhispr 已無法擷取其他與會者的聲音。請停止錄製後重新開始,或檢查您的音訊輸出裝置。"+ },+ "systemAudioQuiet": {+ "title": "會議音訊已靜默",+ "description": "已有幾分鐘未偵測到任何人聲。如果通話仍在進行,請檢查您的聲音輸出裝置。"}},"meetingPill": {diff --git a/src/stores/meetingRecordingStore.ts b/src/stores/meetingRecordingStore.tsindex f7bb4d9a7..01feda941 100644--- a/src/stores/meetingRecordingStore.ts+++ b/src/stores/meetingRecordingStore.ts@@ -11,7 +11,12 @@ import {resolveInitialSpeakerCountOverride,resolveParticipantSpeakerCountSync,} from "../utils/participants";-import type { NoteItem, SystemAudioAccessResult, SystemAudioStrategy } from "../types/electron";+import type {+ MeetingSystemAudioInterruption,+ NoteItem,+ SystemAudioAccessResult,+ SystemAudioStrategy,+} from "../types/electron";import type { CalendarAttendee } from "../types/calendar";import {DEFAULT_SYSTEM_AUDIO_ACCESS,@@ -101,6 +106,11 @@ interface MeetingRecordingState {errorNonce: number;/** Latched once per recording when main reports the system-audio tap has produced only silence. */systemAudioSilentWarning: boolean;+ /** Most recent interruption; quiet warnings clear when audible system audio resumes. */+ systemAudioInterrupted: { recovering: boolean; reason: string } | null;+ /** Bumped on every interruption report so a repeated one still re-notifies. */+ systemAudioInterruptedNonce: number;+ systemAudioInterruptedDeliveredNonce: number;currentMicLevel: number;micCaptureStatus: "inactive" | "active" | "reconnecting" | "unavailable";windowWidth: number;@@ -438,6 +448,9 @@ export const useMeetingRecordingStore = create<MeetingRecordingState>()(() => ({error: null,errorNonce: 0,systemAudioSilentWarning: false,+ systemAudioInterrupted: null,+ systemAudioInterruptedNonce: 0,+ systemAudioInterruptedDeliveredNonce: 0,currentMicLevel: 0,micCaptureStatus: "inactive",windowWidth: typeof window !== "undefined" ? window.innerWidth : SIDE_PANEL_BREAKPOINT_PX,@@ -818,10 +831,23 @@ export async function startRecording(args: StartRecordingArgs): Promise<boolean>completedDiarization: null,error: null,systemAudioSilentWarning: false,+ systemAudioInterrupted: null,micCaptureStatus: "inactive",});isRecordingFlag = true;+ let systemAudioAvailabilityResolved = false;+ let pendingSystemAudioInterruption: MeetingSystemAudioInterruption | null = null;+ const publishSystemAudioInterruption = (data: MeetingSystemAudioInterruption): void => {+ logger.warn("Meeting system audio was interrupted", data, "meeting");+ useMeetingRecordingStore.setState((state) => ({+ systemAudioInterrupted: {+ recovering: data.recovering === true,+ reason: data.reason,+ },+ systemAudioInterruptedNonce: state.systemAudioInterruptedNonce + 1,+ }));+ };let setupMicResult: MediaStream | null = null;let setupSystemCaptureResult: { stream: MediaStream | null; error: Error | null } = {stream: null,@@ -850,6 +876,32 @@ export async function startRecording(args: StartRecordingArgs): Promise<boolean>};try {+ // Main capture can fail while microphone permission is still pending.+ // Keep its latest report until setup establishes whether this session+ // actually has system audio, including a possible mic-only fallback.+ const interruptedCleanup = window.electronAPI?.onMeetingSystemAudioInterrupted?.((data) => {+ if (activeRecordingSessionId !== sessionId || !isRecordingFlag) return;+ if (!systemAudioAvailabilityResolved) {+ pendingSystemAudioInterruption = data;+ } else if (sessionSystemAudioActive) {+ publishSystemAudioInterruption(data);+ }+ });+ const resumedCleanup = window.electronAPI?.onMeetingSystemAudioResumed?.(() => {+ if (activeRecordingSessionId !== sessionId || !isRecordingFlag) return;+ if (pendingSystemAudioInterruption?.reason === "gone_quiet") {+ pendingSystemAudioInterruption = null;+ }+ if (useMeetingRecordingStore.getState().systemAudioInterrupted?.reason === "gone_quiet") {+ useMeetingRecordingStore.setState({ systemAudioInterrupted: null });+ }+ });+ ipcCleanups.push(() => {+ pendingSystemAudioInterruption = null;+ interruptedCleanup?.();+ resumedCleanup?.();+ });+if (preparePromise) {logger.debug("Waiting for in-flight prepare to finish...", {}, "meeting");await preparePromise;@@ -956,6 +1008,7 @@ export async function startRecording(args: StartRecordingArgs): Promise<boolean>setupSystemCaptureResult = { stream: null, error: null };isRecordingFlag = false;isStartingFlag = false;+ await cleanup();releaseSession();return;}@@ -1407,6 +1460,11 @@ export async function startRecording(args: StartRecordingArgs): Promise<boolean>const systemAudioAvailable = systemAudioHandledInMain || systemStream !== null;sessionSystemAudioActive = systemAudioAvailable;+ systemAudioAvailabilityResolved = true;+ if (systemAudioAvailable && pendingSystemAudioInterruption) {+ publishSystemAudioInterruption(pendingSystemAudioInterruption);+ }+ pendingSystemAudioInterruption = null;try {const availabilityResult =await window.electronAPI?.meetingTranscriptionSetSystemAudioAvailable?.(@@ -1494,6 +1552,7 @@ export async function stopRecording(expectedSessionId?: string): Promise<StopRecsystemPartialSpeakerId: null,systemPartialSpeakerName: null,systemAudioSilentWarning: false,+ systemAudioInterrupted: null,currentMicLevel: 0,});return { diarizationSessionId: null, stopped: false };@@ -1580,6 +1639,7 @@ export async function stopRecording(expectedSessionId?: string): Promise<StopRecsystemPartialSpeakerId: null,systemPartialSpeakerName: null,systemAudioSilentWarning: false,+ systemAudioInterrupted: null,currentMicLevel: 0,});diff --git a/src/types/electron.ts b/src/types/electron.tsindex cd6680c9d..fe97ab007 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -693,6 +693,12 @@ export type SystemAudioMode = "native" | "loopback" | "portal" | "unsupported";export type SystemAudioStrategy ="native" | "loopback" | "pipewire-loopback" | "wasapi-loopback" | "unsupported";+export interface MeetingSystemAudioInterruption {+ systemAudioStrategy: SystemAudioStrategy;+ reason: "no_audio_delivered" | "device_invalidated" | "gone_quiet";+ recovering: boolean;+}+export interface SystemAudioAccessResult {granted: boolean;status: "granted" | "denied" | "not-determined" | "restricted" | "unknown" | "unsupported";@@ -2792,6 +2798,10 @@ declare global {callback: (data: { systemAudioStrategy: SystemAudioStrategy }) => void) => () => void;onMeetingSystemAudioDegraded?: (callback: () => void) => () => void;+ onMeetingSystemAudioInterrupted?: (+ callback: (data: MeetingSystemAudioInterruption) => void+ ) => () => void;+ onMeetingSystemAudioResumed?: (callback: () => void) => () => void;// Speaker diarizationdownloadDiarizationModels?: () => Promise<{ success: boolean; error?: string }>;diff --git a/test/components/meetingInterruptionWarning.test.js b/test/components/meetingInterruptionWarning.test.jsnew file mode 100644index 000000000..4714e3f70--- /dev/null+++ b/test/components/meetingInterruptionWarning.test.js@@ -0,0 +1,262 @@+const { createRequire } = require("node:module");+const requireRepo = createRequire(require("node:path").resolve(__dirname, "../../package.json"));+const test = require("node:test");+const assert = require("node:assert/strict");+const React = requireRepo("react");+const { createRoot } = requireRepo("react-dom/client");+const { createRendererServer, installBrowserGlobals, installHookDom, installMicCaptureGlobals } =+ requireRepo("./test/lib/rendererTestHarness");++async function setup(t) {+ let root;+ let store;+ t.after(async () => {+ if (store) await React.act(async () => store.stopRecording());+ if (root) await React.act(async () => root.unmount());+ delete globalThis.__interruptionToasts;+ delete globalThis.__interruptionDismissals;+ });+ const listeners = {};+ const noop = () => () => {};+ const api = {+ checkSystemAudioAccess: async () => ({+ granted: true,+ status: "granted",+ mode: "native",+ strategy: "native",+ }),+ meetingTranscriptionStart: async () => ({+ success: true,+ systemAudioMode: "native",+ systemAudioStrategy: "native",+ }),+ meetingTranscriptionSetSystemAudioAvailable: async () => ({ success: true }),+ meetingTranscriptionStop: async () => ({ success: true }),+ meetingTranscriptionSend() {},+ onMeetingTranscriptionSegment: noop,+ onMeetingSpeakerIdentified: noop,+ onMeetingSpeakersMerged: noop,+ onMeetingSessionSpeakerConfigUpdated: noop,+ onMeetingTranscriptionError: noop,+ onMeetingTranscriptionFatalError: noop,+ onMeetingSystemAudioSilent: noop,+ onMeetingSystemAudioInterrupted(callback) {+ listeners.interrupted = callback;+ return () => {+ if (listeners.interrupted === callback) listeners.interrupted = null;+ };+ },+ onMeetingSystemAudioResumed(callback) {+ listeners.resumed = callback;+ return () => {+ if (listeners.resumed === callback) listeners.resumed = null;+ };+ },+ };+ installBrowserGlobals(t, { window: { electronAPI: api } });+ installMicCaptureGlobals(t);+ const container = installHookDom(t);+ globalThis.document.visibilityState = "visible";+ globalThis.document.hidden = false;+ let focused = true;+ globalThis.document.hasFocus = () => focused;+ const events = new Map();+ for (const target of [globalThis.window, globalThis.document]) {+ target.addEventListener = (name, callback) => events.set(name, callback);+ target.removeEventListener = (name, callback) => {+ if (events.get(name) === callback) events.delete(name);+ };+ }+ const focus = async (value) => {+ focused = value;+ await React.act(async () => events.get("focus")?.());+ };+ const reveal = async () => {+ globalThis.document.hidden = false;+ globalThis.document.visibilityState = "visible";+ await React.act(async () => events.get("visibilitychange")?.());+ };+ globalThis.__interruptionToasts = [];+ globalThis.__interruptionDismissals = [];+ const vite = await createRendererServer(t, {+ cachePrefix: "pr2040-renderer-warning-review-",+ mockModules: {+ "/ui/useToast": `const toast = (props) => { globalThis.__interruptionToasts.push({ ...props, visibility: globalThis.document.visibilityState }); return String(globalThis.__interruptionToasts.length); }; const dismiss = (id) => globalThis.__interruptionDismissals.push(id); export const useToast = () => ({ toast, dismiss });`,+ },+ });+ const { default: Mount } = await vite.ssrLoadModule("/components/MeetingRecordingMount.tsx");+ store = await vite.ssrLoadModule("/stores/meetingRecordingStore.ts");+ root = createRoot(container);+ const render = async (visible, strict = false) =>+ React.act(async () =>+ root.render(+ visible+ ? strict+ ? React.createElement(React.StrictMode, null, React.createElement(Mount))+ : React.createElement(Mount)+ : null+ )+ );+ await render(true);+ await React.act(async () =>+ store.startRecording({ noteId: null, noteTitle: null, folderId: null, autoEndEligible: false })+ );+ assert.equal(store.useMeetingRecordingStore.getState().isRecording, true);+ const interrupt = async (details = {}) =>+ React.act(async () =>+ listeners.interrupted({+ systemAudioStrategy: "native",+ reason: "no_audio_delivered",+ recovering: false,+ ...details,+ })+ );+ const { default: i18n } = await vite.ssrLoadModule("/i18n.ts");+ const resume = async () => React.act(async () => listeners.resumed?.());+ return { store, render, interrupt, resume, focus, reveal, i18n };+}++test("audio resuming while hidden discards the quiet warning before focus", async (t) => {+ const { interrupt, resume, focus, reveal } = await setup(t);+ globalThis.document.visibilityState = "hidden";+ await focus(false);+ await interrupt({ reason: "gone_quiet" });+ await resume();+ await reveal();+ await focus(true);+ assert.equal(globalThis.__interruptionToasts.length, 0);+});++test("audio resuming with Mount absent clears its pending quiet warning", async (t) => {+ const { render, interrupt, resume } = await setup(t);+ await render(false);+ await interrupt({ reason: "gone_quiet" });+ await resume();+ await render(true);+ assert.equal(globalThis.__interruptionToasts.length, 0);+});++test("audio resuming dismisses a visible quiet warning even after unmount", async (t) => {+ const { render, interrupt, resume } = await setup(t);+ await interrupt({ reason: "gone_quiet" });+ assert.equal(globalThis.__interruptionToasts.length, 1);+ await render(false);+ await resume();+ assert.deepEqual(globalThis.__interruptionDismissals, ["1"]);+ await render(true);+ assert.equal(globalThis.__interruptionToasts.length, 1);+});++test("hidden and covered warnings wait for a focused visible window", async (t) => {+ const { interrupt, focus, reveal } = await setup(t);+ globalThis.document.hidden = true;+ globalThis.document.visibilityState = "hidden";+ await interrupt();+ assert.equal(globalThis.__interruptionToasts.length, 0);+ await focus(false);+ await reveal();+ assert.equal(globalThis.__interruptionToasts.length, 0);+ await focus(true);+ assert.equal(globalThis.__interruptionToasts.length, 1);+ assert.equal(globalThis.__interruptionToasts[0].duration, 0);+});++test("unmounted events deliver once on remount and repeated events replace the warning", async (t) => {+ const { render, interrupt } = await setup(t);+ await render(false);+ await interrupt();+ await render(true);+ assert.equal(globalThis.__interruptionToasts.length, 1);+ await render(true);+ assert.equal(globalThis.__interruptionToasts.length, 1);+ await render(false);+ assert.equal(globalThis.__interruptionDismissals.length, 0);+ await render(true);+ assert.equal(globalThis.__interruptionToasts.length, 1);+ await interrupt();+ assert.equal(globalThis.__interruptionToasts.length, 2);+});++test("persistent warning offers a scoped stop and does not leak into the next session", async (t) => {+ const { store, interrupt, render } = await setup(t);+ await interrupt();+ const warning = globalThis.__interruptionToasts[0];+ assert.equal(warning.duration, 0);+ assert.ok(warning.action);+ await React.act(async () => warning.action.props.onClick());+ assert.equal(store.useMeetingRecordingStore.getState().isRecording, false);+ await React.act(async () =>+ store.startRecording({ noteId: null, noteTitle: null, folderId: null, autoEndEligible: false })+ );+ await React.act(async () => warning.action.props.onClick());+ assert.equal(store.useMeetingRecordingStore.getState().isRecording, true);+ await render(false);+ await render(true);+ assert.equal(globalThis.__interruptionToasts.length, 1);+});++test("stop before returning discards an unseen interruption", async (t) => {+ const { store, interrupt, focus, render } = await setup(t);+ await focus(false);+ await interrupt();+ await React.act(async () => store.stopRecording());+ await focus(true);+ await render(false);+ await render(true);+ assert.equal(globalThis.__interruptionToasts.length, 0);+});++test("latest pending event delivers once and cautious warnings do not offer stop", async (t) => {+ const { interrupt, focus } = await setup(t);+ await focus(false);+ await interrupt();+ await interrupt({ reason: "gone_quiet" });+ await focus(true);+ assert.equal(globalThis.__interruptionToasts.length, 1);+ assert.equal(globalThis.__interruptionToasts[0].title, "Meeting audio has gone quiet");+ assert.equal(globalThis.__interruptionToasts[0].action, undefined);+ await interrupt({ recovering: true });+ assert.deepEqual(globalThis.__interruptionDismissals, ["1"]);+ assert.equal(globalThis.__interruptionToasts[1].title, "Meeting audio interrupted");+ assert.equal(globalThis.__interruptionToasts[1].action, undefined);+ assert.equal(globalThis.__interruptionToasts[1].duration, 8000);+});++test("locale changes do not replay delivered interruptions", async (t) => {+ const { interrupt, i18n } = await setup(t);+ await interrupt();+ try {+ await React.act(async () => i18n.changeLanguage("es"));+ assert.equal(globalThis.__interruptionToasts.length, 1);+ } finally {+ await React.act(async () => i18n.changeLanguage("en"));+ }+});++test("StrictMode does not replay or dismiss a delivered persistent warning", async (t) => {+ const { interrupt, render } = await setup(t);+ await interrupt();+ await render(false);+ await render(true, true);+ assert.equal(globalThis.__interruptionToasts.length, 1);+ assert.equal(globalThis.__interruptionDismissals.length, 0);+});++test("replacement while hidden dismisses the old warning and remains pending", async (t) => {+ const { interrupt, focus } = await setup(t);+ await interrupt();+ await focus(false);+ await interrupt();+ assert.deepEqual(globalThis.__interruptionDismissals, ["1"]);+ assert.equal(globalThis.__interruptionToasts.length, 1);+ await focus(true);+ assert.equal(globalThis.__interruptionToasts.length, 2);+});++test("stopping with Mount absent removes its persistent warning", async (t) => {+ const { store, interrupt, render } = await setup(t);+ await interrupt();+ await render(false);+ await React.act(async () => store.stopRecording());+ assert.deepEqual(globalThis.__interruptionDismissals, ["1"]);+});diff --git a/test/helpers/audioTapManagerWarnings.test.js b/test/helpers/audioTapManagerWarnings.test.jsnew file mode 100644index 000000000..27046dd78--- /dev/null+++ b/test/helpers/audioTapManagerWarnings.test.js@@ -0,0 +1,190 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const { EventEmitter } = require("node:events");+const Module = require("node:module");+const createMeetingSystemAudioWatchdog = require("../../src/helpers/meetingSystemAudioWatchdog");++// The tap helper reports a stranded device as a stderr warning rather than by+// exiting, so the forwarding path is the only thing that can tell the main+// process capture has stopped (#1990). Warnings must never settle or fail the+// start handshake either, which is what the mid-handshake test pins.++const managerModulePath = require.resolve("../../src/helpers/audioTapManager");+const originalLoad = Module._load;++let lastChild = null;++function createFakeChild() {+ const child = new EventEmitter();+ child.stdout = new EventEmitter();+ child.stderr = new EventEmitter();+ child.killed = false;+ child.kill = () => {+ child.killed = true;+ setImmediate(() => child.emit("exit", 0, null));+ };+ return child;+}++function loadManagerClass() {+ delete require.cache[managerModulePath];+ Module._load = function loadWithMocks(request, parent, isMain) {+ if (request === "child_process") {+ return {+ spawn: () => {+ lastChild = createFakeChild();+ return lastChild;+ },+ };+ }+ if (request === "./debugLogger") {+ return { info() {}, debug() {}, error() {}, warn() {} };+ }+ return originalLoad(request, parent, isMain);+ };+ try {+ return require(managerModulePath);+ } finally {+ Module._load = originalLoad;+ }+}++const AudioTapManager = loadManagerClass();++// Same instance-seam style as windowsLoopbackAudioManager.test.js: the binary+// lookup and the macOS version gate are not what is under test here.+function createManager() {+ const manager = new AudioTapManager();+ manager.isSupported = () => true;+ manager._prepareBinary = () => "/fake/macos-audio-tap";+ return manager;+}++const emitLine = (child, message) => child.stderr.emit("data", `${JSON.stringify(message)}\n`);++test("a device_invalidated warning reaches onWarning and not onError", async () => {+ const manager = createManager();+ const warnings = [];+ const errors = [];++ const started = manager.start({+ onChunk: () => {},+ onError: (error) => errors.push(error),+ onWarning: (warning) => warnings.push(warning),+ });+ emitLine(lastChild, { type: "start" });+ await started;++ emitLine(lastChild, {+ type: "warning",+ code: "device_invalidated",+ reason: "default_output_changed",+ message: "System audio device changed",+ });++ assert.equal(warnings.length, 1);+ assert.equal(warnings[0].code, "device_invalidated");+ assert.equal(warnings[0].reason, "default_output_changed");+ assert.deepEqual(errors, []);+});++test("a warning during the start handshake neither resolves nor rejects it", async () => {+ const manager = createManager();+ const warnings = [];+ let settled = false;++ const started = manager.start({ onWarning: (warning) => warnings.push(warning) }).then(() => {+ settled = true;+ });++ const child = lastChild;+ emitLine(child, { type: "warning", code: "listener_unavailable", message: "no listener" });+ await new Promise((resolve) => setImmediate(resolve));++ assert.equal(warnings.length, 1);+ assert.equal(settled, false, "a warning must not be mistaken for the start acknowledgement");++ emitLine(child, { type: "start" });+ await started;+ assert.equal(settled, true);+});++test("restarting an already-running manager re-points the warning handler", async () => {+ const manager = createManager();+ const first = [];+ const second = [];++ const started = manager.start({ onWarning: (warning) => first.push(warning) });+ const child = lastChild;+ emitLine(child, { type: "start" });+ await started;++ // startManagedMeetingSystemAudio calls start() again on the live manager, and+ // the new session's callbacks have to take over from the previous ones.+ await manager.start({ onWarning: (warning) => second.push(warning) });+ emitLine(child, { type: "warning", code: "device_invalidated", message: "changed" });++ assert.deepEqual(first, []);+ assert.equal(second.length, 1);+});++test("stop drops the warning handler along with the rest of the callbacks", async () => {+ const manager = createManager();+ const warnings = [];++ const started = manager.start({ onWarning: (warning) => warnings.push(warning) });+ const child = lastChild;+ emitLine(child, { type: "start" });+ await started;++ await manager.stop();+ assert.equal(manager.onWarning, null);++ emitLine(child, { type: "warning", code: "device_invalidated", message: "changed" });+ assert.deepEqual(warnings, [], "a warning from the dead helper must not reach the new session");+});++test("a device warning beside the replacement start acknowledgement triggers another recovery", async (t) => {+ const manager = createManager();+ const interruptions = [];+ const watchdog = createMeetingSystemAudioWatchdog({+ onInterrupted: (payload) => interruptions.push(payload),+ });+ const flush = () => new Promise((resolve) => setImmediate(resolve));+ const startCapture = () =>+ manager.start({+ onWarning: (warning) => {+ if (warning.code === "device_invalidated") watchdog.reportDeviceInvalidated();+ },+ });+ watchdog.attachCapture({ stop: () => manager.stop(), start: startCapture });+ t.after(async () => {+ watchdog.stop();+ await manager.stop();+ });++ const started = startCapture();+ emitLine(lastChild, { type: "start" });+ await started;+ watchdog.start({ systemAudioStrategy: "native", watchesDelivery: true });+ emitLine(lastChild, { type: "warning", code: "device_invalidated" });+ await flush();+ await flush();+ const replacement = lastChild;++ // A busy main process can read both native messages in the same pipe chunk.+ replacement.stderr.emit(+ "data",+ '{"type":"start"}\n{"type":"warning","code":"device_invalidated"}\n'+ );+ await flush();+ await flush();++ assert.notEqual(lastChild, replacement, "the invalidated replacement must be replaced too");+ emitLine(lastChild, { type: "start" });+ await flush();+ assert.equal(interruptions.length, 2);+ assert.ok(+ interruptions.every((entry) => entry.reason === "device_invalidated" && entry.recovering)+ );+});diff --git a/test/helpers/meetingAudioTimeline.test.js b/test/helpers/meetingAudioTimeline.test.jsnew file mode 100644index 000000000..96d741062--- /dev/null+++ b/test/helpers/meetingAudioTimeline.test.js@@ -0,0 +1,378 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const fs = require("node:fs");+const path = require("node:path");+const vm = require("node:vm");+const { createRequire } = require("node:module");+const createWatchdog = require("../../src/helpers/meetingSystemAudioWatchdog");+const micGate = require("../../src/helpers/meetingMicGate");++// Execute the real IPC closures with only their native/network boundaries replaced.+const ipcPath = path.join(__dirname, "../../src/helpers/ipcHandlers.js");+const source = fs.readFileSync(ipcPath, "utf8");+function section(from, to) {+ return source.slice(source.indexOf(from), source.indexOf(to));+}+function harness({ native = true, local = false } = {}) {+ let now = 0;+ let onChunk;+ const pcm = [];+ const live = [];+ const streamed = [];+ const observed = [];+ const echo = [];+ const aec = [];+ const capture = {+ start: async (callbacks) => {+ onChunk = callbacks.onChunk;+ },+ stop: async () => {},+ };+ const watchdog = createWatchdog({ now: () => now });+ const watchdogChunks = [];+ const recordChunk = watchdog.recordChunk;+ watchdog.recordChunk = (audible) => {+ watchdogChunks.push(audible);+ recordChunk(audible);+ };+ const context = {+ require: (specifier) => {+ const imported = createRequire(ipcPath)(specifier);+ return specifier === "./meetingAudioTimeline"+ ? () => imported({ now: () => now, wallNow: () => now })+ : imported;+ },+ Buffer,+ path,+ Date: { now: () => now },+ performance: { now: () => now },+ BrowserWindow: { fromWebContents: () => null },+ debugLogger: { warn() {}, debug() {}, error() {}, info() {} },+ meetingDetectionEngine: { recordMeetingAudioChunk: (_, buffer) => observed.push(buffer) },+ audioTapManager: native ? capture : {},+ meetingAecManager: {+ processSystemBuffer: (buffer) => {+ aec.push(buffer);+ return true;+ },+ },+ meetingSystemAudioWatchdog: watchdog,+ meetingEchoLeakDetector: { recordSystemChunk: (buffer) => echo.push(buffer) },+ meetingAecEnabled: true,+ flushPendingMeetingMicChunks() {},+ meetingLiveSpeakerActive: true,+ meetingLiveSpeakerStartedAt: null,+ liveSpeakerIdentifier: { feedAudio: (buffer) => live.push(buffer) },+ meetingDiarizationStream: null,+ meetingDiarizationStartedAt: null,+ meetingDiarizationPath: null,+ fs: { createWriteStream: () => ({ write: (buffer) => pcm.push(buffer) }) },+ meetingSystemAudioHeard: false,+ dropMeetingMicDiarizationCapture() {},+ ...micGate,+ meetingLocalMode: local,+ meetingLocalBuffers: { mic: [], system: [] },+ meetingSendCounts: { mic: 0, system: 0 },+ _meetingSystemStreaming: { sendAudio: (buffer) => streamed.push(buffer) },+ meetingReconnectAudioBuffers: { mic: [], system: [] },+ meetingReconnectAudioBytes: { mic: 0, system: 0 },+ meetingReconnectReplaySources: new Set(),+ MEETING_RECONNECT_BUFFER_MAX_BYTES: 24000 * 2 * 30,+ capture,+ };+ vm.createContext(context);+ vm.runInContext(+ `+ ${section("const resetMeetingReconnectAudio =", "// Labels the socket for field logs")}+ ${section("const dispatchMeetingAudioBuffer =", "const stopMeetingAec =")}+ ${section("const sendMeetingAudio =", "// The Windows helper reports capture_silent")}+ ${section("const startManagedMeetingSystemAudio =", "const fallBackToMicOnly =")}+ globalThis.startCapture = () => startManagedMeetingSystemAudio({ sender: {} }, capture, "warning");+ globalThis.replaySystemAudio = (streaming) => replayMeetingReconnectAudio("system", streaming);+ `,+ context+ );+ return {+ context,+ watchdog,+ watchdogChunks,+ pcm,+ live,+ streamed,+ observed,+ echo,+ aec,+ at: (value) => {+ now = value;+ },+ start: context.startCapture,+ chunk: (durationMs = 100, silent = false) =>+ onChunk(Buffer.alloc(durationMs * 48, silent ? 0 : 1)),+ restart: async () => {+ watchdog.reportDeviceInvalidated();+ await new Promise(setImmediate);+ },+ };+}+const bytes = (buffers) => buffers.reduce((total, buffer) => total + buffer.length, 0);++function createTimestampedStream(provider, connectedAt) {+ const StreamingClient = require(`../../src/helpers/${provider}Streaming`);+ const streaming = new StreamingClient();+ const frames = [];+ const timestamps = [];+ streaming.ws = { readyState: 1, send: (buffer) => frames.push(buffer) };+ streaming.isConnected = true;+ streaming.configAccepted = true;+ streaming.sessionStartedAt = connectedAt;+ streaming.onFinalTranscript = (_text, timestamp) => timestamps.push(timestamp);+ return {+ streaming,+ frames,+ timestamps,+ finalizeSpeech(afterFrame = 0) {+ const speechStart = frames.findIndex(+ (buffer, index) => index >= afterFrame && buffer.some((value) => value !== 0)+ );+ assert.ok(speechStart >= 0, "the provider must receive the recovered speech");+ const start = bytes(frames.slice(0, speechStart)) / 48000;+ const message =+ provider === "deepgram"+ ? {+ type: "Results",+ is_final: true,+ start,+ channel: { alternatives: [{ transcript: "I am back" }] },+ }+ : { type: "transcript", data: { isFinal: true, start, text: "I am back" } };+ streaming.handleMessage(Buffer.from(JSON.stringify(message)));+ },+ };+}++for (const provider of ["deepgram", "corti"]) {+ test(`${provider} preserves an established socket's origin across capture recovery`, async () => {+ const run = harness();+ await run.start();+ run.watchdog.start({ systemAudioStrategy: "native", watchesDelivery: true });+ const existing = createTimestampedStream(provider, 0);+ run.context._meetingSystemStreaming = existing.streaming;+ run.at(1000);+ run.chunk(1000);+ const previousFrameCount = existing.frames.length;+ run.at(8000);+ await run.restart();+ run.at(10000);+ run.chunk();+ existing.finalizeSpeech(previousFrameCount);+ assert.deepEqual(existing.timestamps, [10000]);+ assert.equal(existing.streaming.sessionStartedAt, 1000);+ run.watchdog.stop();+ });++ test(`${provider} capture recovery keeps transcript time after the provider reconnects`, async () => {+ const run = harness();+ await run.start();+ run.watchdog.start({ systemAudioStrategy: "native", watchesDelivery: true });+ run.chunk(1000);+ run.at(8000);+ await run.restart();+ const recovered = createTimestampedStream(provider, 8000);+ run.context._meetingSystemStreaming = recovered.streaming;+ run.at(10000);+ run.chunk();+ recovered.finalizeSpeech();+ assert.deepEqual(recovered.timestamps, [10000]);+ assert.equal(bytes(run.pcm), 484800, "diarization retains the entire recording timeline");+ assert.equal(bytes(run.live), 484800);+ run.watchdog.stop();+ });++ test(`${provider} reconnect replay retains the sample origin of recovered audio`, async () => {+ const run = harness();+ await run.start();+ run.watchdog.start({ systemAudioStrategy: "native", watchesDelivery: true });+ run.chunk(1000);+ run.at(8000);+ await run.restart();+ run.context.meetingReconnectReplaySources.add("system");+ run.context._meetingSystemStreaming = { sendAudio: () => false };+ run.at(10000);+ run.chunk();+ const recovered = createTimestampedStream(provider, 12000);+ assert.equal(run.context.replaySystemAudio(recovered.streaming), true);+ recovered.finalizeSpeech();+ assert.deepEqual(recovered.timestamps, [10000]);+ run.watchdog.stop();+ });++ test(`${provider} trimmed reconnect replay uses the first retained sample's origin`, async () => {+ const run = harness();+ await run.start();+ run.watchdog.start({ systemAudioStrategy: "native", watchesDelivery: true });+ run.chunk(1000);+ run.at(8000);+ await run.restart();+ run.context.meetingReconnectReplaySources.add("system");+ run.context.MEETING_RECONNECT_BUFFER_MAX_BYTES = 48000;+ run.context._meetingSystemStreaming = { sendAudio: () => false };+ run.at(10000);+ run.chunk();+ const recovered = createTimestampedStream(provider, 12000);+ assert.equal(run.context.replaySystemAudio(recovered.streaming), true);+ assert.equal(bytes(recovered.frames), 48000);+ recovered.finalizeSpeech();+ assert.deepEqual(recovered.timestamps, [10000]);+ run.watchdog.stop();+ });+}++test("real watchdog recovery preserves the missing seconds for diarization, live ID and streaming", async () => {+ const run = harness();+ await run.start();+ run.watchdog.start({ systemAudioStrategy: "native", watchesDelivery: true });+ run.chunk();+ run.watchdog.tick();+ for (const at of [2000, 4000, 6000, 8000]) {+ run.at(at);+ run.watchdog.tick();+ }+ await new Promise(setImmediate);+ run.at(8250);+ run.chunk();+ // Chunk starts at 8.25s: 0.1s recorded + 8.15s missing + 0.1s recovered.+ for (const buffers of [run.pcm, run.live, run.streamed]) {+ assert.equal(bytes(buffers), 400800);+ assert.ok(buffers.slice(1, -1).every((buffer) => buffer.every((value) => value === 0)));+ assert.ok(buffers.every((buffer) => buffer.length <= 48000));+ }+ assert.equal(run.observed.length, 2);+ assert.equal(run.watchdogChunks.length, 2);+ assert.equal(run.echo.length, 2);+ assert.equal(run.aec.length, 2);+ assert.equal(run.context.meetingSendCounts.system, 2);+ run.watchdog.stop();+});++test("normal jitter, buffered bursts and actual silence never insert synthetic audio", async () => {+ const run = harness();+ await run.start();+ run.chunk();+ run.at(2500);+ run.chunk(1000, true);+ run.chunk(1500);+ assert.equal(bytes(run.pcm), 124800);+ assert.equal(run.pcm.length, 3);+});++test("repeated recovery pads only the remaining deficit and a new capture resets the timeline", async () => {+ const run = harness();+ await run.start();+ run.watchdog.start({ systemAudioStrategy: "native", watchesDelivery: true });+ run.chunk();+ run.at(2000);+ await run.restart();+ run.at(2200);+ run.chunk(100, true);+ run.at(3000);+ await run.restart();+ run.at(3500);+ run.chunk();+ assert.equal(bytes(run.pcm), 172800);+ run.watchdog.stop();+ await run.start();+ run.at(100000);+ run.chunk();+ assert.equal(bytes(run.pcm), 177600);+});++test("a restart before the first packet does not move the first-packet anchor", async () => {+ const run = harness();+ await run.start();+ run.watchdog.start({ systemAudioStrategy: "native", watchesDelivery: true });+ run.at(2000);+ await run.restart();+ run.at(3000);+ run.chunk();+ assert.equal(bytes(run.pcm), 4800);+ assert.equal(run.context.meetingDiarizationStartedAt, 3000);+});++test("other native platform helpers keep their existing idle-gap behavior", async () => {+ const run = harness({ native: false });+ await run.start();+ run.watchdog.start({ systemAudioStrategy: "wasapi-loopback" });+ run.chunk();+ run.at(10000);+ await run.restart();+ run.chunk();+ assert.equal(bytes(run.pcm), 9600);+});++test("local transcription excludes synthetic silence while diarization retains the gap", async () => {+ const run = harness({ local: true });+ await run.start();+ run.watchdog.start({ systemAudioStrategy: "native", watchesDelivery: true });+ run.chunk();+ run.at(10000);+ await run.restart();+ run.chunk();+ assert.equal(bytes(run.context.meetingLocalBuffers.system), 9600);+ assert.equal(bytes(run.pcm), 484800);+});++test("restarts without packets are padded only once when audio finally arrives", async () => {+ const run = harness();+ await run.start();+ run.watchdog.start({ systemAudioStrategy: "native", watchesDelivery: true });+ run.chunk();+ run.at(2000);+ await run.restart();+ run.at(12000);+ await run.restart();+ run.at(15000);+ run.chunk();+ run.chunk();+ assert.equal(bytes(run.pcm), 729600);+ assert.equal(run.observed.length, 3);+});++test("a long recovery uses bounded reusable silence rather than a gap-sized allocation", async () => {+ const run = harness();+ await run.start();+ run.watchdog.start({ systemAudioStrategy: "native", watchesDelivery: true });+ run.chunk();+ run.at(2000);+ await run.restart();+ run.at(3600000);+ run.chunk();+ assert.equal(bytes(run.pcm), 172804800);+ const silence = run.pcm.slice(1, -1);+ assert.ok(silence.every((buffer) => buffer.length <= 48000));+ assert.equal(new Set(silence.map((buffer) => buffer.buffer)).size, 1);+});++test("recovery silence plus AssemblyAI's pending partial packet stays within its frame limit", () => {+ const AssemblyAiStreaming = require("../../src/helpers/assemblyAiStreaming");+ const createTimeline = require("../../src/helpers/meetingAudioTimeline");+ let now = 0;+ const timeline = createTimeline({ now: () => now });+ const streaming = new AssemblyAiStreaming();+ const frames = [];+ streaming.ws = { readyState: 1, send: (frame) => frames.push(frame) };+ const send = (buffer) => streaming.sendAudio(buffer);+ timeline.write(Buffer.alloc(960, 1), send); // 20ms, below the provider's flush threshold.+ assert.equal(frames.length, 0);+ timeline.markRestart();+ now = 2020;+ timeline.write(Buffer.alloc(4800, 2), send);+ assert.ok(+ frames.every((frame) => frame.length <= 48000),+ "24kHz frames must not exceed 1000ms"+ );+ const output = Buffer.concat(frames);+ assert.equal(output.length, 101760); // 20ms real + 2000ms missing + 100ms real.+ assert.ok(output.subarray(0, 960).every((value) => value === 1));+ assert.ok(output.subarray(960, 96960).every((value) => value === 0));+ assert.ok(output.subarray(96960).every((value) => value === 2));+});diff --git a/test/helpers/meetingStreamingWiring.test.js b/test/helpers/meetingStreamingWiring.test.jsindex a3a1f9dba..1b007e14d 100644--- a/test/helpers/meetingStreamingWiring.test.js+++ b/test/helpers/meetingStreamingWiring.test.js@@ -84,3 +84,76 @@ test("a silent Windows capture hands the live session to renderer loopback", ()2);});++test("the system-audio watchdog is armed beside the silence timer and torn down with it", () => {+ // Same gate as the one-shot warning: never armed for a mic-only session.+ assert.match(+ source,+ /result\.systemAudioStrategy && result\.systemAudioStrategy !== "unsupported"[\s\S]{0,240}?startMeetingSystemAudioWatchdog\(meetingConnectionWin, result\.systemAudioStrategy\)/+ );+ // Only the macOS tap emits a chunk per period, so only it can be judged on+ // delivery gaps; the loopback helpers may legitimately go idle.+ assert.match(source, /watchesDelivery: systemAudioStrategy === "native"/);++ // The ticker is the only timer the controller owns, and leaking one would+ // keep judging a session that has already ended.+ assert.match(+ source,+ /const stopMeetingSystemAudioWatchdog = \(\) => \{[\s\S]{0,400}?clearMeetingSystemAudioTicker\(\);[\s\S]{0,300}?meetingSystemAudioWatchdog\.stop\(\);/+ );++ // Arming runs after capture has started and attached itself, so it must clear+ // only the ticker. Calling the full teardown here detaches the capture the+ // start path just installed, which is how the first draft shipped a watchdog+ // that reported stalls it could not recover from.+ const armStart = source.indexOf("const startMeetingSystemAudioWatchdog");+ assert.ok(armStart >= 0);+ const armSection = source.slice(armStart, source.indexOf("const rollbackMeetingTranscriptionStart"));+ assert.match(armSection, /clearMeetingSystemAudioTicker\(\);/);+ assert.doesNotMatch(armSection, /stopMeetingSystemAudioWatchdog\(\);/);+ assert.doesNotMatch(armSection, /detachCapture\(\)/);++ // Every path that clears the one-shot timer also stops the watchdog, plus the+ // mic-only fallback, which strands the restart hook on a dead manager.+ for (const [label, from, to] of [+ [+ "rollback",+ "const rollbackMeetingTranscriptionStart",+ "const setupDictationCallbacks",+ ],+ ["stop", "const stopMeetingTranscription", "const meetingTranscriptionLifecycle"],+ ["mic-only fallback", "const fallBackToMicOnly", "const startMeetingSystemAudio = async"],+ ]) {+ const start = source.indexOf(from);+ const end = source.indexOf(to);+ assert.ok(start >= 0 && end > start, `${label} section not found`);+ assert.match(source.slice(start, end), /stopMeetingSystemAudioWatchdog\(\);/, label);+ }+});++test("the watchdog sees every system chunk and the helper's device warning", () => {+ // The audible check used to be skipped once the call had been heard, which is+ // exactly the window in which the tap dies (#1990).+ assert.match(+ source,+ /const audible = rms >= MEETING_MIC_SILENCE_RMS \|\| peak >= MEETING_MIC_SILENCE_PEAK;\s*meetingSystemAudioWatchdog\.recordChunk\(audible\);/+ );+ assert.match(+ source,+ /if \(code === "device_invalidated"\) \{\s*meetingSystemAudioWatchdog\.reportDeviceInvalidated\(\);/+ );++ // Recovery bounces the helper process, so the capture must be attached by the+ // same call that started it, not by the arming path.+ const managedStart = source.indexOf("const startManagedMeetingSystemAudio");+ assert.ok(managedStart >= 0);+ const managedSection = source.slice(managedStart, source.indexOf("const fallBackToMicOnly"));+ assert.match(+ managedSection,+ /meetingSystemAudioWatchdog\.attachCapture\(\{\s*stop: \(\) => manager\.stop\(\),\s*start: startCapture,/+ );++ // The interruption reaches the renderer; a log-only warning would leave the+ // user watching a recording that has stopped hearing the call.+ assert.match(source, /send\("meeting-system-audio-interrupted", payload\)/);+});diff --git a/test/helpers/meetingSystemAudioWatchdog.test.js b/test/helpers/meetingSystemAudioWatchdog.test.jsnew file mode 100644index 000000000..105ca9a7f--- /dev/null+++ b/test/helpers/meetingSystemAudioWatchdog.test.js@@ -0,0 +1,462 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const createMeetingSystemAudioWatchdog = require("../../src/helpers/meetingSystemAudioWatchdog");++const { STALL_MS, GONE_QUIET_MS, MAX_RESTARTS, TICK_GAP_MS } = createMeetingSystemAudioWatchdog;++const START_TIME = 1_000_000;+const TICK_MS = 2_000;++// The restart hook settles on the microtask queue, so every helper that can+// trigger one yields the loop before the caller inspects state.+const flush = () => new Promise((resolve) => setImmediate(resolve));++const createHarness = ({ startImpl, stopImpl } = {}) => {+ let now = START_TIME;+ const calls = [];+ const interruptions = [];+ const resumed = [];++ const watchdog = createMeetingSystemAudioWatchdog({+ now: () => now,+ onInterrupted: (payload) => interruptions.push(payload),+ onResumed: () => resumed.push(now),+ });++ // Mirrors startManagedMeetingSystemAudio: capture is attached when it starts,+ // which is before the session is armed.+ const attach = () =>+ watchdog.attachCapture({+ stop: () => {+ calls.push("stop");+ return Promise.resolve(stopImpl?.());+ },+ start: () => {+ calls.push("start");+ return Promise.resolve(startImpl?.());+ },+ });++ const advance = async (ms) => {+ let remaining = ms;+ while (remaining > 0) {+ const step = Math.min(TICK_MS, remaining);+ now += step;+ remaining -= step;+ watchdog.tick();+ await flush();+ }+ };++ return {+ watchdog,+ calls,+ interruptions,+ resumed,+ attach,+ advance,+ jump: (ms) => {+ now += ms;+ },+ restarts: () => calls.filter((call) => call === "start").length,+ deliver: (audible = false) => watchdog.recordChunk(audible),+ };+};++// Real ordering: attach, arm, then the first chunk proves the stream delivers.+const startNative = (harness, { deliver = true } = {}) => {+ harness.attach();+ harness.watchdog.start({ systemAudioStrategy: "native", watchesDelivery: true });+ if (deliver) harness.deliver(true);+};++test("a stream that keeps delivering never restarts", async () => {+ const h = createHarness();+ startNative(h);++ for (let i = 0; i < 100; i += 1) {+ h.deliver(true);+ await h.advance(TICK_MS);+ }++ assert.deepEqual(h.calls, []);+ assert.deepEqual(h.interruptions, []);+});++test("delivery stopping past the stall window restarts capture once", async () => {+ const h = createHarness();+ startNative(h);++ await h.advance(STALL_MS);+ assert.equal(h.restarts(), 0, "must not fire before the window elapses");++ await h.advance(TICK_MS);+ assert.deepEqual(h.calls, ["stop", "start"], "recovery bounces the helper process");+ assert.deepEqual(h.interruptions, [+ { systemAudioStrategy: "native", reason: "no_audio_delivered", recovering: true },+ ]);+});++// The regression that shipped in the first draft: capture attaches during start+// and the session is armed afterwards, so arming must not detach it. It did,+// and the watchdog reported stalls it could not actually recover from.+test("arming the session keeps the capture attached by the start path", async () => {+ const h = createHarness();+ h.attach();+ h.watchdog.start({ systemAudioStrategy: "native", watchesDelivery: true });+ h.deliver(true);++ h.watchdog.reportDeviceInvalidated();+ await flush();++ assert.deepEqual(h.calls, ["stop", "start"], "arming must not drop the restart target");+});++test("a restart resets the stall window rather than firing again immediately", async () => {+ const h = createHarness();+ startNative(h);++ await h.advance(STALL_MS + TICK_MS);+ assert.equal(h.restarts(), 1);++ // Still no audio, but the clock restarts from the restart, not the last chunk.+ await h.advance(STALL_MS);+ assert.equal(h.restarts(), 1);++ await h.advance(TICK_MS);+ assert.equal(h.restarts(), 2);+});++test("restart attempts are capped and the give-up report is sent exactly once", async () => {+ const h = createHarness();+ startNative(h);++ await h.advance((STALL_MS + TICK_MS) * (MAX_RESTARTS + 4));++ assert.equal(h.restarts(), MAX_RESTARTS);+ const gaveUp = h.interruptions.filter((entry) => entry.recovering === false);+ assert.equal(gaveUp.length, 1);+ assert.equal(gaveUp[0].reason, "no_audio_delivered");+ assert.equal(h.interruptions.filter((entry) => entry.recovering === true).length, MAX_RESTARTS);+});++test("giving up suppresses the later quiet report rather than piling on", async () => {+ const h = createHarness();+ startNative(h);++ await h.advance((STALL_MS + TICK_MS) * (MAX_RESTARTS + 1));+ assert.equal(h.interruptions.filter((entry) => entry.recovering === false).length, 1);++ // The delivery branch is latched off, so the quiet check is reachable again;+ // it must not add a second, weaker verdict on top of the give-up one.+ await h.advance(GONE_QUIET_MS + TICK_MS);+ assert.equal(h.interruptions.filter((entry) => entry.reason === "gone_quiet").length, 0);+});++test("a device event after the cap is exhausted cannot hand out more attempts", async () => {+ const h = createHarness();+ startNative(h);++ await h.advance((STALL_MS + TICK_MS) * (MAX_RESTARTS + 1));+ assert.equal(h.restarts(), MAX_RESTARTS);++ h.watchdog.reportDeviceInvalidated();+ await flush();+ assert.equal(h.restarts(), MAX_RESTARTS);+ assert.equal(h.interruptions.filter((entry) => entry.recovering === false).length, 1);+});++test("a device invalidation restarts without waiting for the stall window", async () => {+ const h = createHarness();+ startNative(h);++ h.watchdog.reportDeviceInvalidated();+ await flush();++ assert.deepEqual(h.calls, ["stop", "start"]);+ assert.deepEqual(h.interruptions, [+ { systemAudioStrategy: "native", reason: "device_invalidated", recovering: true },+ ]);+});++test("device warnings from retiring capture do not use another restart attempt", async () => {+ const h = createHarness({ stopImpl: () => h.watchdog.reportDeviceInvalidated() });+ startNative(h);++ h.watchdog.reportDeviceInvalidated();+ await flush();++ assert.deepEqual(h.calls, ["stop", "start"]);+ assert.equal(h.interruptions.length, 1);+});++test("replacement device warnings respect the restart cap", async () => {+ const h = createHarness({ startImpl: () => h.watchdog.reportDeviceInvalidated() });+ startNative(h);++ h.watchdog.reportDeviceInvalidated();+ await flush();++ assert.equal(h.restarts(), MAX_RESTARTS);+ assert.equal(h.interruptions.filter((entry) => entry.recovering).length, MAX_RESTARTS);+ assert.deepEqual(h.interruptions.at(-1), {+ systemAudioStrategy: "native",+ reason: "device_invalidated",+ recovering: false,+ });+});++test("a restart that throws still clears the in-flight flag", async () => {+ const h = createHarness({+ startImpl: () => Promise.reject(new Error("helper would not start")),+ });+ startNative(h);++ await h.advance(STALL_MS + TICK_MS);+ assert.equal(h.restarts(), 1);++ await h.advance(STALL_MS + TICK_MS);+ assert.equal(h.restarts(), 2, "a failed restart must not wedge the watchdog");+});++test("nothing is judged while a restart is still in flight", async () => {+ let release;+ const h = createHarness({+ startImpl: () => new Promise((resolve) => (release = resolve)),+ });+ startNative(h);++ await h.advance(STALL_MS + TICK_MS);+ assert.equal(h.restarts(), 1);++ // The helper is slow to come back; ticks during that must not stack restarts.+ await h.advance(STALL_MS * 3);+ assert.equal(h.restarts(), 1);++ release();+ await flush();+ await h.advance(STALL_MS + TICK_MS);+ assert.equal(h.restarts(), 2);+});++test("delivery gaps are ignored for strategies that may legitimately go idle", async () => {+ const h = createHarness();+ h.attach();+ h.watchdog.start({ systemAudioStrategy: "wasapi-loopback", watchesDelivery: false });+ h.deliver(true);++ await h.advance(STALL_MS * 10);++ assert.deepEqual(h.calls, []);+ assert.deepEqual(h.interruptions, []);+});++// Capture that never produced a single chunk belongs to the one-shot silence+// warning. Judging it here would restart during startup, before the renderer+// has even registered its listener.+test("a stream that has never delivered is not judged on delivery", async () => {+ const h = createHarness();+ startNative(h, { deliver: false });++ await h.advance(STALL_MS * 10);+ assert.deepEqual(h.calls, []);+ assert.deepEqual(h.interruptions, []);++ // Once it has delivered, the window applies normally.+ h.deliver(true);+ await h.advance(STALL_MS + TICK_MS);+ assert.equal(h.restarts(), 1);+});++// Date.now() jumps across sleep, and a blocked main process delivers the timer+// tick before the stdout data it should have been judging.+test("a tick gap longer than the sleep threshold rebases the delivery window", async () => {+ const h = createHarness();+ startNative(h);++ await h.advance(TICK_MS);+ h.jump(TICK_GAP_MS + STALL_MS * 5);+ h.watchdog.tick();+ await flush();++ assert.deepEqual(h.calls, [], "waking from sleep must not read as a dead tap");++ // The rebase is one-shot: a stall that outlives it is still caught.+ await h.advance(STALL_MS + TICK_MS);+ assert.equal(h.restarts(), 1);+});++test("a call that goes quiet is reported once and never restarted", async () => {+ const h = createHarness();+ startNative(h);++ // Chunks keep arriving, so delivery is healthy; they are simply silent.+ let elapsed = 0;+ while (elapsed <= GONE_QUIET_MS + TICK_MS * 2) {+ h.deliver(false);+ await h.advance(TICK_MS);+ elapsed += TICK_MS;+ }++ assert.deepEqual(h.calls, [], "a quiet call must never cost the user a restart");+ assert.deepEqual(h.interruptions, [+ { systemAudioStrategy: "native", reason: "gone_quiet", recovering: false },+ ]);+});++test("a session that was never audible does not report going quiet", async () => {+ const h = createHarness();+ h.attach();+ h.watchdog.start({ systemAudioStrategy: "wasapi-loopback", watchesDelivery: false });++ let elapsed = 0;+ while (elapsed <= GONE_QUIET_MS * 2) {+ h.deliver(false);+ await h.advance(TICK_MS);+ elapsed += TICK_MS;+ }++ // That case belongs to the one-shot start-of-session warning, not here.+ assert.deepEqual(h.interruptions, []);+});++for (const systemAudioStrategy of ["native", "wasapi-loopback"]) {+ test(`${systemAudioStrategy} warns again when a new quiet period follows audible recovery`, async () => {+ const h = createHarness();+ h.attach();+ h.watchdog.start({ systemAudioStrategy, watchesDelivery: systemAudioStrategy === "native" });++ for (let quietPeriod = 0; quietPeriod < 2; quietPeriod += 1) {+ h.deliver(true);+ for (let elapsed = 0; elapsed <= GONE_QUIET_MS + TICK_MS; elapsed += TICK_MS) {+ h.deliver(false);+ await h.advance(TICK_MS);+ }+ assert.equal(h.interruptions.length, quietPeriod + 1);+ }++ assert.deepEqual(h.calls, [], "silence is a warning, never a reason to restart");+ assert.ok(h.interruptions.every((entry) => entry.reason === "gone_quiet"));+ });+}++test("audible audio reports resumption once for each quiet warning", async () => {+ const h = createHarness();+ startNative(h);+ assert.deepEqual(h.resumed, [], "ordinary audible capture is not a resumption");++ for (let quietPeriod = 0; quietPeriod < 2; quietPeriod += 1) {+ for (let elapsed = 0; elapsed <= GONE_QUIET_MS + TICK_MS; elapsed += TICK_MS) {+ h.deliver(false);+ await h.advance(TICK_MS);+ }+ assert.equal(h.resumed.length, quietPeriod, "silence must keep the warning active");+ h.deliver(true);+ assert.equal(h.resumed.length, quietPeriod + 1, "audible return clears the quiet warning");+ h.deliver(true);+ assert.equal(h.resumed.length, quietPeriod + 1, "subsequent audible chunks do not repeat it");+ }+});++test("resumption does not clear historical capture interruptions", async () => {+ const h = createHarness();+ startNative(h);+ h.watchdog.reportDeviceInvalidated();+ await flush();+ h.deliver(true);++ assert.equal(h.interruptions.length, 1);+ assert.deepEqual(h.resumed, []);+});++test("audible audio after exhausted recovery does not rearm the weaker quiet warning", async () => {+ const h = createHarness();+ startNative(h);+ await h.advance((STALL_MS + TICK_MS) * (MAX_RESTARTS + 1));++ h.deliver(true);+ for (let elapsed = 0; elapsed <= GONE_QUIET_MS + TICK_MS; elapsed += TICK_MS) {+ h.deliver(false);+ await h.advance(TICK_MS);+ }+ h.watchdog.reportDeviceInvalidated();+ await flush();++ assert.equal(h.restarts(), MAX_RESTARTS);+ assert.equal(h.interruptions.filter((entry) => !entry.recovering).length, 1);+ assert.equal(h.interruptions.filter((entry) => entry.reason === "gone_quiet").length, 0);+ assert.deepEqual(h.resumed, [], "audible capture cannot dismiss exhausted recovery");+});++test("stop ends the session and a late restart cannot resurrect it", async () => {+ let release;+ const h = createHarness({+ startImpl: () => new Promise((resolve) => (release = resolve)),+ });+ startNative(h);++ await h.advance(STALL_MS + TICK_MS);+ assert.equal(h.restarts(), 1);++ h.watchdog.stop();+ release();+ await flush();++ await h.advance(STALL_MS * 5);+ assert.equal(h.restarts(), 1);+});++// A meeting can end in the window between the helper being killed and the+// replacement being spawned. Without the generation check the restart would+// complete anyway and leave an orphan process holding a CoreAudio process tap.+test("a session that ends mid-restart never starts a replacement helper", async () => {+ let releaseStop;+ const h = createHarness({+ stopImpl: () => new Promise((resolve) => (releaseStop = resolve)),+ });+ startNative(h);++ await h.advance(STALL_MS + TICK_MS);+ assert.deepEqual(h.calls, ["stop"], "suspended between the two halves");++ h.watchdog.stop();+ releaseStop();+ await flush();+ await flush();++ assert.deepEqual(h.calls, ["stop"], "the replacement must never be spawned");+});++test("a session that ends while the replacement is starting stops the orphan", async () => {+ let releaseStart;+ const h = createHarness({+ startImpl: () => new Promise((resolve) => (releaseStart = resolve)),+ });+ startNative(h);++ await h.advance(STALL_MS + TICK_MS);+ assert.deepEqual(h.calls, ["stop", "start"]);++ h.watchdog.reportDeviceInvalidated();+ h.watchdog.stop();+ releaseStart();+ await flush();+ await flush();++ assert.deepEqual(h.calls, ["stop", "start", "stop"], "the helper it started must be killed");+ assert.equal(h.interruptions.length, 1, "queued invalidation must not outlive its session");+});++test("starting again clears the previous session's attempt count", async () => {+ const h = createHarness();+ startNative(h);+ await h.advance((STALL_MS + TICK_MS) * (MAX_RESTARTS + 1));+ assert.equal(h.restarts(), MAX_RESTARTS);++ h.watchdog.stop();+ startNative(h);+ await h.advance(STALL_MS + TICK_MS);++ assert.equal(h.restarts(), MAX_RESTARTS + 1);+});diff --git a/test/stores/meetingRecordingStoreSystemAudioInterrupted.test.js b/test/stores/meetingRecordingStoreSystemAudioInterrupted.test.jsnew file mode 100644index 000000000..8799adf2f--- /dev/null+++ b/test/stores/meetingRecordingStoreSystemAudioInterrupted.test.js@@ -0,0 +1,346 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const {+ createRendererServer,+ installBrowserGlobals,+ installMicCaptureGlobals,+} = require("../lib/rendererTestHarness");++// Sibling of meetingRecordingStoreSystemAudioSilence: that warning latches once+// per recording, this one repeats, because capture can stop and be restarted+// several times in one call and each break is worth surfacing (#1990).++const START_ARGS = {+ noteId: null,+ noteTitle: null,+ folderId: null,+ autoEndEligible: false,+};++function createElectronAPI({ systemAudioMode, systemAudioStrategy }) {+ const listeners = { systemAudioInterrupted: null, systemAudioResumed: null };+ const noopListener = () => () => {};+ const api = {+ checkSystemAudioAccess: async () => ({+ granted: systemAudioMode !== "unsupported",+ status: systemAudioMode === "unsupported" ? "unsupported" : "granted",+ mode: systemAudioMode,+ strategy: systemAudioStrategy,+ }),+ meetingTranscriptionStart: async () => ({+ success: true,+ systemAudioMode,+ systemAudioStrategy,+ }),+ meetingTranscriptionSetSystemAudioAvailable: async () => ({ success: true }),+ meetingTranscriptionStop: async () => ({ success: true }),+ meetingTranscriptionSend: () => {},+ onMeetingTranscriptionSegment: noopListener,+ onMeetingSpeakerIdentified: noopListener,+ onMeetingSpeakersMerged: noopListener,+ onMeetingSessionSpeakerConfigUpdated: noopListener,+ onMeetingTranscriptionError: noopListener,+ onMeetingTranscriptionFatalError: noopListener,+ onMeetingSystemAudioSilent: noopListener,+ onMeetingSystemAudioInterrupted: (callback) => {+ listeners.systemAudioInterrupted = callback;+ return () => {+ if (listeners.systemAudioInterrupted === callback) {+ listeners.systemAudioInterrupted = null;+ }+ };+ },+ onMeetingSystemAudioResumed: (callback) => {+ listeners.systemAudioResumed = callback;+ return () => {+ if (listeners.systemAudioResumed === callback) listeners.systemAudioResumed = null;+ };+ },+ };+ return { api, listeners };+}++async function loadStore(t, api) {+ installBrowserGlobals(t, {+ window: { electronAPI: api, setTimeout: (fn, ms) => setTimeout(fn, ms) },+ });+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-meeting-system-audio-interrupted-test-",+ });+ return vite.ssrLoadModule("/stores/meetingRecordingStore.ts");+}++async function startWithPendingMicrophone(t, startResult) {+ installMicCaptureGlobals(t);+ const micStream = await navigator.mediaDevices.getUserMedia();+ const microphone = Promise.withResolvers();+ const micRequested = Promise.withResolvers();+ const mainStarted = Promise.withResolvers();+ navigator.mediaDevices.getUserMedia = () => {+ micRequested.resolve();+ return microphone.promise;+ };+ const { api, listeners } = createElectronAPI({+ systemAudioMode: "native",+ systemAudioStrategy: "native",+ });+ const startMain = api.meetingTranscriptionStart;+ api.meetingTranscriptionStart = async () => {+ mainStarted.resolve();+ return startResult ?? startMain();+ };+ const store = await loadStore(t, api);+ const starting = store.startRecording(START_ARGS);+ const finishStart = async () => {+ microphone.resolve(micStream);+ await starting;+ };+ t.after(async () => {+ await finishStart();+ await store.stopRecording();+ });+ await Promise.all([mainStarted.promise, micRequested.promise]);+ return { api, listeners, store, finishStart };+}++const stoppedCapture = {+ systemAudioStrategy: "native",+ reason: "no_audio_delivered",+ recovering: false,+};++test("the final startup interruption survives a pending microphone permission", async (t) => {+ const { listeners, store, finishStart } = await startWithPendingMicrophone(t);+ for (let attempt = 0; attempt < 3; attempt += 1) {+ listeners.systemAudioInterrupted?.({ ...stoppedCapture, recovering: true });+ }+ listeners.systemAudioInterrupted?.(stoppedCapture);+ assert.equal(store.useMeetingRecordingStore.getState().systemAudioInterrupted, null);++ await finishStart();++ assert.deepEqual(store.useMeetingRecordingStore.getState().systemAudioInterrupted, {+ recovering: false,+ reason: "no_audio_delivered",+ });+ assert.equal(store.useMeetingRecordingStore.getState().systemAudioInterruptedNonce, 1);+});++test("resumed audio discards a quiet warning buffered during microphone setup", async (t) => {+ const { listeners, store, finishStart } = await startWithPendingMicrophone(t);+ listeners.systemAudioInterrupted?.({ ...stoppedCapture, reason: "gone_quiet" });+ listeners.systemAudioResumed?.();+ await finishStart();+ assert.equal(store.useMeetingRecordingStore.getState().systemAudioInterrupted, null);+ assert.equal(store.useMeetingRecordingStore.getState().systemAudioInterruptedNonce, 0);+});++test("resumed audio preserves a capture-loss warning buffered during microphone setup", async (t) => {+ const { listeners, store, finishStart } = await startWithPendingMicrophone(t);+ listeners.systemAudioInterrupted?.(stoppedCapture);+ listeners.systemAudioResumed?.();+ await finishStart();+ assert.deepEqual(store.useMeetingRecordingStore.getState().systemAudioInterrupted, {+ recovering: false,+ reason: "no_audio_delivered",+ });+});++test("a mic-only fallback discards buffered system-audio interruptions", async (t) => {+ const { listeners, store, finishStart } = await startWithPendingMicrophone(t, {+ success: true,+ systemAudioMode: "unsupported",+ systemAudioStrategy: "unsupported",+ });+ listeners.systemAudioInterrupted?.(stoppedCapture);+ await finishStart();+ listeners.systemAudioInterrupted?.(stoppedCapture);+ assert.equal(store.useMeetingRecordingStore.getState().isRecording, true);+ assert.equal(store.useMeetingRecordingStore.getState().systemAudioInterrupted, null);+ assert.equal(store.useMeetingRecordingStore.getState().systemAudioInterruptedNonce, 0);+});++test("failed startup removes early interruption listeners before another session", async (t) => {+ const { api, listeners, store, finishStart } = await startWithPendingMicrophone(t, {+ success: false,+ error: "capture startup failed",+ });+ const lateInterrupted = listeners.systemAudioInterrupted;+ const lateResumed = listeners.systemAudioResumed;+ listeners.systemAudioInterrupted?.(stoppedCapture);+ await finishStart();+ assert.equal(store.useMeetingRecordingStore.getState().isRecording, false);+ assert.equal(store.useMeetingRecordingStore.getState().systemAudioInterrupted, null);+ assert.equal(listeners.systemAudioInterrupted, null);+ assert.equal(listeners.systemAudioResumed, null);++ api.meetingTranscriptionStart = async () => ({+ success: true,+ systemAudioMode: "native",+ systemAudioStrategy: "native",+ });+ await store.startRecording(START_ARGS);+ listeners.systemAudioInterrupted({ ...stoppedCapture, reason: "gone_quiet" });+ lateInterrupted?.(stoppedCapture);+ lateResumed?.();+ assert.equal(+ store.useMeetingRecordingStore.getState().systemAudioInterrupted.reason,+ "gone_quiet"+ );+});++test("stopping during microphone setup discards buffered warnings and early listeners", async (t) => {+ const { listeners, store, finishStart } = await startWithPendingMicrophone(t);+ listeners.systemAudioInterrupted?.(stoppedCapture);+ const stopping = store.stopRecording();+ await finishStart();+ await stopping;+ assert.equal(listeners.systemAudioInterrupted, null);+ assert.equal(listeners.systemAudioResumed, null);+ assert.equal(store.useMeetingRecordingStore.getState().systemAudioInterrupted, null);+ assert.equal(store.useMeetingRecordingStore.getState().systemAudioInterruptedNonce, 0);+});++test("resumed audio clears only quiet warnings without creating another interruption", async (t) => {+ installMicCaptureGlobals(t);+ const { api, listeners } = createElectronAPI({+ systemAudioMode: "native",+ systemAudioStrategy: "native",+ });+ const store = await loadStore(t, api);+ t.after(() => store.stopRecording());+ await store.startRecording(START_ARGS);+ listeners.systemAudioInterrupted({ ...stoppedCapture, reason: "gone_quiet" });+ const nonce = store.useMeetingRecordingStore.getState().systemAudioInterruptedNonce;+ listeners.systemAudioResumed?.();+ assert.equal(store.useMeetingRecordingStore.getState().systemAudioInterrupted, null);+ assert.equal(store.useMeetingRecordingStore.getState().systemAudioInterruptedNonce, nonce);+ for (const recovering of [true, false]) {+ listeners.systemAudioInterrupted({ ...stoppedCapture, recovering });+ listeners.systemAudioResumed?.();+ assert.deepEqual(store.useMeetingRecordingStore.getState().systemAudioInterrupted, {+ reason: "no_audio_delivered",+ recovering,+ });+ }++ const lateResumed = listeners.systemAudioResumed;+ await store.stopRecording();+ await store.startRecording(START_ARGS);+ listeners.systemAudioInterrupted({ ...stoppedCapture, reason: "gone_quiet" });+ lateResumed?.();+ assert.equal(+ store.useMeetingRecordingStore.getState().systemAudioInterrupted.reason,+ "gone_quiet"+ );+});++test("every interruption bumps the nonce so a repeat still notifies", async (t) => {+ const { api, listeners } = createElectronAPI({+ systemAudioMode: "native",+ systemAudioStrategy: "native",+ });+ const store = await loadStore(t, api);++ assert.equal(await store.startRecording(START_ARGS), true);+ assert.equal(store.useMeetingRecordingStore.getState().systemAudioInterrupted, null);+ assert.equal(typeof listeners.systemAudioInterrupted, "function");++ listeners.systemAudioInterrupted({+ systemAudioStrategy: "native",+ reason: "no_audio_delivered",+ recovering: true,+ });+ let state = store.useMeetingRecordingStore.getState();+ assert.deepEqual(state.systemAudioInterrupted, {+ recovering: true,+ reason: "no_audio_delivered",+ });+ const firstNonce = state.systemAudioInterruptedNonce;++ listeners.systemAudioInterrupted({+ systemAudioStrategy: "native",+ reason: "device_invalidated",+ recovering: true,+ });+ state = store.useMeetingRecordingStore.getState();+ assert.equal(state.systemAudioInterruptedNonce, firstNonce + 1);++ await store.stopRecording();+ assert.equal(store.useMeetingRecordingStore.getState().systemAudioInterrupted, null);+});++// The reason has to survive the hop: the toast copy for a quiet call is much+// weaker than the one for capture that has actually stopped, and only the+// reason separates them.+test("a give-up report carries recovering false and its reason through to the store", async (t) => {+ const { api, listeners } = createElectronAPI({+ systemAudioMode: "native",+ systemAudioStrategy: "native",+ });+ const store = await loadStore(t, api);++ assert.equal(await store.startRecording(START_ARGS), true);+ listeners.systemAudioInterrupted({+ systemAudioStrategy: "native",+ reason: "gone_quiet",+ recovering: false,+ });++ assert.deepEqual(store.useMeetingRecordingStore.getState().systemAudioInterrupted, {+ recovering: false,+ reason: "gone_quiet",+ });++ listeners.systemAudioInterrupted({+ systemAudioStrategy: "native",+ reason: "no_audio_delivered",+ recovering: false,+ });+ assert.deepEqual(store.useMeetingRecordingStore.getState().systemAudioInterrupted, {+ recovering: false,+ reason: "no_audio_delivered",+ });++ await store.stopRecording();+});++test("an interruption arriving after stop is ignored without crashing", async (t) => {+ const { api, listeners } = createElectronAPI({+ systemAudioMode: "native",+ systemAudioStrategy: "native",+ });+ const store = await loadStore(t, api);++ assert.equal(await store.startRecording(START_ARGS), true);+ const lateCallback = listeners.systemAudioInterrupted;+ await store.stopRecording();++ lateCallback({+ systemAudioStrategy: "native",+ reason: "no_audio_delivered",+ recovering: true,+ });+ assert.equal(store.useMeetingRecordingStore.getState().systemAudioInterrupted, null);+});++test("no interruption state when the session had no system audio", async (t) => {+ installMicCaptureGlobals(t);+ const { api, listeners } = createElectronAPI({+ systemAudioMode: "unsupported",+ systemAudioStrategy: "unsupported",+ });+ const store = await loadStore(t, api);++ assert.equal(await store.startRecording(START_ARGS), true);+ assert.equal(store.useMeetingRecordingStore.getState().micCaptureStatus, "active");++ listeners.systemAudioInterrupted({+ systemAudioStrategy: "unsupported",+ reason: "no_audio_delivered",+ recovering: true,+ });+ assert.equal(store.useMeetingRecordingStore.getState().systemAudioInterrupted, null);++ await store.stopRecording();+});