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): Prevent playback from triggering detection (#2071)
Chad Pihac6a871db1b8a
diff --git a/CLAUDE.md b/CLAUDE.mdindex a82988072..e2f804f85 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -51,7 +51,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)-- **macos-mic-listener.swift**: Swift source for CoreAudio mic property listener (event-driven mic detection)+- **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)@@ -130,10 +130,10 @@ OpenWhispr is an Electron-based desktop dictation application that uses whisper.- macOS: Event-driven via `systemPreferences.subscribeWorkspaceNotification` (zero CPU)- Windows/Linux: Shared `processListCache` polling (30s interval)- **audioActivityDetector.js**: Detects microphone usage for unscheduled meetings- - macOS: Event-driven via `macos-mic-listener` binary (CoreAudio property listeners)+ - macOS: Event-driven via `macos-mic-listener` binary (CoreAudio process objects; aggregate device activity prompts only while a known meeting app is running)- Windows: Event-driven via `windows-mic-listener.exe` (WASAPI sessions, self-PID exclusion)- Linux: Event-driven via `pactl subscribe` (PulseAudio source-output events)- - All platforms: Graceful fallback to polling if native approach fails+ - Windows/Linux: Graceful fallback to polling if the native approach fails; macOS has no safe polling signal and respawns the listener with backoff instead- **processListCache.js**: Shared singleton process list cache (5s TTL, `ps-list` npm)- **meetingEchoLeakDetector.js**: Audio-layer echo analysis for meeting recordings — correlates each mic chunk against the recent system-audio tap (lag search 0–500 ms in 5 ms steps) and classifies it `clean_local` / `suspected_render_bleed` / `double_talk`; drives chunk muting and per-segment suppression flags. PCM-driven tests in `test/helpers/meetingEchoLeakDetector.test.js`- **meetingMicGate.js**: Pure RMS/peak chunk stats + the meeting mic gate verdict (`send` / `zero` for streaming, `send` / `skip` for local) with the exported silence and bleed thresholds; `ipcHandlers.js` (`dispatchMeetingAudioBuffer`, `transcribeLocalMeetingChunk`) only applies the verdict. Unit-tested in `test/helpers/meetingMicGate.test.js`@@ -615,13 +615,14 @@ Detects meetings via three independent sources, orchestrated by `MeetingDetectio- macOS: `systemPreferences.subscribeWorkspaceNotification` — zero CPU, instant detection- Windows/Linux: `processListCache` shared polling (30s interval, `ps-list` npm)+- Context-only: a running meeting app never prompts by itself (FaceTime idles in the background). It corroborates unattributed macOS device activity (below) and drives the auto-end process-exit fast path**Microphone Detection** (unscheduled/browser meetings like Google Meet):-- macOS: `macos-mic-listener` binary — CoreAudio `kAudioDevicePropertyDeviceIsRunningSomewhere` property listeners with hot-plug support-- Windows: `windows-mic-listener.exe` — WASAPI `IAudioSessionManager2` session monitoring, `--exclude-pid` for self-mic exclusion+- macOS: `macos-mic-listener` binary — CoreAudio process-object input monitoring, excluding the background `com.apple.CoreSpeech` service (it runs input during ordinary playback). `CAPABILITY PID` transitions prompt on their own. `CAPABILITY AGGREGATE` device activity (no process objects — roughly macOS < 14.2 — or a transient snapshot failure) includes playback on combined input/output devices, so it prompts only while a known meeting app is running; the helper retries PID monitoring every 30s from its heartbeat and the detector accepts the later `CAPABILITY PID`. Capability is logged at info level; `sustained-audio-detected` carries `attributed`+- Windows: `windows-mic-listener.exe` — WASAPI `IAudioSessionManager2` session monitoring; self-mic exclusion happens in JavaScript using current OpenWhispr and capture-helper PIDs- Linux: `pactl subscribe` — PulseAudio source-output events-- All platforms: Graceful fallback to polling if native binary/command unavailable+- Windows/Linux: Fall back to polling if the native binary/command is unavailable. macOS has no safe polling signal: a missing binary pauses audio prompts, a crashed listener is respawned with exponential backoff (5s → 60s), and meanwhile only calendar reminders prompt while auto-end uses its existing silence fallback**Calendar Reminders** (scheduled meetings):@@ -821,11 +822,11 @@ Raster UI assets live in `src/assets/` (onboarding ones are named `onboarding-*`- CI workflow (`.github/workflows/build-windows-key-listener.yml`) auto-builds on push to main6. **Meeting Detection Not Working**:- - Check debug logs for "event-driven" vs "polling" mode+ - Check debug logs for "event-driven" vs "polling" mode; macOS also logs `macOS microphone detection capability` as `PID` or `AGGREGATE`- macOS: Verify `macos-mic-listener` binary exists in `resources/bin/` (compiled during `npm run compile:native`)- Windows: Verify `windows-mic-listener.exe` exists in `resources/bin/` (downloaded during `prebuild:win`)- Linux: Verify `pactl` is installed (`pulseaudio-utils` or `pipewire-pulse` package)- - If event-driven binary is missing, detection falls back to polling automatically+ - If the event-driven binary is missing, Windows/Linux fall back to polling; macOS pauses audio prompts (and respawns a crashed listener with backoff)7. **Local Semantic Search Not Working**:- Qdrant binary should be in `resources/bin/qdrant-{platform}-{arch}` (auto-downloaded during `predev`/`prebuild`)@@ -908,7 +909,7 @@ Raster UI assets live in `src/assets/` (onboarding ones are named `onboarding-*`- Temporary file cleanup- Memory usage with large models- Process timeout protection (5 minutes)-- Meeting detection uses event-driven OS APIs (near-zero CPU) with polling fallback+- Meeting detection uses event-driven OS APIs (near-zero CPU) with polling fallback on Windows/Linux- Process list cache shared between detectors to avoid duplicate `tasklist`/`pgrep` calls- Calendar sync (Google/Microsoft) uses exponential backoff to avoid hammering APIs on network failuresdiff --git a/main.js b/main.jsindex a77257891..90dd4c4b8 100644--- a/main.js+++ b/main.js@@ -488,9 +488,10 @@ function initializeCoreManagers() {calendarReminderScheduler);appleCalendarManager = new AppleCalendarManager(databaseManager, calendarReminderScheduler);+ const meetingProcessDetector = new MeetingProcessDetector();meetingDetectionEngine = new MeetingDetectionEngine(calendarReminderScheduler,- new MeetingProcessDetector(),+ meetingProcessDetector,new AudioActivityDetector(// The capture-helper managers are created a few lines below; the provider// is only invoked on mic events, long after initialization completes.@@ -500,7 +501,8 @@ function initializeCoreManagers() {linuxPortalAudioManager,windowsLoopbackAudioManager,])- )+ ),+ () => meetingProcessDetector.getDetectedProcesses().length > 0),windowManager,databaseManagerdiff --git a/resources/macos-mic-listener.swift b/resources/macos-mic-listener.swiftindex 9a60eadee..b85d2480d 100644--- a/resources/macos-mic-listener.swift+++ b/resources/macos-mic-listener.swift@@ -2,8 +2,9 @@* macOS Microphone Listener** Uses CoreAudio process objects when available to emit PID-scoped microphone- * transitions. Older systems fall back to aggregate device activity for the- * meeting-start prompt only.+ * transitions. Older systems report aggregate device activity without reliable+ * microphone attribution; PID monitoring is retried from the heartbeat because+ * a transient snapshot failure lands in the same mode.** Compile: swiftc -O macos-mic-listener.swift -o macos-mic-listener -framework CoreAudio -framework Foundation*/@@ -23,6 +24,8 @@ var activeInputPids: Set<pid_t> = []var processListListenerRegistered = falsevar inputDevices: [AudioDeviceID] = []var previouslyAggregateActive = false+var aggregateHeartbeats = 0+let processRetryHeartbeats = 6var signalSources: [DispatchSourceSignal] = []func stringProperty(@@ -219,21 +222,27 @@ func removeProcessMonitoring() {// list yields no readable object at all — a systemic failure where reported// state could no longer be trusted.func prepareProcessSnapshot(- _ processObjects: [AudioObjectID]+ _ processObjects: [AudioObjectID],+ readPid: (AudioObjectID) -> pid_t? = getProcessPid,+ readInputRunning: (AudioObjectID) -> Bool? = isProcessRunningInput,+ readBundleID: (AudioObjectID) -> String? = {+ stringProperty($0, selector: kAudioProcessPropertyBundleID)+ }) -> (pids: [AudioObjectID: pid_t], active: Set<pid_t>)? {var pids: [AudioObjectID: pid_t] = [:]var active: Set<pid_t> = []for processObject in processObjects {guard- let processId = getProcessPid(processObject),- let isRunningInput = isProcessRunningInput(processObject)+ let processId = readPid(processObject),+ let isRunningInput = readInputRunning(processObject)else {continue}pids[processObject] = processId- if isRunningInput {+ // CoreSpeech also processes ordinary playback, so it is not evidence of a meeting.+ if isRunningInput && readBundleID(processObject) != "com.apple.CoreSpeech" {active.insert(processId)}}@@ -518,6 +527,20 @@ func startAggregateFallback() {emit(previouslyAggregateActive ? "MIC_ACTIVE" : "MIC_INACTIVE")}+func announceProcessMonitoring() {+ emit("CAPABILITY PID")+ for processId in activeInputPids.sorted() {+ emit("MIC_START \(processId)")+ }+}++func recoverProcessMonitoring(start: () -> Bool = startProcessMonitoring) {+ guard listenerMode == .aggregate, start() else { return }+ removeAggregateMonitoring()+ listenerMode = .process+ announceProcessMonitoring()+}+func removeAllListeners() {switch listenerMode {case .process:@@ -542,6 +565,55 @@ func setupSignalHandlers() {}}+#if MIC_LISTENER_STATE_TEST+struct ProcessFixture: Decodable {+ let objectID: AudioObjectID+ let pid: pid_t?+ let inputRunning: Bool?+ let bundleID: String?+}++struct RecoveryFixture: Decodable {+ let startSucceeds: Bool+ let activePids: [pid_t]+}++do {+ if CommandLine.arguments[1] == "--recover-from-aggregate" {+ let fixture = try JSONDecoder().decode(+ RecoveryFixture.self,+ from: Data(CommandLine.arguments[2].utf8)+ )+ listenerMode = .aggregate+ recoverProcessMonitoring(start: {+ activeInputPids = Set(fixture.activePids)+ return fixture.startSucceeds+ })+ emit(#"{"mode":"\#(listenerMode == .process ? "process" : "aggregate")"}"#)+ } else {+ let fixtures = try JSONDecoder().decode(+ [ProcessFixture].self,+ from: Data(CommandLine.arguments[1].utf8)+ )+ let processes = Dictionary(uniqueKeysWithValues: fixtures.map { ($0.objectID, $0) })+ if let snapshot = prepareProcessSnapshot(+ fixtures.map(\.objectID),+ readPid: { processes[$0]?.pid },+ readInputRunning: { processes[$0]?.inputRunning },+ readBundleID: { processes[$0]?.bundleID }+ ) {+ let result = ["pids": snapshot.pids.values.sorted(), "active": snapshot.active.sorted()]+ let data = try JSONSerialization.data(withJSONObject: result)+ emit(String(decoding: data, as: UTF8.self))+ } else {+ emit("null")+ }+ }+} catch {+ emitError("Native snapshot test failed: \(error)")+ exit(1)+}+#elseif CommandLine.arguments.contains("--print-default-input") {exit(printDefaultInputDevice())}@@ -549,10 +621,7 @@ if CommandLine.arguments.contains("--print-default-input") {setupSignalHandlers()if startProcessMonitoring() {listenerMode = .process- emit("CAPABILITY PID")- for processId in activeInputPids.sorted() {- emit("MIC_START \(processId)")- }+ announceProcessMonitoring()} else {startAggregateFallback()}@@ -565,6 +634,10 @@ heartbeatTimer.setEventHandler {reconcileProcessMonitoring()case .aggregate:checkAndEmitAggregateState()+ aggregateHeartbeats += 1+ if aggregateHeartbeats % processRetryHeartbeats == 0 {+ recoverProcessMonitoring()+ }case .none:break}@@ -572,3 +645,4 @@ heartbeatTimer.setEventHandler {heartbeatTimer.resume()CFRunLoopRun()+#endifdiff --git a/src/helpers/audioActivityDetector.js b/src/helpers/audioActivityDetector.jsindex 984c5cfcb..5eedafdb8 100644--- a/src/helpers/audioActivityDetector.js+++ b/src/helpers/audioActivityDetector.js@@ -15,15 +15,24 @@ const INACTIVE_RESET_MS = 60 * 1000;// PipeWire/PulseAudio emit 'change' subscribe events several times a second on// cork/volume churn, and every reconcile forks a pactl subprocess.const LINUX_RECONCILE_MIN_SPACING_MS = 1000;+// macOS has no polling fallback, so a lost listener is respawned instead.+const LISTENER_RESPAWN_BASE_MS = 5 * 1000;+const LISTENER_RESPAWN_MAX_MS = 60 * 1000;const EXEC_OPTS = { timeout: 5000, encoding: "utf8" };class AudioActivityDetector extends EventEmitter {// `getExcludedProcessIds` lists every pid whose mic use is OpenWhispr's own:// the Electron process tree by default, plus any live capture helpers when- // main.js composes them in (see electronProcessIds.js).- constructor(getExcludedProcessIds = () => [...getOwnProcessPids()]) {+ // main.js composes them in (see electronProcessIds.js). `isMeetingAppRunning`+ // corroborates macOS device activity that cannot be attributed to a process;+ // without it such activity never prompts.+ constructor(+ getExcludedProcessIds = () => [...getOwnProcessPids()],+ isMeetingAppRunning = () => false+ ) {super();this._getExcludedProcessIds = getExcludedProcessIds;+ this._isMeetingAppRunning = isMeetingAppRunning;this.checkInterval = null;this.consecutiveChecks = 0;this.audioActiveStart = null;@@ -41,7 +50,10 @@ class AudioActivityDetector extends EventEmitter {this._startGeneration = 0;this._micWarmHold = false;this._lastKnownMicState = false;+ this._lastKnownMicAttributed = true;this._cooldownReevalTimer = null;+ this._respawnTimer = null;+ this._respawnAttempts = 0;this._linuxOwnershipRequest = 0;this._linuxReconcileQueued = false;this._linuxReconcileRunning = false;@@ -126,9 +138,16 @@ class AudioActivityDetector extends EventEmitter {debugLogger.debug("Mic warm-hold state changed", { active }, "meeting");}+ // Unattributed device activity is gated on a running meeting app, so an app+ // launching after the device edge is one more gate lifting.+ notifyMeetingAppsChanged() {+ if (!this._lastKnownMicAttributed) this._reevaluateAfterGate();+ }+async start() {if (this._running) return;this._running = true;+ this._respawnAttempts = 0;const generation = ++this._startGeneration;const started = await this._tryEventDriven(generation);@@ -144,11 +163,6 @@ class AudioActivityDetector extends EventEmitter {} else {this._eventDriven = false;this._startPolling();- debugLogger.info(- "Audio activity detector started (polling)",- { intervalMs: CHECK_INTERVAL_MS, threshold: SUSTAINED_THRESHOLD_CHECKS },- "meeting"- );}}@@ -156,6 +170,7 @@ class AudioActivityDetector extends EventEmitter {if (!this._running) return;this._running = false;this._killListenerProcess();+ this._clearRespawnTimer();this._clearSustainedTimer();this._clearResetTimer();this._resetListenerState();@@ -304,7 +319,11 @@ class AudioActivityDetector extends EventEmitter {}this._listenerProcess = child;- this._readLines(child.stdout, onLine);+ this._readLines(child.stdout, (line) => {+ // stdout can still drain after exit or after a replacement listener starts.+ if (this._listenerProcess !== child || this._isStale(generation)) return;+ onLine(line);+ });child.stderr.on("data", (data) => {debugLogger.debug(`${label} stderr`, { output: data.toString().trim() }, "meeting");});@@ -347,6 +366,7 @@ class AudioActivityDetector extends EventEmitter {if (this._running && this._eventDriven) {this._eventDriven = false;this._startPolling();+ if (process.platform === "darwin") this._scheduleListenerRespawn();}};@@ -364,7 +384,7 @@ class AudioActivityDetector extends EventEmitter {_tryEventDrivenDarwin(generation) {const binaryPath = resolveBundledBinary("macos-mic-listener", "meeting");if (!binaryPath) {- debugLogger.warn("macos-mic-listener binary not found, will use polling", {}, "meeting");+ debugLogger.warn("macos-mic-listener binary not found", {}, "meeting");return false;}@@ -380,26 +400,68 @@ class AudioActivityDetector extends EventEmitter {_parseDarwinListenerLine(line) {if (!this._running) return;- if (line === "CAPABILITY PID") {- this._setPidScopedCapability(true);- return;- }- if (line === "CAPABILITY AGGREGATE") {- this._setPidScopedCapability(false);- return;- }- if (line === "MIC_ACTIVE") {- this._onMicStateChanged(true);+ if (line === "CAPABILITY PID" || line === "CAPABILITY AGGREGATE") {+ const pidScoped = line === "CAPABILITY PID";+ debugLogger.info(+ "macOS microphone detection capability",+ { capability: pidScoped ? "PID" : "AGGREGATE" },+ "meeting"+ );+ // The lines that follow re-announce every live capture, so state derived+ // from the previous mode is stale.+ this._activeMicPids.clear();+ this._setPidScopedCapability(pidScoped);+ this._onMicStateChanged(false, pidScoped);return;}- if (line === "MIC_INACTIVE") {- this._onMicStateChanged(false);++ // Device-wide activity includes playback on combined input/output devices,+ // so it is recorded as unattributed and only prompts once a running meeting+ // app corroborates it (see _evaluateMicState).+ if (line === "MIC_ACTIVE" || line === "MIC_INACTIVE") {+ this._onMicStateChanged(line === "MIC_ACTIVE", false);return;}+ if (!this._pidScopedCapability) return;this._parsePidScopedListenerLine(line);}+ _scheduleListenerRespawn() {+ this._clearRespawnTimer();+ const delayMs = Math.min(+ LISTENER_RESPAWN_BASE_MS * 2 ** this._respawnAttempts,+ LISTENER_RESPAWN_MAX_MS+ );+ this._respawnAttempts++;+ debugLogger.info("Retrying the macOS microphone listener", { delayMs }, "meeting");+ this._respawnTimer = setTimeout(() => {+ this._respawnTimer = null;+ void this._respawnListener();+ }, delayMs);+ }++ async _respawnListener() {+ if (!this._running || this._listenerProcess) return;+ const generation = this._startGeneration;+ const started = await this._tryEventDriven(generation);+ if (this._isStale(generation)) return;++ if (started) {+ this._eventDriven = true;+ debugLogger.info("macOS microphone listener restored", {}, "meeting");+ } else {+ this._scheduleListenerRespawn();+ }+ }++ _clearRespawnTimer() {+ if (this._respawnTimer) {+ clearTimeout(this._respawnTimer);+ this._respawnTimer = null;+ }+ }+_tryEventDrivenWin32(generation) {const binaryPath = resolveBundledBinary("windows-mic-listener.exe", "meeting");if (!binaryPath) {@@ -670,9 +732,10 @@ class AudioActivityDetector extends EventEmitter {// The listeners are edge-triggered: they announce transitions, never steady// state. A gate may swallow the only edge a call will ever produce, so the// state is recorded unconditionally and re-evaluated when gates lift.- _onMicStateChanged(active) {+ _onMicStateChanged(active, attributed = true) {if (!this._running) return;this._lastKnownMicState = active;+ this._lastKnownMicAttributed = attributed;this._rearmPromptForSourceChange(active);this._evaluateMicState(active);}@@ -703,6 +766,10 @@ class AudioActivityDetector extends EventEmitter {}}+ _isUnattributedActivityCorroborated() {+ return this._lastKnownMicAttributed || this._isMeetingAppRunning();+ }+_evaluateMicState(active) {if (this._userRecording) {debugLogger.debug("Mic state changed but user recording, ignoring", { active }, "meeting");@@ -726,6 +793,10 @@ class AudioActivityDetector extends EventEmitter {}return;}+ if (active && !this._isUnattributedActivityCorroborated()) {+ debugLogger.debug("Unattributed mic activity without a meeting app, waiting", {}, "meeting");+ return;+ }debugLogger.debug("Mic state changed (event-driven)",@@ -746,16 +817,18 @@ class AudioActivityDetector extends EventEmitter {this._sustainedTimer = null;if (this._userRecording || this._micWarmHold || this.hasPrompted) return;if (this.lastDismissedAt && Date.now() - this.lastDismissedAt < COOLDOWN_MS) return;+ if (!this._isUnattributedActivityCorroborated()) return;this._markPrompted();const now = Date.now();const durationMs = now - this.audioActiveStart;+ const attributed = this._lastKnownMicAttributed;debugLogger.info("Sustained audio activity detected (event-driven)",- { durationMs },+ { durationMs, attributed },"meeting");- this.emit("sustained-audio-detected", { durationMs, detectedAt: now });+ this.emit("sustained-audio-detected", { durationMs, detectedAt: now, attributed });}, SUSTAINED_EVENT_DRIVEN_MS);}} else {@@ -770,8 +843,25 @@ class AudioActivityDetector extends EventEmitter {// ---------------------------------------------------------------------------_startPolling() {+ if (process.platform === "darwin") {+ this._clearSustainedTimer();+ this.audioActiveStart = null;+ this._lastKnownMicState = false;+ debugLogger.info(+ "macOS microphone listener unavailable; automatic audio prompts paused",+ {},+ "meeting"+ );+ return;+ }+this._check();this.checkInterval = setInterval(() => this._check(), CHECK_INTERVAL_MS);+ debugLogger.info(+ "Audio activity detector started (polling)",+ { intervalMs: CHECK_INTERVAL_MS, threshold: SUSTAINED_THRESHOLD_CHECKS },+ "meeting"+ );}async _check() {@@ -804,7 +894,7 @@ class AudioActivityDetector extends EventEmitter {{ consecutiveChecks: this.consecutiveChecks, durationMs },"meeting");- this.emit("sustained-audio-detected", { durationMs, detectedAt: now });+ this.emit("sustained-audio-detected", { durationMs, detectedAt: now, attributed: true });}} else {if (this.consecutiveChecks > 0) {@@ -825,8 +915,6 @@ class AudioActivityDetector extends EventEmitter {async _isMicActive() {switch (process.platform) {- case "darwin":- return this._checkDarwin();case "win32":return this._checkWin32();case "linux":@@ -836,18 +924,6 @@ class AudioActivityDetector extends EventEmitter {}}- async _checkDarwin() {- try {- const { stdout } = await execAsync(- "ioreg -l -w 0 | grep '\"IOAudioEngineState\" = 1'",- EXEC_OPTS- );- return stdout.trim().length > 0;- } catch {- return false;- }- }-async _checkWin32() {try {const processListCache = require("./processListCache");diff --git a/src/helpers/meetingDetectionEngine.js b/src/helpers/meetingDetectionEngine.jsindex 3447f686b..11fbc8895 100644--- a/src/helpers/meetingDetectionEngine.js+++ b/src/helpers/meetingDetectionEngine.js@@ -89,14 +89,16 @@ class MeetingDetectionEngine {}_bindListeners() {- // Process detection is context-only — track running apps but don't trigger notifications.- // This avoids false positives from apps like FaceTime running in the background.+ // Process detection is context-only — a running app never prompts by itself+ // (FaceTime idles in the background), but it corroborates device activity+ // the mic detector could not attribute to a process.this.meetingProcessDetector.on("meeting-process-detected", (data) => {debugLogger.info("Meeting app running (context only)",{ processKey: data.processKey, appName: data.appName },"meeting");+ this.audioActivityDetector.notifyMeetingAppsChanged();});this.meetingProcessDetector.on("meeting-process-ended", (data) => {diff --git a/test/helpers/audioActivityDetector.test.js b/test/helpers/audioActivityDetector.test.jsindex 805d74f97..9f40157f3 100644--- a/test/helpers/audioActivityDetector.test.js+++ b/test/helpers/audioActivityDetector.test.js@@ -20,13 +20,20 @@ function setPlatform(platform) {afterEach(() => setPlatform(originalPlatform));-function loadDetector(platform, spawn, exec) {+function loadDetector(platform, spawn, exec, logEntries) {delete require.cache[detectorModulePath];setPlatform(platform);Module._load = function loadWithMocks(request, parent, isMain) {if (request === "./debugLogger") {- return { info() {}, warn() {}, debug() {}, error() {} };+ return {+ info(message, data) {+ logEntries.push({ message, data });+ },+ warn() {},+ debug() {},+ error() {},+ };}if (request === "child_process") {return { ...childProcess, exec, spawn };@@ -71,13 +78,14 @@ function createFakeChild(spawnError) {// here. Both spellings feed the detector's excluded-pid provider.function createDetector(platform,- { excludedProcessIds, ownPids, execResponses = [], spawnError } = {}+ { excludedProcessIds, ownPids, execResponses = [], spawnError, isMeetingAppRunning } = {}) {const getExcludedProcessIds =excludedProcessIds ?? (ownPids ? () => [...ownPids] : () => [process.pid]);const children = [];const calls = [];const execCalls = [];+ const logEntries = [];const fakeExec = () => {};fakeExec[Symbol.for("nodejs.util.promisify.custom")] = async (command, options) => {execCalls.push({ command, options });@@ -98,12 +106,13 @@ function createDetector(children.push(child);return child;},- fakeExec+ fakeExec,+ logEntries);- const detector = new AudioActivityDetector(getExcludedProcessIds);+ const detector = new AudioActivityDetector(getExcludedProcessIds, isMeetingAppRunning);detector._isMicActive = async () => false;- return { detector, children, calls, execCalls };+ return { detector, children, calls, execCalls, logEntries };}const flush = () => new Promise((resolve) => setTimeout(resolve, 0));@@ -122,13 +131,18 @@ const createDeferred = () => {const PLATFORMS = ["darwin", "win32", "linux"];for (const platform of PLATFORMS) {- test(`${platform}: a listener that fails to launch falls back to polling`, async () => {+ test(`${platform}: a listener that fails to launch uses only a safe fallback`, async (t) => {const { detector } = createDetector(platform, { spawnError: "spawn ENOENT" });+ t.after(() => detector.stop());await detector.start();assert.equal(detector._eventDriven, false);- assert.notEqual(detector.checkInterval, null, "polling must take over");+ if (platform === "darwin") {+ assert.equal(detector.checkInterval, null, "device-wide polling cannot attribute mic use");+ } else {+ assert.notEqual(detector.checkInterval, null, "polling must take over");+ }detector.stop();});@@ -188,14 +202,14 @@ for (const platform of PLATFORMS) {});}-test("darwin: MIC_ACTIVE then MIC_INACTIVE drives the sustained timer", async () => {+test("darwin: attributed microphone transitions drive the sustained timer", async () => {const { detector, children } = createDetector("darwin");await detector.start();- children[0].stdout.emit("data", "MIC_ACTIVE\n");+ children[0].stdout.emit("data", "CAPABILITY PID\nMIC_START 900\n");assert.notEqual(detector._sustainedTimer, null);- children[0].stdout.emit("data", "MIC_INACTIVE\n");+ children[0].stdout.emit("data", "MIC_STOP 900\n");assert.equal(detector._sustainedTimer, null);detector.stop();});@@ -297,53 +311,299 @@ test("darwin: PID events exclude current OpenWhispr processes and continue durindetector.stop();});-test("darwin: aggregate fallback remains prompt-only and unreliable", async () => {+test("darwin: aggregate playback cannot prompt without a running meeting app, even after gates lift", async (t) => {+ t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 10_000 });const { detector, children } = createDetector("darwin");+ t.after(() => detector.stop());const externalStates = [];+ const detections = [];detector.on("external-mic-state-changed", (state) => externalStates.push(state));+ detector.on("sustained-audio-detected", (data) => detections.push(data));await detector.start();+ detector.setUserRecording(true);+ detector.dismiss();children[0].stdout.emit("data", "CAPABILITY AGGREGATE\nMIC_ACTIVE\n");+ detector.setUserRecording(false);+ t.mock.timers.tick(COOLDOWN_MS);+ t.mock.timers.tick(SUSTAINED_MS);assert.deepEqual(detector.getExternalMicState(), {reliable: false,externalMicActive: false,});assert.deepEqual(externalStates, []);- assert.notEqual(detector._sustainedTimer, null, "aggregate activity must still drive prompts");+ assert.deepEqual(detections, []);+ assert.equal(detector._sustainedTimer, null);detector.stop();});-test("darwin: losing PID capability emits an unreliable external-mic snapshot", async () => {+test("darwin: losing PID capability cancels pending prompts and discards stale ownership", async (t) => {+ t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 10_000 });const { detector, children } = createDetector("darwin");+ t.after(() => detector.stop());const externalStates = [];+ const detections = [];detector.on("external-mic-state-changed", (state) => externalStates.push(state));+ detector.on("sustained-audio-detected", (data) => detections.push(data));await detector.start();children[0].stdout.emit("data", "CAPABILITY PID\nMIC_START 900\nCAPABILITY AGGREGATE\n");+ children[0].stdout.emit("data", "MIC_ACTIVE\nMIC_START 901\n");+ t.mock.timers.tick(SUSTAINED_MS);assert.deepEqual(externalStates.at(-1), {reliable: false,externalMicActive: false,});+ assert.deepEqual(detections, []);+ assert.equal(detector._activeMicPids.size, 0);++ children[0].stdout.emit("data", "CAPABILITY PID\nMIC_START 902\n");+ t.mock.timers.tick(SUSTAINED_MS);+ assert.equal(detections.length, 1, "an attributed call must be detected after recovery");+ children[0].stdout.emit("data", "MIC_STOP 902\n");+ assert.deepEqual(detector.getExternalMicState(), { reliable: true, externalMicActive: false });detector.stop();});-test("darwin: listener exit emits reliability loss before polling fallback", async () => {+test("darwin: listener exit emits reliability loss and cancels pending audio prompts", async (t) => {+ t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 10_000 });const { detector, children } = createDetector("darwin");+ t.after(() => detector.stop());const externalStates = [];+ const detections = [];detector.on("external-mic-state-changed", (state) => externalStates.push(state));+ detector.on("sustained-audio-detected", (data) => detections.push(data));await detector.start();children[0].stdout.emit("data", "CAPABILITY PID\nMIC_START 900\n");children[0].emit("exit", 1);+ children[0].stdout.emit("data", "CAPABILITY PID\nMIC_START 901\n");+ t.mock.timers.tick(SUSTAINED_MS);assert.deepEqual(externalStates.at(-1), {reliable: false,externalMicActive: false,});- assert.notEqual(detector.checkInterval, null);+ assert.deepEqual(detections, []);+ assert.equal(detector.checkInterval, null);+ detector.stop();+});++test("darwin: output from a replaced listener cannot downgrade the current microphone owner", async (t) => {+ const { detector, children } = createDetector("darwin");+ t.after(() => detector.stop());+ await detector.start();+ detector.stop();+ await detector.start();+ children[1].stdout.emit("data", "CAPABILITY PID\nMIC_START 902\n");+ children[0].stdout.emit("data", "CAPABILITY AGGREGATE\nMIC_INACTIVE\n");+ assert.deepEqual(detector.getExternalMicState(), { reliable: true, externalMicActive: true });+ assert.deepEqual([...detector._activeMicPids], [902]);+});++test("darwin: legacy aggregate messages cannot start an audio prompt", async (t) => {+ t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 10_000 });+ const { detector, children } = createDetector("darwin");+ t.after(() => detector.stop());+ const detections = [];+ detector.on("sustained-audio-detected", (data) => detections.push(data));+ await detector.start();+ children[0].stdout.emit("data", "MIC_ACTIVE\nMIC_START 900\n");+ t.mock.timers.tick(SUSTAINED_MS);+ assert.deepEqual(detections, []);+ assert.equal(detector._activeMicPids.size, 0);+});++test("darwin: polling does not mistake an output audio engine for microphone capture", async () => {+ const { detector, execCalls } = createDetector("darwin", {+ execResponses: [{ stdout: '"IOAudioEngineState" = 1' }],+ });+ assert.equal(await Object.getPrototypeOf(detector)._isMicActive.call(detector), false);+ assert.deepEqual(execCalls, [], "there is no safe ioreg microphone-attribution fallback");+});++test("darwin: capability changes are logged at info level", async (t) => {+ const { detector, children, logEntries } = createDetector("darwin");+ t.after(() => detector.stop());+ await detector.start();+ children[0].stdout.emit("data", "CAPABILITY PID\nCAPABILITY AGGREGATE\n");+ assert.deepEqual(+ logEntries.filter(({ message }) => message === "macOS microphone detection capability"),+ [+ { message: "macOS microphone detection capability", data: { capability: "PID" } },+ { message: "macOS microphone detection capability", data: { capability: "AGGREGATE" } },+ ]+ );+});++test("darwin: aggregate activity prompts once a running meeting app corroborates it", async (t) => {+ t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 10_000 });+ const { detector, children } = createDetector("darwin", { isMeetingAppRunning: () => true });+ t.after(() => detector.stop());+ const detections = [];+ detector.on("sustained-audio-detected", (data) => detections.push(data));++ await detector.start();+ children[0].stdout.emit("data", "CAPABILITY AGGREGATE\nMIC_ACTIVE\n");+ t.mock.timers.tick(SUSTAINED_MS);++ assert.equal(detections.length, 1);+ assert.equal(detections[0].attributed, false);+ assert.deepEqual(detector.getExternalMicState(), { reliable: false, externalMicActive: false });++ children[0].stdout.emit("data", "MIC_INACTIVE\n");+ assert.equal(detector._sustainedTimer, null);+});++test("darwin: a meeting app launching during aggregate activity is re-evaluated", async (t) => {+ t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 10_000 });+ let meetingAppRunning = false;+ const { detector, children } = createDetector("darwin", {+ isMeetingAppRunning: () => meetingAppRunning,+ });+ t.after(() => detector.stop());+ const detections = [];+ detector.on("sustained-audio-detected", (data) => detections.push(data));++ await detector.start();+ children[0].stdout.emit("data", "CAPABILITY AGGREGATE\nMIC_ACTIVE\n");+ t.mock.timers.tick(SUSTAINED_MS);+ assert.deepEqual(detections, [], "device activity alone is not a meeting");++ meetingAppRunning = true;+ detector.notifyMeetingAppsChanged();+ t.mock.timers.tick(SUSTAINED_MS);+ assert.equal(detections.length, 1, "the running meeting app corroborates the live device");+ assert.equal(detections[0].attributed, false);+});++test("darwin: a meeting app quitting before the sustained window cancels the aggregate prompt", async (t) => {+ t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 10_000 });+ let meetingAppRunning = true;+ const { detector, children } = createDetector("darwin", {+ isMeetingAppRunning: () => meetingAppRunning,+ });+ t.after(() => detector.stop());+ const detections = [];+ detector.on("sustained-audio-detected", (data) => detections.push(data));++ await detector.start();+ children[0].stdout.emit("data", "CAPABILITY AGGREGATE\nMIC_ACTIVE\n");+ meetingAppRunning = false;+ t.mock.timers.tick(SUSTAINED_MS);++ assert.deepEqual(detections, []);+ assert.equal(detector.hasPrompted, false, "an uncorroborated edge must not consume the prompt");+});++test("darwin: attributed transitions prompt without a running meeting app", async (t) => {+ t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 10_000 });+ const { detector, children } = createDetector("darwin", { isMeetingAppRunning: () => false });+ t.after(() => detector.stop());+ const detections = [];+ detector.on("sustained-audio-detected", (data) => detections.push(data));++ await detector.start();+ children[0].stdout.emit("data", "CAPABILITY PID\nMIC_START 900\n");+ t.mock.timers.tick(SUSTAINED_MS);++ assert.equal(detections.length, 1);+ assert.equal(detections[0].attributed, true);+});++test("darwin: regaining PID capability discards unattributed aggregate state", async (t) => {+ t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 10_000 });+ let meetingAppRunning = false;+ const { detector, children } = createDetector("darwin", {+ isMeetingAppRunning: () => meetingAppRunning,+ });+ t.after(() => detector.stop());+ const detections = [];+ detector.on("sustained-audio-detected", (data) => detections.push(data));++ await detector.start();+ children[0].stdout.emit("data", "CAPABILITY AGGREGATE\nMIC_ACTIVE\nCAPABILITY PID\n");+ meetingAppRunning = true;+ detector.notifyMeetingAppsChanged();+ t.mock.timers.tick(SUSTAINED_MS);++ assert.deepEqual(detections, [], "the PID transitions that follow are the only evidence");+ assert.equal(detector._lastKnownMicState, false);+});++test("darwin: a crashed listener is respawned with backoff and attributed detection resumes", async (t) => {+ t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 10_000 });+ const { detector, children } = createDetector("darwin");+ t.after(() => detector.stop());+ const detections = [];+ detector.on("sustained-audio-detected", (data) => detections.push(data));++ await detector.start();+ children[0].stdout.emit("data", "CAPABILITY PID\nMIC_START 900\n");+ children[0].emit("exit", 1);+ assert.equal(children.length, 1, "the respawn must wait for the backoff delay");++ t.mock.timers.tick(RESPAWN_MS);+ await flushImmediate();+ assert.equal(children.length, 2);+ assert.equal(detector._eventDriven, true);++ children[1].stdout.emit("data", "CAPABILITY PID\nMIC_START 900\n");+ t.mock.timers.tick(SUSTAINED_MS);+ assert.equal(detections.length, 1);+ assert.deepEqual(detector.getExternalMicState(), { reliable: true, externalMicActive: true });+});++test("darwin: repeated listener crashes back off exponentially", async (t) => {+ t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 10_000 });+ const { detector, children } = createDetector("darwin");+ t.after(() => detector.stop());++ await detector.start();+ children[0].emit("exit", 1);+ t.mock.timers.tick(RESPAWN_MS);+ await flushImmediate();+ assert.equal(children.length, 2);++ children[1].emit("exit", 1);+ t.mock.timers.tick(RESPAWN_MS);+ await flushImmediate();+ assert.equal(children.length, 2, "the second retry must wait twice as long");+ t.mock.timers.tick(RESPAWN_MS);+ await flushImmediate();+ assert.equal(children.length, 3);+});++test("darwin: stop() cancels a pending listener respawn", async (t) => {+ t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 10_000 });+ const { detector, children } = createDetector("darwin");+ t.after(() => detector.stop());++ await detector.start();+ children[0].emit("exit", 1);detector.stop();+ // The stale timer would fire inside the restart's spawn window, when no+ // listener is registered yet, and launch a duplicate.+ const restarted = detector.start();+ t.mock.timers.tick(RESPAWN_MS * 64);+ await restarted;+ await flushImmediate();++ assert.equal(children.length, 2, "only the restart may spawn a listener");+});++test("darwin: a listener that fails to launch is not respawned", async (t) => {+ t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 10_000 });+ const { detector, children } = createDetector("darwin", { spawnError: "spawn ENOENT" });+ t.after(() => detector.stop());++ await detector.start();+ t.mock.timers.tick(RESPAWN_MS * 64);+ await flushImmediate();++ assert.equal(children.length, 1);});test("darwin: exclusion-provider failure emits reliability loss", async () => {@@ -708,6 +968,136 @@ test("linux: a stale startup reconciliation cannot restore reliability after lisdetector.stop();});+test("darwin: native snapshots exclude background speech while preserving meeting capture", async (t) => {+ if (originalPlatform !== "darwin") {+ t.skip("the native microphone listener requires macOS");+ return;+ }++ const compiler = childProcess.spawnSync("swiftc", ["--version"], { encoding: "utf8" });+ if (compiler.error?.code === "ENOENT" || compiler.status !== 0) {+ t.skip("no Swift compiler is available for the native-state test");+ return;+ }++ const temporaryDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-mac-mic-listener-"));+ const executablePath = path.join(temporaryDirectory, "mic-listener-state-test");+ t.after(() => fs.rmSync(temporaryDirectory, { force: true, recursive: true }));++ const compileResult = childProcess.spawnSync(+ "swiftc",+ [+ "-D",+ "MIC_LISTENER_STATE_TEST",+ path.resolve(__dirname, "../../resources/macos-mic-listener.swift"),+ "-module-cache-path",+ path.join(temporaryDirectory, "module-cache"),+ "-framework",+ "CoreAudio",+ "-framework",+ "Foundation",+ "-o",+ executablePath,+ ],+ { encoding: "utf8", timeout: 120_000 }+ );+ assert.equal(compileResult.status, 0, compileResult.error?.message || compileResult.stderr);++ const coreSpeech = {+ objectID: 1,+ pid: 101,+ inputRunning: true,+ bundleID: "com.apple.CoreSpeech",+ };+ const browser = { objectID: 2, pid: 102, inputRunning: true, bundleID: "com.google.Chrome" };+ const unknown = { objectID: 3, pid: 103, inputRunning: true, bundleID: null };+ const scenarios = [+ {+ name: "playback alone keeps PID monitoring available without active meeting capture",+ processes: [coreSpeech],+ expected: { pids: [101], active: [] },+ },+ {+ name: "browser calls and unknown processes survive concurrent background speech",+ processes: [coreSpeech, browser, unknown],+ expected: { pids: [101, 102, 103], active: [102, 103] },+ },+ {+ name: "native meeting apps survive concurrent background speech",+ processes: [coreSpeech, { ...browser, bundleID: "us.zoom.xos" }],+ expected: { pids: [101, 102], active: [102] },+ },+ {+ name: "other Apple apps remain eligible",+ processes: [{ ...browser, bundleID: "com.apple.Safari" }],+ expected: { pids: [102], active: [102] },+ },+ {+ name: "an inactive browser is not meeting capture",+ processes: [{ ...browser, inputRunning: false }],+ expected: { pids: [102], active: [] },+ },+ {+ name: "vanished process objects do not hide a live browser call",+ processes: [{ ...coreSpeech, pid: null }, browser, { ...unknown, inputRunning: null }],+ expected: { pids: [102], active: [102] },+ },+ {+ name: "no processes is a valid idle snapshot",+ processes: [],+ expected: { pids: [], active: [] },+ },+ {+ name: "no readable process objects still signals systemic failure",+ processes: [+ { ...coreSpeech, pid: null },+ { ...browser, inputRunning: null },+ ],+ expected: null,+ },+ ];++ for (const { name, processes, expected } of scenarios) {+ await t.test(name, () => {+ const result = childProcess.spawnSync(executablePath, [JSON.stringify(processes)], {+ encoding: "utf8",+ timeout: 5000,+ });+ assert.equal(result.status, 0, result.error?.message || result.stderr);+ assert.deepEqual(JSON.parse(result.stdout), expected);+ });+ }++ // Aggregate mode is entered on transient snapshot failures too, so the+ // heartbeat retries PID monitoring; the JS side already accepts a later+ // CAPABILITY PID.+ const recoveryScenarios = [+ {+ name: "a successful retry re-announces PID capability and the live captures",+ fixture: { startSucceeds: true, activePids: [102, 101] },+ expected: { lines: ["CAPABILITY PID", "MIC_START 101", "MIC_START 102"], mode: "process" },+ },+ {+ name: "a failed retry stays in aggregate mode without emitting anything",+ fixture: { startSucceeds: false, activePids: [] },+ expected: { lines: [], mode: "aggregate" },+ },+ ];+ for (const { name, fixture, expected } of recoveryScenarios) {+ await t.test(name, () => {+ const result = childProcess.spawnSync(+ executablePath,+ ["--recover-from-aggregate", JSON.stringify(fixture)],+ { encoding: "utf8", timeout: 5000 }+ );+ assert.equal(result.status, 0, result.error?.message || result.stderr);+ const lines = result.stdout.trim().split("\n");+ const summary = JSON.parse(lines.pop());+ assert.deepEqual({ lines, mode: summary.mode }, expected);+ });+ }+});+test("win32: portable native state seam handles reference counts and failures", (t) => {const temporaryDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-mic-listener-"));const executablePath = path.join(temporaryDirectory, "mic-listener-state-test");@@ -757,6 +1147,8 @@ test("win32: portable native state seam handles reference counts and failures",// Mirrors SUSTAINED_EVENT_DRIVEN_MS and COOLDOWN_MS in audioActivityDetector.js.const SUSTAINED_MS = 2 * 1000;const COOLDOWN_MS = 5 * 60 * 1000;+// Mirrors LISTENER_RESPAWN_BASE_MS in audioActivityDetector.js.+const RESPAWN_MS = 5 * 1000;test("darwin: a mic edge swallowed by the recording gate is re-evaluated when recording stops", async (t) => {t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 10_000 });@@ -766,7 +1158,7 @@ test("darwin: a mic edge swallowed by the recording gate is re-evaluated when reawait detector.start();detector.setUserRecording(true);- children[0].stdout.emit("data", "MIC_ACTIVE\n");+ children[0].stdout.emit("data", "CAPABILITY PID\nMIC_START 900\n");assert.equal(detector._sustainedTimer, null, "a gated edge must not arm the sustained timer");detector.setUserRecording(false);@@ -784,7 +1176,7 @@ test("darwin: a mic edge swallowed by the dismissal cooldown is re-evaluated wheawait detector.start();detector.dismiss();- children[0].stdout.emit("data", "MIC_ACTIVE\n");+ children[0].stdout.emit("data", "CAPABILITY PID\nMIC_START 900\n");assert.equal(detector._sustainedTimer, null, "the cooldown must still swallow the prompt");// Split ticks: mocked timers do not cascade timers armed inside a callback.@@ -802,7 +1194,7 @@ test("darwin: a dismissed call that keeps running re-prompts after the cooldown"detector.on("sustained-audio-detected", (data) => emitted.push(data));await detector.start();- children[0].stdout.emit("data", "MIC_ACTIVE\n");+ children[0].stdout.emit("data", "CAPABILITY PID\nMIC_START 900\n");t.mock.timers.tick(SUSTAINED_MS);assert.equal(emitted.length, 1);@@ -822,8 +1214,8 @@ test("darwin: a mic that went quiet while recording does not re-prompt when recoawait detector.start();detector.setUserRecording(true);- children[0].stdout.emit("data", "MIC_ACTIVE\n");- children[0].stdout.emit("data", "MIC_INACTIVE\n");+ children[0].stdout.emit("data", "CAPABILITY PID\nMIC_START 900\n");+ children[0].stdout.emit("data", "MIC_STOP 900\n");detector.setUserRecording(false);t.mock.timers.tick(SUSTAINED_MS * 2);@@ -839,7 +1231,7 @@ test("darwin: a call that outlives the mic warm-hold is detected when the hold rawait detector.start();detector.setMicWarmHold(true);- children[0].stdout.emit("data", "MIC_ACTIVE\n");+ children[0].stdout.emit("data", "CAPABILITY PID\nMIC_START 900\n");assert.equal(detector._sustainedTimer,null,@@ -861,9 +1253,9 @@ test("darwin: a warm-hold that releases cleanly does not produce a stale prompt"await detector.start();detector.setMicWarmHold(true);- children[0].stdout.emit("data", "MIC_ACTIVE\n");+ children[0].stdout.emit("data", "CAPABILITY PID\nMIC_START 900\n");detector.setMicWarmHold(false);- children[0].stdout.emit("data", "MIC_INACTIVE\n");+ children[0].stdout.emit("data", "MIC_STOP 900\n");t.mock.timers.tick(SUSTAINED_MS * 2);assert.equal(emitted.length, 0, "the release edge must cancel the pending re-evaluation");diff --git a/test/helpers/meetingDetectionEngine.test.js b/test/helpers/meetingDetectionEngine.test.jsindex 36630e59d..438ede6a1 100644--- a/test/helpers/meetingDetectionEngine.test.js+++ b/test/helpers/meetingDetectionEngine.test.js@@ -49,6 +49,8 @@ function createEngine() {audioDetector.resetPrompt = () => {};audioDetector.setUserRecording = () => {};audioDetector.setMicWarmHold = () => {};+ audioDetector.meetingAppNotifications = 0;+ audioDetector.notifyMeetingAppsChanged = () => audioDetector.meetingAppNotifications++;audioDetector.start = () => {};audioDetector.stop = () => {};@@ -68,7 +70,7 @@ function createEngine() {{});- return { engine, audioDetector, shown };+ return { engine, audioDetector, processDetector, shown };}test("an unanswered audio prompt expires without cooling down the mic detector", () => {@@ -101,3 +103,16 @@ test("a detection card closed without a response allows the next prompt", () =>assert.equal(shown.length, 2);});++test("a meeting app appearing asks the mic detector to re-evaluate unattributed activity", () => {+ const { audioDetector, processDetector, shown } = createEngine();++ processDetector.emit("meeting-process-detected", {+ processKey: "zoom",+ appName: "Zoom",+ detectedAt: 0,+ });++ assert.equal(audioDetector.meetingAppNotifications, 1);+ assert.equal(shown.length, 0, "a running meeting app alone stays context-only");+});