Skip to content

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

fix(meetings): capture and diagnose silent system-audio transcription (#1864)

Gabriel Stein025ae934224f
diff --git a/preload.js b/preload.js
index 9924e1320..d23e14ab5 100644
--- a/preload.js
+++ b/preload.js
@@ -822,6 +822,10 @@ contextBridge.exposeInMainWorld("electronAPI", {
"meeting-transcription-fatal-error",
(callback) => (_event, data) => callback(data)
),
+ onMeetingSystemAudioSilent: registerListener(
+ "meeting-system-audio-silent",
+ (callback) => (_event, data) => callback(data)
+ ),
// Dictation realtime streaming
dictationRealtimeWarmup: (options) => ipcRenderer.invoke("dictation-realtime-warmup", options),
diff --git a/src/components/MeetingRecordingMount.tsx b/src/components/MeetingRecordingMount.tsx
index 08a6e3f18..8427699d1 100644
--- a/src/components/MeetingRecordingMount.tsx
+++ b/src/components/MeetingRecordingMount.tsx
@@ -27,8 +27,10 @@ export default function MeetingRecordingMount(): null {
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 micCaptureStatus = useMeetingRecordingStore((s) => s.micCaptureStatus);
const wasMicUnavailable = useRef(false);
+ const wasSystemAudioSilent = useRef(false);
useEffect(() => {
primeMeetingWorklet();
@@ -90,6 +92,22 @@ export default function MeetingRecordingMount(): null {
// errorNonce re-fires this toast when the same error repeats back-to-back.
}, [error, errorNonce, toast, t]);
+ // The store latches this once per recording; the ref keeps dependency
+ // changes (e.g. a language switch recreating `t`) from re-firing the toast.
+ useEffect(() => {
+ if (!systemAudioSilentWarning) {
+ wasSystemAudioSilent.current = false;
+ return;
+ }
+ if (wasSystemAudioSilent.current) return;
+ wasSystemAudioSilent.current = true;
+ toast({
+ title: t("notes.meeting.systemAudioSilent.title"),
+ description: t("notes.meeting.systemAudioSilent.description"),
+ duration: 8000,
+ });
+ }, [systemAudioSilentWarning, toast, t]);
+
useEffect(() => {
if (micCaptureStatus === "unavailable" && !wasMicUnavailable.current) {
wasMicUnavailable.current = true;
diff --git a/src/helpers/externalUrlOpener.js b/src/helpers/externalUrlOpener.js
new file mode 100644
index 000000000..c3e4f424c
--- /dev/null
+++ b/src/helpers/externalUrlOpener.js
@@ -0,0 +1,46 @@
+const { shell } = require("electron");
+const { spawn } = require("child_process");
+const path = require("path");
+const debugLogger = require("./debugLogger");
+
+// On Windows, shell.openExternal runs ShellExecuteExW inside the Electron main
+// process, so a cold-started default browser (and any meeting client it
+// protocol-launches) becomes a descendant of our PID. The system-audio helper
+// captures with PROCESS_LOOPBACK_MODE_EXCLUDE_TARGET_PROCESS_TREE rooted at
+// that PID (windowsLoopbackAudioManager.js --exclude-pid), which would silence
+// the meeting's audio. Handing http/https URLs to explorer.exe forwards the
+// open to the long-running desktop shell via COM, so the browser is created
+// outside our process tree. The protocol gate is load-bearing: explorer.exe
+// EXECUTES non-URL arguments such as file paths. The absolute path is too:
+// a bare "explorer.exe" resolves from the CWD first (binary planting).
+async function openExternalUrl(url) {
+ const { protocol, href } = new URL(url);
+ if (process.platform === "win32" && (protocol === "http:" || protocol === "https:")) {
+ const explorerPath = path.win32.join(process.env.SystemRoot || "C:\\Windows", "explorer.exe");
+ try {
+ await new Promise((resolve, reject) => {
+ const child = spawn(explorerPath, [href], {
+ detached: true,
+ stdio: "ignore",
+ windowsHide: true,
+ });
+ child.once("error", reject);
+ child.once("spawn", resolve);
+ child.unref();
+ });
+ return;
+ } catch (error) {
+ // No spawnable shell (relocated SystemRoot, LTSC/Server images, execution
+ // policy). Degraded system-audio capture beats a link that never opens,
+ // so fall through to the direct open rather than failing the click.
+ debugLogger.warn(
+ "explorer.exe launch failed, opening URL in-process",
+ { error: error.message },
+ "window"
+ );
+ }
+ }
+ return shell.openExternal(url);
+}
+
+module.exports = { openExternalUrl };
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 3b98c16a6..2db47ab01 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -6,6 +6,7 @@ const crypto = require("crypto");
const debugLogger = require("./debugLogger");
const { PARAKEET_UNSUPPORTED_OS_CODE } = require("./parakeetCapability");
const { broadcastToWindows } = require("./windowBroadcast");
+const { openExternalUrl } = require("./externalUrlOpener");
const { resolveFailedGpuBackends } = require("./whisper");
const { BYOK_API_KEYS } = require("../config/secretKeys");
const tokenStore = require("./tokenStore");
@@ -129,6 +130,12 @@ const { getCalendarAvailability } = require("./calendarAvailabilityService");
// streaming providers must be told the true PCM rate or they misread the audio.
const MEETING_STREAM_SAMPLE_RATE = 24000;
const MEETING_RECONNECT_BUFFER_MAX_BYTES = MEETING_STREAM_SAMPLE_RATE * 2 * 30;
+// The realtime clients default to a 0.6 server-VAD threshold, raised in #630 to
+// keep mic ambient noise from opening turns. The system loopback channel's noise
+// floor is digital silence, so it keeps the original, more sensitive threshold —
+// at 0.6 quiet remote speech may never trip the VAD and the whole channel
+// transcribes to nothing.
+const MEETING_SYSTEM_VAD_THRESHOLD = 0.3;
const MISTRAL_TRANSCRIPTION_URL = "https://api.mistral.ai/v1/audio/transcriptions";
@@ -3754,7 +3761,7 @@ class IPCHandlers {
if (!["http:", "https:", "mailto:"].includes(protocol)) {
return { success: false, error: `Blocked URL scheme: ${protocol}` };
}
- await shell.openExternal(url);
+ await openExternalUrl(url);
return { success: true };
} catch (error) {
return { success: false, error: error.message };
@@ -6175,6 +6182,14 @@ class IPCHandlers {
return replayed;
};
+ // Labels the socket for field logs and, for system, swaps in the more
+ // sensitive threshold (see MEETING_SYSTEM_VAD_THRESHOLD).
+ const withMeetingSourceConnectOpts = (connectOpts, source) => ({
+ ...connectOpts,
+ streamLabel: source,
+ ...(source === "system" ? { vadThreshold: MEETING_SYSTEM_VAD_THRESHOLD } : {}),
+ });
+
const reconnectMeetingStreams = ({ restoreOldOnFailure = false } = {}) => {
if (meetingReconnectPromise) return meetingReconnectPromise;
@@ -6233,16 +6248,26 @@ class IPCHandlers {
if (newSystem) {
const secrets = await fetchRealtimeToken(tokenEvent, options, { streams: 2 });
pairs = [
- { streaming: newMic, secret: secrets[0] },
- { streaming: newSystem, secret: secrets[1] },
+ { streaming: newMic, secret: secrets[0], source: "mic" },
+ { streaming: newSystem, secret: secrets[1], source: "system" },
];
} else {
- pairs = [{ streaming: newMic, secret: await fetchRealtimeToken(tokenEvent, options) }];
+ pairs = [
+ {
+ streaming: newMic,
+ secret: await fetchRealtimeToken(tokenEvent, options),
+ source: "mic",
+ },
+ ];
}
await Promise.all(
- pairs.map(({ streaming, secret }) =>
- streaming.connect({ apiKey: secret, token: secret, ...connectOpts })
+ pairs.map(({ streaming, secret, source }) =>
+ streaming.connect({
+ apiKey: secret,
+ token: secret,
+ ...withMeetingSourceConnectOpts(connectOpts, source),
+ })
)
);
@@ -6453,8 +6478,12 @@ class IPCHandlers {
try {
await Promise.all(
- pairs.map(({ ref, secret }) =>
- this[ref].connect({ apiKey: secret, token: secret, ...connectOpts })
+ pairs.map(({ ref, secret, source }) =>
+ this[ref].connect({
+ apiKey: secret,
+ token: secret,
+ ...withMeetingSourceConnectOpts(connectOpts, source),
+ })
)
);
if (pairs.some(({ ref }) => !this[ref]?.isConnected)) {
@@ -6478,7 +6507,9 @@ class IPCHandlers {
const MEETING_STARTUP_WARMUP_MS = 1500;
const MEETING_MIC_BLEED_LOOKBACK_MS = 500;
const MEETING_MIC_STATS_LOG_LIMIT = 200;
+ const MEETING_SYSTEM_AUDIO_SILENCE_WARNING_MS = 45000;
let meetingMicStatsLogCount = 0;
+ let meetingSystemAudioSilenceTimer = null;
let meetingStartedAt = null;
let meetingSendCounts = { mic: 0, system: 0 };
const meetingEchoLeakDetector = new MeetingEchoLeakDetector();
@@ -6632,6 +6663,18 @@ class IPCHandlers {
zeroed: outbound !== buffer,
});
}
+ } else if (source === "system" && buffer.length >= 2) {
+ // 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;
+ if (chunkCount === 1 || chunkCount % 200 === 0) {
+ const { rms, peak } = computeChunkStats(buffer);
+ debugLogger.debug("Meeting system audio stats", {
+ rms: rms.toFixed(4),
+ peak: peak.toFixed(4),
+ chunkCount,
+ });
+ }
}
queueMeetingReconnectAudio(source, outbound);
@@ -7257,7 +7300,35 @@ class IPCHandlers {
return results;
};
+ const clearMeetingSystemAudioSilenceTimer = () => {
+ if (meetingSystemAudioSilenceTimer) {
+ clearTimeout(meetingSystemAudioSilenceTimer);
+ meetingSystemAudioSilenceTimer = null;
+ }
+ };
+
+ // One-shot: system capture is active but nothing audible has arrived by the
+ // deadline, so tell the meeting window the remote side may be missing from
+ // the transcript. Audio arriving before the deadline cancels it outright;
+ // the toast itself is time-boxed by the renderer, not by later audio.
+ const armMeetingSystemAudioSilenceTimer = (win, systemAudioStrategy) => {
+ clearMeetingSystemAudioSilenceTimer();
+ meetingSystemAudioSilenceTimer = setTimeout(() => {
+ meetingSystemAudioSilenceTimer = null;
+ if (meetingSystemAudioHeard) return;
+ debugLogger.debug(
+ "Meeting system audio still silent past warning window",
+ { systemAudioStrategy, timeoutMs: MEETING_SYSTEM_AUDIO_SILENCE_WARNING_MS },
+ "meeting"
+ );
+ if (win && !win.isDestroyed()) {
+ win.webContents.send("meeting-system-audio-silent", { systemAudioStrategy });
+ }
+ }, MEETING_SYSTEM_AUDIO_SILENCE_WARNING_MS);
+ };
+
const rollbackMeetingTranscriptionStart = async () => {
+ clearMeetingSystemAudioSilenceTimer();
if (this.audioTapManager) {
await this.audioTapManager.stop().catch(() => {});
}
@@ -7482,6 +7553,12 @@ class IPCHandlers {
// Auto-end stays fail-safe until the renderer confirms a real source.
systemAudioAvailable: false,
});
+ // Arms on any active system-audio strategy — capture follows platform
+ // capability, not call detection — so the warning copy also covers
+ // in-person recordings where a silent system tap is expected.
+ if (result.systemAudioStrategy && result.systemAudioStrategy !== "unsupported") {
+ armMeetingSystemAudioSilenceTimer(meetingConnectionWin, result.systemAudioStrategy);
+ }
return { ...result, sessionId: recordingSessionId };
};
@@ -7803,6 +7880,7 @@ class IPCHandlers {
return { success: false, reason: "stale-session" };
}
this.meetingDetectionEngine?.setUserRecording(false);
+ clearMeetingSystemAudioSilenceTimer();
try {
if (this.audioTapManager) {
await this.audioTapManager.stop();
diff --git a/src/helpers/meetingDetectionEngine.js b/src/helpers/meetingDetectionEngine.js
index c97e272d7..6540201b6 100644
--- a/src/helpers/meetingDetectionEngine.js
+++ b/src/helpers/meetingDetectionEngine.js
@@ -1,5 +1,5 @@
-const { shell } = require("electron");
const debugLogger = require("./debugLogger");
+const { openExternalUrl } = require("./externalUrlOpener");
const { getMeetingJoinUrl } = require("./meetingJoinUrl");
const createMeetingAutoEndController = require("./meetingAutoEndController");
const { createMeetingAudioActivityMonitor } = require("./meetingAudioActivityMonitor");
@@ -477,15 +477,13 @@ class MeetingDetectionEngine {
if (action === "join") {
const joinUrl = getMeetingJoinUrl(detection.event);
if (joinUrl) {
- shell
- .openExternal(joinUrl)
- .catch((error) =>
- debugLogger.error(
- "Failed to open meeting link",
- { error: error.message, joinUrl },
- "meeting"
- )
- );
+ openExternalUrl(joinUrl).catch((error) =>
+ debugLogger.error(
+ "Failed to open meeting link",
+ { error: error.message, joinUrl },
+ "meeting"
+ )
+ );
}
}
diff --git a/src/helpers/menuManager.js b/src/helpers/menuManager.js
index a62af4eed..1f39a9792 100644
--- a/src/helpers/menuManager.js
+++ b/src/helpers/menuManager.js
@@ -105,8 +105,8 @@ class MenuManager {
{
label: i18nMain.t("menu.learnMore"),
click: async () => {
- const { shell } = require("electron");
- await shell.openExternal("https://github.com/OpenWhispr/openwhispr");
+ const { openExternalUrl } = require("./externalUrlOpener");
+ await openExternalUrl("https://github.com/OpenWhispr/openwhispr");
},
},
],
diff --git a/src/helpers/oauthLoopbackFlow.js b/src/helpers/oauthLoopbackFlow.js
index abad38e28..c4308cdac 100644
--- a/src/helpers/oauthLoopbackFlow.js
+++ b/src/helpers/oauthLoopbackFlow.js
@@ -1,6 +1,6 @@
const http = require("http");
const crypto = require("crypto");
-const { shell } = require("electron");
+const { openExternalUrl } = require("./externalUrlOpener");
const OAUTH_TIMEOUT_MS = 120000;
const DEFAULT_DESKTOP_CALLBACK_URL = "https://openwhispr.com/auth/desktop-callback";
@@ -121,7 +121,9 @@ function runOAuthLoopbackFlow({ buildAuthUrl, handleCallback, errorParam }) {
server.listen(0, "127.0.0.1", () => {
const port = server.address().port;
const redirectUri = `http://127.0.0.1:${port}`;
- shell.openExternal(buildAuthUrl(redirectUri, state, codeChallenge));
+ // Fire-and-forget like the shell.openExternal call it replaced: a failed
+ // browser launch surfaces as the flow timeout.
+ openExternalUrl(buildAuthUrl(redirectUri, state, codeChallenge)).catch(() => {});
});
timeoutId = setTimeout(() => {
diff --git a/src/helpers/openaiRealtimeStreaming.js b/src/helpers/openaiRealtimeStreaming.js
index e5152d3ad..58920f40e 100644
--- a/src/helpers/openaiRealtimeStreaming.js
+++ b/src/helpers/openaiRealtimeStreaming.js
@@ -8,6 +8,9 @@ const COLD_START_BUFFER_MAX = 3 * SAMPLE_RATE * 2; // 3 seconds of 16-bit PCM
const KEEPALIVE_INTERVAL_MS = 15000;
// OpenAI Realtime sessions die at 60 minutes; reconnect proactively before that.
const SESSION_PREEMPT_MS = 55 * 60 * 1000;
+// Raised from 0.3 to keep mic ambient noise from opening turns (#630); callers
+// on a cleaner channel pass their own vadThreshold.
+const DEFAULT_VAD_THRESHOLD = 0.6;
// A socket factory does network work before the socket exists, so the dial
// must be bounded; a socket resolving after the deadline is closed, not leaked.
@@ -51,6 +54,12 @@ class OpenAIRealtimeStreaming {
// Subclasses (Tinfoil) override this so logs name the provider actually
// carrying the audio — a Tinfoil session must never log as OpenAI.
this.providerLabel = "OpenAI Realtime";
+ // Meetings run two instances of this class at once (mic + system); the
+ // label is the only way field logs can tell the sockets apart.
+ this.streamLabel = null;
+ this.vadThreshold = DEFAULT_VAD_THRESHOLD;
+ this.speechStartedCount = 0;
+ this._vadEventCount = 0;
this.model = "gpt-4o-mini-transcribe";
this.inputRate = SAMPLE_RATE;
this.captureRate = SAMPLE_RATE;
@@ -75,11 +84,20 @@ class OpenAIRealtimeStreaming {
}
async connect(options = {}) {
- const { apiKey, model, preconfigured, inputRate, captureRate, createSocket } = options;
+ const {
+ apiKey,
+ model,
+ preconfigured,
+ inputRate,
+ captureRate,
+ createSocket,
+ streamLabel,
+ vadThreshold,
+ } = options;
if (!apiKey) throw new Error(`${this.providerLabel} API key is required`);
if (this.isConnected || this.isConnecting) {
- debugLogger.debug(`${this.providerLabel} already connected/connecting`);
+ debugLogger.debug(`${this.providerLabel} already connected/connecting`, this._logContext());
return;
}
@@ -92,15 +110,19 @@ class OpenAIRealtimeStreaming {
this.preconfigured = !!preconfigured;
this.inputRate = inputRate || SAMPLE_RATE;
this.captureRate = captureRate || this.inputRate;
+ this.streamLabel = streamLabel || null;
+ this.vadThreshold = vadThreshold ?? DEFAULT_VAD_THRESHOLD;
this.completedSegments = [];
this.currentPartial = "";
this.audioBytesSent = 0;
this.speechStartedAt = null;
+ this.speechStartedCount = 0;
+ this._vadEventCount = 0;
this._sessionExpired = false;
this._connectionLossNotified = false;
const url = "wss://api.openai.com/v1/realtime?intent=transcription";
- debugLogger.debug(`${this.providerLabel} connecting`, { model: this.model });
+ debugLogger.debug(`${this.providerLabel} connecting`, this._logContext({ model: this.model }));
// Attested providers (Tinfoil) supply their socket via an async factory.
let ws;
@@ -127,7 +149,7 @@ class OpenAIRealtimeStreaming {
this.ws = ws;
this.ws.on("open", () => {
- debugLogger.debug(`${this.providerLabel} WebSocket opened`);
+ debugLogger.debug(`${this.providerLabel} WebSocket opened`, this._logContext());
});
this.ws.on("message", (data) => {
@@ -136,7 +158,10 @@ class OpenAIRealtimeStreaming {
this.ws.on("error", (error) => {
const wasActive = this.isConnected;
- debugLogger.error(`${this.providerLabel} WebSocket error`, { error: error.message });
+ debugLogger.error(
+ `${this.providerLabel} WebSocket error`,
+ this._logContext({ error: error.message })
+ );
this.isConnecting = false;
this.cleanup();
if (this.pendingReject) {
@@ -154,11 +179,14 @@ class OpenAIRealtimeStreaming {
this.ws.on("close", (code, reason) => {
const wasActive = this.isConnected;
this.isConnecting = false;
- debugLogger.debug(`${this.providerLabel} WebSocket closed`, {
- code,
- reason: reason?.toString(),
- wasActive,
- });
+ debugLogger.debug(
+ `${this.providerLabel} WebSocket closed`,
+ this._logContext({
+ code,
+ reason: reason?.toString(),
+ wasActive,
+ })
+ );
if (this.pendingReject) {
this.pendingReject(new Error(`WebSocket closed before ready (code: ${code})`));
this.pendingReject = null;
@@ -182,14 +210,27 @@ class OpenAIRealtimeStreaming {
if (this.preconfigured) {
// Server-side ephemeral token already configured the session;
// sending an update would strip language and noise-reduction.
- debugLogger.debug(`${this.providerLabel} session created (preconfigured)`, {
- model: this.model,
- });
+ // Echo the server's VAD + format — the only place preconfigured
+ // (cloud) session settings ever appear in field logs.
+ const sessionInput = event.session?.audio?.input;
+ debugLogger.debug(
+ `${this.providerLabel} session created (preconfigured)`,
+ this._logContext({
+ model: this.model,
+ turnDetection:
+ sessionInput?.turn_detection ?? event.session?.turn_detection ?? null,
+ inputFormat: sessionInput?.format ?? event.session?.input_audio_format ?? null,
+ })
+ );
this._markConnected();
} else {
- debugLogger.debug(`${this.providerLabel} session created, sending configuration`, {
- model: this.model,
- });
+ debugLogger.debug(
+ `${this.providerLabel} session created, sending configuration`,
+ this._logContext({
+ model: this.model,
+ vadThreshold: this.vadThreshold,
+ })
+ );
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) break;
this.ws.send(
JSON.stringify({
@@ -202,7 +243,7 @@ class OpenAIRealtimeStreaming {
transcription: { model: this.model },
turn_detection: {
type: "server_vad",
- threshold: 0.6,
+ threshold: this.vadThreshold,
silence_duration_ms: 600,
prefix_padding_ms: 500,
},
@@ -217,9 +258,12 @@ class OpenAIRealtimeStreaming {
case "session.updated": {
if (this.pendingResolve) {
- debugLogger.debug(`${this.providerLabel} session configured`, {
- model: this.model,
- });
+ debugLogger.debug(
+ `${this.providerLabel} session configured`,
+ this._logContext({
+ model: this.model,
+ })
+ );
this._markConnected();
}
break;
@@ -245,20 +289,48 @@ class OpenAIRealtimeStreaming {
if (transcript) {
const fullText = this.getFullTranscript();
this.onFinalTranscript?.(fullText, speechTimestamp);
- debugLogger.debug(`${this.providerLabel} turn completed`, {
- turnText: transcript.slice(0, 100),
- totalLength: fullText.length,
- segments: this.completedSegments.length,
- });
+ debugLogger.debug(
+ `${this.providerLabel} turn completed`,
+ this._logContext({
+ turnText: transcript.slice(0, 100),
+ totalLength: fullText.length,
+ segments: this.completedSegments.length,
+ })
+ );
+ } else {
+ debugLogger.debug(
+ `${this.providerLabel} turn completed with empty transcript`,
+ this._logContext({
+ itemId: event.item_id,
+ audioBytesSent: this.audioBytesSent,
+ })
+ );
}
break;
}
+ // Log-only by convention: completedSegments holds only server-confirmed
+ // transcripts and onError is reserved for `error` events, so a failed
+ // turn counts toward nothing and must not look like a connection problem.
+ case "conversation.item.input_audio_transcription.failed": {
+ debugLogger.debug(
+ `${this.providerLabel} turn transcription failed`,
+ this._logContext({
+ itemId: event.item_id,
+ error: event.error?.message || event.error?.code || null,
+ })
+ );
+ break;
+ }
+
case "input_audio_buffer.speech_started":
this.speechStartedAt = Date.now();
+ this.speechStartedCount++;
+ this._logVadEvent(event.type);
break;
case "input_audio_buffer.speech_stopped":
case "input_audio_buffer.committed":
+ this._logVadEvent(event.type);
break;
case "error": {
@@ -267,7 +339,10 @@ class OpenAIRealtimeStreaming {
// Only consumers that attach onSessionExpired (meetings) get the
// reconnect path; others (dictation) keep the onError/onSessionEnd flow.
if (errCode === "session_expired" && this.onSessionExpired) {
- debugLogger.warn(`${this.providerLabel} session expired`, { message: errMsg });
+ debugLogger.warn(
+ `${this.providerLabel} session expired`,
+ this._logContext({ message: errMsg })
+ );
this._sessionExpired = true;
this.onSessionExpired({ proactive: false });
break;
@@ -277,14 +352,20 @@ class OpenAIRealtimeStreaming {
errMsg.includes("buffer too small") ||
errMsg.includes("commit_empty");
if (isEmptyBuffer) {
- debugLogger.debug(`${this.providerLabel} empty buffer (server VAD already committed)`, {
- code: errCode,
- });
+ debugLogger.debug(
+ `${this.providerLabel} empty buffer (server VAD already committed)`,
+ this._logContext({
+ code: errCode,
+ })
+ );
} else {
- debugLogger.error(`${this.providerLabel} error event`, {
- code: errCode,
- message: errMsg,
- });
+ debugLogger.error(
+ `${this.providerLabel} error event`,
+ this._logContext({
+ code: errCode,
+ message: errMsg,
+ })
+ );
}
this.onError?.(new Error(errMsg));
break;
@@ -294,7 +375,32 @@ class OpenAIRealtimeStreaming {
break;
}
} catch (err) {
- debugLogger.error(`${this.providerLabel} message parse error`, { error: err.message });
+ debugLogger.error(
+ `${this.providerLabel} message parse error`,
+ this._logContext({ error: err.message })
+ );
+ }
+ }
+
+ // Unlabelled sockets (dictation) keep their pre-label log shape exactly.
+ _logContext(extra) {
+ if (this.streamLabel == null) return extra;
+ return { stream: this.streamLabel, ...extra };
+ }
+
+ // Throttled to first-3-then-every-50th: a normal meeting produces hundreds of
+ // these, so ZERO over a whole meeting means server VAD never fired.
+ _logVadEvent(type) {
+ this._vadEventCount++;
+ if (this._vadEventCount <= 3 || this._vadEventCount % 50 === 0) {
+ debugLogger.debug(
+ `${this.providerLabel} VAD event`,
+ this._logContext({
+ event: type,
+ count: this._vadEventCount,
+ audioBytesSent: this.audioBytesSent,
+ })
+ );
}
}
@@ -326,7 +432,8 @@ class OpenAIRealtimeStreaming {
this._sessionTimer = setTimeout(() => {
if (!this.isConnected) return;
debugLogger.debug(
- `${this.providerLabel} session approaching 60min limit, requesting reconnect`
+ `${this.providerLabel} session approaching 60min limit, requesting reconnect`,
+ this._logContext()
);
this.onSessionExpired?.({ proactive: true });
}, SESSION_PREEMPT_MS);
@@ -353,7 +460,8 @@ class OpenAIRealtimeStreaming {
}
if (socket.isAlive === false) {
debugLogger.debug(
- `${this.providerLabel} keep-alive missed pong, terminating stale connection`
+ `${this.providerLabel} keep-alive missed pong, terminating stale connection`,
+ this._logContext()
);
socket.terminate();
return;
@@ -362,7 +470,10 @@ class OpenAIRealtimeStreaming {
try {
socket.ping();
} catch (err) {
- debugLogger.debug(`${this.providerLabel} keep-alive ping failed`, { error: err.message });
+ debugLogger.debug(
+ `${this.providerLabel} keep-alive ping failed`,
+ this._logContext({ error: err.message })
+ );
socket.terminate();
}
}, KEEPALIVE_INTERVAL_MS);
@@ -404,10 +515,13 @@ class OpenAIRealtimeStreaming {
}
if (this.coldStartBuffer.length > 0) {
- debugLogger.debug(`${this.providerLabel} flushing cold-start buffer`, {
- chunks: this.coldStartBuffer.length,
- bytes: this.coldStartBufferSize,
- });
+ debugLogger.debug(
+ `${this.providerLabel} flushing cold-start buffer`,
+ this._logContext({
+ chunks: this.coldStartBuffer.length,
+ bytes: this.coldStartBufferSize,
+ })
+ );
for (const buf of this.coldStartBuffer) {
const audio = this._resampleToInputRate(buf);
this.ws.send(
@@ -428,12 +542,17 @@ class OpenAIRealtimeStreaming {
}
async disconnect({ commit = true } = {}) {
- debugLogger.debug(`${this.providerLabel} disconnect`, {
- audioBytesSent: this.audioBytesSent,
- segments: this.completedSegments.length,
- textLength: this.getFullTranscript().length,
- readyState: this.ws?.readyState,
- });
+ debugLogger.debug(
+ `${this.providerLabel} disconnect`,
+ this._logContext({
+ audioBytesSent: this.audioBytesSent,
+ segments: this.completedSegments.length,
+ textLength: this.getFullTranscript().length,
+ // Discriminates "VAD never fired" from "turns fired but empty/failed".
+ speechStartedCount: this.speechStartedCount,
+ readyState: this.ws?.readyState,
+ })
+ );
if (!this.ws) return { text: this.getFullTranscript() };
@@ -453,7 +572,10 @@ class OpenAIRealtimeStreaming {
await new Promise((resolve) => {
const tid = setTimeout(() => {
- debugLogger.debug(`${this.providerLabel} commit timeout, using accumulated text`);
+ debugLogger.debug(
+ `${this.providerLabel} commit timeout, using accumulated text`,
+ this._logContext()
+ );
resolve();
}, DISCONNECT_TIMEOUT_MS);
diff --git a/src/helpers/tinfoilRealtimeStreaming.js b/src/helpers/tinfoilRealtimeStreaming.js
index d2791cc77..3617c3c5a 100644
--- a/src/helpers/tinfoilRealtimeStreaming.js
+++ b/src/helpers/tinfoilRealtimeStreaming.js
@@ -166,7 +166,10 @@ class TinfoilRealtimeStreaming extends OpenAIRealtimeStreaming {
return true;
} catch (error) {
this._settleCommit();
- debugLogger.debug(`${this.providerLabel} commit send failed`, { error: error.message });
+ debugLogger.debug(
+ `${this.providerLabel} commit send failed`,
+ this._logContext({ error: error.message })
+ );
return false;
}
}
@@ -174,9 +177,12 @@ class TinfoilRealtimeStreaming extends OpenAIRealtimeStreaming {
_requestRecovery(error, surfaceError = true) {
if (this._recoveryRequested) return;
this._recoveryRequested = true;
- debugLogger.warn(`${this.providerLabel} connection recovery requested`, {
- error: error.message,
- });
+ debugLogger.warn(
+ `${this.providerLabel} connection recovery requested`,
+ this._logContext({
+ error: error.message,
+ })
+ );
if (this.onConnectionLost) {
this._notifyConnectionLost(error);
} else if (surfaceError) {
diff --git a/src/helpers/windowManager.js b/src/helpers/windowManager.js
index fa00ed44e..40417042f 100644
--- a/src/helpers/windowManager.js
+++ b/src/helpers/windowManager.js
@@ -1,5 +1,7 @@
-const { app, screen, BrowserWindow, shell, dialog, ipcMain } = require("electron");
+const { app, screen, BrowserWindow, dialog, ipcMain } = require("electron");
const debugLogger = require("./debugLogger");
+// Aliased: this class has an openExternalUrl method wrapping the helper.
+const { openExternalUrl: openUrlInExternalBrowser } = require("./externalUrlOpener");
const HotkeyManager = require("./hotkeyManager");
const { isGlobeLikeHotkey } = HotkeyManager;
const DragManager = require("./dragManager");
@@ -1080,7 +1082,7 @@ class WindowManager {
}
openExternalUrl(url, showError = true) {
- shell.openExternal(url).catch((error) => {
+ openUrlInExternalBrowser(url).catch((error) => {
if (showError) {
dialog.showErrorBox(
i18nMain.t("dialog.openLink.title"),
diff --git a/src/locales/de/translation.json b/src/locales/de/translation.json
index 43d5651e0..158f4ee52 100644
--- a/src/locales/de/translation.json
+++ b/src/locales/de/translation.json
@@ -3117,7 +3117,11 @@
"description": "Transkriptionen und strukturierte Zusammenfassungen",
"back": "Zurück",
"restrictedByOrg": "Die Transkription von Besprechungen ist durch Ihre Organisation eingeschränkt.",
- "autoEnded": "Die Aufnahme wurde nach dem Ende des Meetings automatisch beendet."
+ "autoEnded": "Die Aufnahme wurde nach dem Ende des Meetings automatisch beendet.",
+ "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."
+ }
},
"meetingPill": {
"returnToNote": "Zurück zur Aufnahme",
diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json
index 8beff1c0f..41695fdab 100644
--- a/src/locales/en/translation.json
+++ b/src/locales/en/translation.json
@@ -3117,7 +3117,11 @@
"description": "Transcriptions & structured summaries",
"back": "Back",
"restrictedByOrg": "Meeting transcription is restricted by your organization.",
- "autoEnded": "Recording stopped automatically after your meeting ended."
+ "autoEnded": "Recording stopped automatically after your meeting ended.",
+ "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."
+ }
},
"meetingPill": {
"returnToNote": "Return to recording",
diff --git a/src/locales/es/translation.json b/src/locales/es/translation.json
index cc3b9ee56..6c7a84afb 100644
--- a/src/locales/es/translation.json
+++ b/src/locales/es/translation.json
@@ -2954,7 +2954,11 @@
"description": "Transcripciones y resúmenes estructurados",
"back": "Atrás",
"restrictedByOrg": "La transcripción de reuniones está restringida por tu organización.",
- "autoEnded": "La grabación se detuvo automáticamente cuando terminó la reunión."
+ "autoEnded": "La grabación se detuvo automáticamente cuando terminó la reunión.",
+ "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."
+ }
},
"meetingPill": {
"returnToNote": "Volver a la grabación",
diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.json
index 1d3e8fe65..9ae02c2af 100644
--- a/src/locales/fr/translation.json
+++ b/src/locales/fr/translation.json
@@ -3117,7 +3117,11 @@
"description": "Transcriptions et résumés structurés",
"back": "Retour",
"restrictedByOrg": "La transcription des réunions est restreinte par votre organisation.",
- "autoEnded": "L'enregistrement s'est arrêté automatiquement à la fin de votre réunion."
+ "autoEnded": "L'enregistrement s'est arrêté automatiquement à la fin de votre réunion.",
+ "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."
+ }
},
"meetingPill": {
"returnToNote": "Revenir à l'enregistrement",
diff --git a/src/locales/it/translation.json b/src/locales/it/translation.json
index 66644c32b..fb804ca81 100644
--- a/src/locales/it/translation.json
+++ b/src/locales/it/translation.json
@@ -2906,7 +2906,11 @@
"description": "Trascrizioni e riassunti strutturati",
"back": "Indietro",
"restrictedByOrg": "La trascrizione delle riunioni è limitata dalla tua organizzazione.",
- "autoEnded": "La registrazione si è interrotta automaticamente al termine della riunione."
+ "autoEnded": "La registrazione si è interrotta automaticamente al termine della riunione.",
+ "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."
+ }
},
"meetingPill": {
"returnToNote": "Torna alla registrazione",
diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.json
index e5a18d670..5b54be0c2 100644
--- a/src/locales/ja/translation.json
+++ b/src/locales/ja/translation.json
@@ -2890,7 +2890,11 @@
"description": "文字起こしと構造化されたサマリー",
"back": "戻る",
"restrictedByOrg": "会議の文字起こしは組織によって制限されています。",
- "autoEnded": "会議の終了後、録音は自動的に停止しました。"
+ "autoEnded": "会議の終了後、録音は自動的に停止しました。",
+ "systemAudioSilent": {
+ "title": "会議の音声がまだ検出されていません",
+ "description": "これまでのところ、音声を拾っているのはマイクのみです。ビデオ会議中の場合は、会議の音声がこのコンピューターで再生されており、ミュートになっていないことを確認してください。対面で録音している場合は、この通知は無視してかまいません。マイクが室内の音を拾います。"
+ }
},
"meetingPill": {
"returnToNote": "録音に戻る",
diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.json
index 08bc9a90d..ca3f9a176 100644
--- a/src/locales/pt/translation.json
+++ b/src/locales/pt/translation.json
@@ -2906,7 +2906,11 @@
"description": "Transcrições e resumos estruturados",
"back": "Voltar",
"restrictedByOrg": "A transcrição de reuniões está restrita pela sua organização.",
- "autoEnded": "A gravação parou automaticamente após o fim da reunião."
+ "autoEnded": "A gravação parou automaticamente após o fim da reunião.",
+ "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."
+ }
},
"meetingPill": {
"returnToNote": "Voltar à gravação",
diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.json
index 935257172..23fd3857f 100644
--- a/src/locales/ru/translation.json
+++ b/src/locales/ru/translation.json
@@ -2928,7 +2928,11 @@
"description": "Транскрипции и структурированные резюме",
"back": "Назад",
"restrictedByOrg": "Транскрипция встреч ограничена вашей организацией.",
- "autoEnded": "Запись автоматически остановлена после завершения встречи."
+ "autoEnded": "Запись автоматически остановлена после завершения встречи.",
+ "systemAudioSilent": {
+ "title": "Звук встречи пока не обнаружен",
+ "description": "Пока звук поступает только с вашего микрофона. Вы на видеозвонке? Убедитесь, что звук встречи воспроизводится на этом компьютере и не отключён. Записываете встречу вживую? Это предупреждение можно игнорировать — ваш микрофон улавливает звук в помещении."
+ }
},
"meetingPill": {
"returnToNote": "Вернуться к записи",
diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.json
index e470a85bf..b3c928d75 100644
--- a/src/locales/zh-CN/translation.json
+++ b/src/locales/zh-CN/translation.json
@@ -2906,7 +2906,11 @@
"description": "转录与结构化摘要",
"back": "返回",
"restrictedByOrg": "会议转录已被您的组织限制。",
- "autoEnded": "会议结束后,录音已自动停止。"
+ "autoEnded": "会议结束后,录音已自动停止。",
+ "systemAudioSilent": {
+ "title": "尚未检测到会议音频",
+ "description": "到目前为止,只有您的麦克风采集到声音。正在进行视频通话?请检查会议音频是否正在此电脑上播放且未被静音。正在进行现场录音?您可以忽略此提示——您的麦克风会采集房间内的声音。"
+ }
},
"meetingPill": {
"returnToNote": "返回到录音",
diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.json
index 0ecc91c5b..4a7257f29 100644
--- a/src/locales/zh-TW/translation.json
+++ b/src/locales/zh-TW/translation.json
@@ -2906,7 +2906,11 @@
"description": "轉錄與結構化摘要",
"back": "返回",
"restrictedByOrg": "會議轉錄已被您的組織限制。",
- "autoEnded": "會議結束後,錄音已自動停止。"
+ "autoEnded": "會議結束後,錄音已自動停止。",
+ "systemAudioSilent": {
+ "title": "尚未偵測到會議音訊",
+ "description": "到目前為止,只有您的麥克風收到聲音。正在進行視訊通話?請檢查會議音訊是否正在此電腦上播放且未被靜音。正在進行現場錄音?您可以忽略此提示——您的麥克風會收錄房間內的聲音。"
+ }
},
"meetingPill": {
"returnToNote": "返回到錄音",
diff --git a/src/stores/meetingRecordingStore.ts b/src/stores/meetingRecordingStore.ts
index 9aaff167e..615609809 100644
--- a/src/stores/meetingRecordingStore.ts
+++ b/src/stores/meetingRecordingStore.ts
@@ -99,6 +99,8 @@ interface MeetingRecordingState {
error: string | null;
/** Bumped on every error report so identical repeated errors still re-notify. */
errorNonce: number;
+ /** Latched once per recording when main reports the system-audio tap has produced only silence. */
+ systemAudioSilentWarning: boolean;
currentMicLevel: number;
micCaptureStatus: "inactive" | "active" | "reconnecting" | "unavailable";
windowWidth: number;
@@ -412,6 +414,7 @@ let systemPartialSpeakerIdValue: string | null = null;
let recentSystemSpeaker: RecentSystemSpeaker | null = null;
let speakerLocks: Map<string, string> = new Map();
let pushConfigTimeout: ReturnType<typeof setTimeout> | null = null;
+let sessionSystemAudioActive = false;
export const useMeetingRecordingStore = create<MeetingRecordingState>()(() => ({
isRecording: false,
@@ -433,6 +436,7 @@ export const useMeetingRecordingStore = create<MeetingRecordingState>()(() => ({
userTouchedStepper: false,
error: null,
errorNonce: 0,
+ systemAudioSilentWarning: false,
currentMicLevel: 0,
micCaptureStatus: "inactive",
windowWidth: typeof window !== "undefined" ? window.innerWidth : SIDE_PANEL_BREAKPOINT_PX,
@@ -688,6 +692,7 @@ async function cleanup(): Promise<void> {
isPrepared = false;
isRecordingFlag = false;
isStartingFlag = false;
+ sessionSystemAudioActive = false;
}
export async function prepareTranscription(): Promise<void> {
@@ -788,6 +793,7 @@ export async function startRecording(args: StartRecordingArgs): Promise<boolean>
recentSystemSpeaker = null;
speakerLocks = locks;
systemPartialSpeakerIdValue = null;
+ sessionSystemAudioActive = false;
useMeetingRecordingStore.setState({
isRecording: true,
@@ -810,6 +816,7 @@ export async function startRecording(args: StartRecordingArgs): Promise<boolean>
diarizationSessionId: null,
completedDiarization: null,
error: null,
+ systemAudioSilentWarning: false,
micCaptureStatus: "inactive",
});
@@ -1158,6 +1165,22 @@ export async function startRecording(args: StartRecordingArgs): Promise<boolean>
});
if (fatalErrorCleanup) ipcCleanups.push(fatalErrorCleanup);
+ // One-shot from main (~45s in) when the system tap has streamed only
+ // silence; main never emits it for mic-only sessions, but gate on this
+ // session's own system-audio state anyway.
+ const systemAudioSilentCleanup = window.electronAPI?.onMeetingSystemAudioSilent?.((data) => {
+ if (activeRecordingSessionId !== sessionId || !isRecordingFlag) return;
+ if (!sessionSystemAudioActive) return;
+ if (useMeetingRecordingStore.getState().systemAudioSilentWarning) return;
+ logger.warn(
+ "Meeting system audio has produced only silence",
+ { systemAudioStrategy: data?.systemAudioStrategy },
+ "meeting"
+ );
+ useMeetingRecordingStore.setState({ systemAudioSilentWarning: true });
+ });
+ if (systemAudioSilentCleanup) ipcCleanups.push(systemAudioSilentCleanup);
+
// Main re-derives the expected count when participants are added mid-meeting
// (never for a count set explicitly via the stepper — main skips those).
const speakerConfigCleanup = window.electronAPI?.onMeetingSessionSpeakerConfigUpdated?.(
@@ -1355,6 +1378,7 @@ export async function startRecording(args: StartRecordingArgs): Promise<boolean>
}
const systemAudioAvailable = systemAudioHandledInMain || systemStream !== null;
+ sessionSystemAudioActive = systemAudioAvailable;
try {
const availabilityResult =
await window.electronAPI?.meetingTranscriptionSetSystemAudioAvailable?.(
@@ -1438,6 +1462,7 @@ export async function stopRecording(expectedSessionId?: string): Promise<StopRec
systemPartial: "",
systemPartialSpeakerId: null,
systemPartialSpeakerName: null,
+ systemAudioSilentWarning: false,
currentMicLevel: 0,
});
return { diarizationSessionId: null };
@@ -1523,6 +1548,7 @@ export async function stopRecording(expectedSessionId?: string): Promise<StopRec
systemPartial: "",
systemPartialSpeakerId: null,
systemPartialSpeakerName: null,
+ systemAudioSilentWarning: false,
currentMicLevel: 0,
});
diff --git a/src/types/electron.ts b/src/types/electron.ts
index cf328b612..b2f0a24e6 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -2521,6 +2521,9 @@ declare global {
) => () => void;
onMeetingTranscriptionError?: (callback: (error: string) => void) => () => void;
onMeetingTranscriptionFatalError?: (callback: (error: string) => void) => () => void;
+ onMeetingSystemAudioSilent?: (
+ callback: (data: { systemAudioStrategy: SystemAudioStrategy }) => void
+ ) => () => void;
// Speaker diarization
downloadDiarizationModels?: () => Promise<{ success: boolean; error?: string }>;
diff --git a/test/helpers/externalUrlOpener.test.js b/test/helpers/externalUrlOpener.test.js
new file mode 100644
index 000000000..e2fe523a4
--- /dev/null
+++ b/test/helpers/externalUrlOpener.test.js
@@ -0,0 +1,172 @@
+const test = require("node:test");
+const { afterEach } = require("node:test");
+const assert = require("node:assert/strict");
+const Module = require("node:module");
+const { EventEmitter } = require("node:events");
+const childProcess = require("node:child_process");
+
+const openerModulePath = require.resolve("../../src/helpers/externalUrlOpener");
+const originalLoad = Module._load;
+const originalPlatform = process.platform;
+const originalSystemRoot = process.env.SystemRoot;
+
+function setPlatform(platform) {
+ Object.defineProperty(process, "platform", { value: platform, configurable: true });
+}
+
+function setSystemRoot(value) {
+ if (value === undefined) delete process.env.SystemRoot;
+ else process.env.SystemRoot = value;
+}
+
+function makeChild() {
+ const child = new EventEmitter();
+ child.unrefCalls = 0;
+ child.unref = () => {
+ child.unrefCalls += 1;
+ };
+ return child;
+}
+
+// Returns the helper plus the spawn and shell.openExternal calls it made.
+// spawnOutcome picks which child-process event the mock spawn fires.
+function loadOpener({ spawnOutcome = "spawn" } = {}) {
+ delete require.cache[openerModulePath];
+
+ const spawnCalls = [];
+ const openExternalCalls = [];
+ const spawn = (command, args, options) => {
+ const child = makeChild();
+ spawnCalls.push({ command, args, options, child });
+ process.nextTick(() => {
+ if (spawnOutcome === "error") {
+ child.emit("error", new Error("spawn failed"));
+ } else {
+ child.emit("spawn");
+ }
+ });
+ return child;
+ };
+
+ Module._load = function loadWithMocks(request, parent, isMain) {
+ if (request === "electron") {
+ return {
+ shell: {
+ openExternal: (url) => {
+ openExternalCalls.push(url);
+ return Promise.resolve();
+ },
+ },
+ };
+ }
+ if (request === "child_process") {
+ return { ...childProcess, spawn };
+ }
+ return originalLoad(request, parent, isMain);
+ };
+
+ try {
+ const { openExternalUrl } = require(openerModulePath);
+ return { openExternalUrl, spawnCalls, openExternalCalls };
+ } finally {
+ Module._load = originalLoad;
+ }
+}
+
+afterEach(() => {
+ Module._load = originalLoad;
+ setPlatform(originalPlatform);
+ setSystemRoot(originalSystemRoot);
+});
+
+test("win32 https URLs launch through explorer.exe, outside our process tree", async () => {
+ const { openExternalUrl, spawnCalls, openExternalCalls } = loadOpener();
+ setPlatform("win32");
+ setSystemRoot("C:\\WINDOWS");
+
+ await openExternalUrl("https://meet.google.com/abc-defg-hij");
+
+ assert.equal(openExternalCalls.length, 0);
+ assert.equal(spawnCalls.length, 1);
+ // Absolute path: a bare "explorer.exe" would resolve from the CWD first.
+ assert.equal(spawnCalls[0].command, "C:\\WINDOWS\\explorer.exe");
+ assert.deepEqual(spawnCalls[0].args, ["https://meet.google.com/abc-defg-hij"]);
+ assert.deepEqual(spawnCalls[0].options, { detached: true, stdio: "ignore", windowsHide: true });
+ assert.equal(spawnCalls[0].child.unrefCalls, 1);
+});
+
+test("explorer.exe path falls back to C:\\Windows when SystemRoot is unset", async () => {
+ const { openExternalUrl, spawnCalls } = loadOpener();
+ setPlatform("win32");
+ setSystemRoot(undefined);
+
+ await openExternalUrl("https://meet.google.com/abc-defg-hij");
+
+ assert.equal(spawnCalls[0].command, "C:\\Windows\\explorer.exe");
+});
+
+test("win32 http URLs take the explorer.exe path too", async () => {
+ const { openExternalUrl, spawnCalls, openExternalCalls } = loadOpener();
+ setPlatform("win32");
+
+ await openExternalUrl("http://example.com/join");
+
+ assert.equal(openExternalCalls.length, 0);
+ assert.deepEqual(spawnCalls[0].args, ["http://example.com/join"]);
+});
+
+test("explorer.exe receives a single percent-encoded argv token", async () => {
+ const { openExternalUrl, spawnCalls } = loadOpener();
+ setPlatform("win32");
+
+ await openExternalUrl('https://example.com/join?name=a b"c');
+
+ assert.deepEqual(spawnCalls[0].args, ["https://example.com/join?name=a%20b%22c"]);
+});
+
+test("win32 mailto URLs fall through to shell.openExternal untouched", async () => {
+ const { openExternalUrl, spawnCalls, openExternalCalls } = loadOpener();
+ setPlatform("win32");
+
+ await openExternalUrl("mailto:[email protected]");
+
+ assert.equal(spawnCalls.length, 0);
+ assert.deepEqual(openExternalCalls, ["mailto:[email protected]"]);
+});
+
+test("non-win32 platforms always use shell.openExternal", async () => {
+ const { openExternalUrl, spawnCalls, openExternalCalls } = loadOpener();
+
+ for (const platform of ["darwin", "linux"]) {
+ setPlatform(platform);
+ await openExternalUrl("https://meet.google.com/abc-defg-hij");
+ }
+
+ assert.equal(spawnCalls.length, 0);
+ assert.deepEqual(openExternalCalls, [
+ "https://meet.google.com/abc-defg-hij",
+ "https://meet.google.com/abc-defg-hij",
+ ]);
+});
+
+test("invalid URLs reject without launching anything", async () => {
+ const { openExternalUrl, spawnCalls, openExternalCalls } = loadOpener();
+ setPlatform("win32");
+
+ await assert.rejects(openExternalUrl("not a url"), TypeError);
+
+ assert.equal(spawnCalls.length, 0);
+ assert.equal(openExternalCalls.length, 0);
+});
+
+test("an unspawnable explorer.exe still opens the link, in-process", async () => {
+ const { openExternalUrl, spawnCalls, openExternalCalls } = loadOpener({ spawnOutcome: "error" });
+ setPlatform("win32");
+
+ await openExternalUrl("https://example.com/join");
+
+ // Degraded capture (the browser may land inside the excluded process tree)
+ // beats a Join button that does nothing on shell-less Windows images.
+ assert.equal(spawnCalls.length, 1);
+ assert.deepEqual(openExternalCalls, ["https://example.com/join"]);
+});
diff --git a/test/helpers/meetingStreamingWiring.test.js b/test/helpers/meetingStreamingWiring.test.js
new file mode 100644
index 000000000..3ac95ccab
--- /dev/null
+++ b/test/helpers/meetingStreamingWiring.test.js
@@ -0,0 +1,55 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const path = require("node:path");
+
+// The meeting dispatch/start/teardown paths live inside the IPCHandlers
+// registration closure, so — like ipcPolicyHeaderCoverage.test.js — this pins
+// the wiring at the source level.
+const source = fs.readFileSync(path.join(__dirname, "../../src/helpers/ipcHandlers.js"), "utf8");
+
+test("every meeting realtime connect labels the stream and gives system its own VAD threshold", () => {
+ assert.match(source, /const MEETING_SYSTEM_VAD_THRESHOLD = 0\.3;/);
+ assert.match(
+ source,
+ /withMeetingSourceConnectOpts = \(connectOpts, source\) => \(\{\s*\.\.\.connectOpts,\s*streamLabel: source,\s*\.\.\.\(source === "system" \? \{ vadThreshold: MEETING_SYSTEM_VAD_THRESHOLD \} : \{\}\),\s*\}\)/
+ );
+ // Initial connect and mid-meeting reconnect both go through the helper; a
+ // bare ...connectOpts spread would silently drop the system channel's
+ // threshold and its stream label.
+ assert.equal(
+ (source.match(/\.\.\.withMeetingSourceConnectOpts\(connectOpts, source\)/g) ?? []).length,
+ 2
+ );
+ assert.doesNotMatch(source, /connect\(\{ apiKey: secret, token: secret, \.\.\.connectOpts \}\)/);
+});
+
+test("streaming dispatch logs system-channel levels", () => {
+ assert.match(
+ source,
+ /source === "system" && buffer\.length >= 2[\s\S]{0,400}?"Meeting system audio stats"/
+ );
+});
+
+test("silent system audio warning arms on start and clears on every teardown path", () => {
+ // Armed only when a system-audio strategy is active (never for mic-only).
+ assert.match(
+ source,
+ /result\.systemAudioStrategy && result\.systemAudioStrategy !== "unsupported"[\s\S]{0,160}?armMeetingSystemAudioSilenceTimer\(/
+ );
+ assert.match(source, /send\("meeting-system-audio-silent", \{ systemAudioStrategy \}\)/);
+ // Normal/forced stop and error rollback both clear the one-shot timer.
+ const rollbackStart = source.indexOf("const rollbackMeetingTranscriptionStart");
+ const stopStart = source.indexOf("const stopMeetingTranscription");
+ assert.ok(rollbackStart >= 0 && stopStart > rollbackStart);
+ const rollbackSection = source.slice(
+ rollbackStart,
+ source.indexOf("const setupDictationCallbacks")
+ );
+ assert.match(rollbackSection, /clearMeetingSystemAudioSilenceTimer\(\);/);
+ const stopSection = source.slice(
+ stopStart,
+ source.indexOf("const meetingTranscriptionLifecycle")
+ );
+ assert.match(stopSection, /clearMeetingSystemAudioSilenceTimer\(\);/);
+});
diff --git a/test/helpers/openaiRealtimeStreaming.test.js b/test/helpers/openaiRealtimeStreaming.test.js
index 8d69041d9..6852825c6 100644
--- a/test/helpers/openaiRealtimeStreaming.test.js
+++ b/test/helpers/openaiRealtimeStreaming.test.js
@@ -33,6 +33,19 @@ async function connectPreconfigured(streaming, socket) {
await connected;
}
+function captureLogs(t) {
+ const debugLogger = require("../../src/helpers/debugLogger");
+ const entries = [];
+ for (const level of ["debug", "warn", "error"]) {
+ const original = debugLogger[level];
+ debugLogger[level] = (message, meta) => entries.push({ level, message, meta });
+ t.after(() => {
+ debugLogger[level] = original;
+ });
+ }
+ return entries;
+}
+
test("sendAudio buffers frames arriving before the socket exists (token-fetch window)", async () => {
const OpenAIRealtimeStreaming = (await load()).default;
const streaming = new OpenAIRealtimeStreaming();
@@ -565,6 +578,50 @@ test("BYOK session.update is byte-for-byte today's payload when no VAD/language/
streaming.cleanup();
});
+test("BYOK session.update is byte-for-byte the overridden payload when vadThreshold is passed (system socket)", async () => {
+ const OpenAIRealtimeStreaming = (await load()).default;
+ const streaming = new OpenAIRealtimeStreaming();
+ const socket = makeFakeSocket(WS.CONNECTING);
+
+ const connected = streaming.connect({
+ apiKey: "sk-test",
+ model: "gpt-4o-mini-transcribe",
+ streamLabel: "system",
+ vadThreshold: 0.3,
+ createSocket: async () => socket,
+ });
+ await new Promise((resolve) => setImmediate(resolve));
+ socket.readyState = WS.OPEN;
+ socket.emit("message", JSON.stringify({ type: "session.created" }));
+
+ const updates = socket.sent
+ .map((raw) => JSON.parse(raw))
+ .filter((e) => e.type === "session.update");
+ assert.equal(updates.length, 1, "exactly one session.update after session.created");
+ assert.deepEqual(updates[0], {
+ type: "session.update",
+ session: {
+ type: "transcription",
+ audio: {
+ input: {
+ format: { type: "audio/pcm", rate: 24000 },
+ transcription: { model: "gpt-4o-mini-transcribe" },
+ turn_detection: {
+ type: "server_vad",
+ threshold: 0.3,
+ silence_duration_ms: 600,
+ prefix_padding_ms: 500,
+ },
+ },
+ },
+ },
+ });
+
+ socket.emit("message", JSON.stringify({ type: "session.updated" }));
+ await connected;
+ streaming.cleanup();
+});
+
test("dictation-style connect (inputRate 16000, custom socket factory) declares the 16kHz format and the same VAD", async () => {
const OpenAIRealtimeStreaming = (await load()).default;
const streaming = new OpenAIRealtimeStreaming();
@@ -641,3 +698,172 @@ test("characterization: a final that lands during disconnect()'s commit window r
// Phase 1 changes this line to `typeof calls[0].timestamp === "number"`.
assert.equal(calls[0].timestamp, undefined);
});
+
+// -- diagnostic logging: stream labels, VAD events, failed/empty turns --
+
+test("transcription.failed is logged with the stream label and stays log-only (no onError, no segment)", async (t) => {
+ const OpenAIRealtimeStreaming = (await load()).default;
+ const streaming = new OpenAIRealtimeStreaming();
+ streaming.streamLabel = "system";
+ const logs = captureLogs(t);
+ let errorCalled = false;
+ streaming.onError = () => {
+ errorCalled = true;
+ };
+
+ streaming.handleMessage(
+ JSON.stringify({
+ type: "conversation.item.input_audio_transcription.failed",
+ item_id: "item_1",
+ error: { code: "audio_unintelligible", message: "audio too noisy" },
+ })
+ );
+
+ const line = logs.find((entry) => entry.message.includes("turn transcription failed"));
+ assert.ok(line, "failed turn must produce a debug line");
+ assert.equal(line.level, "debug");
+ assert.equal(line.meta.stream, "system");
+ assert.equal(line.meta.itemId, "item_1");
+ assert.equal(line.meta.error, "audio too noisy");
+ assert.equal(errorCalled, false, "failed turns must not surface as errors");
+ assert.equal(streaming.completedSegments.length, 0, "failed turns must not count as segments");
+});
+
+test("empty-transcript completed events are logged and add no segment", async (t) => {
+ const OpenAIRealtimeStreaming = (await load()).default;
+ const streaming = new OpenAIRealtimeStreaming();
+ streaming.streamLabel = "system";
+ streaming.audioBytesSent = 4800;
+ const logs = captureLogs(t);
+ let finalCalled = false;
+ streaming.onFinalTranscript = () => {
+ finalCalled = true;
+ };
+
+ streaming.handleMessage(
+ JSON.stringify({
+ type: "conversation.item.input_audio_transcription.completed",
+ item_id: "item_2",
+ transcript: " ",
+ })
+ );
+
+ const line = logs.find((entry) => entry.message.includes("turn completed with empty transcript"));
+ assert.ok(line, "empty completion must produce a debug line");
+ assert.equal(line.meta.stream, "system");
+ assert.equal(line.meta.itemId, "item_2");
+ assert.equal(line.meta.audioBytesSent, 4800);
+ assert.equal(finalCalled, false);
+ assert.equal(streaming.completedSegments.length, 0);
+});
+
+test("VAD events log first-3-then-every-50th with streamLabel and audioBytesSent", async (t) => {
+ const OpenAIRealtimeStreaming = (await load()).default;
+ const streaming = new OpenAIRealtimeStreaming();
+ streaming.streamLabel = "system";
+ streaming.audioBytesSent = 1234;
+ const logs = captureLogs(t);
+ const vadLines = () => logs.filter((entry) => entry.message.includes("VAD event"));
+
+ streaming.handleMessage(JSON.stringify({ type: "input_audio_buffer.speech_started" }));
+ streaming.handleMessage(JSON.stringify({ type: "input_audio_buffer.speech_stopped" }));
+ streaming.handleMessage(JSON.stringify({ type: "input_audio_buffer.committed" }));
+ assert.equal(vadLines().length, 3, "first 3 events all log");
+ assert.equal(vadLines()[0].meta.stream, "system");
+ assert.equal(vadLines()[0].meta.event, "input_audio_buffer.speech_started");
+ assert.equal(vadLines()[0].meta.audioBytesSent, 1234);
+
+ // Events 4..49 are throttled; the 50th logs again.
+ for (let i = 4; i <= 49; i++) {
+ streaming.handleMessage(JSON.stringify({ type: "input_audio_buffer.committed" }));
+ }
+ assert.equal(vadLines().length, 3, "events 4..49 stay silent");
+ streaming.handleMessage(JSON.stringify({ type: "input_audio_buffer.speech_started" }));
+ assert.equal(vadLines().length, 4, "the 50th event logs");
+ assert.equal(vadLines()[3].meta.count, 50);
+
+ assert.equal(streaming.speechStartedCount, 2, "only speech_started increments the counter");
+});
+
+test("disconnect summary carries streamLabel and speechStartedCount", async (t) => {
+ const OpenAIRealtimeStreaming = (await load()).default;
+ const streaming = new OpenAIRealtimeStreaming();
+ const socket = makeFakeSocket(WS.CONNECTING);
+ const connected = streaming.connect({
+ apiKey: "key",
+ preconfigured: true,
+ streamLabel: "system",
+ createSocket: async () => socket,
+ });
+ await new Promise((resolve) => setImmediate(resolve));
+ socket.readyState = WS.OPEN;
+ socket.emit("message", JSON.stringify({ type: "session.created" }));
+ await connected;
+
+ socket.emit("message", JSON.stringify({ type: "input_audio_buffer.speech_started" }));
+ socket.emit("message", JSON.stringify({ type: "input_audio_buffer.speech_started" }));
+
+ const logs = captureLogs(t);
+ await streaming.disconnect();
+
+ const line = logs.find((entry) => entry.message === "OpenAI Realtime disconnect");
+ assert.ok(line, "disconnect must log a summary");
+ assert.equal(line.meta.stream, "system");
+ assert.equal(line.meta.speechStartedCount, 2);
+ assert.equal(line.meta.segments, 0);
+ assert.equal(line.meta.audioBytesSent, 0);
+});
+
+test("preconfigured session.created echoes the server VAD config and format into the log", async (t) => {
+ const OpenAIRealtimeStreaming = (await load()).default;
+ const streaming = new OpenAIRealtimeStreaming();
+ const socket = makeFakeSocket(WS.CONNECTING);
+ const logs = captureLogs(t);
+
+ const connected = streaming.connect({
+ apiKey: "key",
+ preconfigured: true,
+ streamLabel: "system",
+ createSocket: async () => socket,
+ });
+ await new Promise((resolve) => setImmediate(resolve));
+ socket.readyState = WS.OPEN;
+ socket.emit(
+ "message",
+ JSON.stringify({
+ type: "session.created",
+ session: {
+ audio: {
+ input: {
+ format: { type: "audio/pcm", rate: 24000 },
+ turn_detection: { type: "server_vad", threshold: 0.5, silence_duration_ms: 600 },
+ },
+ },
+ },
+ })
+ );
+ await connected;
+
+ const lines = logs.filter((entry) => entry.message.includes("session created (preconfigured)"));
+ assert.equal(lines.length, 1, "server config echo logs once per socket");
+ assert.equal(lines[0].meta.stream, "system");
+ assert.deepEqual(lines[0].meta.turnDetection, {
+ type: "server_vad",
+ threshold: 0.5,
+ silence_duration_ms: 600,
+ });
+ assert.deepEqual(lines[0].meta.inputFormat, { type: "audio/pcm", rate: 24000 });
+ streaming.cleanup();
+});
+
+test("without a streamLabel (dictation) log metadata carries no stream key", async (t) => {
+ const OpenAIRealtimeStreaming = (await load()).default;
+ const streaming = new OpenAIRealtimeStreaming();
+ const logs = captureLogs(t);
+
+ await streaming.disconnect();
+
+ const line = logs.find((entry) => entry.message === "OpenAI Realtime disconnect");
+ assert.ok(line);
+ assert.equal("stream" in line.meta, false, "unlabelled sockets keep today's metadata shape");
+});
diff --git a/test/helpers/tinfoilRealtimeStreaming.test.js b/test/helpers/tinfoilRealtimeStreaming.test.js
index 89f960e00..72c37eb4e 100644
--- a/test/helpers/tinfoilRealtimeStreaming.test.js
+++ b/test/helpers/tinfoilRealtimeStreaming.test.js
@@ -207,6 +207,63 @@ test("meeting sessions declare the 24kHz PCM input format", async () => {
streaming.cleanup();
});
+test("meeting session.update honors streamLabel + vadThreshold overrides through the subclass", async () => {
+ const { TinfoilRealtimeStreaming } = await load();
+ const socket = makeFakeSocket(WS.CONNECTING);
+ const { factory } = makeRecordingFactory(socket);
+ const streaming = new TinfoilRealtimeStreaming(factory);
+
+ const connected = streaming.connect({
+ apiKey: "tk-secret",
+ streamLabel: "system",
+ vadThreshold: 0.3,
+ });
+ await new Promise((resolve) => setImmediate(resolve));
+ socket.readyState = WS.OPEN;
+ socket.emit("message", JSON.stringify({ type: "session.created" }));
+
+ const [update] = sentEvents(socket, "session.update");
+ assert.deepEqual(update.session.audio.input.turn_detection, {
+ type: "server_vad",
+ threshold: 0.3,
+ silence_duration_ms: 600,
+ prefix_padding_ms: 500,
+ });
+ assert.equal(streaming.streamLabel, "system");
+
+ socket.emit("message", JSON.stringify({ type: "session.updated" }));
+ await connected;
+ streaming.cleanup();
+});
+
+test("labelled Tinfoil sessions carry the stream label in log metadata", async () => {
+ const debugLogger = require("../../src/helpers/debugLogger");
+ const { TinfoilRealtimeStreaming } = await load();
+ const socket = makeFakeSocket(WS.CONNECTING);
+ const { factory } = makeRecordingFactory(socket);
+ const streaming = new TinfoilRealtimeStreaming(factory);
+
+ const entries = [];
+ const levels = ["debug", "warn", "error"];
+ const originals = Object.fromEntries(levels.map((level) => [level, debugLogger[level]]));
+ for (const level of levels) {
+ debugLogger[level] = (message, meta) => entries.push({ message, meta });
+ }
+ try {
+ const connected = streaming.connect({ apiKey: "tk-secret", streamLabel: "system" });
+ await finishConnect(streaming, socket);
+ await connected;
+ await streaming.disconnect();
+ } finally {
+ for (const level of levels) debugLogger[level] = originals[level];
+ }
+
+ const summary = entries.find((entry) => entry.message === "Tinfoil Realtime disconnect");
+ assert.ok(summary, "disconnect summary must be logged");
+ assert.equal(summary.meta.stream, "system");
+ assert.equal(typeof summary.meta.speechStartedCount, "number");
+});
+
test("preconfigured sessions do not send a client session update", async () => {
const { TinfoilRealtimeStreaming } = await load();
const socket = makeFakeSocket(WS.CONNECTING);
diff --git a/test/stores/meetingRecordingStoreSystemAudioSilence.test.js b/test/stores/meetingRecordingStoreSystemAudioSilence.test.js
new file mode 100644
index 000000000..0f1c5016e
--- /dev/null
+++ b/test/stores/meetingRecordingStoreSystemAudioSilence.test.js
@@ -0,0 +1,189 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");
+
+// Drives the real startRecording/stopRecording flow through the renderer
+// harness and pins the meeting-system-audio-silent warning: latched once per
+// recording, cleared on stop, and never set for a session without system audio.
+
+const START_ARGS = {
+ noteId: null,
+ noteTitle: null,
+ folderId: null,
+ autoEndEligible: false,
+};
+
+function createElectronAPI({ systemAudioMode, systemAudioStrategy }) {
+ const listeners = { systemAudioSilent: 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: (callback) => {
+ listeners.systemAudioSilent = callback;
+ return () => {
+ if (listeners.systemAudioSilent === callback) listeners.systemAudioSilent = 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-silence-test-",
+ });
+ return vite.ssrLoadModule("/stores/meetingRecordingStore.ts");
+}
+
+// Minimal Web Audio + capture stubs so the mic pipeline can run under Node.
+function installMicCaptureGlobals(t) {
+ const track = {
+ readyState: "live",
+ label: "Fake Mic",
+ stop() {},
+ getSettings: () => ({}),
+ };
+ const stream = {
+ getTracks: () => [track],
+ getAudioTracks: () => [track],
+ getVideoTracks: () => [],
+ };
+ const mediaDevices = {
+ getUserMedia: async () => stream,
+ enumerateDevices: async () => [],
+ addEventListener() {},
+ removeEventListener() {},
+ };
+ const node = () => ({
+ connect() {},
+ disconnect() {},
+ gain: { value: 0 },
+ fftSize: 0,
+ smoothingTimeConstant: 0,
+ });
+ class FakeAudioContext {
+ constructor() {
+ this.state = "running";
+ this.audioWorklet = { addModule: async () => {} };
+ this.destination = {};
+ }
+ createMediaStreamSource() {
+ return node();
+ }
+ createGain() {
+ return node();
+ }
+ createAnalyser() {
+ return node();
+ }
+ async resume() {}
+ async close() {}
+ }
+ class FakeAudioWorkletNode {
+ constructor() {
+ this.port = { onmessage: null, postMessage() {} };
+ }
+ connect() {}
+ disconnect() {}
+ }
+
+ const originalNavigator = Object.getOwnPropertyDescriptor(globalThis, "navigator");
+ Object.defineProperty(globalThis, "navigator", {
+ value: { mediaDevices },
+ configurable: true,
+ writable: true,
+ });
+ globalThis.AudioContext = FakeAudioContext;
+ globalThis.AudioWorkletNode = FakeAudioWorkletNode;
+ t.after(() => {
+ if (originalNavigator) Object.defineProperty(globalThis, "navigator", originalNavigator);
+ else delete globalThis.navigator;
+ delete globalThis.AudioContext;
+ delete globalThis.AudioWorkletNode;
+ });
+}
+
+test("silence event latches the warning once during a system-audio session", 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().isRecording, true);
+ assert.equal(store.useMeetingRecordingStore.getState().systemAudioSilentWarning, false);
+ assert.equal(typeof listeners.systemAudioSilent, "function");
+
+ listeners.systemAudioSilent({ systemAudioStrategy: "native" });
+ assert.equal(store.useMeetingRecordingStore.getState().systemAudioSilentWarning, true);
+
+ // A repeated event must not re-set state (the UI toasts on the transition).
+ let notifications = 0;
+ const unsubscribe = store.useMeetingRecordingStore.subscribe(() => {
+ notifications += 1;
+ });
+ listeners.systemAudioSilent({ systemAudioStrategy: "native" });
+ unsubscribe();
+ assert.equal(notifications, 0);
+ assert.equal(store.useMeetingRecordingStore.getState().systemAudioSilentWarning, true);
+
+ await store.stopRecording();
+ assert.equal(store.useMeetingRecordingStore.getState().isRecording, false);
+ assert.equal(store.useMeetingRecordingStore.getState().systemAudioSilentWarning, false);
+});
+
+test("a silence event 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.systemAudioSilent;
+ await store.stopRecording();
+
+ lateCallback({ systemAudioStrategy: "native" });
+ assert.equal(store.useMeetingRecordingStore.getState().systemAudioSilentWarning, false);
+});
+
+test("no warning 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().isRecording, true);
+ assert.equal(store.useMeetingRecordingStore.getState().micCaptureStatus, "active");
+
+ listeners.systemAudioSilent({ systemAudioStrategy: "unsupported" });
+ assert.equal(store.useMeetingRecordingStore.getState().systemAudioSilentWarning, false);
+
+ await store.stopRecording();
+});