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
feat: replace polling-based meeting detection with event-driven OS APIs
Gabriel Steinb97d0600edf3
diff --git a/package-lock.json b/package-lock.jsonindex bed6de2fa..fc6940a2e 100644--- a/package-lock.json+++ b/package-lock.json@@ -31,6 +31,7 @@"i18next": "^25.8.4","lucide-react": "^0.518.0","object-assign": "^4.1.1",+ "ps-list": "^9.0.0","react": "^19.1.0","react-dom": "^19.1.0","react-i18next": "^15.7.4",@@ -2487,22 +2488,6 @@}}},- "node_modules/@neondatabase/auth-ui/node_modules/better-sqlite3": {- "version": "12.6.2",- "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-12.6.2.tgz",- "integrity": "sha512-8VYKM3MjCa9WcaSAI3hzwhmyHVlH8tiGFwf0RlTsZPWJ1I5MkzjiudCo4KC4DxOaL/53A5B1sI/IbldNFDbsKA==",- "hasInstallScript": true,- "license": "MIT",- "optional": true,- "peer": true,- "dependencies": {- "bindings": "^1.5.0",- "prebuild-install": "^7.1.1"- },- "engines": {- "node": "20.x || 22.x || 23.x || 24.x || 25.x"- }- },"node_modules/@neondatabase/auth-ui/node_modules/lucide-react": {"version": "0.555.0","resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.555.0.tgz",@@ -2512,54 +2497,6 @@"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"}},- "node_modules/@neondatabase/auth-ui/node_modules/pg": {- "version": "8.20.0",- "resolved": "https://registry.npmjs.org/pg/-/pg-8.20.0.tgz",- "integrity": "sha512-ldhMxz2r8fl/6QkXnBD3CR9/xg694oT6DZQ2s6c/RI28OjtSOpxnPrUCGOBJ46RCUxcWdx3p6kw/xnDHjKvaRA==",- "license": "MIT",- "optional": true,- "peer": true,- "dependencies": {- "pg-connection-string": "^2.12.0",- "pg-pool": "^3.13.0",- "pg-protocol": "^1.13.0",- "pg-types": "2.2.0",- "pgpass": "1.0.5"- },- "engines": {- "node": ">= 16.0.0"- },- "optionalDependencies": {- "pg-cloudflare": "^1.3.0"- },- "peerDependencies": {- "pg-native": ">=3.0.1"- },- "peerDependenciesMeta": {- "pg-native": {- "optional": true- }- }- },- "node_modules/@neondatabase/auth-ui/node_modules/pg-pool": {- "version": "3.13.0",- "resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.13.0.tgz",- "integrity": "sha512-gB+R+Xud1gLFuRD/QgOIgGOBE2KCQPaPwkzBBGC9oG69pHTkhQeIuejVIk3/cnDyX39av2AxomQiyPT13WKHQA==",- "license": "MIT",- "optional": true,- "peer": true,- "peerDependencies": {- "pg": ">=8.0"- }- },- "node_modules/@neondatabase/auth-ui/node_modules/pg-protocol": {- "version": "1.13.0",- "resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.13.0.tgz",- "integrity": "sha512-zzdvXfS6v89r6v7OcFCHfHlyG/wvry1ALxZo4LqgUoy7W9xhBDMaqOuMiF3qEV45VqsN6rdlcehHrfDtlCPc8w==",- "license": "MIT",- "optional": true,- "peer": true- },"node_modules/@neondatabase/auth-ui/node_modules/zod": {"version": "4.3.6","resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz",@@ -14132,6 +14069,18 @@"node": ">= 0.10"}},+ "node_modules/ps-list": {+ "version": "9.0.0",+ "resolved": "https://registry.npmjs.org/ps-list/-/ps-list-9.0.0.tgz",+ "integrity": "sha512-lxMEoIL/BQlk2KunFzxwUPwMvjFH7x7cmvzSLsSHpyMXl9FFfLUlfKrYwFc4wx/ZaIxxuXC4n8rjQ1CX/tkXVQ==",+ "license": "MIT",+ "engines": {+ "node": ">=20"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },"node_modules/psl": {"version": "1.15.0","resolved": "https://registry.npmjs.org/psl/-/psl-1.15.0.tgz",diff --git a/package.json b/package.jsonindex 912d71209..97ff5c339 100644--- a/package.json+++ b/package.json@@ -12,7 +12,8 @@"compile:winpaste": "node scripts/build-windows-fast-paste.js","compile:linux-paste": "node scripts/build-linux-fast-paste.js","compile:media-remote": "node scripts/build-media-remote.js",- "compile:native": "npm run compile:globe && npm run compile:fast-paste && npm run compile:winkeys && npm run compile:winpaste && npm run compile:linux-paste && npm run compile:text-monitor && npm run compile:media-remote",+ "compile:mic-listener": "node scripts/build-macos-mic-listener.js",+ "compile:native": "npm run compile:globe && npm run compile:fast-paste && npm run compile:winkeys && npm run compile:winpaste && npm run compile:linux-paste && npm run compile:text-monitor && npm run compile:media-remote && npm run compile:mic-listener","prestart": "npm run compile:native","start": "electron .","predev": "npm run compile:native",@@ -28,7 +29,7 @@"build:mac": "npm run build:renderer && electron-builder --mac","build:mac:arm64": "npm run build:renderer && electron-builder --mac --arm64","build:mac:x64": "npm run build:renderer && electron-builder --mac --x64",- "prebuild:win": "npm run compile:native && npm run download:whisper-cpp && npm run download:llama-server && npm run download:sherpa-onnx && npm run download:nircmd && npm run download:windows-fast-paste && npm run download:windows-key-listener",+ "prebuild:win": "npm run compile:native && npm run download:whisper-cpp && npm run download:llama-server && npm run download:sherpa-onnx && npm run download:nircmd && npm run download:windows-fast-paste && npm run download:windows-key-listener && npm run download:windows-mic-listener","build:win": "npm run build:renderer && electron-builder --win","prebuild:linux": "npm run compile:native && npm run download:whisper-cpp && npm run download:llama-server && npm run download:sherpa-onnx","build:linux": "npm run build:renderer && electron-builder --linux",@@ -50,6 +51,7 @@"download:nircmd": "node scripts/download-nircmd.js","download:windows-fast-paste": "node scripts/download-windows-fast-paste.js","download:windows-key-listener": "node scripts/download-windows-key-listener.js",+ "download:windows-mic-listener": "node scripts/download-windows-mic-listener.js","format:js": "eslint . --fix && cd src && eslint . --fix && prettier --write \"**/*.{js,jsx,ts,tsx,json,css,md}\"","format": "npm run format:js","format:check": "eslint . && cd src && eslint . && prettier --check \"**/*.{js,jsx,ts,tsx,json,css,md}\"",@@ -118,6 +120,7 @@"i18next": "^25.8.4","lucide-react": "^0.518.0","object-assign": "^4.1.1",+ "ps-list": "^9.0.0","react": "^19.1.0","react-dom": "^19.1.0","react-i18next": "^15.7.4",diff --git a/resources/macos-mic-listener.swift b/resources/macos-mic-listener.swiftnew file mode 100644index 000000000..de54e9bf4--- /dev/null+++ b/resources/macos-mic-listener.swift@@ -0,0 +1,291 @@+/**+ * macOS Microphone Listener+ *+ * Long-running process that monitors microphone usage via CoreAudio property listeners.+ * Outputs MIC_ACTIVE / MIC_INACTIVE state transitions to stdout.+ *+ * Replaces the fire-and-forget macos-mic-check.swift with an event-driven approach.+ *+ * Compile: swiftc -O macos-mic-listener.swift -o macos-mic-listener -framework CoreAudio -framework Foundation+ */++import CoreAudio+import Foundation++// MARK: - State++var previouslyActive = false+var inputDevices: [AudioDeviceID] = []++// MARK: - Output++func emit(_ message: String) {+ print(message)+ fflush(stdout)+}++func emitError(_ message: String) {+ FileHandle.standardError.write((message + "\n").data(using: .utf8)!)+}++// MARK: - Device Enumeration++func getInputDevices() -> [AudioDeviceID] {+ var address = AudioObjectPropertyAddress(+ mSelector: kAudioHardwarePropertyDevices,+ mScope: kAudioObjectPropertyScopeGlobal,+ mElement: kAudioObjectPropertyElementMain+ )++ var dataSize: UInt32 = 0+ var status = AudioObjectGetPropertyDataSize(+ AudioObjectID(kAudioObjectSystemObject),+ &address,+ 0,+ nil,+ &dataSize+ )+ guard status == noErr else {+ emitError("Failed to get device list size: \(status)")+ return []+ }++ let deviceCount = Int(dataSize) / MemoryLayout<AudioDeviceID>.size+ guard deviceCount > 0 else { return [] }++ var devices = [AudioDeviceID](repeating: 0, count: deviceCount)+ status = AudioObjectGetPropertyData(+ AudioObjectID(kAudioObjectSystemObject),+ &address,+ 0,+ nil,+ &dataSize,+ &devices+ )+ guard status == noErr else {+ emitError("Failed to get device list: \(status)")+ return []+ }++ // Filter to input devices by checking stream configuration for input scope+ return devices.filter { deviceID in+ var streamAddress = AudioObjectPropertyAddress(+ mSelector: kAudioDevicePropertyStreamConfiguration,+ mScope: kAudioObjectPropertyScopeInput,+ mElement: kAudioObjectPropertyElementMain+ )++ var streamSize: UInt32 = 0+ let sizeStatus = AudioObjectGetPropertyDataSize(+ deviceID,+ &streamAddress,+ 0,+ nil,+ &streamSize+ )+ guard sizeStatus == noErr, streamSize > 0 else { return false }++ let bufferListPtr = UnsafeMutablePointer<AudioBufferList>.allocate(capacity: 1)+ defer { bufferListPtr.deallocate() }++ let streamStatus = AudioObjectGetPropertyData(+ deviceID,+ &streamAddress,+ 0,+ nil,+ &streamSize,+ bufferListPtr+ )+ guard streamStatus == noErr else { return false }++ let bufferList = bufferListPtr.pointee+ // Device has input channels if any buffer has channels+ return bufferList.mNumberBuffers > 0 && bufferList.mBuffers.mNumberChannels > 0+ }+}++// MARK: - Running State Check++func isDeviceRunning(_ deviceID: AudioDeviceID) -> Bool {+ var address = AudioObjectPropertyAddress(+ mSelector: kAudioDevicePropertyDeviceIsRunningSomewhere,+ mScope: kAudioObjectPropertyScopeInput,+ mElement: kAudioObjectPropertyElementMain+ )+ var isRunning: UInt32 = 0+ var size = UInt32(MemoryLayout<UInt32>.size)++ let status = AudioObjectGetPropertyData(deviceID, &address, 0, nil, &size, &isRunning)+ guard status == noErr else { return false }++ return isRunning > 0+}++func isAnyInputRunning() -> Bool {+ for device in inputDevices {+ if isDeviceRunning(device) {+ return true+ }+ }+ return false+}++// MARK: - State Change Handler++func checkAndEmitState() {+ let active = isAnyInputRunning()+ if active != previouslyActive {+ previouslyActive = active+ emit(active ? "MIC_ACTIVE" : "MIC_INACTIVE")+ }+}++// MARK: - Property Listener Callbacks++/// Callback for device running state changes (kAudioDevicePropertyDeviceIsRunningSomewhere)+let propertyListener: AudioObjectPropertyListenerProc = {+ (objectID: AudioObjectID,+ numberAddresses: UInt32,+ addresses: UnsafePointer<AudioObjectPropertyAddress>,+ clientData: UnsafeMutableRawPointer?) -> OSStatus in++ checkAndEmitState()+ return noErr+}++/// Callback for device list changes (kAudioHardwarePropertyDevices) — hot-plug support+let deviceListListener: AudioObjectPropertyListenerProc = {+ (objectID: AudioObjectID,+ numberAddresses: UInt32,+ addresses: UnsafePointer<AudioObjectPropertyAddress>,+ clientData: UnsafeMutableRawPointer?) -> OSStatus in++ let newDevices = getInputDevices()+ let previousDeviceSet = Set(inputDevices)+ let newDeviceSet = Set(newDevices)++ // Register listeners on newly added input devices+ let addedDevices = newDeviceSet.subtracting(previousDeviceSet)+ for deviceID in addedDevices {+ registerRunningListener(on: deviceID)+ }++ // Remove listeners from removed devices (best effort, device may already be gone)+ let removedDevices = previousDeviceSet.subtracting(newDeviceSet)+ for deviceID in removedDevices {+ removeRunningListener(from: deviceID)+ }++ inputDevices = newDevices++ // Re-check state since a removed device may have been the active one+ checkAndEmitState()++ return noErr+}++// MARK: - Listener Registration++func registerRunningListener(on deviceID: AudioDeviceID) {+ var address = AudioObjectPropertyAddress(+ mSelector: kAudioDevicePropertyDeviceIsRunningSomewhere,+ mScope: kAudioObjectPropertyScopeInput,+ mElement: kAudioObjectPropertyElementMain+ )++ let status = AudioObjectAddPropertyListener(deviceID, &address, propertyListener, nil)+ if status != noErr {+ emitError("Warning: Failed to register listener on device \(deviceID): \(status)")+ }+}++func removeRunningListener(from deviceID: AudioDeviceID) {+ var address = AudioObjectPropertyAddress(+ mSelector: kAudioDevicePropertyDeviceIsRunningSomewhere,+ mScope: kAudioObjectPropertyScopeInput,+ mElement: kAudioObjectPropertyElementMain+ )++ // Best effort — device may already be disconnected+ AudioObjectRemovePropertyListener(deviceID, &address, propertyListener, nil)+}++func registerListeners() {+ // Discover all current input devices+ inputDevices = getInputDevices()++ // Register running-state listener on each input device+ for deviceID in inputDevices {+ registerRunningListener(on: deviceID)+ }++ // Register device list change listener on the system object for hot-plug support+ var deviceListAddress = AudioObjectPropertyAddress(+ mSelector: kAudioHardwarePropertyDevices,+ mScope: kAudioObjectPropertyScopeGlobal,+ mElement: kAudioObjectPropertyElementMain+ )++ let status = AudioObjectAddPropertyListener(+ AudioObjectID(kAudioObjectSystemObject),+ &deviceListAddress,+ deviceListListener,+ nil+ )+ if status != noErr {+ emitError("Failed to register device list listener: \(status)")+ }+}++func removeAllListeners() {+ // Remove running-state listeners from all tracked input devices+ for deviceID in inputDevices {+ removeRunningListener(from: deviceID)+ }++ // Remove device list listener+ var deviceListAddress = AudioObjectPropertyAddress(+ mSelector: kAudioHardwarePropertyDevices,+ mScope: kAudioObjectPropertyScopeGlobal,+ mElement: kAudioObjectPropertyElementMain+ )+ AudioObjectRemovePropertyListener(+ AudioObjectID(kAudioObjectSystemObject),+ &deviceListAddress,+ deviceListListener,+ nil+ )+}++// MARK: - Signal Handling++func setupSignalHandlers() {+ let signals: [Int32] = [SIGTERM, SIGINT]++ for sig in signals {+ signal(sig, SIG_IGN)+ let source = DispatchSource.makeSignalSource(signal: sig, queue: .main)+ source.setEventHandler {+ removeAllListeners()+ exit(0)+ }+ source.resume()+ // Keep the source alive by storing it (otherwise ARC deallocates it)+ signalSources.append(source)+ }+}++var signalSources: [DispatchSourceSignal] = []++// MARK: - Main++setupSignalHandlers()+registerListeners()++// Emit initial state+let active = isAnyInputRunning()+previouslyActive = active+emit(active ? "MIC_ACTIVE" : "MIC_INACTIVE")++// Keep the process alive+CFRunLoopRun()diff --git a/resources/windows-mic-listener.c b/resources/windows-mic-listener.cnew file mode 100644index 000000000..ce4d99110--- /dev/null+++ b/resources/windows-mic-listener.c@@ -0,0 +1,450 @@+/**+ * Windows Microphone Listener+ *+ * Monitors WASAPI audio capture sessions for microphone usage.+ * Outputs MIC_START/MIC_STOP events with PIDs to stdout.+ *+ * Uses IAudioSessionManager2 to enumerate and monitor capture sessions.+ * Supports --exclude-pid to ignore OpenWhispr's own microphone usage.+ *+ * Compile with: cl /O2 windows-mic-listener.c /Fe:windows-mic-listener.exe ole32.lib oleaut32.lib+ * Or with MinGW: gcc -O2 windows-mic-listener.c -o windows-mic-listener.exe -lole32 -loleaut32+ */++#define WIN32_LEAN_AND_MEAN+#define COBJMACROS+#define CINTERFACE++#include <windows.h>+#include <initguid.h>+#include <mmdeviceapi.h>+#include <audiopolicy.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++static DWORD g_excludePid = 0;+static volatile BOOL g_running = TRUE;++/* ========================================================================+ * Forward declarations for COM interface implementations+ * ======================================================================== */++typedef struct SessionEvents SessionEvents;+typedef struct SessionNotification SessionNotification;++/* ========================================================================+ * IAudioSessionEvents implementation — monitors state changes per session+ * ======================================================================== */++typedef struct SessionEvents {+ IAudioSessionEventsVtbl *lpVtbl;+ LONG refCount;+ DWORD pid;+} SessionEvents;++static HRESULT STDMETHODCALLTYPE SE_QueryInterface(+ IAudioSessionEvents *This, REFIID riid, void **ppvObject)+{+ if (IsEqualIID(riid, &IID_IUnknown) || IsEqualIID(riid, &IID_IAudioSessionEvents)) {+ *ppvObject = This;+ This->lpVtbl->AddRef(This);+ return S_OK;+ }+ *ppvObject = NULL;+ return E_NOINTERFACE;+}++static ULONG STDMETHODCALLTYPE SE_AddRef(IAudioSessionEvents *This)+{+ SessionEvents *self = (SessionEvents *)This;+ return InterlockedIncrement(&self->refCount);+}++static ULONG STDMETHODCALLTYPE SE_Release(IAudioSessionEvents *This)+{+ SessionEvents *self = (SessionEvents *)This;+ LONG count = InterlockedDecrement(&self->refCount);+ if (count == 0) {+ free(self);+ }+ return count;+}++static HRESULT STDMETHODCALLTYPE SE_OnDisplayNameChanged(+ IAudioSessionEvents *This, LPCWSTR NewDisplayName, LPCGUID EventContext)+{+ (void)This; (void)NewDisplayName; (void)EventContext;+ return S_OK;+}++static HRESULT STDMETHODCALLTYPE SE_OnIconPathChanged(+ IAudioSessionEvents *This, LPCWSTR NewIconPath, LPCGUID EventContext)+{+ (void)This; (void)NewIconPath; (void)EventContext;+ return S_OK;+}++static HRESULT STDMETHODCALLTYPE SE_OnSimpleVolumeChanged(+ IAudioSessionEvents *This, float NewVolume, BOOL NewMute, LPCGUID EventContext)+{+ (void)This; (void)NewVolume; (void)NewMute; (void)EventContext;+ return S_OK;+}++static HRESULT STDMETHODCALLTYPE SE_OnChannelVolumeChanged(+ IAudioSessionEvents *This, DWORD ChannelCount, float NewChannelVolumeArray[],+ DWORD ChangedChannel, LPCGUID EventContext)+{+ (void)This; (void)ChannelCount; (void)NewChannelVolumeArray;+ (void)ChangedChannel; (void)EventContext;+ return S_OK;+}++static HRESULT STDMETHODCALLTYPE SE_OnGroupingParamChanged(+ IAudioSessionEvents *This, LPCGUID NewGroupingParam, LPCGUID EventContext)+{+ (void)This; (void)NewGroupingParam; (void)EventContext;+ return S_OK;+}++static HRESULT STDMETHODCALLTYPE SE_OnStateChanged(+ IAudioSessionEvents *This, AudioSessionState NewState)+{+ SessionEvents *self = (SessionEvents *)This;+ DWORD pid = self->pid;++ if (g_excludePid != 0 && pid == g_excludePid) {+ return S_OK;+ }++ if (NewState == AudioSessionStateActive) {+ printf("MIC_START %lu\n", (unsigned long)pid);+ fflush(stdout);+ } else if (NewState == AudioSessionStateInactive || NewState == AudioSessionStateExpired) {+ printf("MIC_STOP %lu\n", (unsigned long)pid);+ fflush(stdout);+ }++ return S_OK;+}++static HRESULT STDMETHODCALLTYPE SE_OnSessionDisconnected(+ IAudioSessionEvents *This, AudioSessionDisconnectReason DisconnectReason)+{+ SessionEvents *self = (SessionEvents *)This;+ DWORD pid = self->pid;++ if (g_excludePid != 0 && pid == g_excludePid) {+ return S_OK;+ }++ printf("MIC_STOP %lu\n", (unsigned long)pid);+ fflush(stdout);++ return S_OK;+}++static IAudioSessionEventsVtbl g_sessionEventsVtbl = {+ SE_QueryInterface,+ SE_AddRef,+ SE_Release,+ SE_OnDisplayNameChanged,+ SE_OnIconPathChanged,+ SE_OnSimpleVolumeChanged,+ SE_OnChannelVolumeChanged,+ SE_OnGroupingParamChanged,+ SE_OnStateChanged,+ SE_OnSessionDisconnected+};++static SessionEvents *CreateSessionEvents(DWORD pid)+{+ SessionEvents *se = (SessionEvents *)calloc(1, sizeof(SessionEvents));+ if (!se) return NULL;+ se->lpVtbl = &g_sessionEventsVtbl;+ se->refCount = 1;+ se->pid = pid;+ return se;+}++/* ========================================================================+ * IAudioSessionNotification implementation — detects new capture sessions+ * ======================================================================== */++typedef struct SessionNotification {+ IAudioSessionNotificationVtbl *lpVtbl;+ LONG refCount;+} SessionNotification;++static HRESULT STDMETHODCALLTYPE SN_QueryInterface(+ IAudioSessionNotification *This, REFIID riid, void **ppvObject)+{+ if (IsEqualIID(riid, &IID_IUnknown) || IsEqualIID(riid, &IID_IAudioSessionNotification)) {+ *ppvObject = This;+ This->lpVtbl->AddRef(This);+ return S_OK;+ }+ *ppvObject = NULL;+ return E_NOINTERFACE;+}++static ULONG STDMETHODCALLTYPE SN_AddRef(IAudioSessionNotification *This)+{+ SessionNotification *self = (SessionNotification *)This;+ return InterlockedIncrement(&self->refCount);+}++static ULONG STDMETHODCALLTYPE SN_Release(IAudioSessionNotification *This)+{+ SessionNotification *self = (SessionNotification *)This;+ LONG count = InterlockedDecrement(&self->refCount);+ if (count == 0) {+ free(self);+ }+ return count;+}++static void RegisterSessionEventsOnControl(IAudioSessionControl *pSessionControl);++static HRESULT STDMETHODCALLTYPE SN_OnSessionCreated(+ IAudioSessionNotification *This, IAudioSessionControl *NewSession)+{+ (void)This;+ if (NewSession) {+ RegisterSessionEventsOnControl(NewSession);+ }+ return S_OK;+}++static IAudioSessionNotificationVtbl g_sessionNotificationVtbl = {+ SN_QueryInterface,+ SN_AddRef,+ SN_Release,+ SN_OnSessionCreated+};++static SessionNotification *CreateSessionNotification(void)+{+ SessionNotification *sn = (SessionNotification *)calloc(1, sizeof(SessionNotification));+ if (!sn) return NULL;+ sn->lpVtbl = &g_sessionNotificationVtbl;+ sn->refCount = 1;+ return sn;+}++/* ========================================================================+ * Helper: register IAudioSessionEvents on a session control+ * ======================================================================== */++static void RegisterSessionEventsOnControl(IAudioSessionControl *pSessionControl)+{+ IAudioSessionControl2 *pCtl2 = NULL;+ HRESULT hr;++ hr = pSessionControl->lpVtbl->QueryInterface(+ pSessionControl, &IID_IAudioSessionControl2, (void **)&pCtl2);+ if (FAILED(hr) || !pCtl2) {+ return;+ }++ DWORD pid = 0;+ pCtl2->lpVtbl->GetProcessId(pCtl2, &pid);++ SessionEvents *events = CreateSessionEvents(pid);+ if (events) {+ pSessionControl->lpVtbl->RegisterAudioSessionNotification(+ pSessionControl, (IAudioSessionEvents *)events);+ /* Don't release — the session holds a reference and we want the callback alive */+ }++ /* Also check current state and emit if already active */+ AudioSessionState state;+ hr = pSessionControl->lpVtbl->GetState(pSessionControl, &state);+ if (SUCCEEDED(hr) && state == AudioSessionStateActive) {+ if (g_excludePid == 0 || pid != g_excludePid) {+ printf("MIC_START %lu\n", (unsigned long)pid);+ fflush(stdout);+ }+ }++ pCtl2->lpVtbl->Release(pCtl2);+}++/* ========================================================================+ * Monitor capture sessions on a single device+ * ======================================================================== */++static void MonitorDevice(IMMDevice *pDevice)+{+ IAudioSessionManager2 *pSessionMgr = NULL;+ HRESULT hr;++ hr = pDevice->lpVtbl->Activate(+ pDevice,+ &IID_IAudioSessionManager2,+ CLSCTX_ALL,+ NULL,+ (void **)&pSessionMgr+ );+ if (FAILED(hr) || !pSessionMgr) {+ return;+ }++ /* Register notification for new sessions */+ SessionNotification *notification = CreateSessionNotification();+ if (notification) {+ pSessionMgr->lpVtbl->RegisterSessionNotification(+ pSessionMgr, (IAudioSessionNotification *)notification);+ }++ /* Enumerate existing sessions */+ IAudioSessionEnumerator *pEnum = NULL;+ hr = pSessionMgr->lpVtbl->GetSessionEnumerator(pSessionMgr, &pEnum);+ if (SUCCEEDED(hr) && pEnum) {+ int count = 0;+ pEnum->lpVtbl->GetCount(pEnum, &count);++ for (int i = 0; i < count; i++) {+ IAudioSessionControl *pCtl = NULL;+ hr = pEnum->lpVtbl->GetSession(pEnum, i, &pCtl);+ if (SUCCEEDED(hr) && pCtl) {+ RegisterSessionEventsOnControl(pCtl);+ /* Don't release pCtl — we need callbacks to stay alive */+ }+ }+ /* Don't release pEnum — keep references alive */+ }++ /* Don't release pSessionMgr — notifications require it to stay alive */+}++/* ========================================================================+ * Console handler for clean shutdown+ * ======================================================================== */++BOOL WINAPI ConsoleHandler(DWORD signal)+{+ if (signal == CTRL_C_EVENT || signal == CTRL_BREAK_EVENT || signal == CTRL_CLOSE_EVENT) {+ g_running = FALSE;+ PostThreadMessage(GetCurrentThreadId(), WM_QUIT, 0, 0);+ return TRUE;+ }+ return FALSE;+}++/* ========================================================================+ * Stdin monitoring thread — detect parent process death+ * ======================================================================== */++static DWORD WINAPI StdinMonitorThread(LPVOID param)+{+ DWORD mainThreadId = (DWORD)(DWORD_PTR)param;+ char buf[64];+ HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);++ while (g_running) {+ DWORD bytesRead = 0;+ BOOL ok = ReadFile(hStdin, buf, sizeof(buf), &bytesRead, NULL);+ if (!ok || bytesRead == 0) {+ /* stdin closed — parent process died */+ g_running = FALSE;+ PostThreadMessage(mainThreadId, WM_QUIT, 0, 0);+ break;+ }+ }+ return 0;+}++/* ========================================================================+ * Main+ * ======================================================================== */++int main(int argc, char *argv[])+{+ /* Parse arguments */+ for (int i = 1; i < argc; i++) {+ if (strcmp(argv[i], "--exclude-pid") == 0 && i + 1 < argc) {+ g_excludePid = (DWORD)atol(argv[i + 1]);+ i++;+ }+ }++ if (g_excludePid) {+ fprintf(stderr, "Excluding PID: %lu\n", (unsigned long)g_excludePid);+ }++ /* Initialize COM */+ HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);+ if (FAILED(hr)) {+ fprintf(stderr, "Error: CoInitializeEx failed (0x%08lx)\n", (unsigned long)hr);+ return 1;+ }++ /* Create device enumerator */+ IMMDeviceEnumerator *pEnumerator = NULL;+ hr = CoCreateInstance(+ &CLSID_MMDeviceEnumerator,+ NULL,+ CLSCTX_ALL,+ &IID_IMMDeviceEnumerator,+ (void **)&pEnumerator+ );+ if (FAILED(hr) || !pEnumerator) {+ fprintf(stderr, "Error: Failed to create device enumerator (0x%08lx)\n", (unsigned long)hr);+ CoUninitialize();+ return 1;+ }++ /* Enumerate active capture (microphone) devices */+ IMMDeviceCollection *pCollection = NULL;+ hr = pEnumerator->lpVtbl->EnumAudioEndpoints(+ pEnumerator, eCapture, DEVICE_STATE_ACTIVE, &pCollection);+ if (FAILED(hr) || !pCollection) {+ fprintf(stderr, "Error: Failed to enumerate capture devices (0x%08lx)\n", (unsigned long)hr);+ pEnumerator->lpVtbl->Release(pEnumerator);+ CoUninitialize();+ return 1;+ }++ UINT deviceCount = 0;+ pCollection->lpVtbl->GetCount(pCollection, &deviceCount);+ fprintf(stderr, "Found %u capture device(s)\n", deviceCount);++ for (UINT i = 0; i < deviceCount; i++) {+ IMMDevice *pDevice = NULL;+ hr = pCollection->lpVtbl->Item(pCollection, i, &pDevice);+ if (SUCCEEDED(hr) && pDevice) {+ MonitorDevice(pDevice);+ /* Don't release pDevice — session managers need it alive */+ }+ }++ /* Set up console handler for clean shutdown */+ SetConsoleCtrlHandler(ConsoleHandler, TRUE);++ /* Start stdin monitor thread to detect parent process death */+ DWORD mainThreadId = GetCurrentThreadId();+ HANDLE hThread = CreateThread(NULL, 0, StdinMonitorThread, (LPVOID)(DWORD_PTR)mainThreadId, 0, NULL);+ if (hThread) {+ CloseHandle(hThread);+ }++ /* Signal readiness */+ printf("READY\n");+ fflush(stdout);++ /* Message loop — keeps the process alive */+ MSG msg;+ while (g_running && GetMessage(&msg, NULL, 0, 0) > 0) {+ TranslateMessage(&msg);+ DispatchMessage(&msg);+ }++ /* Cleanup */+ pCollection->lpVtbl->Release(pCollection);+ pEnumerator->lpVtbl->Release(pEnumerator);+ CoUninitialize();++ return 0;+}diff --git a/scripts/build-macos-mic-listener.js b/scripts/build-macos-mic-listener.jsnew file mode 100644index 000000000..0571dd429--- /dev/null+++ b/scripts/build-macos-mic-listener.js@@ -0,0 +1,187 @@+#!/usr/bin/env node++const { spawnSync } = require("child_process");+const crypto = require("crypto");+const fs = require("fs");+const path = require("path");++const isMac = process.platform === "darwin";+if (!isMac) {+ process.exit(0);+}++// Support cross-compilation via --arch flag or TARGET_ARCH env var+const archIndex = process.argv.indexOf("--arch");+const targetArch =+ (archIndex !== -1 && process.argv[archIndex + 1]) || process.env.TARGET_ARCH || process.arch;++const ARCH_TO_TARGET = {+ arm64: "arm64-apple-macosx11.0",+ x64: "x86_64-apple-macosx10.15",+};+const swiftTarget = ARCH_TO_TARGET[targetArch];+if (!swiftTarget) {+ console.error(`[mic-listener] Unsupported architecture: ${targetArch}`);+ process.exit(1);+}++const projectRoot = path.resolve(__dirname, "..");+const swiftSource = path.join(projectRoot, "resources", "macos-mic-listener.swift");+const outputDir = path.join(projectRoot, "resources", "bin");+const outputBinary = path.join(outputDir, "macos-mic-listener");+const hashFile = path.join(outputDir, `.macos-mic-listener.${targetArch}.hash`);+const moduleCacheDir = path.join(outputDir, ".swift-module-cache");++// Mach-O CPU type constants for architecture verification+const ARCH_CPU_TYPE = {+ arm64: 0x0100000c, // CPU_TYPE_ARM64+ x64: 0x01000007, // CPU_TYPE_X86_64+};++function log(message) {+ console.log(`[mic-listener] ${message}`);+}++function ensureDir(dirPath) {+ if (!fs.existsSync(dirPath)) {+ fs.mkdirSync(dirPath, { recursive: true });+ }+}++function verifyBinaryArch(binaryPath, expectedArch) {+ try {+ const fd = fs.openSync(binaryPath, "r");+ const header = Buffer.alloc(8);+ fs.readSync(fd, header, 0, 8, 0);+ fs.closeSync(fd);++ const magic = header.readUInt32LE(0);+ if (magic !== 0xfeedfacf) {+ // Not a 64-bit Mach-O+ return false;+ }+ const cpuType = header.readInt32LE(4);+ const expectedCpu = ARCH_CPU_TYPE[expectedArch];+ return cpuType === expectedCpu;+ } catch {+ return false;+ }+}++if (!fs.existsSync(swiftSource)) {+ console.error(`[mic-listener] Swift source not found at ${swiftSource}`);+ process.exit(1);+}++ensureDir(outputDir);+ensureDir(moduleCacheDir);++let needsBuild = true;+if (fs.existsSync(outputBinary)) {+ // Verify existing binary matches the target architecture+ if (!verifyBinaryArch(outputBinary, targetArch)) {+ log(`Existing binary is wrong architecture (expected ${targetArch}), rebuild needed`);+ needsBuild = true;+ } else {+ try {+ const binaryStat = fs.statSync(outputBinary);+ const sourceStat = fs.statSync(swiftSource);+ if (binaryStat.mtimeMs >= sourceStat.mtimeMs) {+ needsBuild = false;+ }+ } catch {+ needsBuild = true;+ }+ }+}++// Secondary check: compare source hash+if (!needsBuild && fs.existsSync(outputBinary)) {+ try {+ const sourceContent = fs.readFileSync(swiftSource, "utf8");+ const currentHash = crypto.createHash("sha256").update(sourceContent).digest("hex");++ if (fs.existsSync(hashFile)) {+ const savedHash = fs.readFileSync(hashFile, "utf8").trim();+ if (savedHash !== currentHash) {+ log("Source hash changed, rebuild needed");+ needsBuild = true;+ }+ } else {+ // No hash file for this architecture — force rebuild to ensure correct arch+ log(`No hash file for ${targetArch}, rebuild needed`);+ needsBuild = true;+ }+ } catch (err) {+ log(`Hash check failed: ${err.message}, forcing rebuild`);+ needsBuild = true;+ }+}++if (!needsBuild) {+ process.exit(0);+}++function attemptCompile(command, args) {+ log(`Compiling with ${[command, ...args].join(" ")}`);+ return spawnSync(command, args, {+ stdio: "inherit",+ env: {+ ...process.env,+ SWIFT_MODULE_CACHE_PATH: moduleCacheDir,+ },+ });+}++const compileArgs = [+ swiftSource,+ "-O",+ "-target",+ swiftTarget,+ "-module-cache-path",+ moduleCacheDir,+ "-o",+ outputBinary,+ "-framework",+ "CoreAudio",+ "-framework",+ "Foundation",+];++let result = attemptCompile("xcrun", ["swiftc", ...compileArgs]);++if (result.status !== 0) {+ result = attemptCompile("swiftc", compileArgs);+}++if (result.status !== 0) {+ console.error("[mic-listener] Failed to compile macOS mic listener binary.");+ process.exit(result.status ?? 1);+}++try {+ fs.chmodSync(outputBinary, 0o755);+} catch (error) {+ console.warn(`[mic-listener] Unable to set executable permissions: ${error.message}`);+}++// Verify the compiled binary matches the target architecture+if (!verifyBinaryArch(outputBinary, targetArch)) {+ console.error(+ `[mic-listener] FATAL: Compiled binary architecture does not match target (${targetArch}). ` ++ `This can happen when cross-compiling without setting TARGET_ARCH env var.`+ );+ process.exit(1);+}++// Save source hash after successful build+try {+ const sourceContent = fs.readFileSync(swiftSource, "utf8");+ const hash = crypto.createHash("sha256").update(sourceContent).digest("hex");+ fs.writeFileSync(hashFile, hash);+} catch (err) {+ // Non-critical, just log+ log(`Warning: Could not save source hash: ${err.message}`);+}++log(`Successfully built macOS mic listener binary (${targetArch}).`);diff --git a/scripts/download-windows-mic-listener.js b/scripts/download-windows-mic-listener.jsnew file mode 100644index 000000000..7ef874bf0--- /dev/null+++ b/scripts/download-windows-mic-listener.js@@ -0,0 +1,136 @@+#!/usr/bin/env node+/**+ * Downloads prebuilt Windows mic listener binary from GitHub releases.+ * Used for microphone activity detection on Windows.+ *+ * Usage:+ * node scripts/download-windows-mic-listener.js [--force]+ *+ * Options:+ * --force Re-download even if binary already exists+ */++const fs = require("fs");+const path = require("path");+const {+ downloadFile,+ extractZip,+ fetchLatestRelease,+ setExecutable,+} = require("./lib/download-utils");++const REPO = "OpenWhispr/openwhispr";+const TAG_PREFIX = "windows-mic-listener-v";+const ZIP_NAME = "windows-mic-listener-win32-x64.zip";+const BINARY_NAME = "windows-mic-listener.exe";++// Version can be pinned via environment variable for reproducible builds+const VERSION_OVERRIDE = process.env.WINDOWS_MIC_LISTENER_VERSION || null;++const BIN_DIR = path.join(__dirname, "..", "resources", "bin");++async function main() {+ // Only needed on Windows+ if (process.platform !== "win32") {+ console.log("[windows-mic-listener] Skipping download (not Windows)");+ return;+ }++ const forceDownload = process.argv.includes("--force");+ const outputPath = path.join(BIN_DIR, BINARY_NAME);++ // Check if already exists+ if (fs.existsSync(outputPath) && !forceDownload) {+ console.log("[windows-mic-listener] Already exists (use --force to re-download)");+ console.log(` ${outputPath}`);+ return;+ }++ // Fetch release (pinned version or latest)+ if (VERSION_OVERRIDE) {+ console.log(`\n[windows-mic-listener] Using pinned version: ${VERSION_OVERRIDE}`);+ } else {+ console.log("\n[windows-mic-listener] Fetching latest release...");+ }+ const tagToFind = VERSION_OVERRIDE || TAG_PREFIX;+ const release = await fetchLatestRelease(REPO, { tagPrefix: tagToFind });++ if (!release) {+ console.error("[windows-mic-listener] Could not find a release matching prefix:", TAG_PREFIX);+ console.log(+ "[windows-mic-listener] Mic detection will use fallback mode (polling)"+ );+ return;+ }++ // Find the zip asset+ const zipAsset = release.assets.find((a) => a.name === ZIP_NAME);+ if (!zipAsset) {+ console.error(`[windows-mic-listener] Release ${release.tag} does not contain ${ZIP_NAME}`);+ console.log(+ "[windows-mic-listener] Available assets:",+ release.assets.map((a) => a.name).join(", ")+ );+ return;+ }++ console.log(`\nDownloading Windows mic listener (${release.tag})...\n`);++ // Ensure bin directory exists+ fs.mkdirSync(BIN_DIR, { recursive: true });++ const zipPath = path.join(BIN_DIR, ZIP_NAME);+ console.log(` Downloading from: ${zipAsset.url}`);++ try {+ await downloadFile(zipAsset.url, zipPath);++ // Extract zip+ const extractDir = path.join(BIN_DIR, "temp-windows-mic-listener");+ fs.mkdirSync(extractDir, { recursive: true });++ console.log(" Extracting...");+ await extractZip(zipPath, extractDir);++ // Find and copy the binary+ const binaryPath = path.join(extractDir, BINARY_NAME);+ if (fs.existsSync(binaryPath)) {+ fs.copyFileSync(binaryPath, outputPath);+ setExecutable(outputPath);+ console.log(` Extracted to: ${BINARY_NAME}`);+ } else {+ throw new Error(`Binary not found in archive: ${BINARY_NAME}`);+ }++ // Cleanup+ fs.rmSync(extractDir, { recursive: true, force: true });+ if (fs.existsSync(zipPath)) {+ fs.unlinkSync(zipPath);+ }++ const stats = fs.statSync(outputPath);+ console.log(+ `\n[windows-mic-listener] Successfully downloaded ${release.tag} (${Math.round(stats.size / 1024)}KB)`+ );+ } catch (error) {+ console.error(`\n[windows-mic-listener] Download failed: ${error.message}`);++ // Cleanup on failure+ if (fs.existsSync(zipPath)) {+ fs.unlinkSync(zipPath);+ }++ // Don't fail the build — mic detection can fall back to polling+ console.log(+ "[windows-mic-listener] Mic detection will use fallback mode (polling)"+ );+ console.log(+ "[windows-mic-listener] To compile locally, install Visual Studio Build Tools or MinGW-w64"+ );+ }+}++main().catch((error) => {+ console.error("[windows-mic-listener] Unexpected error:", error);+ // Don't fail the build+});diff --git a/src/helpers/audioActivityDetector.js b/src/helpers/audioActivityDetector.jsindex e2c76576a..916c1bd24 100644--- a/src/helpers/audioActivityDetector.js+++ b/src/helpers/audioActivityDetector.js@@ -1,4 +1,4 @@-const { exec, execFile } = require("child_process");+const { exec, execFile, spawn } = require("child_process");const { promisify } = require("util");const path = require("path");const fs = require("fs");@@ -8,9 +8,9 @@ const debugLogger = require("./debugLogger");const execAsync = promisify(exec);const execFileAsync = promisify(execFile);-// Windows uses tasklist (process spawn) per check; poll less frequently to reduce overhead.const CHECK_INTERVAL_MS = process.platform === "win32" ? 15 * 1000 : 5 * 1000;const SUSTAINED_THRESHOLD_CHECKS = process.platform === "win32" ? 2 : 3;+const SUSTAINED_EVENT_DRIVEN_MS = 15 * 1000;const COOLDOWN_MS = 30 * 60 * 1000;const EXEC_OPTS = { timeout: 5000, encoding: "utf8" };@@ -25,6 +25,12 @@ class AudioActivityDetector extends EventEmitter {this._micCheckBinary = null;this._userRecording = false;this._checking = false;+ this._listenerProcess = null;+ this._activeMicPids = new Set();+ this._activeSources = 0;+ this._sustainedTimer = null;+ this._running = false;+ this._eventDriven = false;}setUserRecording(active) {@@ -32,34 +38,52 @@ class AudioActivityDetector extends EventEmitter {if (active) {this.consecutiveChecks = 0;this.audioActiveStart = null;+ this._clearSustainedTimer();}debugLogger.debug("User recording state changed", { active }, "meeting");}- start() {- if (this.checkInterval) return;- if (process.platform === "darwin") this._resolveMicCheckBinary();- debugLogger.info(- "Audio activity detector started",- { intervalMs: CHECK_INTERVAL_MS, threshold: SUSTAINED_THRESHOLD_CHECKS },- "meeting"- );- this._check();- this.checkInterval = setInterval(() => this._check(), CHECK_INTERVAL_MS);+ async start() {+ if (this._running) return;+ this._running = true;++ const started = await this._tryEventDriven();+ if (started) {+ this._eventDriven = true;+ debugLogger.info(+ "Audio activity detector started (event-driven)",+ { platform: process.platform },+ "meeting"+ );+ } else {+ this._eventDriven = false;+ this._startPolling();+ debugLogger.info(+ "Audio activity detector started (polling)",+ { intervalMs: CHECK_INTERVAL_MS, threshold: SUSTAINED_THRESHOLD_CHECKS },+ "meeting"+ );+ }}stop() {+ if (!this._running) return;+ this._running = false;+ this._killListenerProcess();+ this._clearSustainedTimer();if (this.checkInterval) {clearInterval(this.checkInterval);this.checkInterval = null;}this._reset();+ this._eventDriven = false;debugLogger.info("Audio activity detector stopped", {}, "meeting");}dismiss() {this.lastDismissedAt = Date.now();this._reset();+ this._clearSustainedTimer();debugLogger.info("Audio detection dismissed, cooldown started",{ cooldownMs: COOLDOWN_MS },@@ -71,6 +95,280 @@ class AudioActivityDetector extends EventEmitter {this.consecutiveChecks = 0;this.audioActiveStart = null;this.hasPrompted = false;+ this._activeMicPids.clear();+ this._activeSources = 0;+ }++ _clearSustainedTimer() {+ if (this._sustainedTimer) {+ clearTimeout(this._sustainedTimer);+ this._sustainedTimer = null;+ }+ }++ _killListenerProcess() {+ if (this._listenerProcess) {+ try {+ this._listenerProcess.kill();+ } catch {+ // already exited+ }+ this._listenerProcess = null;+ }+ }++ // ---------------------------------------------------------------------------+ // Event-driven approach+ // ---------------------------------------------------------------------------++ async _tryEventDriven() {+ switch (process.platform) {+ case "darwin":+ return this._tryEventDrivenDarwin();+ case "win32":+ return this._tryEventDrivenWin32();+ case "linux":+ return this._tryEventDrivenLinux();+ default:+ return false;+ }+ }++ _resolveBinary(binaryName) {+ const candidates = [+ path.join(__dirname, "..", "..", "resources", "bin", binaryName),+ path.join(__dirname, "..", "..", "resources", binaryName),+ ];++ if (process.resourcesPath) {+ candidates.push(+ path.join(process.resourcesPath, binaryName),+ path.join(process.resourcesPath, "bin", binaryName),+ path.join(process.resourcesPath, "resources", "bin", binaryName),+ path.join(process.resourcesPath, "app.asar.unpacked", "resources", "bin", binaryName)+ );+ }++ for (const candidate of candidates) {+ try {+ if (fs.existsSync(candidate)) {+ fs.accessSync(candidate, fs.constants.X_OK);+ debugLogger.info("Resolved binary", { name: binaryName, path: candidate }, "meeting");+ return candidate;+ }+ } catch {+ // continue+ }+ }+ return null;+ }++ _attachFallbackHandlers(child, label) {+ const fallbackToPolling = () => {+ this._listenerProcess = null;+ if (this._running && this._eventDriven) {+ this._eventDriven = false;+ this._startPolling();+ }+ };++ child.on("error", (err) => {+ debugLogger.warn(`${label} error`, { error: err.message }, "meeting");+ fallbackToPolling();+ });++ child.on("exit", (code) => {+ debugLogger.warn(`${label} exited`, { code }, "meeting");+ fallbackToPolling();+ });+ }++ _tryEventDrivenDarwin() {+ const binaryPath = this._resolveBinary("macos-mic-listener");+ if (!binaryPath) {+ debugLogger.warn("macos-mic-listener binary not found, will use polling", {}, "meeting");+ return false;+ }++ try {+ const child = spawn(binaryPath, [], { stdio: ["ignore", "pipe", "pipe"] });+ this._listenerProcess = child;++ let buffer = "";+ child.stdout.on("data", (data) => {+ buffer += data.toString();+ let newlineIdx;+ while ((newlineIdx = buffer.indexOf("\n")) !== -1) {+ const line = buffer.slice(0, newlineIdx).trim();+ buffer = buffer.slice(newlineIdx + 1);+ if (line === "MIC_ACTIVE") {+ this._onMicStateChanged(true);+ } else if (line === "MIC_INACTIVE") {+ this._onMicStateChanged(false);+ }+ }+ });++ child.stderr.on("data", (data) => {+ debugLogger.debug("macos-mic-listener stderr", { output: data.toString().trim() }, "meeting");+ });++ this._attachFallbackHandlers(child, "macos-mic-listener");+ return true;+ } catch (err) {+ debugLogger.warn("Failed to spawn macos-mic-listener", { error: err.message }, "meeting");+ return false;+ }+ }++ _tryEventDrivenWin32() {+ const binaryPath = this._resolveBinary("windows-mic-listener.exe");+ if (!binaryPath) {+ debugLogger.warn("windows-mic-listener.exe not found, will use polling", {}, "meeting");+ return false;+ }++ try {+ // stdin must be "pipe" — the Windows binary monitors stdin for parent death+ const child = spawn(binaryPath, ["--exclude-pid", String(process.pid)], {+ stdio: ["pipe", "pipe", "pipe"],+ });+ this._listenerProcess = child;++ let buffer = "";+ child.stdout.on("data", (data) => {+ buffer += data.toString();+ let newlineIdx;+ while ((newlineIdx = buffer.indexOf("\n")) !== -1) {+ const line = buffer.slice(0, newlineIdx).trim();+ buffer = buffer.slice(newlineIdx + 1);+ this._parseWin32ListenerLine(line);+ }+ });++ child.stderr.on("data", (data) => {+ debugLogger.debug("windows-mic-listener stderr", { output: data.toString().trim() }, "meeting");+ });++ this._attachFallbackHandlers(child, "windows-mic-listener");+ return true;+ } catch (err) {+ debugLogger.warn("Failed to spawn windows-mic-listener", { error: err.message }, "meeting");+ return false;+ }+ }++ _parseWin32ListenerLine(line) {+ const startMatch = line.match(/^MIC_START\s+(\d+)$/);+ if (startMatch) {+ const pid = parseInt(startMatch[1], 10);+ this._activeMicPids.add(pid);+ this._onMicStateChanged(true);+ return;+ }++ const stopMatch = line.match(/^MIC_STOP\s+(\d+)$/);+ if (stopMatch) {+ const pid = parseInt(stopMatch[1], 10);+ this._activeMicPids.delete(pid);+ if (this._activeMicPids.size === 0) {+ this._onMicStateChanged(false);+ }+ return;+ }+ }++ _tryEventDrivenLinux() {+ try {+ const child = spawn("pactl", ["subscribe"], { stdio: ["ignore", "pipe", "pipe"] });+ this._listenerProcess = child;++ let buffer = "";+ child.stdout.on("data", (data) => {+ buffer += data.toString();+ let newlineIdx;+ while ((newlineIdx = buffer.indexOf("\n")) !== -1) {+ const line = buffer.slice(0, newlineIdx).trim();+ buffer = buffer.slice(newlineIdx + 1);+ this._parsePactlSubscribeLine(line);+ }+ });++ this._attachFallbackHandlers(child, "pactl subscribe");+ return true;+ } catch {+ return false;+ }+ }++ _parsePactlSubscribeLine(line) {+ if (!line.includes("source-output")) return;++ if (/Event\s+'new'\s+on\s+source-output/i.test(line)) {+ this._activeSources++;+ this._onMicStateChanged(true);+ } else if (/Event\s+'remove'\s+on\s+source-output/i.test(line)) {+ this._activeSources = Math.max(0, this._activeSources - 1);+ if (this._activeSources === 0) {+ this._onMicStateChanged(false);+ }+ }+ }++ // ---------------------------------------------------------------------------+ // Shared event-driven handler+ // ---------------------------------------------------------------------------++ _onMicStateChanged(active) {+ if (this._userRecording) return;+ if (this.lastDismissedAt && Date.now() - this.lastDismissedAt < COOLDOWN_MS) return;+ if (this.hasPrompted) return;++ debugLogger.debug("Mic state changed (event-driven)", { active }, "meeting");++ if (active) {+ if (!this.audioActiveStart) this.audioActiveStart = Date.now();++ if (!this._sustainedTimer) {+ this._sustainedTimer = setTimeout(() => {+ this._sustainedTimer = null;+ if (this._userRecording || this.hasPrompted) return;+ if (this.lastDismissedAt && Date.now() - this.lastDismissedAt < COOLDOWN_MS) return;++ this.hasPrompted = true;+ const now = Date.now();+ const durationMs = now - this.audioActiveStart;+ debugLogger.info(+ "Sustained audio activity detected (event-driven)",+ { durationMs },+ "meeting"+ );+ this.emit("sustained-audio-detected", { durationMs, detectedAt: now });+ }, SUSTAINED_EVENT_DRIVEN_MS);+ }+ } else {+ this._clearSustainedTimer();+ this.audioActiveStart = null;+ }+ }++ // ---------------------------------------------------------------------------+ // Polling fallback+ // ---------------------------------------------------------------------------++ _startPolling() {+ if (process.platform === "darwin") this._resolveMicCheckBinary();+ this._check();+ this.checkInterval = setInterval(() => this._check(), CHECK_INTERVAL_MS);+ }++ _resolveMicCheckBinary() {+ const resolved = this._resolveBinary("macos-mic-check");+ if (resolved) {+ this._micCheckBinary = resolved;+ } else {+ debugLogger.warn("macos-mic-check binary not found, falling back to ioreg", {}, "meeting");+ }}async _check() {@@ -132,37 +430,6 @@ class AudioActivityDetector extends EventEmitter {}}- _resolveMicCheckBinary() {- const binaryName = "macos-mic-check";- const candidates = [- path.join(__dirname, "..", "..", "resources", "bin", binaryName),- path.join(__dirname, "..", "..", "resources", binaryName),- ];-- if (process.resourcesPath) {- candidates.push(- path.join(process.resourcesPath, binaryName),- path.join(process.resourcesPath, "bin", binaryName),- path.join(process.resourcesPath, "resources", "bin", binaryName),- path.join(process.resourcesPath, "app.asar.unpacked", "resources", "bin", binaryName)- );- }-- for (const candidate of candidates) {- try {- if (fs.existsSync(candidate)) {- fs.accessSync(candidate, fs.constants.X_OK);- this._micCheckBinary = candidate;- debugLogger.info("Resolved mic-check binary", { path: candidate }, "meeting");- return;- }- } catch {- // continue- }- }- debugLogger.warn("macos-mic-check binary not found, falling back to ioreg", {}, "meeting");- }-async _checkDarwin() {if (this._micCheckBinary) {try {@@ -193,12 +460,12 @@ class AudioActivityDetector extends EventEmitter {async _checkWin32() {try {- const { stdout } = await execAsync("tasklist /NH /FO CSV", EXEC_OPTS);- const lower = stdout.toLowerCase();+ const processListCache = require("./processListCache");+ const names = await processListCache.getProcessList();return (- lower.includes('"cpthost.exe"') ||- lower.includes('"ms-teams_modulehost.exe"') ||- lower.includes('"webexmeetingsapp.exe"')+ names.includes("cpthost.exe") ||+ names.includes("ms-teams_modulehost.exe") ||+ names.includes("webexmeetingsapp.exe"));} catch {return false;diff --git a/src/helpers/googleCalendarManager.js b/src/helpers/googleCalendarManager.jsindex e3c6e5718..544930233 100644--- a/src/helpers/googleCalendarManager.js+++ b/src/helpers/googleCalendarManager.js@@ -17,6 +17,7 @@ class GoogleCalendarManager {this.activeMeeting = null;this.notifiedMeetings = new Set();this.SYNC_INTERVAL_MS = 2 * 60 * 1000;+ this._consecutiveFailures = 0;this._lastFocusSync = 0;}@@ -25,7 +26,10 @@ class GoogleCalendarManager {if (this.accounts.size === 0) return;this.syncEvents()- .then(() => this.scheduleNextMeeting())+ .then(() => {+ this.scheduleNextMeeting();+ this._consecutiveFailures = 0;+ }).catch((err) =>debugLogger.error("Initial calendar sync failed", { error: err.message }, "gcal"));@@ -74,6 +78,7 @@ class GoogleCalendarManager {await this.fetchCalendars(result.email);await this.syncEvents();+ this._consecutiveFailures = 0;this.scheduleNextMeeting();this._startSyncInterval();this._broadcastAccountsChanged();@@ -297,9 +302,14 @@ class GoogleCalendarManager {}this.scheduleNextMeeting();- this.syncEvents().catch((err) =>- debugLogger.error("Post-wake sync failed", { error: err.message }, "gcal")- );+ this.syncEvents()+ .then(() => {+ this._consecutiveFailures = 0;+ this._restartSyncInterval();+ })+ .catch((err) =>+ debugLogger.error("Post-wake sync failed", { error: err.message }, "gcal")+ );}syncOnFocus() {@@ -309,7 +319,13 @@ class GoogleCalendarManager {this._lastFocusSync = now;this.syncEvents()- .then(() => this.scheduleNextMeeting())+ .then(() => {+ this.scheduleNextMeeting();+ if (this._consecutiveFailures > 0) {+ this._consecutiveFailures = 0;+ this._restartSyncInterval();+ }+ }).catch((err) =>debugLogger.error("Focus-triggered sync failed", { error: err.message }, "gcal"));@@ -330,6 +346,7 @@ class GoogleCalendarManager {async setCalendarSelection(calendarId, isSelected) {this.databaseManager.updateCalendarSelection(calendarId, isSelected);await this.syncEvents();+ this._consecutiveFailures = 0;this.scheduleNextMeeting();}@@ -360,11 +377,41 @@ class GoogleCalendarManager {_startSyncInterval() {if (this.syncInterval) clearInterval(this.syncInterval);++ const interval = this._getSyncInterval();+ debugLogger.info("Calendar sync scheduled", { intervalMs: interval, consecutiveFailures: this._consecutiveFailures }, "gcal");+this.syncInterval = setInterval(() => {this.syncEvents()- .then(() => this.scheduleNextMeeting())- .catch((err) => debugLogger.error("Calendar sync failed", { error: err.message }, "gcal"));- }, this.SYNC_INTERVAL_MS);+ .then(() => {+ this.scheduleNextMeeting();+ if (this._consecutiveFailures > 0) {+ this._consecutiveFailures = 0;+ this._restartSyncInterval();+ }+ })+ .catch((err) => {+ this._consecutiveFailures++;+ debugLogger.error("Calendar sync failed", {+ error: err.message,+ consecutiveFailures: this._consecutiveFailures,+ nextIntervalMs: this._getSyncInterval()+ }, "gcal");+ this._restartSyncInterval();+ });+ }, interval);+ }++ _getSyncInterval() {+ if (this._consecutiveFailures === 0) return this.SYNC_INTERVAL_MS;+ return Math.min(+ this.SYNC_INTERVAL_MS * Math.pow(2, this._consecutiveFailures),+ 30 * 60 * 1000+ );+ }++ _restartSyncInterval() {+ this._startSyncInterval();}_broadcastAccountsChanged() {@@ -408,6 +455,9 @@ class GoogleCalendarManager {});req.on("error", reject);+ req.setTimeout(10000, () => {+ req.destroy(new Error("Request timed out after 10s"));+ });req.end();});}diff --git a/src/helpers/meetingDetectionEngine.js b/src/helpers/meetingDetectionEngine.jsindex 0bbecc83a..e9f648fa8 100644--- a/src/helpers/meetingDetectionEngine.js+++ b/src/helpers/meetingDetectionEngine.js@@ -18,6 +18,9 @@ class MeetingDetectionEngine {this.databaseManager = databaseManager;this.activeDetections = new Map();this.preferences = { processDetection: true, audioDetection: true };+ this._userRecording = false;+ this._notificationQueue = [];+ this._postRecordingCooldown = null;this._bindListeners();}@@ -64,6 +67,13 @@ class MeetingDetectionEngine {}}+ if (this._userRecording || this._postRecordingCooldown) {+ debugLogger.info("Detection queued — user is recording", { detectionId, source }, "meeting");+ this._notificationQueue.push({ source, key, data });+ this.activeDetections.set(detectionId, { source, key, data, dismissed: false });+ return;+ }+let imminentEvent = null;if (calendarState?.upcomingEvents?.length > 0) {const now = Date.now();@@ -183,6 +193,41 @@ class MeetingDetectionEngine {}}+ _flushNotificationQueue() {+ if (this._notificationQueue.length === 0) return;++ debugLogger.info("Flushing notification queue", { count: this._notificationQueue.length }, "meeting");++ const prioritized = this._notificationQueue.sort((a, b) => {+ const priority = { process: 1, audio: 2 };+ return (priority[a.source] || 0) - (priority[b.source] || 0);+ });++ const best = prioritized[0];+ const detectionId = `${best.source}:${best.key}`;++ const detection = this.activeDetections.get(detectionId);+ if (detection && !detection.dismissed) {+ const calendarState = this.googleCalendarManager?.getActiveMeetingState?.();+ let imminentEvent = null;+ if (calendarState?.upcomingEvents?.length > 0) {+ const now = Date.now();+ imminentEvent = calendarState.upcomingEvents.find((evt) => {+ const start = new Date(evt.start_time).getTime();+ return start - now <= 5 * 60 * 1000 && start > now;+ });+ }++ if (imminentEvent) {+ this._showPrompt(detectionId, best.source, best.key, best.data, imminentEvent);+ } else {+ this._showPrompt(detectionId, best.source, best.key, best.data, null);+ }+ }++ this._notificationQueue = [];+ }+_dismiss(source, key) {if (source === "process") {this.meetingProcessDetector.dismiss(key);@@ -192,7 +237,20 @@ class MeetingDetectionEngine {}setUserRecording(active) {+ this._userRecording = active;this.audioActivityDetector.setUserRecording(active);++ if (active) {+ if (this._postRecordingCooldown) {+ clearTimeout(this._postRecordingCooldown);+ this._postRecordingCooldown = null;+ }+ } else {+ this._postRecordingCooldown = setTimeout(() => {+ this._postRecordingCooldown = null;+ this._flushNotificationQueue();+ }, 2500);+ }}setPreferences(prefs) {@@ -227,6 +285,11 @@ class MeetingDetectionEngine {this.meetingProcessDetector.stop();this.audioActivityDetector.stop();this.activeDetections.clear();+ if (this._postRecordingCooldown) {+ clearTimeout(this._postRecordingCooldown);+ this._postRecordingCooldown = null;+ }+ this._notificationQueue = [];}broadcastToWindows(channel, data) {diff --git a/src/helpers/meetingProcessDetector.js b/src/helpers/meetingProcessDetector.jsindex 044476106..2a6b244e2 100644--- a/src/helpers/meetingProcessDetector.js+++ b/src/helpers/meetingProcessDetector.js@@ -1,68 +1,33 @@-const { exec } = require("child_process");-const { promisify } = require("util");const EventEmitter = require("events");const debugLogger = require("./debugLogger");+const processListCache = require("./processListCache");-const execAsync = promisify(exec);+const POLL_INTERVAL_MS = 30 * 1000;-const POLL_INTERVAL_MS = 20 * 1000;-const EXEC_OPTS = { timeout: 3000, encoding: "utf8" };--async function hasProcess(name) {- try {- await execAsync(`pgrep -f "${name}"`, EXEC_OPTS);- return true;- } catch {- return false;- }-}--async function hasProcessExact(name) {- try {- await execAsync(`pgrep -x "${name}"`, EXEC_OPTS);- return true;- } catch {- return false;- }-}+const BUNDLE_ID_MAP = {+ "us.zoom.xos": "zoom",+ "com.microsoft.teams": "teams",+ "com.microsoft.teams2": "teams",+ "com.cisco.webexmeetingsapp": "webex",+ "com.apple.FaceTime": "facetime",+};-async function hasActiveAudio(appName) {- if (process.platform !== "darwin") return true;- try {- const { stdout } = await execAsync(- `lsof -c "${appName}" 2>/dev/null | grep -i coreaudio`,- EXEC_OPTS- );- return stdout.trim().length > 0;- } catch {- return false;- }-}+const BUNDLE_APP_NAMES = {+ zoom: "Zoom",+ teams: "Microsoft Teams",+ webex: "Webex",+ facetime: "FaceTime",+};const MEETING_APPS = {- darwin: [- { processKey: "zoom", appName: "Zoom", check: () => hasProcessExact("CptHost") },- {- processKey: "teams",- appName: "Microsoft Teams",- check: async () => (await hasProcess("MSTeams")) && (await hasActiveAudio("MSTeams")),- },- {- processKey: "facetime",- appName: "FaceTime",- check: async () => (await hasProcessExact("FaceTime")) && (await hasActiveAudio("FaceTime")),- },- { processKey: "webex", appName: "Webex", check: () => hasProcess("webexmeetingsapp") },- ],- // Windows: single tasklist call in _pollWin32() to avoid per-app process spawns.win32: [{ processKey: "zoom", appName: "Zoom", imageName: "cpthost.exe" },{ processKey: "teams", appName: "Microsoft Teams", imageName: "ms-teams_modulehost.exe" },{ processKey: "webex", appName: "Webex", imageName: "webexmeetingsapp.exe" },],linux: [- { processKey: "zoom", appName: "Zoom", check: () => hasProcess("zoom") },- { processKey: "teams", appName: "Microsoft Teams", check: () => hasProcess("teams") },+ { processKey: "zoom", appName: "Zoom", imageName: "zoom" },+ { processKey: "teams", appName: "Microsoft Teams", imageName: "teams" },],};@@ -73,13 +38,105 @@ class MeetingProcessDetector extends EventEmitter {this.detectedProcesses = new Map();this.dismissedProcesses = new Set();this._polling = false;+ this._subscriptionIds = [];}start() {- if (this.pollInterval) return;- const apps = MEETING_APPS[process.platform] || [];+ if (this.pollInterval || this._subscriptionIds.length > 0) return;++ if (process.platform === "darwin") {+ this._startDarwin();+ } else {+ const apps = MEETING_APPS[process.platform] || [];+ debugLogger.info(+ "Process detector started",+ {+ platform: process.platform,+ appsMonitored: apps.map((a) => a.appName),+ intervalMs: POLL_INTERVAL_MS,+ },+ "meeting"+ );+ this._poll();+ this.pollInterval = setInterval(() => this._poll(), POLL_INTERVAL_MS);+ }+ }++ _startDarwin() {+ let systemPreferences;+ try {+ systemPreferences = require("electron").systemPreferences;+ } catch {+ debugLogger.warn(+ "systemPreferences unavailable, falling back to polling",+ {},+ "meeting"+ );+ this._startPollingFallback();+ return;+ }++ if (!systemPreferences.subscribeWorkspaceNotification) {+ debugLogger.warn(+ "subscribeWorkspaceNotification unavailable, falling back to polling",+ {},+ "meeting"+ );+ this._startPollingFallback();+ return;+ }++ const launchId = systemPreferences.subscribeWorkspaceNotification(+ "NSWorkspaceDidLaunchApplicationNotification",+ (_event, userInfo) => {+ const bundleId = userInfo?.NSApplicationBundleIdentifier;+ const processKey = bundleId ? BUNDLE_ID_MAP[bundleId] : null;+ if (processKey) {+ const appName = BUNDLE_APP_NAMES[processKey] || processKey;+ debugLogger.debug(+ "Workspace app launched",+ { bundleId, processKey },+ "meeting"+ );+ this._updateDetection(processKey, appName, true);+ }+ }+ );++ const terminateId = systemPreferences.subscribeWorkspaceNotification(+ "NSWorkspaceDidTerminateApplicationNotification",+ (_event, userInfo) => {+ const bundleId = userInfo?.NSApplicationBundleIdentifier;+ const processKey = bundleId ? BUNDLE_ID_MAP[bundleId] : null;+ if (processKey) {+ const appName = BUNDLE_APP_NAMES[processKey] || processKey;+ debugLogger.debug(+ "Workspace app terminated",+ { bundleId, processKey },+ "meeting"+ );+ this._updateDetection(processKey, appName, false);+ }+ }+ );++ this._subscriptionIds.push(launchId, terminateId);+debugLogger.info("Process detector started",+ {+ platform: "darwin",+ mode: "NSWorkspace",+ bundleIds: Object.keys(BUNDLE_ID_MAP),+ },+ "meeting"+ );+ }++ _startPollingFallback() {+ const apps = MEETING_APPS.linux || [];+ debugLogger.info(+ "Process detector started (polling fallback)",{platform: process.platform,appsMonitored: apps.map((a) => a.appName),@@ -96,6 +153,19 @@ class MeetingProcessDetector extends EventEmitter {clearInterval(this.pollInterval);this.pollInterval = null;}++ if (this._subscriptionIds.length > 0) {+ try {+ const { systemPreferences } = require("electron");+ for (const id of this._subscriptionIds) {+ systemPreferences.unsubscribeWorkspaceNotification(id);+ }+ } catch {+ // electron may not be available during cleanup+ }+ this._subscriptionIds = [];+ }+this.detectedProcesses.clear();debugLogger.info("Stopped meeting process detector", {}, "meeting");}@@ -114,6 +184,9 @@ class MeetingProcessDetector extends EventEmitter {}_getAppName(processKey) {+ if (process.platform === "darwin") {+ return BUNDLE_APP_NAMES[processKey] || processKey;+ }const apps = MEETING_APPS[process.platform] || [];const entry = apps.find((a) => a.processKey === processKey);return entry ? entry.appName : processKey;@@ -123,10 +196,12 @@ class MeetingProcessDetector extends EventEmitter {if (this._polling) return;this._polling = true;try {- if (process.platform === "win32") {- await this._pollWin32();- } else {- await this._pollDefault();+ const apps = MEETING_APPS[process.platform] || MEETING_APPS.linux || [];+ const processList = await processListCache.getProcessList();++ for (const { processKey, appName, imageName } of apps) {+ const isRunning = processList.includes(imageName);+ this._updateDetection(processKey, appName, isRunning);}} catch (err) {debugLogger.warn("Poll error", { error: err.message }, "meeting");@@ -135,36 +210,6 @@ class MeetingProcessDetector extends EventEmitter {}}- async _pollWin32() {- const apps = MEETING_APPS.win32 || [];- let tasklistOutput = "";- try {- const { stdout } = await execAsync("tasklist /NH /FO CSV", EXEC_OPTS);- tasklistOutput = stdout.toLowerCase();- } catch {- return;- }-- for (const { processKey, appName, imageName } of apps) {- const isRunning = tasklistOutput.includes(`"${imageName}"`);- this._updateDetection(processKey, appName, isRunning);- }- }-- async _pollDefault() {- const apps = MEETING_APPS[process.platform] || [];-- for (const { processKey, appName, check } of apps) {- let isRunning = false;- try {- isRunning = await check();- } catch {- isRunning = false;- }- this._updateDetection(processKey, appName, isRunning);- }- }-_updateDetection(processKey, appName, isRunning) {if (isRunning) {if (!this.detectedProcesses.has(processKey) && !this.dismissedProcesses.has(processKey)) {diff --git a/src/helpers/processListCache.js b/src/helpers/processListCache.jsnew file mode 100644index 000000000..814e61c23--- /dev/null+++ b/src/helpers/processListCache.js@@ -0,0 +1,50 @@+const debugLogger = require("./debugLogger");++const CACHE_TTL_MS = 5000;++class ProcessListCache {+ constructor() {+ this._cache = null;+ this._cacheTime = 0;+ this._pending = null;+ }++ async getProcessList() {+ const now = Date.now();+ if (this._cache && now - this._cacheTime < CACHE_TTL_MS) {+ return this._cache;+ }++ if (this._pending) return this._pending;++ this._pending = this._fetch(now);+ try {+ return await this._pending;+ } finally {+ this._pending = null;+ }+ }++ async _fetch(now) {+ try {+ const psList = (await import("ps-list")).default;+ const procs = await psList();+ const names = procs.map((p) => (p.name || "").toLowerCase());+ this._cache = names;+ this._cacheTime = now;+ debugLogger.debug("Process list refreshed", { count: names.length }, "meeting");+ return names;+ } catch (err) {+ debugLogger.warn("Failed to fetch process list", { error: err.message }, "meeting");+ return [];+ }+ }++ invalidate() {+ this._cache = null;+ this._cacheTime = 0;+ this._pending = null;+ }+}++module.exports = new ProcessListCache();