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(meetings): keep the Windows silent-capture check armed for the whole call (#2233)
void23e5668a1f34
diff --git a/.github/workflows/build-windows-system-audio-helper.yml b/.github/workflows/build-windows-system-audio-helper.ymlindex 536882da8..cbb677390 100644--- a/.github/workflows/build-windows-system-audio-helper.yml+++ b/.github/workflows/build-windows-system-audio-helper.yml@@ -12,7 +12,7 @@ on:version:description: 'Version tag (e.g., 1.0.0)'required: false- default: '1.0.0'+ default: '1.2.0'type: stringpermissions:@@ -70,8 +70,8 @@ jobs:- name: Create or update releaseuses: softprops/action-gh-release@v2with:- tag_name: windows-system-audio-helper-v${{ inputs.version || '1.0.0' }}- name: Windows System Audio Helper v${{ inputs.version || '1.0.0' }}+ tag_name: windows-system-audio-helper-v${{ inputs.version || '1.2.0' }}+ name: Windows System Audio Helper v${{ inputs.version || '1.2.0' }}body: |Prebuilt Windows system audio helper binary for meeting transcription.diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7b4c89c11..e193b7afa 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- **Idle OpenWhispr no longer keeps a vector database and an inference process running.** The Qdrant sidecar and the embedding model started on every launch and stayed up for the whole session, and the meeting detectors ran from boot even with meeting notifications turned off. Semantic search now starts on the first assistant search, serves keyword results while it warms up, and releases Qdrant and the embedding session after five minutes without a search. Note edits made while it is asleep are journaled in the notes database and indexed on the next activation, so search results stay complete. The microphone and meeting-app detectors start only once your saved notification preferences are loaded, stop when meeting notifications are off, and a detector stopped mid-scan can no longer come back reporting a meeting app. (#2143)- **Assistant selection capture handles dormant macOS accessibility trees.** When accessibility exposes only a browser or Electron window, selection capture now tries a synthetic copy instead of assuming nothing is selected. The caret probe also waits long enough for its native retries to finish. Automatic answer delivery still requires a verified writable field at capture and delivery time: an unknown target keeps the answer in the panel and, with Auto-Paste enabled, copies it for manual paste. Dormant inputs still require manual paste because an empty copy cannot distinguish them from an integrated terminal, a page without an input, or some live selections. (#1952)+### Meetings++- **Teams meetings that recorded only your own voice.** Windows hands our native capture the audio of every app except ours — but not Microsoft Teams call audio, which arrives as digital silence no matter which process we aim at or which format we ask for, while the same audio is plainly there on the output device. Since 1.9.2 a recording that hit this switched to the fallback capture a few seconds in, except that the switch was armed only until the first sound we could hear: one notification, or Teams' own join chime, disarmed it, and the rest of the call was recorded without the other participants, with no warning beyond a generic “audio has gone quiet” three minutes later. The check now runs for the whole meeting and compares what we capture against what your speakers are really playing, so a call that goes missing after an earlier sound still switches over. The fallback only takes over once it hears audio our capture is missing, so a false alarm never drops a capture that was working. A meeting spent alongside continuously playing audio, such as music in a browser tab, can still mask it. (#1265, thanks @jaszczurovsky for the report, @TaiFeng and @jsholcomb for the workarounds, @wadamek65 and @KishenG for confirming, and @amarpreet2209 for finding in #1866 that the fallback capture hears Teams)+## [1.10.2] - 2026-09-15A hotfix for 1.10.1. Generate AI Summary with your own API key or an enterprise provider no longer times out on a real transcript, a recording with nothing substantive in it gets a one-line summary instead of a blank page and an error, and OpenRouter models can read screenshots again.diff --git a/CLAUDE.md b/CLAUDE.mdindex 141521b1e..30ea6c359 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -50,7 +50,7 @@ OpenWhispr is an Electron-based desktop dictation application that uses whisper.- **windows-key-listener.c**: C source for Windows low-level keyboard hook (Push-to-Talk)- **windows-mic-listener.c**: C source for WASAPI mic session monitor (event-driven mic detection)-- **windows-system-audio-helper.c**: C source for WASAPI process-loopback system audio capture (meeting transcription). Excludes OpenWhispr's own process tree, so it hears every app on every output device. Requires Windows 10 2004+; falls back to Chromium display-media loopback when unavailable, and mid-session when the helper emits a `capture_silent` warning (its own stream is silent while a render endpoint is metering output — activation success cannot detect that). Outputs 24 kHz mono s16le PCM on stdout, line-delimited JSON events on stderr (same protocol as linux-system-audio-helper)+- **windows-system-audio-helper.c**: C source for WASAPI process-loopback system audio capture (meeting transcription). Excludes OpenWhispr's own process tree, so it hears every app on every output device. Requires Windows 10 2004+; falls back to Chromium display-media loopback when unavailable. Mid-session, the helper emits a `capture_silent` warning when its own stream is silent while a render endpoint is metering output, checked every second for the whole session because Windows keeps some apps' streams out of process loopback (Teams call audio, #1265). Main then starts renderer loopback beside the helper, and `meetingSystemAudioHandover.js` gives loopback the system channel only after it hears audio the helper misses, so a false alarm never drops a working capture. Outputs 24 kHz mono s16le PCM on stdout, line-delimited JSON events on stderr (same protocol as linux-system-audio-helper)- **macos-mic-listener.swift**: Swift source for the CoreAudio process-object microphone listener (event-driven mic detection); falls back to aggregate device activity and retries PID monitoring from its heartbeat- **globe-listener.swift**: Swift source for macOS Globe/Fn key detection- **bin/**: Directory for compiled native binaries (whisper-cpp, nircmd, key/mic listeners)diff --git a/TROUBLESHOOTING.md b/TROUBLESHOOTING.mdindex 6dba65e89..f78dc7621 100644--- a/TROUBLESHOOTING.md+++ b/TROUBLESHOOTING.md@@ -156,7 +156,7 @@ On GNOME and KDE, the first automatic paste can show a remote-interaction permis1. System audio is captured by `windows-system-audio-helper.exe` (WASAPI process loopback), which hears every app on every output device — no permission prompt is needed2. If the helper is missing or fails (requires Windows 10 2004+), OpenWhispr automatically falls back to Chromium loopback, which only hears the _default_ output device — make sure your meeting app plays through the default device in that case-3. On some machines the helper starts successfully but captures only digital silence. OpenWhispr detects this a few seconds in (its capture is silent while an output device is still metering audio) and switches that recording to Chromium loopback; the debug log shows `Windows system audio helper captured only silence, switching to renderer loopback`+3. On some machines the helper starts successfully but captures only digital silence — and Microsoft Teams call audio appears to be hidden from it regardless of configuration. OpenWhispr detects this a few seconds in (its capture is silent while an output device is still metering audio), starts Chromium loopback alongside, and switches the recording to it once it hears audio the helper is missing; the debug log shows `Windows system audio helper captured only silence, starting renderer loopback beside it`, then `Renderer loopback took over system audio capture`. The check runs for the whole meeting, so a call that goes missing after some other sound was captured still switches over — though audio playing continuously alongside the meeting (music in a browser tab, say) can mask it, since our capture never falls silent4. If transcription shows "Continuing with microphone only", system audio capture failed entirely; check debug logs for `windows-system-audio-helper` entries**All Platforms:**diff --git a/resources/windows-system-audio-helper.c b/resources/windows-system-audio-helper.cindex 14b9e39bd..e475664df 100644--- a/resources/windows-system-audio-helper.c+++ b/resources/windows-system-audio-helper.c@@ -352,7 +352,9 @@ static HRESULT activate_process_loopback(* Activation succeeding proves only that the OS exposes process loopback; on* some machines it then delivers nothing but digital silence. Silence alone* is ambiguous — an idle machine looks identical — so it only counts as a- * failure while a render endpoint is metering real output.+ * failure while a render endpoint is metering real output. It stays armed+ * after audible samples: Windows hides some apps' streams from process+ * loopback (Teams call audio, openwhispr#1265) while passing others through.* ======================================================================== */static BOOL any_render_endpoint_audible(IMMDeviceEnumerator *enumerator)@@ -444,9 +446,9 @@ static int run_capture(DWORD excludePid, UINT32 sampleRate)LARGE_INTEGER lastSilenceCheck;UINT64 emittedFrames = 0;IMMDeviceEnumerator *deviceEnumerator = NULL;- /* Disarmed for good once real audio proves capture works, or once the- * warning has been emitted — either way there is nothing left to watch. */+ /* Disarmed once the warning is emitted or when no meter is available. */BOOL silenceDetectionArmed = TRUE;+ BOOL capturedAudibleThisTick = FALSE;int endpointAudibleTicks = 0;const char *errorCode = NULL;HRESULT hr;@@ -548,8 +550,9 @@ static int run_capture(DWORD excludePid, UINT32 sampleRate)}}- if (silenceDetectionArmed && samples_are_audible(monoBuffer, frames)) {- silenceDetectionArmed = FALSE;+ if (silenceDetectionArmed && !capturedAudibleThisTick &&+ samples_are_audible(monoBuffer, frames)) {+ capturedAudibleThisTick = TRUE;}if (!write_pcm(monoBuffer, frames)) {@@ -615,13 +618,14 @@ static int run_capture(DWORD excludePid, UINT32 sampleRate)if (silenceDetectionArmed &&now.QuadPart - lastSilenceCheck.QuadPart >= qpcFrequency.QuadPart) {lastSilenceCheck = now;- if (!any_render_endpoint_audible(deviceEnumerator)) {+ if (capturedAudibleThisTick || !any_render_endpoint_audible(deviceEnumerator)) {endpointAudibleTicks = 0;} else if (++endpointAudibleTicks >= CAPTURE_SILENT_CONFIRM_TICKS) {silenceDetectionArmed = FALSE;emit_event("warning", "capture_silent","Process loopback captured silence while a render endpoint was playing");}+ capturedAudibleThisTick = FALSE;}fflush(stdout);diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex 0600426bc..50e988e85 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -112,6 +112,7 @@ const liveSpeakerIdentifier = require("./liveSpeakerIdentifier");const { supportsLiveSpeakerIdentification } = require("./liveSpeakerIdPolicy");const MeetingEchoLeakDetector = require("./meetingEchoLeakDetector");const createMeetingSystemAudioWatchdog = require("./meetingSystemAudioWatchdog");+const createMeetingSystemAudioHandover = require("./meetingSystemAudioHandover");const {partitionPendingMicFinals,isRiskyMicDuplicateProfile,@@ -6921,7 +6922,7 @@ class IPCHandlers {meetingMicDiarizationPath = null;meetingMicDiarizationStartedAt = null;meetingSystemAudioHeard = false;- meetingSystemAudioDegraded = false;+ meetingSystemAudioHandover.reset();meetingDiarizationSegments = [];const { pcmPath, startedAt, diarizedSource, cleanupPcmPaths } = resolveDiarizationInput({systemPcmPath,@@ -7514,7 +7515,7 @@ class IPCHandlers {let meetingMicDiarizationPath = null;let meetingMicDiarizationStartedAt = null;let meetingSystemAudioHeard = false;- let meetingSystemAudioDegraded = false;+ const meetingSystemAudioHandover = createMeetingSystemAudioHandover();let meetingDiarizationSegments = [];let meetingLiveSpeakerActive = false;let meetingLiveSpeakerState = null;@@ -8120,7 +8121,7 @@ class IPCHandlers {meetingDiarizationStartedAt = null;dropMeetingMicDiarizationCapture();meetingSystemAudioHeard = false;- meetingSystemAudioDegraded = false;+ meetingSystemAudioHandover.reset();meetingDiarizationSegments = [];meetingLocalWin = null;meetingLocalTranscript = "";@@ -8860,24 +8861,28 @@ class IPCHandlers {};// The Windows helper reports capture_silent when its own stream is silent- // while a render endpoint is playing: activation succeeded but no audio- // will ever arrive, so hand the live session to Chromium's renderer- // loopback. The silence watchdog stays armed in case that fails too.- const degradeMeetingSystemAudioToLoopback = async (event) => {- if (meetingSystemAudioDegraded || meetingSystemAudioHeard) return;- meetingSystemAudioDegraded = true;+ // while a render endpoint is playing, which activation success cannot+ // detect. Start renderer loopback beside it; the handover decides whether+ // it takes the channel.+ const degradeMeetingSystemAudioToLoopback = (event) => {+ if (!meetingSystemAudioHandover.begin()) return;debugLogger.warn(- "Windows system audio helper captured only silence, switching to renderer loopback",+ "Windows system audio helper captured only silence, starting renderer loopback beside it",{},"meeting");- await this.windowsLoopbackAudioManager?.stop().catch(() => {});const win = BrowserWindow.fromWebContents(event.sender);if (win && !win.isDestroyed()) {win.webContents.send("meeting-system-audio-degraded");}};+ const completeMeetingSystemAudioHandover = () => {+ debugLogger.info("Renderer loopback took over system audio capture", {}, "meeting");+ meetingSystemAudioWatchdog.detachCapture();+ void this.windowsLoopbackAudioManager?.stop().catch(() => {});+ };+const startManagedMeetingSystemAudio = (event, manager, warningLabel, onWarningCode) => {const win = BrowserWindow.fromWebContents(event.sender);const timeline =@@ -8888,6 +8893,7 @@ class IPCHandlers {captureStarted = true;return manager.start({onChunk: (chunk) => {+ if (!meetingSystemAudioHandover.acceptNativeChunk(chunk)) return;if (timeline) {timeline.write(chunk, (buffer, synthetic, capturedAt) =>sendMeetingAudio(buffer, "system", synthetic, capturedAt)@@ -8978,7 +8984,7 @@ class IPCHandlers {"Windows system audio warning",(code) => {if (code === "capture_silent") {- void degradeMeetingSystemAudioToLoopback(event);+ degradeMeetingSystemAudioToLoopback(event);}});@@ -9018,7 +9024,13 @@ class IPCHandlers {};ipcMain.on("meeting-transcription-send", (_event, audioBuffer, source) => {- sendMeetingAudio(audioBuffer, source);+ const buffer = Buffer.isBuffer(audioBuffer) ? audioBuffer : Buffer.from(audioBuffer);+ if (source === "system") {+ const route = meetingSystemAudioHandover.acceptRendererChunk(buffer);+ if (route === "drop") return;+ if (route === "takeover") completeMeetingSystemAudioHandover();+ }+ sendMeetingAudio(buffer, source);});const stopMeetingTranscription = async (expectedSessionId) => {diff --git a/src/helpers/meetingSystemAudioHandover.js b/src/helpers/meetingSystemAudioHandover.jsnew file mode 100644index 000000000..4623e0d71--- /dev/null+++ b/src/helpers/meetingSystemAudioHandover.js@@ -0,0 +1,50 @@+const {+ computeChunkStats,+ MEETING_MIC_SILENCE_RMS,+ MEETING_MIC_SILENCE_PEAK,+} = require("./meetingMicGate");++const CONFIRM_MS = 1_000;++const isAudible = (buffer) => {+ const { rms, peak } = computeChunkStats(buffer);+ return rms >= MEETING_MIC_SILENCE_RMS || peak >= MEETING_MIC_SILENCE_PEAK;+};++// capture_silent can also fire while the Windows helper is capturing the call+// fine (a hidden stream playing through a lull). Renderer loopback only hears+// the default output device, so it runs beside the helper and takes the system+// channel only after hearing audio the helper missed for CONFIRM_MS.+const createMeetingSystemAudioHandover = ({ now = Date.now } = {}) => {+ let phase = "native";+ let missedSince = null;++ return {+ begin: () => {+ if (phase !== "native") return false;+ phase = "trial";+ return true;+ },+ acceptNativeChunk: (buffer) => {+ if (phase === "renderer") return false;+ if (phase === "trial" && isAudible(buffer)) missedSince = null;+ return true;+ },+ acceptRendererChunk: (buffer) => {+ if (phase !== "trial") return "send";+ if (!isAudible(buffer)) return "drop";+ const at = now();+ missedSince ??= at;+ if (at - missedSince < CONFIRM_MS) return "drop";+ phase = "renderer";+ return "takeover";+ },+ reset: () => {+ phase = "native";+ missedSince = null;+ },+ };+};++module.exports = createMeetingSystemAudioHandover;+module.exports.CONFIRM_MS = CONFIRM_MS;diff --git a/src/stores/meetingRecordingStore.ts b/src/stores/meetingRecordingStore.tsindex 4bf7a83a2..fb72a013d 100644--- a/src/stores/meetingRecordingStore.ts+++ b/src/stores/meetingRecordingStore.ts@@ -667,6 +667,22 @@ function assignProvisionalSpeaker(segment: TranscriptSegment): TranscriptSegment});}+async function releaseSystemAudioCapture(): Promise<void> {+ await flushAndDisconnectProcessor(systemProcessor);+ systemProcessor = null;++ systemSource?.disconnect();+ systemSource = null;++ stopMediaStream(systemStream);+ systemStream = null;++ try {+ await systemContext?.close();+ } catch {}+ systemContext = null;+}+async function cleanup(): Promise<void> {micRecovery?.stop();micRecovery = null;@@ -689,19 +705,7 @@ async function cleanup(): Promise<void> {} catch {}micContext = null;- await flushAndDisconnectProcessor(systemProcessor);- systemProcessor = null;-- systemSource?.disconnect();- systemSource = null;-- stopMediaStream(systemStream);- systemStream = null;-- try {- await systemContext?.close();- } catch {}- systemContext = null;+ await releaseSystemAudioCapture();ipcCleanups.forEach((fn) => fn());ipcCleanups = [];@@ -1430,29 +1434,49 @@ export async function startRecording(args: StartRecordingArgs): Promise<boolean>// Main sends this when a native helper reports it is capturing silence// while audio is really playing, which activation success cannot detect.- // Take the channel over with Chromium loopback for the rest of the call.+ // Main keeps the helper until this loopback hears audio the helper misses.if (systemAudioHandledInMain) {const degradedCleanup = window.electronAPI?.onMeetingSystemAudioDegraded?.(() => {if (activeRecordingSessionId !== sessionId || !isRecordingFlag) return;if (systemStream) return;void (async () => {- const takeover = await requestSystemAudioDisplayStream(- getDisplayCaptureModeForStrategy("loopback")- );- if (!takeover.stream) {+ const reportTakeoverFailure = (error: Error | null) => {logger.warn("Renderer loopback takeover failed after native system audio went silent",- { error: takeover.error?.message },+ { error: error?.message },"meeting");- return;- }+ publishSystemAudioInterruption({+ systemAudioStrategy: "loopback",+ reason: "loopback_takeover_failed",+ recovering: false,+ });+ sessionSystemAudioActive = false;+ void window.electronAPI+ ?.meetingTranscriptionSetSystemAudioAvailable?.(sessionId, false)+ .catch(() => undefined);+ };+ const takeover = await requestSystemAudioDisplayStream(+ getDisplayCaptureModeForStrategy("loopback")+ );if (activeRecordingSessionId !== sessionId || !isRecordingFlag || systemStream) {stopMediaStream(takeover.stream);return;}- await attachRendererSystemAudio(takeover.stream);- logger.info("Renderer loopback took over system audio capture", {}, "meeting");+ if (!takeover.stream) {+ reportTakeoverFailure(takeover.error);+ return;+ }+ try {+ await attachRendererSystemAudio(takeover.stream);+ logger.info("Renderer loopback started beside native system audio", {}, "meeting");+ } catch (error) {+ // A stop mid-attach also lands here, and its cleanup owns the graph.+ if (activeRecordingSessionId === sessionId && isRecordingFlag) {+ reportTakeoverFailure(error as Error);+ await releaseSystemAudioCapture();+ }+ }})();});if (degradedCleanup) ipcCleanups.push(degradedCleanup);diff --git a/src/types/electron.ts b/src/types/electron.tsindex ab99b659a..a2883eda1 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -818,7 +818,7 @@ export type SystemAudioStrategy =export interface MeetingSystemAudioInterruption {systemAudioStrategy: SystemAudioStrategy;- reason: "no_audio_delivered" | "device_invalidated" | "gone_quiet";+ reason: "no_audio_delivered" | "device_invalidated" | "gone_quiet" | "loopback_takeover_failed";recovering: boolean;}diff --git a/test/helpers/meetingAudioTimeline.test.js b/test/helpers/meetingAudioTimeline.test.jsindex 96d741062..67b4936d7 100644--- a/test/helpers/meetingAudioTimeline.test.js+++ b/test/helpers/meetingAudioTimeline.test.js@@ -5,6 +5,7 @@ const path = require("node:path");const vm = require("node:vm");const { createRequire } = require("node:module");const createWatchdog = require("../../src/helpers/meetingSystemAudioWatchdog");+const createMeetingSystemAudioHandover = require("../../src/helpers/meetingSystemAudioHandover");const micGate = require("../../src/helpers/meetingMicGate");// Execute the real IPC closures with only their native/network boundaries replaced.@@ -57,6 +58,7 @@ function harness({ native = true, local = false } = {}) {},},meetingSystemAudioWatchdog: watchdog,+ meetingSystemAudioHandover: createMeetingSystemAudioHandover(),meetingEchoLeakDetector: { recordSystemChunk: (buffer) => echo.push(buffer) },meetingAecEnabled: true,flushPendingMeetingMicChunks() {},diff --git a/test/helpers/meetingStreamingWiring.test.js b/test/helpers/meetingStreamingWiring.test.jsindex effa51781..443c09908 100644--- a/test/helpers/meetingStreamingWiring.test.js+++ b/test/helpers/meetingStreamingWiring.test.js@@ -59,28 +59,21 @@ test("a silent Windows capture hands the live session to renderer loopback", ()// capture_silent warning is the only trigger back to the Chromium fallback.assert.match(source,- /if \(code === "capture_silent"\) \{\s*void degradeMeetingSystemAudioToLoopback\(event\);/+ /if \(code === "capture_silent"\) \{\s*degradeMeetingSystemAudioToLoopback\(event\);/);-- const degradeStart = source.indexOf("const degradeMeetingSystemAudioToLoopback");- assert.ok(degradeStart >= 0);- const degradeSection = source.slice(- degradeStart,- source.indexOf("const startManagedMeetingSystemAudio")- );- // One-shot, and never fires once the helper has proven it can hear audio.assert.match(- degradeSection,- /if \(meetingSystemAudioDegraded \|\| meetingSystemAudioHeard\) return;/+ source,+ /onChunk: \(chunk\) => \{\s*if \(!meetingSystemAudioHandover\.acceptNativeChunk\(chunk\)\) return;/);- assert.match(degradeSection, /windowsLoopbackAudioManager\?\.stop\(\)/);- assert.match(degradeSection, /send\("meeting-system-audio-degraded"\)/);// Leaking the latch across sessions would pin the fallback off for the rest// of the app's life, so it resets everywhere the heard-audio latch does.assert.equal(- (source.match(/meetingSystemAudioHeard = false;\s*\n\s*meetingSystemAudioDegraded = false;/g) ?? [])- .length,+ (+ source.match(+ /meetingSystemAudioHeard = false;\s*\n\s*meetingSystemAudioHandover\.reset\(\);/g+ ) ?? []+ ).length,2);});diff --git a/test/helpers/meetingSystemAudioDegrade.test.js b/test/helpers/meetingSystemAudioDegrade.test.jsnew file mode 100644index 000000000..24f1a4907--- /dev/null+++ b/test/helpers/meetingSystemAudioDegrade.test.js@@ -0,0 +1,92 @@+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 createMeetingSystemAudioHandover = require("../../src/helpers/meetingSystemAudioHandover");+const { makeSine, toInt16Buffer } = require("./harness/pcmFixtures");++const { CONFIRM_MS } = createMeetingSystemAudioHandover;+const AUDIBLE = toInt16Buffer(makeSine({ durationMs: 100, amplitude: 0.3 }));++const source = fs.readFileSync(path.join(__dirname, "../../src/helpers/ipcHandlers.js"), "utf8");++const sliceBetween = (startMarker, endMarker) => {+ const start = source.indexOf(startMarker);+ const end = source.indexOf(endMarker, start);+ assert.ok(start >= 0 && end > start, `${startMarker} not found in ipcHandlers.js`);+ return source.slice(start, end);+};++function harness({ systemAudioHeard = false } = {}) {+ let now = 1_000_000;+ const events = [];+ const handlers = {};+ const context = {+ Buffer,+ meetingSystemAudioHeard: systemAudioHeard,+ meetingSystemAudioHandover: createMeetingSystemAudioHandover({ now: () => now }),+ meetingSystemAudioWatchdog: { detachCapture: () => events.push("detach") },+ debugLogger: { warn() {}, debug() {}, error() {}, info() {} },+ windowsLoopbackAudioManager: { stop: async () => events.push("stop") },+ BrowserWindow: {+ fromWebContents: () => ({+ isDestroyed: () => false,+ webContents: { send: (channel) => events.push(channel) },+ }),+ },+ ipcMain: { on: (channel, handler) => (handlers[channel] = handler) },+ sendMeetingAudio: (_buffer, source) => events.push(`send:${source}`),+ };+ vm.createContext(context);+ vm.runInContext(+ `${sliceBetween(+ "const degradeMeetingSystemAudioToLoopback =",+ "const startManagedMeetingSystemAudio ="+ )}+ ${sliceBetween('ipcMain.on("meeting-transcription-send"', "const stopMeetingTranscription =")}+ globalThis.degrade = () => degradeMeetingSystemAudioToLoopback({ sender: {} });`,+ context+ );+ return {+ events,+ degrade: context.degrade,+ sendRenderer: (buffer) => handlers["meeting-transcription-send"]({}, buffer, "system"),+ advance: (ms) => {+ now += ms;+ },+ };+}++test("a silent capture starts renderer loopback without stopping the helper", () => {+ const { events, degrade } = harness({ systemAudioHeard: true });++ degrade();+ degrade();++ assert.deepEqual(events, ["meeting-system-audio-degraded"]);+});++test("renderer chunks are held back until loopback hears what the helper misses", () => {+ const { events, degrade, sendRenderer, advance } = harness();+ degrade();+ events.length = 0;++ sendRenderer(AUDIBLE);+ assert.deepEqual(events, []);++ advance(CONFIRM_MS);+ sendRenderer(AUDIBLE);+ sendRenderer(AUDIBLE);++ assert.deepEqual(events, ["detach", "stop", "send:system", "send:system"]);+});++test("renderer chunks pass straight through when no helper handover is pending", () => {+ const { events, sendRenderer } = harness();++ sendRenderer(AUDIBLE);++ assert.deepEqual(events, ["send:system"]);+});diff --git a/test/helpers/meetingSystemAudioHandover.test.js b/test/helpers/meetingSystemAudioHandover.test.jsnew file mode 100644index 000000000..4c23e0f9a--- /dev/null+++ b/test/helpers/meetingSystemAudioHandover.test.js@@ -0,0 +1,85 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const createMeetingSystemAudioHandover = require("../../src/helpers/meetingSystemAudioHandover");+const { makeSine, toInt16Buffer } = require("./harness/pcmFixtures");++const { CONFIRM_MS } = createMeetingSystemAudioHandover;++const AUDIBLE = toInt16Buffer(makeSine({ durationMs: 100, amplitude: 0.3 }));+const SILENT = Buffer.alloc(AUDIBLE.length);++const createHarness = () => {+ let now = 1_000_000;+ const handover = createMeetingSystemAudioHandover({ now: () => now });+ return {+ handover,+ advance: (ms) => {+ now += ms;+ },+ };+};++test("without a trial both producers pass straight through", () => {+ const { handover } = createHarness();++ assert.equal(handover.acceptNativeChunk(SILENT), true);+ assert.equal(handover.acceptRendererChunk(AUDIBLE), "send");+});++test("the trial begins once per session", () => {+ const { handover } = createHarness();++ assert.equal(handover.begin(), true);+ assert.equal(handover.begin(), false);+ handover.reset();+ assert.equal(handover.begin(), true);+});++test("renderer loopback takes over once it keeps hearing audio the helper misses", () => {+ const { handover, advance } = createHarness();+ handover.begin();++ assert.equal(handover.acceptNativeChunk(SILENT), true);+ assert.equal(handover.acceptRendererChunk(AUDIBLE), "drop");+ advance(CONFIRM_MS - 1);+ assert.equal(handover.acceptRendererChunk(AUDIBLE), "drop");+ advance(1);+ assert.equal(handover.acceptRendererChunk(AUDIBLE), "takeover");++ assert.equal(handover.acceptRendererChunk(SILENT), "send");+ assert.equal(handover.acceptNativeChunk(AUDIBLE), false);+});++test("the helper keeps the channel while it hears what loopback hears", () => {+ const { handover, advance } = createHarness();+ handover.begin();++ for (let elapsed = 0; elapsed <= CONFIRM_MS * 5; elapsed += 100) {+ assert.equal(handover.acceptRendererChunk(AUDIBLE), "drop");+ assert.equal(handover.acceptNativeChunk(AUDIBLE), true);+ advance(100);+ }+});++test("loopback that hears nothing never takes over", () => {+ const { handover, advance } = createHarness();+ handover.begin();++ advance(CONFIRM_MS * 5);+ assert.equal(handover.acceptRendererChunk(SILENT), "drop");+ assert.equal(handover.acceptNativeChunk(SILENT), true);+});++test("reset returns a taken-over session to the native producer", () => {+ const { handover, advance } = createHarness();+ handover.begin();+ handover.acceptRendererChunk(AUDIBLE);+ advance(CONFIRM_MS);+ assert.equal(handover.acceptRendererChunk(AUDIBLE), "takeover");++ handover.reset();++ assert.equal(handover.acceptNativeChunk(AUDIBLE), true);+ assert.equal(handover.acceptRendererChunk(AUDIBLE), "send");+});diff --git a/test/stores/meetingRecordingStoreSystemAudioDegraded.test.js b/test/stores/meetingRecordingStoreSystemAudioDegraded.test.jsindex 4a295166d..400303eb8 100644--- a/test/stores/meetingRecordingStoreSystemAudioDegraded.test.js+++ b/test/stores/meetingRecordingStoreSystemAudioDegraded.test.js@@ -18,13 +18,25 @@ const START_ARGS = {autoEndEligible: false,};-function installDisplayCaptureGlobals(t) {+function installDisplayCaptureGlobals(t, { capture = null } = {}) {installMicCaptureGlobals(t);- const calls = { getDisplayMedia: 0 };- const makeTrack = (kind) => ({ kind, readyState: "live", stop() {}, getSettings: () => ({}) });+ const calls = { getDisplayMedia: 0, tracks: [] };+ const makeTrack = (kind) => {+ const track = {+ kind,+ readyState: "live",+ stop() {+ track.readyState = "ended";+ },+ getSettings: () => ({}),+ };+ calls.tracks.push(track);+ return track;+ };navigator.mediaDevices.getDisplayMedia = async () => {calls.getDisplayMedia += 1;+ if (capture) return capture.promise;const audio = makeTrack("audio");const video = makeTrack("video");return {@@ -36,8 +48,26 @@ function installDisplayCaptureGlobals(t) {return calls;}+function installFailingSystemAudioContext(addModule) {+ const Base = globalThis.AudioContext;+ const contexts = [];+ globalThis.AudioContext = class extends Base {+ constructor(...args) {+ super(...args);+ this.audioWorklet = { addModule };+ this.closed = false;+ contexts.push(this);+ }+ async close() {+ this.closed = true;+ }+ };+ return contexts;+}+function createElectronAPI({ systemAudioMode, systemAudioStrategy }) {const listeners = { systemAudioDegraded: null };+ const systemAudioAvailability = [];const noopListener = () => () => {};const api = {checkSystemAudioAccess: async () => ({@@ -51,7 +81,10 @@ function createElectronAPI({ systemAudioMode, systemAudioStrategy }) {systemAudioMode,systemAudioStrategy,}),- meetingTranscriptionSetSystemAudioAvailable: async () => ({ success: true }),+ meetingTranscriptionSetSystemAudioAvailable: async (_sessionId, available) => {+ systemAudioAvailability.push(available);+ return { success: true };+ },meetingTranscriptionStop: async () => ({ success: true }),meetingTranscriptionSend: () => {},onMeetingTranscriptionSegment: noopListener,@@ -68,7 +101,7 @@ function createElectronAPI({ systemAudioMode, systemAudioStrategy }) {};},};- return { api, listeners };+ return { api, listeners, systemAudioAvailability };}async function loadStore(t, api) {@@ -125,6 +158,101 @@ test("degrade event is ignored once the recording has stopped", async (t) => {assert.equal(calls.getDisplayMedia, 0);});+test("a failed takeover warns and gives up the session's system channel", async (t) => {+ const capture = Promise.withResolvers();+ installDisplayCaptureGlobals(t, { capture });+ const { api, listeners, systemAudioAvailability } = createElectronAPI({+ systemAudioMode: "loopback",+ systemAudioStrategy: "wasapi-loopback",+ });+ const store = await loadStore(t, api);++ assert.equal(await store.startRecording(START_ARGS), true);+ listeners.systemAudioDegraded();+ capture.reject(new Error("Permission denied by system"));+ await flush();++ assert.deepEqual(store.useMeetingRecordingStore.getState().systemAudioInterrupted, {+ recovering: false,+ reason: "loopback_takeover_failed",+ });+ assert.deepEqual(systemAudioAvailability, [true, false]);++ await store.stopRecording();+});++test("a takeover that fails after the recording stopped touches nothing", async (t) => {+ const capture = Promise.withResolvers();+ installDisplayCaptureGlobals(t, { capture });+ const { api, listeners, systemAudioAvailability } = createElectronAPI({+ systemAudioMode: "loopback",+ systemAudioStrategy: "wasapi-loopback",+ });+ const store = await loadStore(t, api);++ assert.equal(await store.startRecording(START_ARGS), true);+ listeners.systemAudioDegraded();+ await store.stopRecording();+ capture.reject(new Error("Permission denied by system"));+ await flush();++ assert.equal(store.useMeetingRecordingStore.getState().systemAudioInterrupted, null);+ assert.deepEqual(systemAudioAvailability, [true]);+});++test("a takeover whose capture graph throws gives up and releases the capture", async (t) => {+ const calls = installDisplayCaptureGlobals(t);+ const { api, listeners, systemAudioAvailability } = createElectronAPI({+ systemAudioMode: "loopback",+ systemAudioStrategy: "wasapi-loopback",+ });+ const store = await loadStore(t, api);++ assert.equal(await store.startRecording(START_ARGS), true);+ const contexts = installFailingSystemAudioContext(async () => {+ throw new Error("AudioWorklet module failed to load");+ });+ listeners.systemAudioDegraded();+ await flush();++ assert.deepEqual(store.useMeetingRecordingStore.getState().systemAudioInterrupted, {+ recovering: false,+ reason: "loopback_takeover_failed",+ });+ assert.deepEqual(systemAudioAvailability, [true, false]);+ assert.deepEqual(+ calls.tracks.map((track) => track.readyState),+ ["ended", "ended"]+ );+ assert.deepEqual(+ contexts.map((context) => context.closed),+ [true]+ );++ await store.stopRecording();+});++test("a capture graph that throws after the recording stopped touches nothing", async (t) => {+ const attach = Promise.withResolvers();+ installDisplayCaptureGlobals(t);+ const { api, listeners, systemAudioAvailability } = createElectronAPI({+ systemAudioMode: "loopback",+ systemAudioStrategy: "wasapi-loopback",+ });+ const store = await loadStore(t, api);++ assert.equal(await store.startRecording(START_ARGS), true);+ installFailingSystemAudioContext(() => attach.promise);+ listeners.systemAudioDegraded();+ await flush();+ await store.stopRecording();+ attach.reject(new Error("Cannot add module to a closed AudioContext"));+ await flush();++ assert.equal(store.useMeetingRecordingStore.getState().systemAudioInterrupted, null);+ assert.deepEqual(systemAudioAvailability, [true]);+});+test("a renderer-loopback session never registers the takeover listener", async (t) => {installDisplayCaptureGlobals(t);const { api, listeners } = createElectronAPI({