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(meetings): Auto-end forgotten meeting recordings (#1494)
Chad Pihabc306d27d40e
diff --git a/.github/workflows/build-and-notarize.yml b/.github/workflows/build-and-notarize.ymlindex 4c8bf6f40..7c59e3ca0 100644--- a/.github/workflows/build-and-notarize.yml+++ b/.github/workflows/build-and-notarize.yml@@ -146,6 +146,9 @@ jobs:node-version: "24"cache: "npm"+ - name: Setup MSVC environment+ uses: ilammy/msvc-dev-cmd@v1+- name: Install dependenciesrun: npm ci@@ -156,7 +159,9 @@ jobs:uses: actions/cache@v4with:path: resources/bin- key: windows-x64-bin-${{ hashFiles('scripts/download-*.js') }}+ # Native helper sources are in the key so source changes cannot+ # restore stale helper binaries from the cache.+ key: windows-x64-bin-${{ hashFiles('scripts/download-*.js', 'resources/windows-system-audio-helper.c', 'resources/windows-mic-listener.c') }}- name: Download whisper.cpp binariesrun: node scripts/download-whisper-cpp.js --current@@ -201,10 +206,11 @@ jobs:env:GITHUB_TOKEN: ${{ secrets.GH_TOKEN || github.token }}- - name: Download windows-mic-listener.exe- run: node scripts/download-windows-mic-listener.js- env:- GITHUB_TOKEN: ${{ secrets.GH_TOKEN || github.token }}+ - name: Compile windows-mic-listener.exe+ shell: cmd+ run: |+ if not exist resources\bin mkdir resources\bin+ cl /O2 /nologo resources\windows-mic-listener.c /Fe:resources\bin\windows-mic-listener.exe ole32.lib oleaut32.lib- name: Cache Electronuses: actions/cache@v4diff --git a/.github/workflows/build-windows-mic-listener.yml b/.github/workflows/build-windows-mic-listener.ymlindex 1b30fc226..48493286a 100644--- a/.github/workflows/build-windows-mic-listener.yml+++ b/.github/workflows/build-windows-mic-listener.yml@@ -10,9 +10,9 @@ on:workflow_dispatch:inputs:version:- description: 'Version tag (e.g., 1.0.0)'+ description: 'Override version tag (defaults to MIC_LISTENER_VERSION in the C source)'required: false- default: '1.0.0'+ default: ''type: stringpermissions:@@ -24,6 +24,20 @@ jobs:steps:- uses: actions/checkout@v4+ # The release tag comes from the source so protocol changes ship under a+ # new tag and download-windows-mic-listener.js (pinned to the same+ # constant) can never silently pick up a binary built from older source.+ - name: Read binary version from source+ id: version+ run: |+ $match = Select-String -Path resources/windows-mic-listener.c -Pattern 'MIC_LISTENER_VERSION "([0-9.]+)"'+ if (-not $match) {+ Write-Error "MIC_LISTENER_VERSION not found in resources/windows-mic-listener.c"+ exit 1+ }+ "version=$($match.Matches[0].Groups[1].Value)" >> $env:GITHUB_OUTPUT+ shell: pwsh+- name: Setup MSVCuses: microsoft/setup-msbuild@v2@@ -60,13 +74,15 @@ jobs:- name: Create or update releaseuses: softprops/action-gh-release@v2with:- tag_name: windows-mic-listener-v${{ inputs.version || '1.0.0' }}- name: Windows Mic Listener v${{ inputs.version || '1.0.0' }}+ tag_name: windows-mic-listener-v${{ inputs.version || steps.version.outputs.version }}+ name: Windows Mic Listener v${{ inputs.version || steps.version.outputs.version }}body: |Prebuilt Windows mic listener binary for event-driven microphone detection.- Uses WASAPI IAudioSessionManager2 to monitor capture sessions.- Supports --exclude-pid to filter out OpenWhispr's own mic usage.+ Uses WASAPI IAudioSessionManager2 to monitor capture sessions with+ per-PID refcounting across all capture endpoints (hot-plug aware).+ Announces "CAPABILITY PID" on stdout; PID exclusions are handled by+ the JavaScript caller.files: windows-mic-listener-win32-x64.zipmake_latest: falseenv:diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 15e34105d..36a6814d7 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -154,6 +154,9 @@ jobs:node-version: "24"cache: "npm"+ - name: Setup MSVC environment+ uses: ilammy/msvc-dev-cmd@v1+- name: Install dependenciesrun: npm ci@@ -164,9 +167,9 @@ jobs:uses: actions/cache@v4with:path: resources/bin- # The system-audio helper source is in the key so a republished- # helper binary invalidates the cached copy.- key: windows-x64-bin-${{ hashFiles('scripts/download-*.js', 'resources/windows-system-audio-helper.c') }}+ # Native helper sources are in the key so source changes cannot+ # restore stale helper binaries from the cache.+ key: windows-x64-bin-${{ hashFiles('scripts/download-*.js', 'resources/windows-system-audio-helper.c', 'resources/windows-mic-listener.c') }}- name: Download whisper.cpp binariesrun: node scripts/download-whisper-cpp.js --current@@ -211,10 +214,11 @@ jobs:env:GITHUB_TOKEN: ${{ secrets.GH_TOKEN }}- - name: Download windows-mic-listener.exe- run: node scripts/download-windows-mic-listener.js- env:- GITHUB_TOKEN: ${{ secrets.GH_TOKEN }}+ - name: Compile windows-mic-listener.exe+ shell: cmd+ run: |+ if not exist resources\bin mkdir resources\bin+ cl /O2 /nologo resources\windows-mic-listener.c /Fe:resources\bin\windows-mic-listener.exe ole32.lib oleaut32.lib- name: Download windows-system-audio-helper.exerun: node scripts/download-windows-system-audio-helper.jsdiff --git a/main.js b/main.jsindex 0deed2238..9eed8d313 100644--- a/main.js+++ b/main.js@@ -285,6 +285,10 @@ const AppleCalendarManager = require("./src/helpers/appleCalendarManager");const CalendarReminderScheduler = require("./src/helpers/calendarReminderScheduler");const MeetingProcessDetector = require("./src/helpers/meetingProcessDetector");const AudioActivityDetector = require("./src/helpers/audioActivityDetector");+const {+ collectAudioCaptureHelperPids,+ createExcludedProcessIdProvider,+} = require("./src/helpers/electronProcessIds");const AudioTapManager = require("./src/helpers/audioTapManager");const LinuxPortalAudioManager = require("./src/helpers/linuxPortalAudioManager");const WindowsLoopbackAudioManager = require("./src/helpers/windowsLoopbackAudioManager");@@ -457,7 +461,17 @@ function initializeCoreManagers() {meetingDetectionEngine = new MeetingDetectionEngine(calendarReminderScheduler,new MeetingProcessDetector(),- new AudioActivityDetector(),+ new AudioActivityDetector(+ // The capture-helper managers are created a few lines below; the provider+ // is only invoked on mic events, long after initialization completes.+ createExcludedProcessIdProvider(() =>+ collectAudioCaptureHelperPids([+ audioTapManager,+ linuxPortalAudioManager,+ windowsLoopbackAudioManager,+ ])+ )+ ),windowManager,databaseManager);diff --git a/preload.js b/preload.jsindex dc4f60006..369975bb5 100644--- a/preload.js+++ b/preload.js@@ -760,7 +760,10 @@ contextBridge.exposeInMainWorld("electronAPI", {ipcRenderer.invoke("meeting-transcription-start", options),meetingTranscriptionSend: (buffer, source) =>ipcRenderer.send("meeting-transcription-send", buffer, source),- meetingTranscriptionStop: () => ipcRenderer.invoke("meeting-transcription-stop"),+ meetingTranscriptionSetSystemAudioAvailable: (sessionId, available) =>+ ipcRenderer.invoke("meeting-transcription-set-system-audio-available", sessionId, available),+ meetingTranscriptionStop: (expectedSessionId) =>+ ipcRenderer.invoke("meeting-transcription-stop", expectedSessionId),meetingTranscriptionCancel: () => ipcRenderer.invoke("meeting-transcription-cancel"),onMeetingTranscriptionSegment: registerListener("meeting-transcription-segment",@@ -1176,6 +1179,11 @@ contextBridge.exposeInMainWorld("electronAPI", {"meeting-notification-data",(callback) => (_event, data) => callback(data)),+ onMeetingAutoEndRequested: registerListener(+ "meeting-auto-end-requested",+ (callback) => (_event, data) => callback(data)+ ),+ meetingAutoEndKeep: (sessionId) => ipcRenderer.invoke("meeting-auto-end-keep", sessionId),getMeetingNotificationData: () => ipcRenderer.invoke("get-meeting-notification-data"),meetingNotificationReady: () => ipcRenderer.invoke("meeting-notification-ready"),meetingNotificationRespond: (detectionId, action) =>diff --git a/resources/macos-mic-listener.swift b/resources/macos-mic-listener.swiftindex 4baa1eea3..2fc884f6e 100644--- a/resources/macos-mic-listener.swift+++ b/resources/macos-mic-listener.swift@@ -1,8 +1,9 @@/*** macOS Microphone Listener*- * Long-running process that monitors microphone usage via CoreAudio property listeners.- * Outputs MIC_ACTIVE / MIC_INACTIVE state transitions to stdout.+ * 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.** Compile: swiftc -O macos-mic-listener.swift -o macos-mic-listener -framework CoreAudio -framework Foundation*/@@ -10,12 +11,19 @@import CoreAudioimport Foundation-// MARK: - State+enum ListenerMode {+ case none+ case process+ case aggregate+}-var previouslyActive = false+var listenerMode = ListenerMode.none+var processObjectPids: [AudioObjectID: pid_t] = [:]+var activeInputPids: Set<pid_t> = []+var processListListenerRegistered = falsevar inputDevices: [AudioDeviceID] = []--// MARK: - Output+var previouslyAggregateActive = false+var signalSources: [DispatchSourceSignal] = []func emit(_ message: String) {print(message)@@ -23,87 +31,294 @@ func emit(_ message: String) {}func emitError(_ message: String) {- FileHandle.standardError.write((message + "\n").data(using: .utf8)!)+ guard let data = (message + "\n").data(using: .utf8) else { return }+ FileHandle.standardError.write(data)}-// MARK: - Device Enumeration--func getInputDevices() -> [AudioDeviceID] {- var address = AudioObjectPropertyAddress(- mSelector: kAudioHardwarePropertyDevices,+func processPropertyAddress(_ selector: AudioObjectPropertySelector) -> AudioObjectPropertyAddress {+ AudioObjectPropertyAddress(+ mSelector: selector,mScope: kAudioObjectPropertyScopeGlobal,mElement: kAudioObjectPropertyElementMain)+}++func getProcessObjects() -> [AudioObjectID]? {+ let systemObject = AudioObjectID(kAudioObjectSystemObject)+ var address = processPropertyAddress(kAudioHardwarePropertyProcessObjectList)+ guard AudioObjectHasProperty(systemObject, &address) else { return nil }var dataSize: UInt32 = 0- var status = AudioObjectGetPropertyDataSize(- AudioObjectID(kAudioObjectSystemObject),+ var status = AudioObjectGetPropertyDataSize(systemObject, &address, 0, nil, &dataSize)+ guard status == noErr else { return nil }+ guard dataSize > 0 else { return [] }++ let objectCount = Int(dataSize) / MemoryLayout<AudioObjectID>.size+ var processObjects = [AudioObjectID](repeating: 0, count: objectCount)+ status = AudioObjectGetPropertyData(+ systemObject,&address,0,nil,- &dataSize+ &dataSize,+ &processObjects)- guard status == noErr else {- emitError("Failed to get device list size: \(status)")- return []- }+ return status == noErr ? processObjects : nil+}- let deviceCount = Int(dataSize) / MemoryLayout<AudioDeviceID>.size- guard deviceCount > 0 else { return [] }+func getProcessPid(_ processObject: AudioObjectID) -> pid_t? {+ var address = processPropertyAddress(kAudioProcessPropertyPID)+ var processId: pid_t = 0+ var dataSize = UInt32(MemoryLayout<pid_t>.size)+ let status = AudioObjectGetPropertyData(+ processObject,+ &address,+ 0,+ nil,+ &dataSize,+ &processId+ )+ return status == noErr && processId > 0 ? processId : nil+}- var devices = [AudioDeviceID](repeating: 0, count: deviceCount)- status = AudioObjectGetPropertyData(- AudioObjectID(kAudioObjectSystemObject),+func isProcessRunningInput(_ processObject: AudioObjectID) -> Bool? {+ var address = processPropertyAddress(kAudioProcessPropertyIsRunningInput)+ guard AudioObjectHasProperty(processObject, &address) else { return nil }++ var isRunning: UInt32 = 0+ var dataSize = UInt32(MemoryLayout<UInt32>.size)+ let status = AudioObjectGetPropertyData(+ processObject,&address,0,nil,&dataSize,- &devices+ &isRunning)- guard status == noErr else {- emitError("Failed to get device list: \(status)")- return []+ return status == noErr ? isRunning > 0 : nil+}++let processStateListener: AudioObjectPropertyListenerProc = {+ (_: AudioObjectID,+ _: UInt32,+ _: UnsafePointer<AudioObjectPropertyAddress>,+ _: UnsafeMutableRawPointer?) -> OSStatus in++ DispatchQueue.main.async {+ reconcileProcessMonitoring()+ }+ return noErr+}++let processListListener: AudioObjectPropertyListenerProc = {+ (_: AudioObjectID,+ _: UInt32,+ _: UnsafePointer<AudioObjectPropertyAddress>,+ _: UnsafeMutableRawPointer?) -> OSStatus in++ DispatchQueue.main.async {+ reconcileProcessMonitoring()+ }+ return noErr+}++func addProcessStateListener(_ processObject: AudioObjectID) -> Bool {+ var address = processPropertyAddress(kAudioProcessPropertyIsRunningInput)+ return AudioObjectAddPropertyListener(+ processObject,+ &address,+ processStateListener,+ nil+ ) == noErr+}++func removeProcessStateListener(_ processObject: AudioObjectID) {+ var address = processPropertyAddress(kAudioProcessPropertyIsRunningInput)+ AudioObjectRemovePropertyListener(processObject, &address, processStateListener, nil)+}++func removeProcessMonitoring() {+ for processObject in processObjectPids.keys {+ removeProcessStateListener(processObject)+ }+ processObjectPids.removeAll()+ activeInputPids.removeAll()++ if processListListenerRegistered {+ var address = processPropertyAddress(kAudioHardwarePropertyProcessObjectList)+ AudioObjectRemovePropertyListener(+ AudioObjectID(kAudioObjectSystemObject),+ &address,+ processListListener,+ nil+ )+ processListListenerRegistered = false+ }+}++// A process can vanish between enumeration and the per-object property+// queries, so a failing object is skipped (treated as no longer capturing)+// rather than abandoning PID mode. Returns nil only when a non-empty process+// list yields no readable object at all — a systemic failure where reported+// state could no longer be trusted.+func prepareProcessSnapshot(+ _ processObjects: [AudioObjectID]+) -> (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)+ else {+ continue+ }++ pids[processObject] = processId+ if isRunningInput {+ active.insert(processId)+ }+ }++ if !processObjects.isEmpty && pids.isEmpty {+ return nil+ }+ return (pids, active)+}++func startProcessMonitoring() -> Bool {+ let systemObject = AudioObjectID(kAudioObjectSystemObject)+ var listAddress = processPropertyAddress(kAudioHardwarePropertyProcessObjectList)+ guard AudioObjectHasProperty(systemObject, &listAddress) else { return false }++ guard AudioObjectAddPropertyListener(+ systemObject,+ &listAddress,+ processListListener,+ nil+ ) == noErr else {+ return false+ }+ processListListenerRegistered = true++ guard+ let processObjects = getProcessObjects(),+ let snapshot = prepareProcessSnapshot(processObjects)+ else {+ removeProcessMonitoring()+ return false+ }++ for processObject in snapshot.pids.keys {+ guard addProcessStateListener(processObject) else {+ removeProcessMonitoring()+ return false+ }+ processObjectPids[processObject] = snapshot.pids[processObject]+ }+ activeInputPids = snapshot.active+ return true+}++func reconcileProcessMonitoring() {+ guard listenerMode == .process else { return }+ guard+ let processObjects = getProcessObjects(),+ var snapshot = prepareProcessSnapshot(processObjects)+ else {+ startAggregateFallback()+ return+ }++ let nextObjects = Set(snapshot.pids.keys)+ let previousObjects = Set(processObjectPids.keys)++ for processObject in previousObjects.subtracting(nextObjects) {+ removeProcessStateListener(processObject)+ processObjectPids.removeValue(forKey: processObject)}+ for processObject in nextObjects.subtracting(previousObjects) {+ // Registration can lose the same vanish race as the snapshot; drop the+ // object and let the next reconcile retry if it is actually alive. Its+ // pid stays in the active set until then so a live capture is never+ // reported stopped early.+ guard addProcessStateListener(processObject) else {+ snapshot.pids.removeValue(forKey: processObject)+ continue+ }+ processObjectPids[processObject] = snapshot.pids[processObject]+ }++ let stoppedPids = activeInputPids.subtracting(snapshot.active)+ let startedPids = snapshot.active.subtracting(activeInputPids)+ processObjectPids = snapshot.pids+ activeInputPids = snapshot.active++ for processId in stoppedPids.sorted() {+ emit("MIC_STOP \(processId)")+ }+ for processId in startedPids.sorted() {+ emit("MIC_START \(processId)")+ }+}++func getInputDevices() -> [AudioDeviceID] {+ var address = AudioObjectPropertyAddress(+ mSelector: kAudioHardwarePropertyDevices,+ mScope: kAudioObjectPropertyScopeGlobal,+ mElement: kAudioObjectPropertyElementMain+ )+ let systemObject = AudioObjectID(kAudioObjectSystemObject)+ var dataSize: UInt32 = 0+ var status = AudioObjectGetPropertyDataSize(systemObject, &address, 0, nil, &dataSize)+ guard status == noErr else { return [] }++ let deviceCount = Int(dataSize) / MemoryLayout<AudioDeviceID>.size+ guard deviceCount > 0 else { return [] }++ var devices = [AudioDeviceID](repeating: 0, count: deviceCount)+ status = AudioObjectGetPropertyData(systemObject, &address, 0, nil, &dataSize, &devices)+ guard status == noErr else { return [] }- // Filter to input devices by checking stream configuration for input scopereturn devices.filter { deviceID invar streamAddress = AudioObjectPropertyAddress(mSelector: kAudioDevicePropertyStreamConfiguration,mScope: kAudioObjectPropertyScopeInput,mElement: kAudioObjectPropertyElementMain)-var streamSize: UInt32 = 0- let sizeStatus = AudioObjectGetPropertyDataSize(+ guard AudioObjectGetPropertyDataSize(deviceID,&streamAddress,0,nil,&streamSize- )- guard sizeStatus == noErr, streamSize > 0 else { return false }-- let bufferListPtr = UnsafeMutablePointer<AudioBufferList>.allocate(capacity: 1)- defer { bufferListPtr.deallocate() }+ ) == noErr, streamSize > 0 else {+ return false+ }- let streamStatus = AudioObjectGetPropertyData(+ let bufferList = UnsafeMutableRawPointer.allocate(+ byteCount: Int(streamSize),+ alignment: MemoryLayout<AudioBufferList>.alignment+ )+ defer { bufferList.deallocate() }+ guard AudioObjectGetPropertyData(deviceID,&streamAddress,0,nil,&streamSize,- bufferListPtr- )- guard streamStatus == noErr else { return false }+ bufferList+ ) == 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+ let audioBufferList = bufferList.assumingMemoryBound(to: AudioBufferList.self).pointee+ return audioBufferList.mNumberBuffers > 0 && audioBufferList.mBuffers.mNumberChannels > 0}}-// MARK: - Running State Check-func isDeviceRunning(_ deviceID: AudioDeviceID) -> Bool {var address = AudioObjectPropertyAddress(mSelector: kAudioDevicePropertyDeviceIsRunningSomewhere,@@ -111,122 +326,100 @@ func isDeviceRunning(_ deviceID: AudioDeviceID) -> Bool {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+ var dataSize = UInt32(MemoryLayout<UInt32>.size)+ return AudioObjectGetPropertyData(+ deviceID,+ &address,+ 0,+ nil,+ &dataSize,+ &isRunning+ ) == noErr && isRunning > 0}func isAnyInputRunning() -> Bool {- for device in inputDevices {- if isDeviceRunning(device) {- return true- }- }- return false+ inputDevices.contains(where: isDeviceRunning)}-// MARK: - State Change Handler--func checkAndEmitState() {+func checkAndEmitAggregateState() {let active = isAnyInputRunning()- if active != previouslyActive {- previouslyActive = active+ if active != previouslyAggregateActive {+ previouslyAggregateActive = activeemit(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+let aggregateStateListener: AudioObjectPropertyListenerProc = {+ (_: AudioObjectID,+ _: UInt32,+ _: UnsafePointer<AudioObjectPropertyAddress>,+ _: UnsafeMutableRawPointer?) -> OSStatus in- checkAndEmitState()+ DispatchQueue.main.async {+ checkAndEmitAggregateState()+ }return noErr}-/// Callback for device list changes (kAudioHardwarePropertyDevices) — hot-plug supportlet 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)- }+ (_: AudioObjectID,+ _: UInt32,+ _: UnsafePointer<AudioObjectPropertyAddress>,+ _: UnsafeMutableRawPointer?) -> OSStatus in++ DispatchQueue.main.async {+ let newDevices = getInputDevices()+ let previousDeviceSet = Set(inputDevices)+ let newDeviceSet = Set(newDevices)++ for deviceID in newDeviceSet.subtracting(previousDeviceSet) {+ registerAggregateStateListener(on: deviceID)+ }+ for deviceID in previousDeviceSet.subtracting(newDeviceSet) {+ removeAggregateStateListener(from: 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+ checkAndEmitAggregateState()}-- 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) {+func registerAggregateStateListener(on deviceID: AudioDeviceID) {var address = AudioObjectPropertyAddress(mSelector: kAudioDevicePropertyDeviceIsRunningSomewhere,mScope: kAudioObjectPropertyScopeGlobal,mElement: kAudioObjectPropertyElementMain)-- let status = AudioObjectAddPropertyListener(deviceID, &address, propertyListener, nil)+ let status = AudioObjectAddPropertyListener(deviceID, &address, aggregateStateListener, nil)if status != noErr {emitError("Warning: Failed to register listener on device \(deviceID): \(status)")}}-func removeRunningListener(from deviceID: AudioDeviceID) {+func removeAggregateStateListener(from deviceID: AudioDeviceID) {var address = AudioObjectPropertyAddress(mSelector: kAudioDevicePropertyDeviceIsRunningSomewhere,mScope: kAudioObjectPropertyScopeGlobal,mElement: kAudioObjectPropertyElementMain)-- // Best effort — device may already be disconnected- AudioObjectRemovePropertyListener(deviceID, &address, propertyListener, nil)+ AudioObjectRemovePropertyListener(deviceID, &address, aggregateStateListener, nil)}-func registerListeners() {- // Discover all current input devices+func registerAggregateMonitoring() {inputDevices = getInputDevices()-- // Register running-state listener on each input devicefor deviceID in inputDevices {- registerRunningListener(on: deviceID)+ registerAggregateStateListener(on: deviceID)}- // Register device list change listener on the system object for hot-plug support- var deviceListAddress = AudioObjectPropertyAddress(+ var listAddress = AudioObjectPropertyAddress(mSelector: kAudioHardwarePropertyDevices,mScope: kAudioObjectPropertyScopeGlobal,mElement: kAudioObjectPropertyElementMain)-let status = AudioObjectAddPropertyListener(AudioObjectID(kAudioObjectSystemObject),- &deviceListAddress,+ &listAddress,deviceListListener,nil)@@ -235,63 +428,86 @@ func registerListeners() {}}-func removeAllListeners() {- // Remove running-state listeners from all tracked input devices+func removeAggregateMonitoring() {for deviceID in inputDevices {- removeRunningListener(from: deviceID)+ removeAggregateStateListener(from: deviceID)}+ inputDevices.removeAll()- // Remove device list listener- var deviceListAddress = AudioObjectPropertyAddress(+ var listAddress = AudioObjectPropertyAddress(mSelector: kAudioHardwarePropertyDevices,mScope: kAudioObjectPropertyScopeGlobal,mElement: kAudioObjectPropertyElementMain)AudioObjectRemovePropertyListener(AudioObjectID(kAudioObjectSystemObject),- &deviceListAddress,+ &listAddress,deviceListListener,nil)}-// MARK: - Signal Handling+func startAggregateFallback() {+ if listenerMode == .process || processListListenerRegistered {+ removeProcessMonitoring()+ }+ if listenerMode != .aggregate {+ listenerMode = .aggregate+ registerAggregateMonitoring()+ }-func setupSignalHandlers() {- let signals: [Int32] = [SIGTERM, SIGINT]+ previouslyAggregateActive = isAnyInputRunning()+ emit("CAPABILITY AGGREGATE")+ emit(previouslyAggregateActive ? "MIC_ACTIVE" : "MIC_INACTIVE")+}++func removeAllListeners() {+ switch listenerMode {+ case .process:+ removeProcessMonitoring()+ case .aggregate:+ removeAggregateMonitoring()+ case .none:+ break+ }+}- for sig in signals {- signal(sig, SIG_IGN)- let source = DispatchSource.makeSignalSource(signal: sig, queue: .main)+func setupSignalHandlers() {+ for signalNumber in [SIGTERM, SIGINT] {+ signal(signalNumber, SIG_IGN)+ let source = DispatchSource.makeSignalSource(signal: signalNumber, 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")+if startProcessMonitoring() {+ listenerMode = .process+ emit("CAPABILITY PID")+ for processId in activeInputPids.sorted() {+ emit("MIC_START \(processId)")+ }+} else {+ startAggregateFallback()+}-// Heartbeat: periodic check in case property listeners miss eventslet heartbeatTimer = DispatchSource.makeTimerSource(queue: .main)heartbeatTimer.schedule(deadline: .now() + 5, repeating: 5)heartbeatTimer.setEventHandler {- checkAndEmitState()+ switch listenerMode {+ case .process:+ reconcileProcessMonitoring()+ case .aggregate:+ checkAndEmitAggregateState()+ case .none:+ break+ }}heartbeatTimer.resume()-// Keep the process aliveCFRunLoopRun()diff --git a/resources/windows-mic-listener.c b/resources/windows-mic-listener.cindex 46b369f99..d8a9fa2d8 100644--- a/resources/windows-mic-listener.c+++ b/resources/windows-mic-listener.c@@ -1,19 +1,417 @@/*** 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.+ * Monitors every active WASAPI capture endpoint and emits process-scoped+ * MIC_START/MIC_STOP transitions. PID exclusions are deliberately handled by+ * the JavaScript caller so its live process set can change without restarting+ * this helper. Sessions that cannot be attributed to a single process are+ * reported under pid 0; on an unrecoverable coverage gap the helper announces+ * "CAPABILITY AGGREGATE" and keeps emitting best-effort transitions instead+ * of exiting.** Compile with: cl /O2 windows-mic-listener.c /Fe:windows-mic-listener.exe ole32.lib oleaut32.lib user32.lib* Or with MinGW: gcc -O2 windows-mic-listener.c -o windows-mic-listener.exe -lole32 -loleaut32 -luser32*/+/* Single source of truth for the release tag (windows-mic-listener-v<version>).+ * The publisher workflow tags the release from it and the download script pins+ * to it, so build jobs can never silently pick up a binary built from older+ * source. Bump it on any protocol or behavior change. */+#define MIC_LISTENER_VERSION "1.1.0"++#include <stdbool.h>+#include <stddef.h>+#include <stdio.h>+#include <stdlib.h>++typedef unsigned long MicPid;+typedef void *(*MicAllocate)(size_t size, void *context);+typedef void (*MicDeallocate)(void *memory, void *context);+typedef void (*MicTransition)(MicPid pid, bool active, void *context);++typedef struct MicPidActivity {+ MicPid pid;+ unsigned long activeSessions;+ struct MicPidActivity *next;+} MicPidActivity;++typedef struct MicPidRegistry {+ MicPidActivity *head;+ MicAllocate allocate;+ MicDeallocate deallocate;+ MicTransition transition;+ void *context;+} MicPidRegistry;++typedef struct MicSessionState {+ MicPid pid;+ bool active;+} MicSessionState;++typedef struct MicCoverageSetup {+ bool endpointNotificationsRegistered;+ bool endpointsReconciled;+ bool lifetimeMonitoringReady;+} MicCoverageSetup;++static bool MicCoverageSetupIsReady(+ const MicCoverageSetup *setup,+ bool coverageHealthy,+ bool running)+{+ return setup->endpointNotificationsRegistered &&+ setup->endpointsReconciled &&+ setup->lifetimeMonitoringReady &&+ coverageHealthy &&+ running;+}++static bool MicProcessIdentityIsReliable(long result, MicPid pid)+{+ return result == 0 && pid > 0;+}++#define MIC_SESSION_STATE_ACTIVE 1u+#define MIC_SESSION_STATE_EXPIRED 2u++typedef bool (*MicApplySessionState)(void *session, bool active);+typedef bool (*MicQueueSessionCleanup)(void *session);++static bool MicHandleSessionStateChange(+ unsigned int state,+ void *session,+ MicApplySessionState applyState,+ MicQueueSessionCleanup queueCleanup)+{+ if (!applyState(session, state == MIC_SESSION_STATE_ACTIVE)) {+ return false;+ }+ return state != MIC_SESSION_STATE_EXPIRED || queueCleanup(session);+}++static void *MicDefaultAllocate(size_t size, void *context)+{+ (void)context;+ return calloc(1, size);+}++static void MicDefaultDeallocate(void *memory, void *context)+{+ (void)context;+ free(memory);+}++static void MicPidRegistryInitialize(+ MicPidRegistry *registry,+ MicAllocate allocate,+ MicDeallocate deallocate,+ MicTransition transition,+ void *context)+{+ registry->head = NULL;+ registry->allocate = allocate ? allocate : MicDefaultAllocate;+ registry->deallocate = deallocate ? deallocate : MicDefaultDeallocate;+ registry->transition = transition;+ registry->context = context;+}++static bool MicPidRegistrySetSession(+ MicPidRegistry *registry,+ MicPid pid,+ bool active)+{+ MicPidActivity *activity = registry->head;+ MicPidActivity *previous = NULL;++ while (activity && activity->pid != pid) {+ previous = activity;+ activity = activity->next;+ }++ if (active) {+ if (!activity) {+ activity = (MicPidActivity *)registry->allocate(+ sizeof(MicPidActivity), registry->context);+ if (!activity) {+ return false;+ }+ activity->pid = pid;+ activity->activeSessions = 0;+ activity->next = registry->head;+ registry->head = activity;+ }++ activity->activeSessions++;+ if (activity->activeSessions == 1 && registry->transition) {+ registry->transition(pid, true, registry->context);+ }+ return true;+ }++ if (!activity || activity->activeSessions == 0) {+ return true;+ }++ activity->activeSessions--;+ if (activity->activeSessions == 0) {+ if (registry->transition) {+ registry->transition(pid, false, registry->context);+ }+ if (previous) {+ previous->next = activity->next;+ } else {+ registry->head = activity->next;+ }+ registry->deallocate(activity, registry->context);+ }+ return true;+}++static bool MicSessionSetActive(+ MicPidRegistry *registry,+ MicSessionState *session,+ bool active)+{+ if (session->active == active) {+ return true;+ }+ if (!MicPidRegistrySetSession(registry, session->pid, active)) {+ return false;+ }+ session->active = active;+ return true;+}++static void MicPidRegistryDestroy(MicPidRegistry *registry)+{+ MicPidActivity *activity = registry->head;+ while (activity) {+ MicPidActivity *next = activity->next;+ registry->deallocate(activity, registry->context);+ activity = next;+ }+ registry->head = NULL;+}++#ifdef MIC_LISTENER_STATE_TEST++#include <assert.h>+#include <string.h>++typedef struct TestContext {+ MicPid pids[8];+ bool states[8];+ size_t transitionCount;+ bool failAllocation;+} TestContext;++static void *TestAllocate(size_t size, void *context)+{+ TestContext *testContext = (TestContext *)context;+ if (testContext->failAllocation) {+ return NULL;+ }+ return calloc(1, size);+}++static void TestDeallocate(void *memory, void *context)+{+ (void)context;+ free(memory);+}++static void RecordTransition(MicPid pid, bool active, void *context)+{+ TestContext *testContext = (TestContext *)context;+ assert(testContext->transitionCount < 8);+ testContext->pids[testContext->transitionCount] = pid;+ testContext->states[testContext->transitionCount] = active;+ testContext->transitionCount++;+}++static void TestStateTransitions(void)+{+ TestContext context;+ MicPidRegistry registry;+ MicSessionState first = { 42, false };+ MicSessionState second = { 42, false };+ MicSessionState systemSession = { 0, false };+ MicSessionState failedSetup = { 77, false };++ memset(&context, 0, sizeof(context));+ MicPidRegistryInitialize(+ ®istry, TestAllocate, TestDeallocate, RecordTransition, &context);++ assert(MicSessionSetActive(®istry, &first, true));+ assert(MicSessionSetActive(®istry, &first, true));+ assert(MicSessionSetActive(®istry, &second, true));+ assert(context.transitionCount == 1);+ assert(context.pids[0] == 42 && context.states[0]);++ assert(MicSessionSetActive(®istry, &first, false));+ assert(MicSessionSetActive(®istry, &first, false));+ assert(context.transitionCount == 1);+ assert(MicSessionSetActive(®istry, &second, false));+ assert(context.transitionCount == 2);+ assert(context.pids[1] == 42 && !context.states[1]);++ /* Unattributable sessions (pid 0) refcount and emit like any other pid so+ * the JS caller can treat them as external captures. */+ assert(MicSessionSetActive(®istry, &systemSession, true));+ assert(context.transitionCount == 3);+ assert(context.pids[2] == 0 && context.states[2]);+ assert(MicSessionSetActive(®istry, &systemSession, false));+ assert(context.transitionCount == 4);+ assert(context.pids[3] == 0 && !context.states[3]);++ context.failAllocation = true;+ assert(!MicSessionSetActive(®istry, &failedSetup, true));+ assert(!failedSetup.active);+ assert(context.transitionCount == 4);++ MicPidRegistryDestroy(®istry);+ puts("native state tests passed");+}++static void TestProcessOwnership(void)+{+ assert(MicProcessIdentityIsReliable(0, 42));+ assert(!MicProcessIdentityIsReliable(0, 0));+ assert(!MicProcessIdentityIsReliable(1, 42));+ assert(!MicProcessIdentityIsReliable(0x0889000dL, 42));+ puts("invalid process ownership rejected");+}++typedef struct TestSessionLifecycle {+ unsigned long references;+ unsigned long ownerReferences;+ bool linked;+ bool registered;+ bool controlOwned;+ bool instanceIdOwned;+} TestSessionLifecycle;++static void TestReleaseLinkedSession(TestSessionLifecycle *session)+{+ assert(session->linked);+ assert(session->references > 0);+ session->linked = false;+ session->registered = false;+ session->controlOwned = false;+ session->references--;+}++static void TestReleasePostedCallback(TestSessionLifecycle *session)+{+ assert(session->references == 1);+ session->references--;+ session->instanceIdOwned = false;+ assert(session->ownerReferences == 1);+ session->ownerReferences--;+}++static void TestSessionLifecycleRelease(void)+{+ TestSessionLifecycle session = { 2, 1, true, true, true, true };++ TestReleaseLinkedSession(&session);+ assert(session.references == 1);+ assert(!session.linked);+ assert(!session.registered);+ assert(!session.controlOwned);+ assert(session.instanceIdOwned);+ assert(session.ownerReferences == 1);++ TestReleasePostedCallback(&session);+ assert(session.references == 0);+ assert(!session.instanceIdOwned);+ assert(session.ownerReferences == 0);+ puts("session lifecycle fully released");+}++static void TestCoverageGate(void)+{+ MicCoverageSetup setup = { false, false, false };++ assert(!MicCoverageSetupIsReady(&setup, true, true));+ setup.endpointNotificationsRegistered = true;+ setup.endpointsReconciled = true;+ setup.lifetimeMonitoringReady = true;+ assert(MicCoverageSetupIsReady(&setup, true, true));+ assert(!MicCoverageSetupIsReady(&setup, false, true));+ assert(!MicCoverageSetupIsReady(&setup, true, false));+ puts("unhealthy setup rejected");+}++typedef struct TestStateCallbackContext {+ bool active;+ bool cleanupPosted;+ unsigned long cleanupCount;+} TestStateCallbackContext;++static bool TestApplyState(void *context, bool active)+{+ ((TestStateCallbackContext *)context)->active = active;+ return true;+}++static bool TestQueueCleanup(void *context)+{+ TestStateCallbackContext *state = (TestStateCallbackContext *)context;+ if (!state->cleanupPosted) {+ state->cleanupPosted = true;+ state->cleanupCount++;+ }+ return true;+}++static void TestExpiredStateCallback(void)+{+ TestStateCallbackContext context = { false, false, 0 };++ assert(MicHandleSessionStateChange(+ MIC_SESSION_STATE_ACTIVE, &context, TestApplyState, TestQueueCleanup));+ assert(context.active);+ assert(context.cleanupCount == 0);++ assert(MicHandleSessionStateChange(+ MIC_SESSION_STATE_EXPIRED, &context, TestApplyState, TestQueueCleanup));+ assert(!context.active);+ assert(context.cleanupCount == 1);++ assert(MicHandleSessionStateChange(+ MIC_SESSION_STATE_EXPIRED, &context, TestApplyState, TestQueueCleanup));+ assert(context.cleanupCount == 1);+ puts("expired state queued cleanup once");+}++int main(int argc, char *argv[])+{+ if (argc != 2) return 2;+ if (strcmp(argv[1], "state") == 0) {+ TestStateTransitions();+ } else if (strcmp(argv[1], "ownership") == 0) {+ TestProcessOwnership();+ } else if (strcmp(argv[1], "lifecycle") == 0) {+ TestSessionLifecycleRelease();+ } else if (strcmp(argv[1], "expired-state") == 0) {+ TestExpiredStateCallback();+ } else if (strcmp(argv[1], "coverage") == 0) {+ TestCoverageGate();+ } else {+ return 2;+ }+ return 0;+}++#else+#define WIN32_LEAN_AND_MEAN#define COBJMACROS#define CINTERFACE+#ifndef _WIN32_WINNT+#define _WIN32_WINNT 0x0600+#endif#ifdef _MSC_VER#pragma comment(lib, "user32.lib")@@ -23,17 +421,17 @@#include <initguid.h>#include <mmdeviceapi.h>#include <audiopolicy.h>-#include <stdio.h>-#include <stdlib.h>#include <string.h>+#include <wchar.h>-/* The SDK declares these IIDs via MIDL_INTERFACE for C++ __uuidof only —- * no import library defines them and <initguid.h> skips them in C — so- * they must be defined in-source to link. */+/* The SDK exposes these interface IDs via C++ __uuidof, so C builds define+ * them here rather than depending on compiler-specific UUID extensions. */DEFINE_GUID(CLSID_MMDeviceEnumerator,0xbcde0395, 0xe52f, 0x467c, 0x8e, 0x3d, 0xc4, 0x57, 0x92, 0x91, 0x69, 0x2e);DEFINE_GUID(IID_IMMDeviceEnumerator,0xa95664d2, 0x9614, 0x4f35, 0xa7, 0x46, 0xde, 0x8d, 0xb6, 0x36, 0x17, 0xe6);+DEFINE_GUID(IID_IMMNotificationClient,+ 0x7991eec9, 0x7e89, 0x4d85, 0x83, 0x90, 0x6c, 0x70, 0x3c, 0xec, 0x60, 0xc0);DEFINE_GUID(IID_IAudioSessionManager2,0x77aa99a0, 0x1bd6, 0x484f, 0x8b, 0xc7, 0x2c, 0x65, 0x4c, 0x9a, 0x9b, 0x6f);DEFINE_GUID(IID_IAudioSessionControl2,@@ -43,42 +441,138 @@ DEFINE_GUID(IID_IAudioSessionEvents,DEFINE_GUID(IID_IAudioSessionNotification,0x641dd20b, 0x4d41, 0x49cc, 0xab, 0xa3, 0x17, 0x4b, 0x94, 0x77, 0xbb, 0x08);-static DWORD g_excludePid = 0;-static volatile BOOL g_running = TRUE;--/* ========================================================================- * Forward declarations for COM interface implementations- * ======================================================================== */+#define WM_REFRESH_ENDPOINTS (WM_APP + 1)+#define WM_SESSION_CREATED (WM_APP + 2)+#define WM_SESSION_DISCONNECTED (WM_APP + 3)+typedef struct DeviceMonitor DeviceMonitor;typedef struct SessionEvents SessionEvents;typedef struct SessionNotification SessionNotification;+typedef struct EndpointNotification EndpointNotification;-/* ========================================================================- * IAudioSessionEvents implementation — monitors state changes per session- * ======================================================================== */--typedef struct SessionEvents {+struct SessionEvents {IAudioSessionEventsVtbl *lpVtbl;LONG refCount;- DWORD pid;-} SessionEvents;+ MicSessionState activity;+ IAudioSessionControl *control;+ DeviceMonitor *owner;+ LPWSTR instanceId;+ LONG cleanupPosted;+ BOOL linked;+ BOOL registered;+ SessionEvents *next;+};++struct SessionNotification {+ IAudioSessionNotificationVtbl *lpVtbl;+ LONG refCount;+ DeviceMonitor *owner;+};++struct DeviceMonitor {+ LONG refCount;+ BOOL active;+ unsigned long refreshGeneration;+ LPWSTR deviceId;+ IMMDevice *device;+ IAudioSessionManager2 *manager;+ SessionNotification *notification;+ BOOL notificationRegistered;+ SessionEvents *sessions;+ DeviceMonitor *next;+};++struct EndpointNotification {+ IMMNotificationClientVtbl *lpVtbl;+ LONG refCount;+};++typedef struct CreatedSessionMessage {+ DeviceMonitor *owner;+ IAudioSessionControl *control;+} CreatedSessionMessage;++static MicPidRegistry g_pidRegistry;+static SRWLOCK g_pidRegistryLock = SRWLOCK_INIT;+static DeviceMonitor *g_deviceMonitors = NULL;+static DWORD g_mainThreadId = 0;+static volatile LONG g_running = 1;+static volatile LONG g_coverageLost = 0;+static unsigned long g_refreshGeneration = 0;++static void ReportCoverageLost(const char *operation, HRESULT hr);+static BOOL RegisterSessionOnControl(+ DeviceMonitor *owner,+ IAudioSessionControl *sessionControl);+static void DeviceMonitorAddRef(DeviceMonitor *monitor);+static void DeviceMonitorRelease(DeviceMonitor *monitor);++static void EmitPidTransition(MicPid pid, bool active, void *context)+{+ (void)context;+ printf(active ? "MIC_START %lu\n" : "MIC_STOP %lu\n", pid);+ fflush(stdout);+}++static BOOL SetSessionActive(SessionEvents *session, BOOL active)+{+ bool updated;++ AcquireSRWLockExclusive(&g_pidRegistryLock);+ updated = MicSessionSetActive(+ &g_pidRegistry, &session->activity, active ? true : false);+ ReleaseSRWLockExclusive(&g_pidRegistryLock);++ if (!updated) {+ ReportCoverageLost("record session activity", E_OUTOFMEMORY);+ return FALSE;+ }+ return TRUE;+}++static bool ApplySessionState(void *session, bool active)+{+ return SetSessionActive(+ (SessionEvents *)session, active ? TRUE : FALSE) != FALSE;+}++static bool QueueSessionCleanup(void *session)+{+ SessionEvents *events = (SessionEvents *)session;++ if (InterlockedCompareExchange(&events->cleanupPosted, 1, 0) == 0) {+ IAudioSessionEvents_AddRef((IAudioSessionEvents *)events);+ if (!PostThreadMessage(+ g_mainThreadId,+ WM_SESSION_DISCONNECTED,+ 0,+ (LPARAM)events)) {+ IAudioSessionEvents_Release((IAudioSessionEvents *)events);+ ReportCoverageLost(+ "queue session cleanup", HRESULT_FROM_WIN32(GetLastError()));+ return false;+ }+ }+ return true;+}static HRESULT STDMETHODCALLTYPE SE_QueryInterface(- IAudioSessionEvents *This, REFIID riid, void **ppvObject)+ IAudioSessionEvents *This, REFIID riid, void **object){- if (IsEqualIID(riid, &IID_IUnknown) || IsEqualIID(riid, &IID_IAudioSessionEvents)) {- *ppvObject = This;- This->lpVtbl->AddRef(This);+ if (!object) return E_POINTER;+ if (IsEqualIID(riid, &IID_IUnknown) ||+ IsEqualIID(riid, &IID_IAudioSessionEvents)) {+ *object = This;+ IAudioSessionEvents_AddRef(This);return S_OK;}- *ppvObject = NULL;+ *object = NULL;return E_NOINTERFACE;}static ULONG STDMETHODCALLTYPE SE_AddRef(IAudioSessionEvents *This){- SessionEvents *self = (SessionEvents *)This;- return InterlockedIncrement(&self->refCount);+ return (ULONG)InterlockedIncrement(&((SessionEvents *)This)->refCount);}static ULONG STDMETHODCALLTYPE SE_Release(IAudioSessionEvents *This)@@ -86,82 +580,78 @@ static ULONG STDMETHODCALLTYPE SE_Release(IAudioSessionEvents *This)SessionEvents *self = (SessionEvents *)This;LONG count = InterlockedDecrement(&self->refCount);if (count == 0) {+ DeviceMonitor *owner = self->owner;+ if (self->instanceId) CoTaskMemFree(self->instanceId);+ self->instanceId = NULL;+ self->owner = NULL;free(self);+ if (owner) DeviceMonitorRelease(owner);}- return count;+ return (ULONG)count;}static HRESULT STDMETHODCALLTYPE SE_OnDisplayNameChanged(- IAudioSessionEvents *This, LPCWSTR NewDisplayName, LPCGUID EventContext)+ IAudioSessionEvents *This, LPCWSTR name, LPCGUID context){- (void)This; (void)NewDisplayName; (void)EventContext;+ (void)This; (void)name; (void)context;return S_OK;}static HRESULT STDMETHODCALLTYPE SE_OnIconPathChanged(- IAudioSessionEvents *This, LPCWSTR NewIconPath, LPCGUID EventContext)+ IAudioSessionEvents *This, LPCWSTR path, LPCGUID context){- (void)This; (void)NewIconPath; (void)EventContext;+ (void)This; (void)path; (void)context;return S_OK;}static HRESULT STDMETHODCALLTYPE SE_OnSimpleVolumeChanged(- IAudioSessionEvents *This, float NewVolume, BOOL NewMute, LPCGUID EventContext)+ IAudioSessionEvents *This, float volume, BOOL muted, LPCGUID context){- (void)This; (void)NewVolume; (void)NewMute; (void)EventContext;+ (void)This; (void)volume; (void)muted; (void)context;return S_OK;}static HRESULT STDMETHODCALLTYPE SE_OnChannelVolumeChanged(- IAudioSessionEvents *This, DWORD ChannelCount, float NewChannelVolumeArray[],- DWORD ChangedChannel, LPCGUID EventContext)+ IAudioSessionEvents *This,+ DWORD channelCount,+ float volumes[],+ DWORD changedChannel,+ LPCGUID context){- (void)This; (void)ChannelCount; (void)NewChannelVolumeArray;- (void)ChangedChannel; (void)EventContext;+ (void)This; (void)channelCount; (void)volumes;+ (void)changedChannel; (void)context;return S_OK;}static HRESULT STDMETHODCALLTYPE SE_OnGroupingParamChanged(- IAudioSessionEvents *This, LPCGUID NewGroupingParam, LPCGUID EventContext)+ IAudioSessionEvents *This, LPCGUID grouping, LPCGUID context){- (void)This; (void)NewGroupingParam; (void)EventContext;+ (void)This; (void)grouping; (void)context;return S_OK;}static HRESULT STDMETHODCALLTYPE SE_OnStateChanged(- IAudioSessionEvents *This, AudioSessionState NewState)+ 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);- }-+ MicHandleSessionStateChange(+ (unsigned int)newState,+ This,+ ApplySessionState,+ QueueSessionCleanup);return S_OK;}static HRESULT STDMETHODCALLTYPE SE_OnSessionDisconnected(- IAudioSessionEvents *This, AudioSessionDisconnectReason DisconnectReason)+ IAudioSessionEvents *This,+ AudioSessionDisconnectReason reason){- 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);+ (void)reason;+ MicHandleSessionStateChange(+ MIC_SESSION_STATE_EXPIRED,+ This,+ ApplySessionState,+ QueueSessionCleanup);return S_OK;}@@ -178,41 +668,44 @@ static IAudioSessionEventsVtbl g_sessionEventsVtbl = {SE_OnSessionDisconnected};-static SessionEvents *CreateSessionEvents(DWORD pid)+static SessionEvents *CreateSessionEvents(+ DeviceMonitor *owner,+ IAudioSessionControl *control,+ DWORD pid,+ LPWSTR instanceId){- SessionEvents *se = (SessionEvents *)calloc(1, sizeof(SessionEvents));- if (!se) return NULL;- se->lpVtbl = &g_sessionEventsVtbl;- se->refCount = 1;- se->pid = pid;- return se;+ SessionEvents *events = (SessionEvents *)calloc(1, sizeof(SessionEvents));+ if (!events) return NULL;++ events->lpVtbl = &g_sessionEventsVtbl;+ events->refCount = 1;+ events->activity.pid = (MicPid)pid;+ events->activity.active = false;+ events->owner = owner;+ events->control = control;+ events->instanceId = instanceId;+ IAudioSessionControl_AddRef(control);+ DeviceMonitorAddRef(owner);+ return events;}-/* ========================================================================- * 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)+ IAudioSessionNotification *This, REFIID riid, void **object){- if (IsEqualIID(riid, &IID_IUnknown) || IsEqualIID(riid, &IID_IAudioSessionNotification)) {- *ppvObject = This;- This->lpVtbl->AddRef(This);+ if (!object) return E_POINTER;+ if (IsEqualIID(riid, &IID_IUnknown) ||+ IsEqualIID(riid, &IID_IAudioSessionNotification)) {+ *object = This;+ IAudioSessionNotification_AddRef(This);return S_OK;}- *ppvObject = NULL;+ *object = NULL;return E_NOINTERFACE;}static ULONG STDMETHODCALLTYPE SN_AddRef(IAudioSessionNotification *This){- SessionNotification *self = (SessionNotification *)This;- return InterlockedIncrement(&self->refCount);+ return (ULONG)InterlockedIncrement(&((SessionNotification *)This)->refCount);}static ULONG STDMETHODCALLTYPE SN_Release(IAudioSessionNotification *This)@@ -220,19 +713,40 @@ static ULONG STDMETHODCALLTYPE SN_Release(IAudioSessionNotification *This)SessionNotification *self = (SessionNotification *)This;LONG count = InterlockedDecrement(&self->refCount);if (count == 0) {+ DeviceMonitor *owner = self->owner;+ self->owner = NULL;free(self);+ if (owner) DeviceMonitorRelease(owner);}- return count;+ return (ULONG)count;}-static void RegisterSessionEventsOnControl(IAudioSessionControl *pSessionControl);-static HRESULT STDMETHODCALLTYPE SN_OnSessionCreated(- IAudioSessionNotification *This, IAudioSessionControl *NewSession)+ IAudioSessionNotification *This, IAudioSessionControl *newSession){- (void)This;- if (NewSession) {- RegisterSessionEventsOnControl(NewSession);+ SessionNotification *self = (SessionNotification *)This;+ CreatedSessionMessage *message;++ if (!newSession) return E_POINTER;++ message = (CreatedSessionMessage *)calloc(1, sizeof(CreatedSessionMessage));+ if (!message) {+ ReportCoverageLost("allocate session notification", E_OUTOFMEMORY);+ return E_OUTOFMEMORY;+ }++ DeviceMonitorAddRef(self->owner);+ IAudioSessionControl_AddRef(newSession);+ message->owner = self->owner;+ message->control = newSession;+ if (!PostThreadMessage(+ g_mainThreadId, WM_SESSION_CREATED, 0, (LPARAM)message)) {+ HRESULT hr = HRESULT_FROM_WIN32(GetLastError());+ IAudioSessionControl_Release(newSession);+ DeviceMonitorRelease(self->owner);+ free(message);+ ReportCoverageLost("queue new session", hr);+ return hr;}return S_OK;}@@ -244,227 +758,668 @@ static IAudioSessionNotificationVtbl g_sessionNotificationVtbl = {SN_OnSessionCreated};-static SessionNotification *CreateSessionNotification(void)+static SessionNotification *CreateSessionNotification(DeviceMonitor *owner){- SessionNotification *sn = (SessionNotification *)calloc(1, sizeof(SessionNotification));- if (!sn) return NULL;- sn->lpVtbl = &g_sessionNotificationVtbl;- sn->refCount = 1;- return sn;+ SessionNotification *notification =+ (SessionNotification *)calloc(1, sizeof(SessionNotification));+ if (!notification) return NULL;+ notification->lpVtbl = &g_sessionNotificationVtbl;+ notification->refCount = 1;+ notification->owner = owner;+ DeviceMonitorAddRef(owner);+ return notification;}-/* ========================================================================- * Helper: register IAudioSessionEvents on a session control- * ======================================================================== */+static void DeviceMonitorAddRef(DeviceMonitor *monitor)+{+ InterlockedIncrement(&monitor->refCount);+}-static void RegisterSessionEventsOnControl(IAudioSessionControl *pSessionControl)+static void DeviceMonitorRelease(DeviceMonitor *monitor){- IAudioSessionControl2 *pCtl2 = NULL;- HRESULT hr;+ if (InterlockedDecrement(&monitor->refCount) == 0) {+ free(monitor);+ }+}- hr = pSessionControl->lpVtbl->QueryInterface(- pSessionControl, &IID_IAudioSessionControl2, (void **)&pCtl2);- if (FAILED(hr) || !pCtl2) {- return;+static SessionEvents *FindSession(+ DeviceMonitor *owner,+ LPCWSTR instanceId)+{+ SessionEvents *session = owner->sessions;+ while (session) {+ if (session->instanceId && wcscmp(session->instanceId, instanceId) == 0) {+ return session;+ }+ session = session->next;}+ return NULL;+}- DWORD pid = 0;- pCtl2->lpVtbl->GetProcessId(pCtl2, &pid);+static void UnlinkSession(DeviceMonitor *owner, SessionEvents *target)+{+ SessionEvents **cursor = &owner->sessions;+ while (*cursor) {+ if (*cursor == target) {+ *cursor = target->next;+ target->next = NULL;+ target->linked = FALSE;+ return;+ }+ cursor = &(*cursor)->next;+ }+}- 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 */+static void StopMonitoringSession(SessionEvents *events)+{+ if (events->registered && events->control) {+ IAudioSessionControl_UnregisterAudioSessionNotification(+ events->control, (IAudioSessionEvents *)events);+ events->registered = FALSE;}+ SetSessionActive(events, FALSE);+ if (events->control) {+ IAudioSessionControl_Release(events->control);+ events->control = NULL;+ }+}- /* Also check current state and emit if already active */+static void ReleaseOwnedSession(SessionEvents *events)+{+ if (events->linked && events->owner) {+ UnlinkSession(events->owner, events);+ }+ StopMonitoringSession(events);+ IAudioSessionEvents_Release((IAudioSessionEvents *)events);+}++static BOOL RegisterSessionOnControl(+ DeviceMonitor *owner,+ IAudioSessionControl *sessionControl)+{+ IAudioSessionControl2 *control2 = NULL;+ LPWSTR instanceId = NULL;+ SessionEvents *events = NULL;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);- }+ DWORD pid = 0;+ HRESULT hr;++ hr = IAudioSessionControl_QueryInterface(+ sessionControl, &IID_IAudioSessionControl2, (void **)&control2);+ if (FAILED(hr) || !control2) goto fail;++ hr = IAudioSessionControl2_GetProcessId(control2, &pid);+ if (!MicProcessIdentityIsReliable((long)hr, (MicPid)pid)) {+ /* Sessions that cannot be attributed (e.g. cross-process ones returning+ * AUDCLNT_S_NO_SINGLE_PROCESS) are reported under pid 0. The JS caller+ * can never exclude pid 0 as its own, so such a session counts as an+ * external capture — auto-end stays parked while it is active instead+ * of the helper giving up. */+ pid = 0;+ }++ hr = IAudioSessionControl2_GetSessionInstanceIdentifier(control2, &instanceId);+ if (FAILED(hr) || !instanceId) goto fail;++ if (FindSession(owner, instanceId)) {+ CoTaskMemFree(instanceId);+ IAudioSessionControl2_Release(control2);+ return TRUE;}- pCtl2->lpVtbl->Release(pCtl2);+ events = CreateSessionEvents(owner, sessionControl, pid, instanceId);+ if (!events) {+ hr = E_OUTOFMEMORY;+ goto fail;+ }+ instanceId = NULL;+ events->next = owner->sessions;+ owner->sessions = events;+ events->linked = TRUE;++ hr = IAudioSessionControl_RegisterAudioSessionNotification(+ sessionControl, (IAudioSessionEvents *)events);+ if (FAILED(hr)) goto fail_registered;+ events->registered = TRUE;++ hr = IAudioSessionControl_GetState(sessionControl, &state);+ if (FAILED(hr)) goto fail_registered;+ if (!SetSessionActive(events, state == AudioSessionStateActive)) {+ hr = E_FAIL;+ goto fail_registered;+ }++ IAudioSessionControl2_Release(control2);+ return TRUE;++fail_registered:+ ReleaseOwnedSession(events);+fail:+ if (instanceId) CoTaskMemFree(instanceId);+ if (control2) IAudioSessionControl2_Release(control2);+ fprintf(stderr, "Error: Failed to register capture session (0x%08lx)\n",+ (unsigned long)hr);+ return FALSE;}-/* ========================================================================- * Monitor capture sessions on a single device- * ======================================================================== */+static void CleanupDeviceMonitor(DeviceMonitor *monitor)+{+ SessionEvents *session;++ monitor->active = FALSE;+ if (monitor->notificationRegistered && monitor->manager) {+ IAudioSessionManager2_UnregisterSessionNotification(+ monitor->manager,+ (IAudioSessionNotification *)monitor->notification);+ monitor->notificationRegistered = FALSE;+ }-static void MonitorDevice(IMMDevice *pDevice)+ while ((session = monitor->sessions) != NULL) {+ ReleaseOwnedSession(session);+ }++ if (monitor->notification) {+ IAudioSessionNotification_Release(+ (IAudioSessionNotification *)monitor->notification);+ monitor->notification = NULL;+ }+ if (monitor->manager) {+ IAudioSessionManager2_Release(monitor->manager);+ monitor->manager = NULL;+ }+ if (monitor->device) {+ IMMDevice_Release(monitor->device);+ monitor->device = NULL;+ }+ if (monitor->deviceId) {+ CoTaskMemFree(monitor->deviceId);+ monitor->deviceId = NULL;+ }+ DeviceMonitorRelease(monitor);+}++static DeviceMonitor *CreateDeviceMonitor(+ IMMDevice *device,+ LPWSTR deviceId,+ unsigned long refreshGeneration){- IAudioSessionManager2 *pSessionMgr = NULL;+ DeviceMonitor *monitor = NULL;+ IAudioSessionEnumerator *sessionEnumerator = NULL;+ int sessionCount = 0;HRESULT hr;- hr = pDevice->lpVtbl->Activate(- pDevice,+ monitor = (DeviceMonitor *)calloc(1, sizeof(DeviceMonitor));+ if (!monitor) {+ hr = E_OUTOFMEMORY;+ goto fail;+ }+ monitor->refCount = 1;+ monitor->active = TRUE;+ monitor->refreshGeneration = refreshGeneration;+ monitor->device = device;+ monitor->deviceId = deviceId;++ hr = IMMDevice_Activate(+ device,&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 */+ (void **)&monitor->manager);+ if (FAILED(hr) || !monitor->manager) goto fail;++ monitor->notification = CreateSessionNotification(monitor);+ if (!monitor->notification) {+ hr = E_OUTOFMEMORY;+ goto fail;+ }+ hr = IAudioSessionManager2_RegisterSessionNotification(+ monitor->manager,+ (IAudioSessionNotification *)monitor->notification);+ if (FAILED(hr)) goto fail;+ monitor->notificationRegistered = TRUE;++ hr = IAudioSessionManager2_GetSessionEnumerator(+ monitor->manager, &sessionEnumerator);+ if (FAILED(hr) || !sessionEnumerator) goto fail;++ hr = IAudioSessionEnumerator_GetCount(sessionEnumerator, &sessionCount);+ if (FAILED(hr)) goto fail;++ for (int index = 0; index < sessionCount; index++) {+ IAudioSessionControl *sessionControl = NULL;+ hr = IAudioSessionEnumerator_GetSession(+ sessionEnumerator, index, &sessionControl);+ if (FAILED(hr) || !sessionControl) goto fail;++ if (!RegisterSessionOnControl(monitor, sessionControl)) {+ IAudioSessionControl_Release(sessionControl);+ hr = E_FAIL;+ goto fail;+ }+ IAudioSessionControl_Release(sessionControl);+ }++ IAudioSessionEnumerator_Release(sessionEnumerator);+ return monitor;++fail:+ if (sessionEnumerator) IAudioSessionEnumerator_Release(sessionEnumerator);+ if (monitor) {+ CleanupDeviceMonitor(monitor);+ } else {+ if (deviceId) CoTaskMemFree(deviceId);+ if (device) IMMDevice_Release(device);+ }+ fprintf(stderr, "Error: Failed to monitor capture endpoint (0x%08lx)\n",+ (unsigned long)hr);+ return NULL;+}++static DeviceMonitor *FindDeviceMonitor(LPCWSTR deviceId)+{+ DeviceMonitor *monitor = g_deviceMonitors;+ while (monitor) {+ if (monitor->deviceId && wcscmp(monitor->deviceId, deviceId) == 0) {+ return monitor;+ }+ monitor = monitor->next;+ }+ return NULL;+}++static BOOL RefreshDeviceMonitors(IMMDeviceEnumerator *enumerator)+{+ IMMDeviceCollection *collection = NULL;+ unsigned long generation = ++g_refreshGeneration;+ UINT deviceCount = 0;+ HRESULT hr;++ hr = IMMDeviceEnumerator_EnumAudioEndpoints(+ enumerator, eCapture, DEVICE_STATE_ACTIVE, &collection);+ if (FAILED(hr) || !collection) goto fail;++ hr = IMMDeviceCollection_GetCount(collection, &deviceCount);+ if (FAILED(hr)) goto fail;++ for (UINT index = 0; index < deviceCount; index++) {+ IMMDevice *device = NULL;+ LPWSTR deviceId = NULL;+ DeviceMonitor *monitor;++ hr = IMMDeviceCollection_Item(collection, index, &device);+ if (FAILED(hr) || !device) goto fail;++ hr = IMMDevice_GetId(device, &deviceId);+ if (FAILED(hr) || !deviceId) {+ IMMDevice_Release(device);+ goto fail;+ }++ monitor = FindDeviceMonitor(deviceId);+ if (monitor) {+ monitor->refreshGeneration = generation;+ CoTaskMemFree(deviceId);+ IMMDevice_Release(device);+ continue;+ }++ monitor = CreateDeviceMonitor(device, deviceId, generation);+ if (!monitor) {+ hr = E_FAIL;+ goto fail;+ }+ monitor->next = g_deviceMonitors;+ g_deviceMonitors = monitor;+ }++ {+ DeviceMonitor **cursor = &g_deviceMonitors;+ while (*cursor) {+ DeviceMonitor *monitor = *cursor;+ if (monitor->refreshGeneration != generation) {+ *cursor = monitor->next;+ monitor->next = NULL;+ CleanupDeviceMonitor(monitor);+ } else {+ cursor = &monitor->next;}}- /* Don't release pEnum — keep references alive */}- /* Don't release pSessionMgr — notifications require it to stay alive */+ IMMDeviceCollection_Release(collection);+ return TRUE;++fail:+ if (collection) IMMDeviceCollection_Release(collection);+ fprintf(stderr, "Error: Failed to refresh capture endpoints (0x%08lx)\n",+ (unsigned long)hr);+ return FALSE;}-/* ========================================================================- * Console handler for clean shutdown- * ======================================================================== */+static void QueueEndpointRefresh(void)+{+ if (!PostThreadMessage(g_mainThreadId, WM_REFRESH_ENDPOINTS, 0, 0)) {+ ReportCoverageLost("queue endpoint refresh", HRESULT_FROM_WIN32(GetLastError()));+ }+}++static HRESULT STDMETHODCALLTYPE EN_QueryInterface(+ IMMNotificationClient *This, REFIID riid, void **object)+{+ if (!object) return E_POINTER;+ if (IsEqualIID(riid, &IID_IUnknown) ||+ IsEqualIID(riid, &IID_IMMNotificationClient)) {+ *object = This;+ IMMNotificationClient_AddRef(This);+ return S_OK;+ }+ *object = NULL;+ return E_NOINTERFACE;+}++static ULONG STDMETHODCALLTYPE EN_AddRef(IMMNotificationClient *This)+{+ return (ULONG)InterlockedIncrement(&((EndpointNotification *)This)->refCount);+}++static ULONG STDMETHODCALLTYPE EN_Release(IMMNotificationClient *This)+{+ EndpointNotification *self = (EndpointNotification *)This;+ LONG count = InterlockedDecrement(&self->refCount);+ if (count == 0) free(self);+ return (ULONG)count;+}++static HRESULT STDMETHODCALLTYPE EN_OnDeviceStateChanged(+ IMMNotificationClient *This, LPCWSTR deviceId, DWORD newState)+{+ (void)This; (void)deviceId; (void)newState;+ QueueEndpointRefresh();+ return S_OK;+}++static HRESULT STDMETHODCALLTYPE EN_OnDeviceAdded(+ IMMNotificationClient *This, LPCWSTR deviceId)+{+ (void)This; (void)deviceId;+ QueueEndpointRefresh();+ return S_OK;+}++static HRESULT STDMETHODCALLTYPE EN_OnDeviceRemoved(+ IMMNotificationClient *This, LPCWSTR deviceId)+{+ (void)This; (void)deviceId;+ QueueEndpointRefresh();+ return S_OK;+}++static HRESULT STDMETHODCALLTYPE EN_OnDefaultDeviceChanged(+ IMMNotificationClient *This,+ EDataFlow flow,+ ERole role,+ LPCWSTR defaultDeviceId)+{+ (void)This; (void)flow; (void)role; (void)defaultDeviceId;+ QueueEndpointRefresh();+ return S_OK;+}++static HRESULT STDMETHODCALLTYPE EN_OnPropertyValueChanged(+ IMMNotificationClient *This,+ LPCWSTR deviceId,+ const PROPERTYKEY key)+{+ (void)This; (void)deviceId; (void)key;+ QueueEndpointRefresh();+ return S_OK;+}++static IMMNotificationClientVtbl g_endpointNotificationVtbl = {+ EN_QueryInterface,+ EN_AddRef,+ EN_Release,+ EN_OnDeviceStateChanged,+ EN_OnDeviceAdded,+ EN_OnDeviceRemoved,+ EN_OnDefaultDeviceChanged,+ EN_OnPropertyValueChanged+};++static EndpointNotification *CreateEndpointNotification(void)+{+ EndpointNotification *notification =+ (EndpointNotification *)calloc(1, sizeof(EndpointNotification));+ if (!notification) return NULL;+ notification->lpVtbl = &g_endpointNotificationVtbl;+ notification->refCount = 1;+ return notification;+}++/* A coverage gap means per-PID data can no longer be trusted, but degraded+ * MIC_START/MIC_STOP reporting still beats exiting (the JS caller has no+ * respawn, and its polling fallback only knows a few process names). Announce+ * the one-way downgrade so the consumer stops treating the data as reliable,+ * and keep running. Setup-time losses still abort via MicCoverageSetupIsReady,+ * which gates the READY/CAPABILITY handshake on g_coverageLost. */+static void ReportCoverageLost(const char *operation, HRESULT hr)+{+ if (InterlockedCompareExchange(&g_coverageLost, 1, 0) == 0) {+ fprintf(stderr, "Warning: Lost microphone coverage while attempting to %s (0x%08lx)\n",+ operation, (unsigned long)hr);+ printf("CAPABILITY AGGREGATE\n");+ fflush(stdout);+ }+}++static void HandleCreatedSession(CreatedSessionMessage *message)+{+ if (message->owner->active &&+ !RegisterSessionOnControl(message->owner, message->control)) {+ ReportCoverageLost("monitor new capture session", E_FAIL);+ }+ IAudioSessionControl_Release(message->control);+ DeviceMonitorRelease(message->owner);+ free(message);+}++static void HandleDisconnectedSession(SessionEvents *session)+{+ if (session->linked) ReleaseOwnedSession(session);+ IAudioSessionEvents_Release((IAudioSessionEvents *)session);+}++static void DrainPendingMessages(void)+{+ MSG message;+ while (PeekMessage(&message, NULL, WM_APP, WM_APP + 3, PM_REMOVE)) {+ if (message.message == WM_SESSION_CREATED) {+ HandleCreatedSession((CreatedSessionMessage *)message.lParam);+ } else if (message.message == WM_SESSION_DISCONNECTED) {+ HandleDisconnectedSession((SessionEvents *)message.lParam);+ }+ }+}++static void CleanupAllDevices(void)+{+ DeviceMonitor *monitor = g_deviceMonitors;+ g_deviceMonitors = NULL;+ while (monitor) {+ DeviceMonitor *next = monitor->next;+ monitor->next = NULL;+ CleanupDeviceMonitor(monitor);+ monitor = next;+ }+}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);+ if (signal == CTRL_C_EVENT ||+ signal == CTRL_BREAK_EVENT ||+ signal == CTRL_CLOSE_EVENT) {+ InterlockedExchange(&g_running, 0);+ PostThreadMessage(g_mainThreadId, WM_QUIT, 0, 0);return TRUE;}return FALSE;}-/* ========================================================================- * Stdin monitoring thread — detect parent process death- * ======================================================================== */--static DWORD WINAPI StdinMonitorThread(LPVOID param)+static DWORD WINAPI StdinMonitorThread(LPVOID parameter){- DWORD mainThreadId = (DWORD)(DWORD_PTR)param;- char buf[64];- HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);+ char buffer[64];+ HANDLE stdinHandle = GetStdHandle(STD_INPUT_HANDLE);+ (void)parameter;- while (g_running) {+ while (InterlockedCompareExchange(&g_running, 1, 1)) {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);+ BOOL read = ReadFile(+ stdinHandle, buffer, sizeof(buffer), &bytesRead, NULL);+ if (!read || bytesRead == 0) {+ InterlockedExchange(&g_running, 0);+ PostThreadMessage(g_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);+ IMMDeviceEnumerator *enumerator = NULL;+ EndpointNotification *endpointNotification = NULL;+ BOOL endpointRegistered = FALSE;+ BOOL consoleHandlerRegistered = FALSE;+ BOOL comInitialized = FALSE;+ HANDLE stdinThread = NULL;+ MicCoverageSetup setup = { false, false, false };+ MSG message;+ HRESULT hr = E_FAIL;+ int exitCode = 1;+ (void)argc;+ (void)argv;++ g_mainThreadId = GetCurrentThreadId();+ PeekMessage(&message, NULL, WM_USER, WM_USER, PM_NOREMOVE);+ MicPidRegistryInitialize(+ &g_pidRegistry, NULL, NULL, EmitPidTransition, NULL);++ hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);if (FAILED(hr)) {fprintf(stderr, "Error: CoInitializeEx failed (0x%08lx)\n", (unsigned long)hr);- return 1;+ goto cleanup;}+ comInitialized = TRUE;- /* 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;+ (void **)&enumerator);+ if (FAILED(hr) || !enumerator) {+ fprintf(stderr, "Error: Failed to create device enumerator (0x%08lx)\n",+ (unsigned long)hr);+ goto cleanup;}- /* 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;+ endpointNotification = CreateEndpointNotification();+ if (!endpointNotification) {+ hr = E_OUTOFMEMORY;+ fprintf(stderr, "Error: Failed to create endpoint notification\n");+ goto cleanup;}- 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 */- }+ hr = IMMDeviceEnumerator_RegisterEndpointNotificationCallback(+ enumerator, (IMMNotificationClient *)endpointNotification);+ if (FAILED(hr)) {+ fprintf(stderr, "Error: Failed to register endpoint notification (0x%08lx)\n",+ (unsigned long)hr);+ goto cleanup;}+ endpointRegistered = TRUE;+ setup.endpointNotificationsRegistered = true;- /* Set up console handler for clean shutdown */- SetConsoleCtrlHandler(ConsoleHandler, TRUE);+ if (!RefreshDeviceMonitors(enumerator)) {+ hr = E_FAIL;+ goto cleanup;+ }+ setup.endpointsReconciled = 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);+ if (!SetConsoleCtrlHandler(ConsoleHandler, TRUE)) {+ hr = HRESULT_FROM_WIN32(GetLastError());+ fprintf(stderr, "Error: Failed to register console handler (0x%08lx)\n",+ (unsigned long)hr);+ goto cleanup;+ }+ consoleHandlerRegistered = TRUE;++ stdinThread = CreateThread(NULL, 0, StdinMonitorThread, NULL, 0, NULL);+ if (!stdinThread) {+ hr = HRESULT_FROM_WIN32(GetLastError());+ fprintf(stderr, "Error: Failed to start stdin monitor (0x%08lx)\n",+ (unsigned long)hr);+ goto cleanup;+ }+ CloseHandle(stdinThread);+ stdinThread = NULL;+ setup.lifetimeMonitoringReady = true;++ if (!MicCoverageSetupIsReady(+ &setup,+ InterlockedCompareExchange(&g_coverageLost, 0, 0) == 0,+ InterlockedCompareExchange(&g_running, 1, 1) != 0)) {+ hr = E_UNEXPECTED;+ goto cleanup;}- /* Signal readiness */printf("READY\n");+ /* Distinct from READY (which pre-refcounting builds also print) so the JS+ * consumer only trusts per-PID data from binaries that actually provide it. */+ printf("CAPABILITY PID\n");fflush(stdout);+ exitCode = 0;++ while (InterlockedCompareExchange(&g_running, 1, 1)) {+ BOOL result = GetMessage(&message, NULL, 0, 0);+ if (result <= 0) break;- /* Message loop — keeps the process alive */- MSG msg;- while (g_running && GetMessage(&msg, NULL, 0, 0) > 0) {- TranslateMessage(&msg);- DispatchMessage(&msg);+ if (message.message == WM_REFRESH_ENDPOINTS) {+ if (!RefreshDeviceMonitors(enumerator)) {+ ReportCoverageLost("refresh capture endpoints", E_FAIL);+ }+ } else if (message.message == WM_SESSION_CREATED) {+ HandleCreatedSession((CreatedSessionMessage *)message.lParam);+ } else if (message.message == WM_SESSION_DISCONNECTED) {+ HandleDisconnectedSession((SessionEvents *)message.lParam);+ } else {+ TranslateMessage(&message);+ DispatchMessage(&message);+ }}- /* Cleanup */- pCollection->lpVtbl->Release(pCollection);- pEnumerator->lpVtbl->Release(pEnumerator);- CoUninitialize();+ if (InterlockedCompareExchange(&g_coverageLost, 0, 0)) exitCode = 2;- return 0;+cleanup:+ InterlockedExchange(&g_running, 0);+ if (endpointRegistered) {+ IMMDeviceEnumerator_UnregisterEndpointNotificationCallback(+ enumerator, (IMMNotificationClient *)endpointNotification);+ }+ DrainPendingMessages();+ CleanupAllDevices();+ DrainPendingMessages();+ if (endpointNotification) {+ IMMNotificationClient_Release(+ (IMMNotificationClient *)endpointNotification);+ }+ if (enumerator) IMMDeviceEnumerator_Release(enumerator);+ if (consoleHandlerRegistered) SetConsoleCtrlHandler(ConsoleHandler, FALSE);+ AcquireSRWLockExclusive(&g_pidRegistryLock);+ MicPidRegistryDestroy(&g_pidRegistry);+ ReleaseSRWLockExclusive(&g_pidRegistryLock);+ if (comInitialized) CoUninitialize();+ return exitCode;}++#endifdiff --git a/scripts/download-windows-mic-listener.js b/scripts/download-windows-mic-listener.jsindex c0289158c..e957c92b4 100644--- a/scripts/download-windows-mic-listener.js+++ b/scripts/download-windows-mic-listener.js@@ -8,6 +8,10 @@** Options:* --force Re-download even if binary already exists+ *+ * The release tag is pinned to MIC_LISTENER_VERSION in the C source (override+ * with the WINDOWS_MIC_LISTENER_VERSION env var). In CI a failed download+ * fails the job; locally it falls back to polling mode.*/const fs = require("fs");@@ -23,12 +27,41 @@ 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";+const SOURCE_FILE = path.join(__dirname, "..", "resources", "windows-mic-listener.c");-// Version can be pinned via environment variable for reproducible builds+// Full tag override via environment variable (e.g. windows-mic-listener-v1.1.0)const VERSION_OVERRIDE = process.env.WINDOWS_MIC_LISTENER_VERSION || null;const BIN_DIR = path.join(__dirname, "..", "resources", "bin");+// The C source's MIC_LISTENER_VERSION is the single source of truth for which+// release tag matches this checkout, so a build can never silently pick up a+// binary published from older source (the publisher workflow tags from the+// same constant).+function readPinnedTag() {+ const source = fs.readFileSync(SOURCE_FILE, "utf8");+ const match = source.match(/MIC_LISTENER_VERSION "([0-9.]+)"/);+ if (!match) {+ throw new Error(`MIC_LISTENER_VERSION not found in ${SOURCE_FILE}`);+ }+ return `${TAG_PREFIX}${match[1]}`;+}++// CI must never fall back to polling silently — a missing pinned release means+// the publisher workflow has not finished (or failed) and the job should retry+// instead of baking a stale or absent binary into the build cache.+function failDownload(message) {+ console.error(`[windows-mic-listener] ${message}`);+ if (process.env.CI) {+ process.exitCode = 1;+ return;+ }+ 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"+ );+}+async function main() {// Only needed on Windowsif (process.platform !== "win32") {@@ -46,28 +79,21 @@ async function main() {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 tagToFind = VERSION_OVERRIDE || readPinnedTag();+ console.log(`\n[windows-mic-listener] Using pinned version: ${tagToFind}`);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)");+ failDownload(`Could not find a release matching: ${tagToFind}`);return;}// Find the zip assetconst 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(", ")+ failDownload(+ `Release ${release.tag} does not contain ${ZIP_NAME} ` ++ `(available: ${release.assets.map((a) => a.name).join(", ")})`);return;}@@ -111,22 +137,15 @@ async function main() {`\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 failureif (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"- );+ failDownload(`Download failed: ${error.message}`);}}main().catch((error) => {- console.error("[windows-mic-listener] Unexpected error:", error);- // Don't fail the build+ failDownload(`Unexpected error: ${error.message}`);});diff --git a/src/components/MeetingNotificationCard.tsx b/src/components/MeetingNotificationCard.tsxindex 31fae373c..2814547bc 100644--- a/src/components/MeetingNotificationCard.tsx+++ b/src/components/MeetingNotificationCard.tsx@@ -8,6 +8,7 @@ interface MeetingNotificationCardProps {onDismiss?: () => void;/** Controls the close button's hover fade. Ignored when `onDismiss` is absent. */closeVisible?: boolean;+ allowTitleWrap?: boolean;className?: string;onMouseEnter?: () => void;onMouseLeave?: () => void;@@ -26,6 +27,7 @@ export function MeetingNotificationCard({onStart,onDismiss,closeVisible = true,+ allowTitleWrap = false,className = "",onMouseEnter,onMouseLeave,@@ -70,15 +72,22 @@ export function MeetingNotificationCard({</div><div className="flex-1 min-w-0">- <p className="text-[12px] font-semibold text-foreground leading-tight truncate">+ <p+ className={[+ "text-[12px] font-semibold text-foreground leading-tight",+ allowTitleWrap ? "whitespace-normal break-words" : "truncate",+ ].join(" ")}+ >{title}</p>- <p className="text-[11px] text-muted-foreground leading-tight mt-0.5">{body}</p>+ <p className="text-[11px] text-muted-foreground leading-tight mt-0.5 break-words">+ {body}+ </p></div><buttononClick={onStart}- className="shrink-0 bg-primary text-primary-foreground hover:bg-primary/90 text-[11px] font-medium px-2.5 py-1 rounded-md transition-colors"+ className="shrink-0 whitespace-nowrap bg-primary text-primary-foreground hover:bg-primary/90 text-[11px] font-medium px-2.5 py-1 rounded-md transition-colors">{startLabel}</button>diff --git a/src/components/MeetingNotificationOverlay.tsx b/src/components/MeetingNotificationOverlay.tsxindex b3a79d5a3..99a51596d 100644--- a/src/components/MeetingNotificationOverlay.tsx+++ b/src/components/MeetingNotificationOverlay.tsx@@ -1,51 +1,41 @@import { useState, useEffect, useCallback } from "react";import { useTranslation } from "react-i18next";+import type { MeetingNotificationData } from "../types/electron";import { MeetingNotificationCard } from "./MeetingNotificationCard";--type PromptVariant = "detected" | "starting" | "underway";--interface NotificationData {- detectionId: string;- source: string;- key: string;- event: { summary?: string | null } | null;- variant: PromptVariant;- joinUrl: string | null;-}+import {+ getMeetingNotificationPresentation,+ initializeMeetingNotificationOverlay,+ subscribeMeetingAutoEndCountdown,+} from "./meetingNotificationModel";export default function MeetingNotificationOverlay() {const { t } = useTranslation();- const [data, setData] = useState<NotificationData | null>(null);+ const [data, setData] = useState<MeetingNotificationData | null>(null);const [isVisible, setIsVisible] = useState(false);const [isHovered, setIsHovered] = useState(false);+ const [secondsRemaining, setSecondsRemaining] = useState(0);useEffect(() => {- let shown = false;-- const show = (d: NotificationData) => {- if (shown) return;- shown = true;- setData(d);- setTimeout(() => {- setIsVisible(true);- window.electronAPI?.meetingNotificationReady?.();- }, 50);- };-- const cleanup = window.electronAPI?.onMeetingNotificationData?.((incoming: NotificationData) =>- show(incoming)- );-- window.electronAPI?.getMeetingNotificationData?.().then((pulled: NotificationData | null) => {- if (pulled) show(pulled);+ return initializeMeetingNotificationOverlay({+ subscribe: (callback) => window.electronAPI?.onMeetingNotificationData?.(callback),+ getPendingData: () =>+ window.electronAPI?.getMeetingNotificationData?.() ?? Promise.resolve(null),+ onData: setData,+ onVisible: () => setIsVisible(true),+ onReady: () => {+ void window.electronAPI?.meetingNotificationReady?.();+ },});-- return () => cleanup?.();}, []);+ useEffect(() => {+ if (data?.kind !== "auto-end") return;+ return subscribeMeetingAutoEndCountdown(data.expiresAt, setSecondsRemaining);+ }, [data]);+const respond = useCallback(async (action: string) => {- if (!data) return;+ if (data?.kind !== "detection") return;setIsVisible(false);await new Promise((r) => setTimeout(r, 200));window.electronAPI?.meetingNotificationRespond?.(data.detectionId, action);@@ -53,6 +43,11 @@ export default function MeetingNotificationOverlay() {[data]);+ const keepRecording = useCallback(() => {+ if (data?.kind !== "auto-end") return;+ void window.electronAPI?.meetingAutoEndKeep?.(data.sessionId);+ }, [data]);+const handleMouseEnter = useCallback(() => {setIsHovered(true);window.electronAPI?.setNotificationInteractivity?.(true);@@ -63,18 +58,25 @@ export default function MeetingNotificationOverlay() {window.electronAPI?.setNotificationInteractivity?.(false);}, []);- const variant: PromptVariant = data?.variant ?? "detected";- const title = (variant !== "detected" && data?.event?.summary) || t("meetingNotification.title");+ const presentation = getMeetingNotificationPresentation(data, secondsRemaining);+ const title = "title" in presentation ? presentation.title : t(presentation.titleKey);+ const body =+ "bodyValues" in presentation+ ? t(presentation.bodyKey, presentation.bodyValues)+ : t(presentation.bodyKey);+ const handleAction =+ presentation.action === "keep" ? keepRecording : () => respond(presentation.action);return (<div className="meeting-notification-window w-full h-full bg-transparent p-3"><MeetingNotificationCardtitle={title}- body={t(`meetingNotification.body.${variant}`)}- startLabel={data?.joinUrl ? t("meetingNotification.join") : t("meetingNotification.start")}- onStart={() => respond(data?.joinUrl ? "join" : "start")}- onDismiss={() => respond("dismiss")}+ body={body}+ startLabel={t(presentation.actionKey)}+ onStart={handleAction}+ onDismiss={presentation.dismissible ? () => respond("dismiss") : undefined}closeVisible={isHovered}+ allowTitleWrap={presentation.allowTitleWrap}onMouseEnter={handleMouseEnter}onMouseLeave={handleMouseLeave}className={[diff --git a/src/components/MeetingRecordingMount.tsx b/src/components/MeetingRecordingMount.tsxindex 3a90a4a73..08a6e3f18 100644--- a/src/components/MeetingRecordingMount.tsx+++ b/src/components/MeetingRecordingMount.tsx@@ -2,10 +2,15 @@ import { useEffect, useRef } from "react";import { useTranslation } from "react-i18next";import { useToast } from "./ui/useToast";import {+ getActiveRecordingSessionId,getMicAnalyser,primeMeetingWorklet,+ stopRecording,useMeetingRecordingStore,} from "../stores/meetingRecordingStore";+import { requestMeetingRecordingAutoEnd } from "../helpers/meetingRecordingSession";+import { serializeTranscriptSegments } from "../utils/transcriptSpeakerState";+import logger from "../utils/logger";const EMA_PREV = 0.5;const EMA_NEXT = 0.5;@@ -19,6 +24,7 @@ export default function MeetingRecordingMount(): null {const { t } = useTranslation();const { toast } = useToast();const isRecording = useMeetingRecordingStore((s) => s.isRecording);+ const isTranscribing = useMeetingRecordingStore((s) => s.isTranscribing);const error = useMeetingRecordingStore((s) => s.error);const errorNonce = useMeetingRecordingStore((s) => s.errorNonce);const micCaptureStatus = useMeetingRecordingStore((s) => s.micCaptureStatus);@@ -28,6 +34,52 @@ export default function MeetingRecordingMount(): null {primeMeetingWorklet();}, []);+ useEffect(() => {+ return window.electronAPI?.onMeetingAutoEndRequested?.((request) => {+ requestMeetingRecordingAutoEnd(+ request,+ (sessionId) => {+ // Toast only when this request actually ends the live session — and+ // even if the user's Keep click lost the race with the countdown, so+ // they learn the recording ended rather than assuming it was kept.+ const endsActiveSession = getActiveRecordingSessionId() === sessionId;+ return stopRecording(sessionId).then((result) => {+ if (endsActiveSession) {+ toast({+ title: t("notes.meeting.title"),+ description: t("notes.meeting.autoEnded"),+ });+ }+ return result;+ });+ },+ (error, sessionId) => {+ logger.error(+ "Meeting auto-end stop failed; recording is still running",+ { error: error instanceof Error ? error.message : String(error), sessionId },+ "meeting"+ );+ }+ );+ });+ }, [toast, t]);++ // Crash-safety net moved out of the notes view: it must keep running when+ // the user switches views mid-recording.+ useEffect(() => {+ if (!isTranscribing) return;++ const interval = setInterval(() => {+ const { recordingNoteId, segments } = useMeetingRecordingStore.getState();+ if (!recordingNoteId || segments.length === 0) return;+ window.electronAPI.updateNote(recordingNoteId, {+ transcript: serializeTranscriptSegments(segments),+ });+ }, 30_000);++ return () => clearInterval(interval);+ }, [isTranscribing]);+useEffect(() => {if (!error) return;toast({diff --git a/src/components/meetingNotificationModel.ts b/src/components/meetingNotificationModel.tsnew file mode 100644index 000000000..edd10cd2a--- /dev/null+++ b/src/components/meetingNotificationModel.ts@@ -0,0 +1,148 @@+import type { MeetingAutoEndReason, MeetingNotificationData } from "../types/electron";++type AutoEndBodyKey =+ | "meetingNotification.autoEnd.body.micReleased"+ | "meetingNotification.autoEnd.body.silence"+ | "meetingNotification.autoEnd.body.processExit";++const AUTO_END_BODY_KEYS: Record<MeetingAutoEndReason, AutoEndBodyKey> = {+ "mic-released": "meetingNotification.autoEnd.body.micReleased",+ silence: "meetingNotification.autoEnd.body.silence",+ "process-exit": "meetingNotification.autoEnd.body.processExit",+};++interface AutoEndPresentation {+ titleKey: "meetingNotification.autoEnd.title";+ bodyKey: AutoEndBodyKey;+ bodyValues: { seconds: number };+ actionKey: "meetingNotification.autoEnd.keep";+ action: "keep";+ dismissible: false;+ allowTitleWrap: true;+}++interface DetectionPresentation {+ title?: string;+ titleKey?: "meetingNotification.title";+ bodyKey:+ | "meetingNotification.body.detected"+ | "meetingNotification.body.starting"+ | "meetingNotification.body.underway";+ actionKey: "meetingNotification.start" | "meetingNotification.join";+ action: "start" | "join";+ dismissible: true;+ allowTitleWrap: false;+}++export type MeetingNotificationPresentation = AutoEndPresentation | DetectionPresentation;++export function getMeetingNotificationPresentation(+ data: MeetingNotificationData | null,+ secondsRemaining: number+): MeetingNotificationPresentation {+ if (data?.kind === "auto-end") {+ return {+ titleKey: "meetingNotification.autoEnd.title",+ bodyKey:+ AUTO_END_BODY_KEYS[data.reason ?? "mic-released"] ?? AUTO_END_BODY_KEYS["mic-released"],+ bodyValues: { seconds: secondsRemaining },+ actionKey: "meetingNotification.autoEnd.keep",+ action: "keep",+ dismissible: false,+ allowTitleWrap: true,+ };+ }++ const variant = data?.variant ?? "detected";+ const eventTitle = variant !== "detected" ? data?.event?.summary : null;+ return {+ ...(eventTitle ? { title: eventTitle } : { titleKey: "meetingNotification.title" }),+ bodyKey: `meetingNotification.body.${variant}`,+ actionKey: data?.joinUrl ? "meetingNotification.join" : "meetingNotification.start",+ action: data?.joinUrl ? "join" : "start",+ dismissible: true,+ allowTitleWrap: false,+ };+}++interface MeetingNotificationInitializationOptions {+ subscribe: (callback: (data: MeetingNotificationData) => void) => (() => void) | undefined;+ getPendingData: () => Promise<MeetingNotificationData | null>;+ onData: (data: MeetingNotificationData) => void;+ onVisible: () => void;+ onReady: () => void;+ setTimeout?: (callback: () => void, delay: number) => ReturnType<typeof setTimeout>;+ clearTimeout?: (timer: ReturnType<typeof setTimeout>) => void;+}++export function initializeMeetingNotificationOverlay({+ subscribe,+ getPendingData,+ onData,+ onVisible,+ onReady,+ setTimeout: schedule = (callback, delay) => setTimeout(callback, delay),+ clearTimeout: cancel = (timer) => clearTimeout(timer),+}: MeetingNotificationInitializationOptions): () => void {+ let active = true;+ let shown = false;+ let revealTimer: ReturnType<typeof setTimeout> | null = null;++ const show = (data: MeetingNotificationData): void => {+ if (!active || shown) return;+ shown = true;+ onData(data);+ revealTimer = schedule(() => {+ revealTimer = null;+ if (!active) return;+ onVisible();+ onReady();+ }, 50);+ };++ const unsubscribe = subscribe(show);+ void getPendingData()+ .then((data) => {+ if (data) show(data);+ })+ .catch(() => undefined);++ return () => {+ active = false;+ unsubscribe?.();+ if (revealTimer !== null) {+ cancel(revealTimer);+ revealTimer = null;+ }+ };+}++interface CountdownClock {+ now: () => number;+ setInterval: (callback: () => void, delay: number) => ReturnType<typeof setInterval>;+ clearInterval: (timer: ReturnType<typeof setInterval>) => void;+}++const defaultCountdownClock: CountdownClock = {+ now: Date.now,+ setInterval: (callback, delay) => setInterval(callback, delay),+ clearInterval: (timer) => clearInterval(timer),+};++export function getMeetingAutoEndSecondsRemaining(expiresAt: number, now: number): number {+ return Math.max(0, Math.ceil((expiresAt - now) / 1000));+}++export function subscribeMeetingAutoEndCountdown(+ expiresAt: number,+ onSecondsChanged: (seconds: number) => void,+ clock: CountdownClock = defaultCountdownClock+): () => void {+ const update = (): void => {+ onSecondsChanged(getMeetingAutoEndSecondsRemaining(expiresAt, clock.now()));+ };++ update();+ const timer = clock.setInterval(update, 250);+ return () => clock.clearInterval(timer);+}diff --git a/src/components/notes/PersonalNotesView.tsx b/src/components/notes/PersonalNotesView.tsxindex 339f502a9..cb15b6219 100644--- a/src/components/notes/PersonalNotesView.tsx+++ b/src/components/notes/PersonalNotesView.tsx@@ -22,7 +22,6 @@ import {import { cn } from "../lib/utils";import logger from "../../utils/logger";import { parseTranscriptSegments } from "../../utils/parseTranscriptSegments";-import { serializeTranscriptSegments } from "../../utils/transcriptSpeakerState";import { isExplicitSpeakerCount, resolveExpectedSpeakerCount } from "../../utils/participants";import {useNotes,@@ -59,6 +58,7 @@ import { usePolicySnapshot, useTranscriptionContextAllowed } from "../../hooks/uimport NotesOnboarding from "./NotesOnboarding";import { notesEmptyTitleKey } from "./shared";import { isRegenerableNoteTitle } from "../../helpers/regenerableNoteTitle";+import { isMeetingAutoEndEligible } from "../../helpers/meetingRecordingSession";import { handleMeetingRecordingRequest } from "../../helpers/meetingRecordingRequest";import { markIntroSeen, NOTES_STRUCTURE_INTRO, shouldShowIntro } from "../../lib/versionedIntro";import {@@ -344,6 +344,7 @@ export default function PersonalNotesView({diarizationEnabled: note?.diarization_enabled == null ? null : note.diarization_enabled === 1,expectedCount: resolveExpectedSpeakerCount(note),expectedCountIsExplicit: isExplicitSpeakerCount(note?.expected_speaker_count),+ autoEndEligible: isMeetingAutoEndEligible(note),});}, [activeNote]);@@ -639,6 +640,9 @@ export default function PersonalNotesView({note?.diarization_enabled == null ? null : note.diarization_enabled === 1,expectedCount: resolveExpectedSpeakerCount(note),expectedCountIsExplicit: isExplicitSpeakerCount(note?.expected_speaker_count),+ // Requests come from meeting detection, so a note that hasn't loaded+ // yet is still a meeting note.+ autoEndEligible: note ? isMeetingAutoEndEligible(note) : true,},startRecording: storeStartRecording,restoreFromMeetingMode: async () => {@@ -654,39 +658,8 @@ export default function PersonalNotesView({});}, [meetingRecordingRequest, activeNoteId, activeNote, onMeetingRecordingRequestHandled]);- const prevTranscribingRef = useRef(false);-- useEffect(() => {- if (prevTranscribingRef.current && !isTranscribing) {- const { transcript: realtimeTranscript, segments: realtimeSegments } =- useMeetingRecordingStore.getState();- const transcript =- realtimeSegments.length > 0- ? serializeTranscriptSegments(realtimeSegments)- : realtimeTranscript;-- if (recordingNoteId && transcript) {- window.electronAPI.updateNote(recordingNoteId, { transcript });- }- }- prevTranscribingRef.current = isTranscribing;- }, [isTranscribing, recordingNoteId]);-- useEffect(() => {- if (!isTranscribing) return;-- const interval = setInterval(() => {- const { recordingNoteId: currentRecordingNoteId, segments: realtimeSegments } =- useMeetingRecordingStore.getState();- if (!currentRecordingNoteId || realtimeSegments.length === 0) return;- window.electronAPI.updateNote(currentRecordingNoteId, {- transcript: serializeTranscriptSegments(realtimeSegments),- });- }, 30_000);-- return () => clearInterval(interval);- }, [isTranscribing]);-+ // Final and periodic transcript persistence live in MeetingRecordingMount /+ // the store — this view can be unmounted when an auto-end stop fires.const isActiveNoteRecording = isTranscribing && recordingNoteId === activeNote?.id;if (!isOnboardingComplete) {diff --git a/src/components/settings/MeetingSettings.tsx b/src/components/settings/MeetingSettings.tsxindex 364f6cdad..06c164a46 100644--- a/src/components/settings/MeetingSettings.tsx+++ b/src/components/settings/MeetingSettings.tsx@@ -30,6 +30,21 @@ export function MeetingSpeakerDetectionRow() {);}+export function MeetingAutoEndRow() {+ const { t } = useTranslation();+ const meetingAutoEndEnabled = useSettingsStore((s) => s.meetingAutoEndEnabled);+ const setMeetingAutoEndEnabled = useSettingsStore((s) => s.setMeetingAutoEndEnabled);++ return (+ <SettingsRow+ label={t("settings.meeting.autoEnd.title")}+ description={t("settings.meeting.autoEnd.description")}+ >+ <Toggle checked={meetingAutoEndEnabled} onChange={setMeetingAutoEndEnabled} />+ </SettingsRow>+ );+}+const noop = () => {};export function MeetingTranscriptionPanel() {@@ -152,6 +167,7 @@ export function MeetingTranscriptionPanel() {{effectiveTranscriptionMode === "providers" && renderTranscriptionPicker("cloud")}{effectiveTranscriptionMode === "local" && renderTranscriptionPicker("local")}<MeetingSpeakerDetectionRow />+ <MeetingAutoEndRow /></div>);}diff --git a/src/helpers/audioActivityDetector.js b/src/helpers/audioActivityDetector.jsindex 7f63f9862..ebae629fa 100644--- a/src/helpers/audioActivityDetector.js+++ b/src/helpers/audioActivityDetector.js@@ -15,8 +15,12 @@ const INACTIVE_RESET_MS = 60 * 1000;const EXEC_OPTS = { timeout: 5000, encoding: "utf8" };class AudioActivityDetector extends EventEmitter {- constructor() {+ // `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()]) {super();+ this._getExcludedProcessIds = getExcludedProcessIds;this.checkInterval = null;this.consecutiveChecks = 0;this.audioActiveStart = null;@@ -35,6 +39,22 @@ class AudioActivityDetector extends EventEmitter {this._micWarmHold = false;this._lastKnownMicState = false;this._cooldownReevalTimer = null;+ this._linuxOwnershipRequest = 0;+ this._linuxReconcileQueued = false;+ this._linuxReconcileRunning = false;+ this._pidScopedCapability = false;+ this._externalMicReliable = false;+ this._externalMicActive = false;+ this._lastEmittedExternalMicReliable = false;+ this._lastEmittedExternalMicActive = false;+ }++ getExternalMicState() {+ this._updateExternalMicState(false);+ return {+ reliable: this._externalMicReliable,+ externalMicActive: this._externalMicActive,+ };}setUserRecording(active) {@@ -138,15 +158,22 @@ class AudioActivityDetector extends EventEmitter {this._clearResetTimer();}- // The pid set and source count mirror what the OS told us is open, not our- // own detection state — only losing the listener invalidates them. Clearing- // them on dismissal would desync the reference count, so an unrelated app's- // mic session ending would report the still-running call as gone.+ // The pid set, source count, and ownership snapshot mirror what the OS told+ // us is open, not our own detection state — only losing the listener+ // invalidates them. Clearing them on dismissal would desync the reference+ // count, so an unrelated app's mic session ending would report the+ // still-running call as gone._resetListenerState() {this._activeMicPids.clear();this._activeSources = 0;this._lastKnownMicState = false;this._clearCooldownReevalTimer();+ this._linuxOwnershipRequest++;+ this._pidScopedCapability = false;+ this._externalMicReliable = false;+ this._externalMicActive = false;+ this._lastEmittedExternalMicReliable = false;+ this._lastEmittedExternalMicActive = false;}_clearSustainedTimer() {@@ -264,9 +291,12 @@ class AudioActivityDetector extends EventEmitter {const fallbackToPolling = () => {if (this._listenerProcess !== child) return;this._listenerProcess = null;+ // Announce the reliability loss before the snapshot is reset, or the+ // emit de-dupe would swallow it.+ this._setPidScopedCapability(false);+ this._resetListenerState();if (this._running && this._eventDriven) {this._eventDriven = false;- this._resetListenerState();this._startPolling();}};@@ -294,16 +324,33 @@ class AudioActivityDetector extends EventEmitter {options: { stdio: ["ignore", "pipe", "pipe"] },label: "macos-mic-listener",generation,- onLine: (line) => {- if (line === "MIC_ACTIVE") {- this._onMicStateChanged(true);- } else if (line === "MIC_INACTIVE") {- this._onMicStateChanged(false);- }- },+ onLine: (line) => this._parseDarwinListenerLine(line),});}+ _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);+ return;+ }+ if (line === "MIC_INACTIVE") {+ this._onMicStateChanged(false);+ return;+ }++ this._parsePidScopedListenerLine(line);+ }+_tryEventDrivenWin32(generation) {const binaryPath = resolveBundledBinary("windows-mic-listener.exe", "meeting");if (!binaryPath) {@@ -313,7 +360,7 @@ class AudioActivityDetector extends EventEmitter {return this._spawnListener({command: binaryPath,- args: ["--exclude-pid", String(process.pid)],+ args: [],// stdin must be "pipe" — the Windows binary monitors stdin for parent deathoptions: { stdio: ["pipe", "pipe", "pipe"], windowsHide: true },label: "windows-mic-listener",@@ -323,31 +370,62 @@ class AudioActivityDetector extends EventEmitter {}_parseWin32ListenerLine(line) {+ if (!this._running) return;+ // Only rebuilt binaries announce CAPABILITY PID. Pre-refcounting builds+ // print READY and MIC_START/MIC_STOP too, but their un-refcounted stop+ // events must never be treated as reliable evidence for auto-end.+ if (line === "CAPABILITY PID") {+ this._setPidScopedCapability(true);+ return;+ }+ // The helper downgrades itself mid-run on an unrecoverable coverage gap+ // and keeps emitting best-effort transitions for meeting detection.+ if (line === "CAPABILITY AGGREGATE") {+ this._setPidScopedCapability(false);+ return;+ }++ this._parsePidScopedListenerLine(line);+ }++ // Our own captures never enter the pid set: dictation opens the mic from+ // Chromium's audio service and the system-audio helpers are child processes,+ // so the OS reports both under pids that are not the main one (#1392). Kept+ // out at ingest so they can neither arm the prompt nor, on their stop, read+ // as "every mic closed" while another app still holds one.+ _isExcludedProcessId(pid) {+ try {+ return this._getExcludedProcessIdSet().has(pid);+ } catch {+ // A failing provider is reported as unreliable by _updateExternalMicState.+ return false;+ }+ }++ _parsePidScopedListenerLine(line) {const startMatch = line.match(/^MIC_START\s+(\d+)$/);if (startMatch) {const pid = parseInt(startMatch[1], 10);- // --exclude-pid only covers the main process, but dictation captures from- // Chromium's audio service, so our own mic reads arrive here as if they- // were another app's (#1392).- if (getOwnProcessPids().has(pid)) return;+ if (this._isExcludedProcessId(pid)) return;this._activeMicPids.add(pid);- this._onMicStateChanged(true);+ const externalMicActive = this._updateExternalMicState();+ this._onMicStateChanged(externalMicActive);return;}const stopMatch = line.match(/^MIC_STOP\s+(\d+)$/);if (stopMatch) {const pid = parseInt(stopMatch[1], 10);+ if (this._isExcludedProcessId(pid)) return;this._activeMicPids.delete(pid);- if (this._activeMicPids.size === 0) {- this._onMicStateChanged(false);- }+ const externalMicActive = this._updateExternalMicState();+ this._onMicStateChanged(externalMicActive);return;}}- _tryEventDrivenLinux(generation) {- return this._spawnListener({+ async _tryEventDrivenLinux(generation) {+ const started = await this._spawnListener({command: "pactl",args: ["subscribe"],options: { stdio: ["ignore", "pipe", "pipe"] },@@ -355,19 +433,135 @@ class AudioActivityDetector extends EventEmitter {generation,onLine: (line) => this._parsePactlSubscribeLine(line),});+ if (!started || this._isStale(generation)) return false;++ await this._reconcileLinuxSourceOutputs(generation);+ return !this._isStale(generation) && this._listenerProcess !== null;}_parsePactlSubscribeLine(line) {- if (!line.includes("source-output")) return;+ if (!this._running || !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);+ this._onMicStateChanged(this._activeSources > 0);+ }++ this._queueLinuxReconcile();+ }++ // Bursts of subscribe events coalesce into at most one running and one queued+ // reconcile instead of spawning a `pactl list` subprocess per line.+ _queueLinuxReconcile() {+ if (this._linuxReconcileQueued) return;+ this._linuxReconcileQueued = true;+ if (this._linuxReconcileRunning) return;++ this._linuxReconcileRunning = true;+ void (async () => {+ try {+ while (this._linuxReconcileQueued && this._running && this._listenerProcess) {+ this._linuxReconcileQueued = false;+ await this._reconcileLinuxSourceOutputs(this._startGeneration);+ }+ } finally {+ this._linuxReconcileQueued = false;+ this._linuxReconcileRunning = false;}+ })();+ }++ async _reconcileLinuxSourceOutputs(generation) {+ const request = ++this._linuxOwnershipRequest;++ try {+ const { stdout } = await execAsync("pactl --format=json list source-outputs", EXEC_OPTS);+ if (this._isStale(generation) || request !== this._linuxOwnershipRequest) return;++ const sourceOutputs = JSON.parse(stdout);+ if (!Array.isArray(sourceOutputs)) throw new Error("pactl returned a non-array response");++ const activeMicPids = new Set();+ for (const sourceOutput of sourceOutputs) {+ // Audio-server plumbing (module-echo-cancel, loopbacks) legitimately+ // lacks application.process.id — client streams always carry it. Skip+ // such streams instead of surrendering PID reliability, or systems+ // with these modules loaded could never arm auto-end.+ const processId = Number(sourceOutput?.properties?.["application.process.id"]);+ if (!Number.isInteger(processId) || processId <= 0) continue;+ activeMicPids.add(processId);+ }++ this._activeMicPids = activeMicPids;+ this._activeSources = sourceOutputs.length;+ this._setPidScopedCapability(true);+ this._onMicStateChanged(this._activeSources > 0);+ } catch (err) {+ if (this._isStale(generation) || request !== this._linuxOwnershipRequest) return;+ this._setPidScopedCapability(false);+ debugLogger.warn(+ "Failed to reconcile pactl source-output ownership",+ { error: err.message },+ "meeting"+ );+ }+ }++ _getExcludedProcessIdSet() {+ const processIds = this._getExcludedProcessIds();+ return new Set(+ [...processIds]+ .map((processId) => Number(processId))+ .filter((processId) => Number.isInteger(processId) && processId > 0)+ );+ }++ _setPidScopedCapability(reliable) {+ this._pidScopedCapability = reliable;+ this._updateExternalMicState();+ }++ _updateExternalMicState(emitChange = true) {+ let excludedProcessIds;+ try {+ excludedProcessIds = this._getExcludedProcessIdSet();+ } catch (err) {+ this._setExternalMicSnapshot(false, false, emitChange);+ debugLogger.warn(+ "Failed to resolve excluded microphone PIDs",+ { error: err.message },+ "meeting"+ );+ return false;+ }++ const externalMicActive = [...this._activeMicPids].some(+ (processId) => !excludedProcessIds.has(processId)+ );+ if (!this._pidScopedCapability) {+ this._setExternalMicSnapshot(false, false, emitChange);+ return externalMicActive;+ }++ this._setExternalMicSnapshot(true, externalMicActive, emitChange);+ return externalMicActive;+ }++ _setExternalMicSnapshot(reliable, externalMicActive, emitChange) {+ this._externalMicReliable = reliable;+ this._externalMicActive = reliable ? externalMicActive : false;+ if (+ emitChange &&+ (this._externalMicReliable !== this._lastEmittedExternalMicReliable ||+ this._externalMicActive !== this._lastEmittedExternalMicActive) &&+ this._running+ ) {+ this._lastEmittedExternalMicReliable = this._externalMicReliable;+ this._lastEmittedExternalMicActive = this._externalMicActive;+ this.emit("external-mic-state-changed", this.getExternalMicState());}}diff --git a/src/helpers/electronProcessIds.js b/src/helpers/electronProcessIds.jsnew file mode 100644index 000000000..2703388da--- /dev/null+++ b/src/helpers/electronProcessIds.js@@ -0,0 +1,24 @@+const { getOwnProcessPids } = require("./ownProcessPids");++// Audio capture helpers (macOS audio tap, Linux portal capture, Windows+// loopback) are plain child processes, so they never appear in the Electron+// process tree — yet the OS attributes their capture to their own pids.+// Without excluding them, the app's own system-audio capture reads as an+// external mic user and auto-end can never arm its countdown.+function collectAudioCaptureHelperPids(managers) {+ return managers+ .map((manager) => manager?.process?.pid)+ .filter((pid) => Number.isInteger(pid) && pid > 0);+}++// Every pid whose mic use is OpenWhispr's own: the Electron process tree plus+// any live capture helper. Evaluated on each call so helpers are covered from+// the moment they spawn and drop out when they exit.+function createExcludedProcessIdProvider(+ getAudioCaptureHelperPids = () => [],+ getOwnPids = getOwnProcessPids+) {+ return () => [...getOwnPids(), ...getAudioCaptureHelperPids()];+}++module.exports = { collectAudioCaptureHelperPids, createExcludedProcessIdProvider };diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex f8297c626..00df09ea5 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -63,6 +63,8 @@ const { TINFOIL_REALTIME_MODEL } = require("./tinfoilRealtimeStreaming");const { getTinfoilChatModels } = require("./tinfoilCatalog");const { transcribeWithTinfoil } = require("./tinfoilTranscription");const AudioStorageManager = require("./audioStorage");+const createMeetingTranscriptionLifecycle = require("./meetingTranscriptionLifecycle");+const { registerMeetingAutoEndKeepHandler } = require("./meetingAutoEndKeep");const liveSpeakerIdentifier = require("./liveSpeakerIdentifier");const { supportsLiveSpeakerIdentification } = require("./liveSpeakerIdPolicy");const MeetingEchoLeakDetector = require("./meetingEchoLeakDetector");@@ -7074,7 +7076,7 @@ class IPCHandlers {return { success: true };});- ipcMain.handle("meeting-transcription-start", async (event, options = {}) => {+ const startMeetingTranscription = async (event, options = {}) => {// Wait for any in-flight prepare to finish before startingif (meetingTranscriptionPreparePromise) {debugLogger.debug("Meeting transcription start: waiting for in-flight prepare");@@ -7086,13 +7088,35 @@ class IPCHandlers {return { success: false, error: "Operation in progress" };}+ if (!ALLOWED_MEETING_PROVIDERS.has(options.provider)) {+ return { success: false, error: `Unsupported provider: ${options.provider}` };+ }+meetingTranscriptionStartInProgress = true;+ // The lifecycle wrapper is the only caller and always injects the same+ // sessionId it registered; re-deriving one here would silently break+ // scoped stop/auto-end matching.+ const recordingSessionId = options.sessionId;meetingStartedAt = Date.now();meetingConnectionOptions = options;meetingConnectionWin = BrowserWindow.fromWebContents(event.sender);meetingReconnectCount = 0;meetingFatalErrorSent = false;+ this.meetingDetectionEngine?.endRecordingSession();this.meetingDetectionEngine?.setUserRecording(true);++ const completeStart = async (result) => {+ await this.meetingDetectionEngine?.beginRecordingSession({+ sessionId: recordingSessionId,+ autoEndEligible: options.autoEndEligible === true,+ ownerWebContents: event.sender,+ // Renderer loopback may still fail after main chooses its strategy.+ // Auto-end stays fail-safe until the renderer confirms a real source.+ systemAudioAvailable: false,+ });+ return { ...result, sessionId: recordingSessionId };+ };+try {const systemAudioPlan = await getMeetingSystemAudioPlan({ refreshWindowsCapability: true });let { mode: systemAudioMode, strategy: systemAudioStrategy } = systemAudioPlan;@@ -7134,12 +7158,12 @@ class IPCHandlers {systemAudioStrategy,"during warm-start reuse"));- return {+ return await completeStart({success: true,systemAudioMode,systemAudioStrategy,oneOnOneAttendee: meetingOneOnOneAttendee,- };+ });}if (options.provider === "local") {@@ -7171,16 +7195,12 @@ class IPCHandlers {systemAudioStrategy,});- return {+ return await completeStart({success: true,systemAudioMode,systemAudioStrategy,oneOnOneAttendee: meetingOneOnOneAttendee,- };- }-- if (!ALLOWED_MEETING_PROVIDERS.has(options.provider)) {- return { success: false, error: `Unsupported provider: ${options.provider}` };+ });}await connectRealtimeStreaming(event, options);@@ -7193,24 +7213,28 @@ class IPCHandlers {systemAudioStrategy,"in realtime mode"));- return {+ return await completeStart({success: true,systemAudioMode,systemAudioStrategy,oneOnOneAttendee: meetingOneOnOneAttendee,- };+ });} catch (error) {await rollbackMeetingTranscriptionStart();+ this.meetingDetectionEngine?.endRecordingSession(recordingSessionId);this.meetingDetectionEngine?.setUserRecording(false);debugLogger.error("Meeting transcription start error", { error: error.message });return toPolicyFailure(error);} finally {meetingTranscriptionStartInProgress = false;}- });+ };const sendMeetingAudio = (audioBuffer, source) => {const outboundBuffer = Buffer.isBuffer(audioBuffer) ? audioBuffer : Buffer.from(audioBuffer);+ // Auto-end judges "is anyone audible" from the raw chunk of either+ // channel, before AEC/holdback/muting can swallow it.+ this.meetingDetectionEngine?.recordMeetingAudioChunk(source, outboundBuffer);if (source === "system") {const receivedAt = Date.now();@@ -7375,7 +7399,13 @@ class IPCHandlers {sendMeetingAudio(audioBuffer, source);});- ipcMain.handle("meeting-transcription-stop", async () => {+ const stopMeetingTranscription = async (expectedSessionId) => {+ // Only a *different* live session blocks teardown — it owns the shared+ // capture now. With no engine session (e.g. after quit-path engine stop)+ // the streams below must still be torn down.+ if (this.meetingDetectionEngine?.endRecordingSession(expectedSessionId) === false) {+ return { success: false, reason: "stale-session" };+ }this.meetingDetectionEngine?.setUserRecording(false);try {if (this.audioTapManager) {@@ -7459,8 +7489,49 @@ class IPCHandlers {debugLogger.error("Meeting transcription stop error", { error: error.message });return { success: false, error: error.message };}+ };++ const meetingTranscriptionLifecycle = createMeetingTranscriptionLifecycle({+ start: ({ sessionId, ownerWebContents, options }) =>+ startMeetingTranscription({ sender: ownerWebContents }, { ...options, sessionId }),+ stop: (sessionId) => stopMeetingTranscription(sessionId),+ onError: (error, sessionId) => {+ debugLogger.error(+ "Meeting transcription owner-loss teardown failed",+ { error: error?.message, sessionId },+ "meeting"+ );+ },+ });++ ipcMain.handle("meeting-transcription-start", (event, options = {}) => {+ const sessionId =+ typeof options.sessionId === "string" && options.sessionId.length > 0+ ? options.sessionId+ : crypto.randomUUID();+ return meetingTranscriptionLifecycle.startSession({+ sessionId,+ ownerWebContents: event.sender,+ options,+ });});+ ipcMain.handle("meeting-transcription-stop", (_event, expectedSessionId) =>+ meetingTranscriptionLifecycle.stopSession(expectedSessionId)+ );++ ipcMain.handle(+ "meeting-transcription-set-system-audio-available",+ async (event, sessionId, available) => {+ const updated = await this.meetingDetectionEngine?.setRecordingSystemAudioAvailable(+ sessionId,+ available === true,+ event.sender+ );+ return updated === true ? { success: true } : { success: false, reason: "stale-session" };+ }+ );+const streamingStartFailure = (err) => {const result = toPolicyFailure(err);if (err.messageKey) result.messageKey = err.messageKey;@@ -9715,6 +9786,8 @@ class IPCHandlers {}});+ registerMeetingAutoEndKeepHandler(ipcMain, () => this.meetingDetectionEngine);+ipcMain.handle("join-calendar-meeting", async (_event, eventId) => {try {await this.meetingDetectionEngine.joinCalendarMeeting(eventId);@@ -9736,8 +9809,8 @@ class IPCHandlers {return this.windowManager?.consumePendingNoteNavigation() ?? null;});- ipcMain.handle("meeting-notification-ready", async () => {- this.windowManager?.showNotificationWindow();+ ipcMain.handle("meeting-notification-ready", async (event) => {+ this.windowManager?.showNotificationWindow(event.sender);});ipcMain.handle("get-update-notification-data", async () => {diff --git a/src/helpers/meetingAudioActivityMonitor.js b/src/helpers/meetingAudioActivityMonitor.jsnew file mode 100644index 000000000..6441a5aa9--- /dev/null+++ b/src/helpers/meetingAudioActivityMonitor.js@@ -0,0 +1,70 @@+const {+ computePcm16Rms,+ MEETING_MIC_ACTIVITY_RMS,+ MEETING_SYSTEM_ACTIVITY_RMS,+} = require("../utils/audioUtils");++// How long a channel stays "active" after its last audible chunk. The system+// tail is longer so gaps between a remote speaker's sentences don't read as+// silence.+const MIC_ACTIVITY_TAIL_MS = 2_000;+const SYSTEM_ACTIVITY_TAIL_MS = 3_000;++const CHANNELS = {+ mic: { threshold: MEETING_MIC_ACTIVITY_RMS, tailMs: MIC_ACTIVITY_TAIL_MS },+ system: { threshold: MEETING_SYSTEM_ACTIVITY_RMS, tailMs: SYSTEM_ACTIVITY_TAIL_MS },+};++// Energy-based activity per meeting channel. Timer-free: the owner feeds every+// PCM chunk through recordChunk() and drives evaluation with a ~1s tick().+// Activity is judged from sample energy, never from chunk arrival — the+// Windows loopback helper streams digital-zero silence continuously.+const createMeetingAudioActivityMonitor = ({ onActivityChanged = () => {} } = {}) => {+ const pending = { mic: false, system: false };+ const lastActiveAt = { mic: null, system: null };+ const active = { mic: false, system: false };++ const getState = () => ({ micActive: active.mic, systemActive: active.system });++ const reset = () => {+ for (const source of Object.keys(CHANNELS)) {+ pending[source] = false;+ lastActiveAt[source] = null;+ active[source] = false;+ }+ };++ // Hot path — runs for every chunk of both channels. Once a chunk in the+ // current tick has crossed the threshold there is nothing left to learn, so+ // the RMS pass is skipped until the next tick clears the flag.+ const recordChunk = (source, buffer) => {+ const channel = CHANNELS[source];+ if (!channel || pending[source]) return;+ pending[source] = computePcm16Rms(buffer) >= channel.threshold;+ };++ const tick = (nowMs) => {+ let changed = false;+ for (const [source, channel] of Object.entries(CHANNELS)) {+ if (pending[source]) {+ pending[source] = false;+ lastActiveAt[source] = nowMs;+ }+ const nextActive =+ lastActiveAt[source] !== null && nowMs - lastActiveAt[source] < channel.tailMs;+ if (nextActive !== active[source]) {+ active[source] = nextActive;+ changed = true;+ }+ }+ if (changed) onActivityChanged(getState());+ };++ return { recordChunk, tick, reset, getState };+};++module.exports = {+ createMeetingAudioActivityMonitor,+ MIC_ACTIVITY_TAIL_MS,+ SYSTEM_ACTIVITY_TAIL_MS,+};diff --git a/src/helpers/meetingAutoEndController.js b/src/helpers/meetingAutoEndController.jsnew file mode 100644index 000000000..d40fc7304--- /dev/null+++ b/src/helpers/meetingAutoEndController.js@@ -0,0 +1,268 @@+const COUNTDOWN_MS = 60_000;+// Fallback mode: both channels must stay quiet this long before prompting.+const SILENCE_WINDOW_MS = 60_000;+// Fallback mode after the tracked meeting app exits — a much stronger signal.+const FAST_SILENCE_MS = 10_000;+// After "Keep recording": no re-prompt sooner than this, even on fresh evidence.+const KEEP_COOLDOWN_MS = 5 * 60_000;+// An external mic hold shorter than this (Siri, a permission prompt, the Sound+// settings input meter) is incidental — it must not arm the mic-ignoring+// ownership path on what is really an in-person recording.+const OWNERSHIP_MIN_ACTIVE_MS = 30_000;+// A tick gap longer than this means the machine slept; silence accumulated+// before the gap is stale and must not fire a stop.+const TICK_GAP_MS = 5_000;++// Two evidence sources decide "the meeting is over":+//+// ownership — an external app held the mic and released it. The countdown+// runs only while the SYSTEM channel is also quiet (remote voices still+// playing means the call is live, e.g. an app that releases the mic on+// mute). The mic channel is deliberately ignored here so room noise,+// typing, or talking to a colleague after the call can't mask the end.+// fallback — ownership is unreliable, or no external app ever held the mic+// this session (in-person meetings). Both channels quiet for the silence+// window prompts; a tracked meeting app exiting shortens the window.+//+// Tick-driven and timer-free: every input updates state and re-evaluates; the+// owner calls tick() about once a second. That keeps sleep handling correct — a+// timer due before sleep would fire on wake and stop the recording before any+// gap check could run.+const createMeetingAutoEndController = ({+ now = Date.now,+ onCountdown,+ onCountdownCanceled = () => {},+ onCountdownExpired = () => {},+ onStop,+}) => {+ let session = null;+ let lastSeenAt = null;++ const isLive = (sessionId) =>+ session !== null && session.sessionId === sessionId && session.eligible && !session.stopped;++ const cancelCountdown = () => {+ if (!session?.countdown) return;+ session.countdown = null;+ onCountdownCanceled(session.sessionId);+ };++ // Every entry point observes the clock first, not just tick(): after sleep,+ // the owner's monitor tick can deliver an activity change before the+ // controller's own tick runs, and that path must not fire a stale countdown.+ const observeClock = () => {+ const nowMs = now();+ const gap = lastSeenAt === null ? 0 : nowMs - lastSeenAt;+ lastSeenAt = nowMs;+ if (gap > TICK_GAP_MS && session) {+ // Slept through the gap: whatever silence accumulated is stale, and a+ // countdown that was running must not fire on wake.+ session.quietSince = nowMs;+ session.fastArmAt = null;+ cancelCountdown();+ }+ return nowMs;+ };++ const startCountdown = (reason) => {+ const expiresAt = now() + COUNTDOWN_MS;+ session.countdown = { expiresAt, reason };+ onCountdown({ sessionId: session.sessionId, expiresAt, reason });+ };++ const evaluate = () => {+ if (!session || !session.eligible || session.stopped) return;+ const nowMs = now();++ if (session.countdown) {+ if (nowMs >= session.countdown.expiresAt) {+ const { reason } = session.countdown;+ const { sessionId } = session;+ session.countdown = null;+ session.stopped = true;+ onCountdownExpired(sessionId);+ onStop(sessionId, reason);+ }+ return;+ }++ if (session.episodeConsumed || nowMs < session.keptUntil) return;++ if (session.mode === "ownership") {+ if (!session.externalMicActive && !session.systemActive) startCountdown("mic-released");+ return;+ }++ if (session.micActive || session.systemActive) return;+ const fastArmed = session.fastArmAt !== null;+ const quietStart = fastArmed+ ? Math.max(session.quietSince, session.fastArmAt)+ : session.quietSince;+ const window = fastArmed ? FAST_SILENCE_MS : SILENCE_WINDOW_MS;+ if (nowMs - quietStart >= window) startCountdown(fastArmed ? "process-exit" : "silence");+ };++ const beginSession = ({+ sessionId,+ eligible,+ reliable,+ externalMicActive,+ micActive = false,+ systemActive = false,+ }) => {+ cancelCountdown();+ const nowMs = now();+ lastSeenAt = nowMs;+ const ownership = eligible && reliable && externalMicActive;+ session = {+ sessionId,+ eligible: eligible === true,+ // Explicit state, never derived: a reliable-but-inactive report after a+ // reliability loss must not jump back into ownership mode.+ mode: ownership ? "ownership" : "fallback",+ externalMicActive: ownership,+ externalMicActiveSince: ownership ? nowMs : null,+ micActive,+ systemActive,+ quietSince: nowMs,+ fastArmAt: null,+ keptUntil: 0,+ episodeConsumed: false,+ countdown: null,+ stopped: false,+ };+ evaluate();+ };++ const handleExternalMicState = ({ sessionId, reliable, externalMicActive }) => {+ const nowMs = observeClock();+ if (!isLive(sessionId)) return;++ if (!reliable) {+ cancelCountdown();+ session.mode = "fallback";+ session.externalMicActive = false;+ session.externalMicActiveSince = null;+ session.quietSince = nowMs;+ evaluate();+ return;+ }++ if (externalMicActive) {+ cancelCountdown();+ if (!session.externalMicActive) session.externalMicActiveSince = nowMs;+ session.externalMicActive = true;+ session.mode = "ownership";+ // A new call is fresh evidence: reopen the episode after a Keep.+ session.episodeConsumed = false;+ session.fastArmAt = null;+ evaluate();+ return;+ }++ if (session.mode === "ownership" && session.externalMicActive) {+ session.externalMicActive = false;+ const heldMs = nowMs - session.externalMicActiveSince;+ session.externalMicActiveSince = null;+ if (heldMs < OWNERSHIP_MIN_ACTIVE_MS) {+ session.mode = "fallback";+ session.quietSince = nowMs;+ } else {+ // A call that was genuinely rejoined and left again is unambiguous+ // evidence; making it wait out the keep cooldown reads as the feature+ // silently failing. The cooldown exists for silence-based nags, which+ // still honor it.+ session.keptUntil = 0;+ }+ }+ evaluate();+ };++ const handleAudioActivity = ({ sessionId, micActive, systemActive }) => {+ const nowMs = observeClock();+ if (!isLive(sessionId)) return;+ const micBecameActive = micActive && !session.micActive;+ const systemBecameActive = systemActive && !session.systemActive;+ const wasQuiet = !session.micActive && !session.systemActive;+ session.micActive = micActive;+ session.systemActive = systemActive;++ if (session.mode === "ownership") {+ // Only remote audio says the call is live; the mic channel is ignored.+ if (systemBecameActive) cancelCountdown();+ } else if (micBecameActive || systemBecameActive) {+ cancelCountdown();+ // Someone spoke — fresh evidence reopens the episode; a process exit+ // no longer describes the current situation.+ session.episodeConsumed = false;+ session.fastArmAt = null;+ }+ if (!wasQuiet && !micActive && !systemActive) session.quietSince = nowMs;+ evaluate();+ };++ const handleMeetingProcessExit = ({ sessionId }) => {+ const nowMs = observeClock();+ if (!isLive(sessionId)) return;+ if (session.mode !== "fallback" || session.countdown) return;+ session.fastArmAt = nowMs;+ // The app quitting is fresh evidence, so a kept session can prompt again —+ // but never sooner than the keep cooldown.+ session.episodeConsumed = false;+ evaluate();+ };++ const handleCountdownUnavailable = (sessionId) => {+ observeClock();+ if (!isLive(sessionId) || !session.countdown) return false;+ cancelCountdown();+ // Do not retry the same episode when the user had no chance to keep it.+ session.episodeConsumed = true;+ return true;+ };++ // Returns false once the countdown has fired: the stop is already in flight,+ // so reporting success would tell the user their recording was kept.+ // Keep is per episode: prompts resume only on fresh evidence. Renewed audio+ // or a process exit (fallback) also wait out the cooldown; a call rejoined+ // for at least OWNERSHIP_MIN_ACTIVE_MS and left again re-prompts at once. In+ // ownership mode with no further call the session is never prompted again.+ const keepRecording = (sessionId) => {+ const nowMs = observeClock();+ if (!session || session.sessionId !== sessionId || session.stopped) return false;+ cancelCountdown();+ session.episodeConsumed = true;+ session.keptUntil = nowMs + KEEP_COOLDOWN_MS;+ return true;+ };++ const endSession = (sessionId) => {+ if (!session || session.sessionId !== sessionId) return;+ cancelCountdown();+ session = null;+ };++ const tick = () => {+ observeClock();+ evaluate();+ };++ return {+ beginSession,+ handleExternalMicState,+ handleAudioActivity,+ handleMeetingProcessExit,+ handleCountdownUnavailable,+ keepRecording,+ endSession,+ tick,+ };+};++module.exports = createMeetingAutoEndController;+module.exports.COUNTDOWN_MS = COUNTDOWN_MS;+module.exports.SILENCE_WINDOW_MS = SILENCE_WINDOW_MS;+module.exports.FAST_SILENCE_MS = FAST_SILENCE_MS;+module.exports.KEEP_COOLDOWN_MS = KEEP_COOLDOWN_MS;+module.exports.OWNERSHIP_MIN_ACTIVE_MS = OWNERSHIP_MIN_ACTIVE_MS;+module.exports.TICK_GAP_MS = TICK_GAP_MS;diff --git a/src/helpers/meetingAutoEndKeep.js b/src/helpers/meetingAutoEndKeep.jsnew file mode 100644index 000000000..af67c884f--- /dev/null+++ b/src/helpers/meetingAutoEndKeep.js@@ -0,0 +1,21 @@+function keepMeetingRecordingSession(engine, sessionId) {+ if (typeof sessionId !== "string" || sessionId.trim().length === 0) {+ return { success: false, reason: "invalid-session" };+ }+ if (engine?.keepRecordingSession(sessionId) !== true) {+ return { success: false, reason: "stale-session" };+ }+ return { success: true };+}++function registerMeetingAutoEndKeepHandler(ipcMain, getMeetingDetectionEngine) {+ ipcMain.handle("meeting-auto-end-keep", async (_event, sessionId) => {+ try {+ return keepMeetingRecordingSession(getMeetingDetectionEngine(), sessionId);+ } catch (error) {+ return { success: false, error: error.message };+ }+ });+}++module.exports = { keepMeetingRecordingSession, registerMeetingAutoEndKeepHandler };diff --git a/src/helpers/meetingDetectionEngine.js b/src/helpers/meetingDetectionEngine.jsindex 061875a83..4d1e80211 100644--- a/src/helpers/meetingDetectionEngine.js+++ b/src/helpers/meetingDetectionEngine.js@@ -1,9 +1,12 @@const { shell } = require("electron");const debugLogger = require("./debugLogger");const { getMeetingJoinUrl } = require("./meetingJoinUrl");+const createMeetingAutoEndController = require("./meetingAutoEndController");+const { createMeetingAudioActivityMonitor } = require("./meetingAudioActivityMonitor");const { broadcastToWindows } = require("./windowBroadcast");const IMMINENT_THRESHOLD_MS = 5 * 60 * 1000;+const AUTO_END_TICK_MS = 1000;const PLACEHOLDER_PREFIX = { __detected__: "detected", __manual__: "manual" };@@ -30,7 +33,14 @@ class MeetingDetectionEngine {meetingProcessDetector,audioActivityDetector,windowManager,- databaseManager+ databaseManager,+ {+ createAutoEndController = createMeetingAutoEndController,+ createAudioActivityMonitor = createMeetingAudioActivityMonitor,+ now = Date.now,+ setInterval = global.setInterval,+ clearInterval = global.clearInterval,+ } = {}) {this.reminderScheduler = reminderScheduler;this.meetingProcessDetector = meetingProcessDetector;@@ -38,11 +48,51 @@ class MeetingDetectionEngine {this.windowManager = windowManager;this.databaseManager = databaseManager;this.activeDetections = new Map();- this.preferences = { processDetection: true, audioDetection: true };+ this.preferences = { processDetection: true, audioDetection: true, autoEnd: true };this._userRecording = false;this._meetingModeActive = false;this._notificationQueue = [];this._postRecordingCooldown = null;+ this._recordingSession = null;+ this._now = now;+ this._setInterval = setInterval;+ this._clearInterval = clearInterval;+ // True only between controller.beginSession and endSession — meeting audio+ // starts streaming before the session is registered, and chunks fed to the+ // monitor before the controller exists would leave the two out of sync.+ this._autoEndActive = false;+ this._autoEndTicker = null;+ this._audioActivityMonitor = createAudioActivityMonitor({+ onActivityChanged: (state) => {+ const session = this._recordingSession;+ if (!this._autoEndActive || !session) return;+ this._autoEndController.handleAudioActivity({ sessionId: session.sessionId, ...state });+ },+ });+ this._autoEndController = createAutoEndController({+ now,+ onCountdown: (countdown) => {+ debugLogger.info("Meeting auto-end countdown started", countdown, "meeting");+ Promise.resolve(this.windowManager.showMeetingAutoEndCountdown?.(countdown)).catch(+ (error) => {+ debugLogger.error(+ "Failed to show meeting auto-end countdown",+ { error: error?.message },+ "meeting"+ );+ this.handleAutoEndNotificationUnavailable(countdown.sessionId);+ }+ );+ },+ onCountdownCanceled: (sessionId) => {+ debugLogger.info("Meeting auto-end countdown canceled", { sessionId }, "meeting");+ this.windowManager.dismissMeetingAutoEndCountdown?.(sessionId);+ },+ onCountdownExpired: (sessionId) => {+ this.windowManager.dismissMeetingAutoEndCountdown?.(sessionId);+ },+ onStop: (sessionId, reason) => this._requestRecordingStop(sessionId, reason),+ });this._bindListeners();}@@ -59,11 +109,250 @@ class MeetingDetectionEngine {this.meetingProcessDetector.on("meeting-process-ended", (data) => {this.activeDetections.delete(`process:${data.processKey}`);++ // The detector removes the ended key before emitting, so an empty list+ // means the last tracked meeting app is gone.+ const session = this._recordingSession;+ if (!this._autoEndActive || !session) return;+ const remaining = this.meetingProcessDetector.getDetectedProcesses?.() ?? [];+ if (remaining.length > 0) return;+ debugLogger.info(+ "Last tracked meeting app exited during recording",+ { sessionId: session.sessionId, processKey: data.processKey },+ "meeting"+ );+ this._autoEndController.handleMeetingProcessExit({ sessionId: session.sessionId });});this.audioActivityDetector.on("sustained-audio-detected", (data) => {this._handleDetection("audio", "sustained-audio", data);});++ this.audioActivityDetector.on("external-mic-state-changed", (state) => {+ const session = this._recordingSession;+ if (!this._autoEndActive || !session) return;++ debugLogger.debug(+ "External mic state for auto-end",+ { sessionId: session.sessionId, ...state },+ "meeting"+ );+ this._autoEndController.handleExternalMicState({+ sessionId: session.sessionId,+ reliable: state.reliable,+ externalMicActive: state.externalMicActive,+ });+ });+ }++ _requestRecordingStop(sessionId, reason) {+ const session = this._recordingSession;+ if (!session || session.sessionId !== sessionId) return;++ debugLogger.info(+ "Meeting auto-end countdown expired, requesting stop",+ { sessionId, reason },+ "meeting"+ );+ const ownerWebContents = session.ownerWebContents;+ if (!ownerWebContents || ownerWebContents.isDestroyed?.()) return;+ try {+ ownerWebContents.send("meeting-auto-end-requested", { sessionId, reason });+ } catch (error) {+ debugLogger.error(+ "Failed to request meeting auto-end from recording renderer",+ { error: error?.message, sessionId },+ "meeting"+ );+ }+ }++ // Hot path — called for every meeting PCM chunk of both channels.+ recordMeetingAudioChunk(source, buffer) {+ if (!this._autoEndActive) return;+ this._audioActivityMonitor.recordChunk(source, buffer);+ }++ _isAutoEndWanted() {+ return (+ this._recordingSession?.autoEndEligible === true &&+ this._recordingSession.systemAudioAvailable === true &&+ this.preferences.autoEnd !== false+ );+ }++ _syncAudioActivityDetector() {+ if (this.preferences.audioDetection || this._isAutoEndWanted()) {+ return this.audioActivityDetector.start();+ }++ this.audioActivityDetector.stop();+ return undefined;+ }++ // The process-exit fast path needs the detector even when the user has turned+ // process detection off for meeting prompts.+ _syncMeetingProcessDetector() {+ if (this.preferences.processDetection || this._isAutoEndWanted()) {+ this.meetingProcessDetector.start();+ return;+ }+ this.meetingProcessDetector.stop();+ }++ _startAutoEndTicker() {+ if (this._autoEndTicker) return;+ this._autoEndTicker = this._setInterval(() => {+ // Monitor first so a fresh activity change reaches the controller before+ // it evaluates its windows for this second.+ this._audioActivityMonitor.tick(this._now());+ this._autoEndController.tick();+ }, AUTO_END_TICK_MS);+ this._autoEndTicker?.unref?.();+ }++ _stopAutoEndTicker() {+ if (!this._autoEndTicker) return;+ this._clearInterval(this._autoEndTicker);+ this._autoEndTicker = null;+ }++ // Ends the controller session for the tracked recording (if any) and stops+ // feeding it audio. Safe to call when nothing is active.+ _deactivateAutoEnd() {+ const session = this._recordingSession;+ this._autoEndActive = false;+ this._stopAutoEndTicker();+ this._audioActivityMonitor.reset();+ if (session) this._autoEndController.endSession(session.sessionId);+ }++ async _activateAutoEnd(sessionId) {+ await this._syncAudioActivityDetector();+ if (this._recordingSession?.sessionId !== sessionId || !this._isAutoEndWanted()) return;++ const externalMicState = this.audioActivityDetector.getExternalMicState();+ debugLogger.info(+ "Auto-end armed for recording session",+ { sessionId, ...externalMicState },+ "meeting"+ );+ this._audioActivityMonitor.reset();+ this._autoEndController.beginSession({+ sessionId,+ eligible: true,+ reliable: externalMicState.reliable,+ externalMicActive: externalMicState.externalMicActive,+ ...this._audioActivityMonitor.getState(),+ });+ this._autoEndActive = true;+ this._startAutoEndTicker();+ }++ async beginRecordingSession({+ sessionId,+ autoEndEligible,+ ownerWebContents,+ systemAudioAvailable = false,+ }) {+ if (this._recordingSession) this._deactivateAutoEnd();++ this._recordingSession = {+ sessionId,+ autoEndEligible: autoEndEligible === true,+ ownerWebContents,+ systemAudioAvailable: systemAudioAvailable === true,+ };+ this._syncMeetingProcessDetector();++ if (!this._isAutoEndWanted()) {+ this._syncAudioActivityDetector();+ return;+ }++ await this._activateAutoEnd(sessionId);+ }++ async setRecordingSystemAudioAvailable(sessionId, available, ownerWebContents) {+ const session = this._recordingSession;+ if (+ !session ||+ session.sessionId !== sessionId ||+ (ownerWebContents && session.ownerWebContents !== ownerWebContents)+ ) {+ return false;+ }++ const autoEndWasWanted = this._isAutoEndWanted();+ session.systemAudioAvailable = available === true;+ const autoEndWanted = this._isAutoEndWanted();++ if (autoEndWasWanted && !autoEndWanted) {+ this._deactivateAutoEnd();+ } else if (!autoEndWasWanted && autoEndWanted) {+ await this._activateAutoEnd(sessionId);+ }++ this._syncMeetingProcessDetector();+ this._syncAudioActivityDetector();+ return true;+ }++ // Returns false only when a *different* session is currently live — the one+ // case where the caller must not tear down shared capture. With no tracked+ // session (e.g. after engine stop at quit) teardown must still proceed.+ endRecordingSession(expectedSessionId) {+ const session = this._recordingSession;+ if (!session) return true;+ if (expectedSessionId != null && session.sessionId !== expectedSessionId) {+ debugLogger.info(+ "Recording session end skipped — another session is live",+ { expectedSessionId, activeSessionId: session.sessionId },+ "meeting"+ );+ return false;+ }++ this._deactivateAutoEnd();+ debugLogger.info(+ "Recording session ended",+ { sessionId: session.sessionId, autoEndEligible: session.autoEndEligible },+ "meeting"+ );+ this._recordingSession = null;+ // Meeting mode was entered when the note was created; the recording it led+ // to is over, so the next call (or the next meeting's reminder) must prompt+ // again. Only the narrow layout's "Back to notes" button cleared it before,+ // which in the wide layout meant no prompts for the rest of the app session.+ if (this._meetingModeActive) this.setMeetingModeActive(false);+ this._syncAudioActivityDetector();+ this._syncMeetingProcessDetector();+ return true;+ }++ keepRecordingSession(sessionId) {+ const session = this._recordingSession;+ if (!this._autoEndActive || !session || session.sessionId !== sessionId) return false;++ const kept = this._autoEndController.keepRecording(sessionId) === true;+ debugLogger.info(+ kept ? "Auto-end paused — user kept recording" : "Keep request lost to expired countdown",+ { sessionId },+ "meeting"+ );+ return kept;+ }++ handleAutoEndNotificationUnavailable(sessionId) {+ const suppressed = this._autoEndController.handleCountdownUnavailable(sessionId) === true;+ if (suppressed) {+ debugLogger.warn(+ "Meeting auto-end suppressed because its countdown was unavailable",+ { sessionId },+ "meeting"+ );+ }+ return suppressed;}// Calendar reminders enter the same pipeline as mic detections, so they share@@ -103,7 +392,11 @@ class MeetingDetectionEngine {return;}- if (this._userRecording || this._postRecordingCooldown) {+ // _userRecording is shared with dictation, so a dictation ending mid-meeting+ // clears it while the recording is still live; the tracked session is the+ // gate that cannot be reset from outside. A prompt shown then would replace+ // a visible auto-end countdown card and let the countdown run on unseen.+ if (this._userRecording || this._postRecordingCooldown || this._recordingSession) {debugLogger.info("Detection queued — user is recording", { detectionId, source }, "meeting");this._notificationQueue.push({ source, key, data });this.activeDetections.set(detectionId, { source, key, data });@@ -166,6 +459,7 @@ class MeetingDetectionEngine {}this.windowManager.showMeetingNotification({+ kind: "detection",detectionId,source,key,@@ -356,6 +650,13 @@ class MeetingDetectionEngine {return;}+ // A dictation's post-recording cooldown can flush while a meeting recording+ // is still live; hold the queue for the flush that follows the recording.+ if (this._recordingSession) {+ debugLogger.info("Holding queued notifications — recording session live", {}, "meeting");+ return;+ }+debugLogger.info("Flushing notification queue",{ count: this._notificationQueue.length },@@ -412,19 +713,21 @@ class MeetingDetectionEngine {setPreferences(prefs) {debugLogger.info("Updating detection preferences", prefs, "meeting");+ const autoEndWasWanted = this._isAutoEndWanted();Object.assign(this.preferences, prefs);-- if (this.preferences.processDetection) {- this.meetingProcessDetector.start();- } else {- this.meetingProcessDetector.stop();+ const autoEndWanted = this._isAutoEndWanted();++ // Toggling auto-end mid-recording takes effect immediately: off dismisses+ // any visible countdown (the recording itself continues); on arms a fresh+ // session from the current mic-ownership state.+ if (autoEndWasWanted && !autoEndWanted) {+ this._deactivateAutoEnd();+ } else if (!autoEndWasWanted && autoEndWanted && this._recordingSession) {+ void this._activateAutoEnd(this._recordingSession.sessionId);}- if (this.preferences.audioDetection) {- this.audioActivityDetector.start();- } else {- this.audioActivityDetector.stop();- }+ this._syncMeetingProcessDetector();+ this._syncAudioActivityDetector();}getPreferences() {@@ -433,12 +736,14 @@ class MeetingDetectionEngine {start() {debugLogger.info("Meeting detection engine started", this.preferences, "meeting");- if (this.preferences.processDetection) this.meetingProcessDetector.start();- if (this.preferences.audioDetection) this.audioActivityDetector.start();+ this._syncMeetingProcessDetector();+ this._syncAudioActivityDetector();}stop() {debugLogger.info("Meeting detection engine stopped", {}, "meeting");+ this._deactivateAutoEnd();+ this._recordingSession = null;this.meetingProcessDetector.stop();this.audioActivityDetector.stop();this.activeDetections.clear();diff --git a/src/helpers/meetingEchoLeakDetector.js b/src/helpers/meetingEchoLeakDetector.jsindex 91b9c4459..da76e91a5 100644--- a/src/helpers/meetingEchoLeakDetector.js+++ b/src/helpers/meetingEchoLeakDetector.js@@ -1,8 +1,14 @@+const {+ pcm16ToFloat32,+ MEETING_MIC_ACTIVITY_RMS,+ MEETING_SYSTEM_ACTIVITY_RMS,+} = require("../utils/audioUtils");+const SAMPLE_RATE = 24000;const MAX_SYSTEM_HISTORY_MS = 6000;const MAX_MIC_HISTORY_MS = 12000;-const MIN_RMS = 0.006;-const MIN_SYSTEM_RMS = 0.004;+const MIN_RMS = MEETING_MIC_ACTIVITY_RMS;+const MIN_SYSTEM_RMS = MEETING_SYSTEM_ACTIVITY_RMS;const MAX_LAG_MS = 500;const LAG_STEP_SAMPLES = 120;const PARTIAL_WINDOW_MS = 600;@@ -30,8 +36,6 @@ const DOUBLE_TALK_EXPLAINED = 0.3;const DOUBLE_TALK_RESIDUAL = 0.2;const DOUBLE_TALK_MIC_TO_SYSTEM_RATIO = 1.16;-const { pcm16ToFloat32 } = require("../utils/audioUtils");-function computeRms(samples) {if (!samples.length) {return 0;diff --git a/src/helpers/meetingRecordingSession.ts b/src/helpers/meetingRecordingSession.tsnew file mode 100644index 000000000..90f0ccbea--- /dev/null+++ b/src/helpers/meetingRecordingSession.ts@@ -0,0 +1,207 @@+import type { NoteItem } from "../types/electron";++export function createMeetingRecordingSessionId(+ randomUUID: () => string = () => crypto.randomUUID()+): string {+ return randomUUID();+}++export function canStopMeetingRecordingSession(+ activeSessionId: string | null,+ expectedSessionId?: string | null+): boolean {+ return expectedSessionId == null || activeSessionId === expectedSessionId;+}++export function requestMeetingRecordingAutoEnd(+ payload: { sessionId?: unknown } | null | undefined,+ stopRecording: (sessionId: string) => unknown,+ onError: (error: unknown, sessionId: string) => void+): boolean {+ const sessionId = payload?.sessionId;+ if (typeof sessionId !== "string" || sessionId.trim().length === 0) return false;++ // A rejected stop means the recording is still running while main already+ // considers the countdown expired — surface it instead of swallowing it.+ void Promise.resolve(stopRecording(sessionId)).catch((error) => onError(error, sessionId));+ return true;+}++export function isMeetingAutoEndEligible(+ note: Pick<NoteItem, "note_type"> | null | undefined+): boolean {+ return note?.note_type === "meeting";+}++export interface MeetingRecordingStopBarrier {+ runStop<T>(operation: () => Promise<T> | T): Promise<T>;+ waitForPendingStop(): Promise<unknown>;+}++export function createMeetingRecordingStopBarrier(): MeetingRecordingStopBarrier {+ let pendingStop: Promise<unknown> | null = null;++ const waitForPendingStop = (): Promise<unknown> => pendingStop ?? Promise.resolve();+ const runStop = <T>(operation: () => Promise<T> | T): Promise<T> => {+ // Concurrent callers share the in-flight stop's result.+ if (pendingStop) return pendingStop as Promise<T>;++ const stopPromise = Promise.resolve().then(operation);+ pendingStop = stopPromise;+ void stopPromise.then(+ () => {+ if (pendingStop === stopPromise) pendingStop = null;+ },+ () => {+ if (pendingStop === stopPromise) pendingStop = null;+ }+ );+ return stopPromise;+ };++ return { runStop, waitForPendingStop };+}++export interface MeetingRecordingStartOperation {+ sessionId: string;+ isCurrent(): boolean;+ markMainStartAttempted(): void;+ markCommitted(): void;+ stopMainOnce(stopMain: () => Promise<unknown> | unknown): Promise<unknown>;+}++interface PendingStart<T> {+ sessionId: string;+ start: (operation: MeetingRecordingStartOperation) => Promise<T> | T;+ resolveStart: (value: T) => void;+ rejectStart: (error: unknown) => void;+ settleStart: () => void;+ settled: Promise<void>;+ canceled: boolean;+ committed: boolean;+ mainStartAttempted: boolean;+ mainStopPromise: Promise<unknown> | null;+}++export interface MeetingRecordingStartCoordinator {+ runStart<T>(+ sessionId: string,+ start: (operation: MeetingRecordingStartOperation) => Promise<T> | T+ ): Promise<T>;+ cancelActiveStart(expectedSessionId?: string | null): Promise<void> | null;+}++export function createMeetingRecordingStartCoordinator(): MeetingRecordingStartCoordinator {+ let activeStart: PendingStart<unknown> | null = null;+ const pendingStarts: PendingStart<unknown>[] = [];++ const startNext = (): void => {+ if (activeStart || pendingStarts.length === 0) return;++ const state = pendingStarts.shift() as PendingStart<unknown>;+ activeStart = state;+ const operation: MeetingRecordingStartOperation = {+ sessionId: state.sessionId,+ isCurrent: () => activeStart === state && !state.canceled,+ markMainStartAttempted: () => {+ state.mainStartAttempted = true;+ },+ markCommitted: () => {+ state.committed = true;+ },+ stopMainOnce: (stopMain) => {+ if (!state.mainStartAttempted) return Promise.resolve();+ if (!state.mainStopPromise) {+ state.mainStopPromise = Promise.resolve().then(stopMain);+ }+ return state.mainStopPromise;+ },+ };++ void Promise.resolve()+ .then(() => state.start(operation))+ .then(+ (value) => {+ if (activeStart === state) activeStart = null;+ state.settleStart();+ state.resolveStart(value);+ startNext();+ },+ (error) => {+ if (activeStart === state) activeStart = null;+ state.settleStart();+ state.rejectStart(error);+ startNext();+ }+ );+ };++ const runStart = <T>(+ sessionId: string,+ start: (operation: MeetingRecordingStartOperation) => Promise<T> | T+ ): Promise<T> => {+ let resolveStart!: (value: T) => void;+ let rejectStart!: (error: unknown) => void;+ const startPromise = new Promise<T>((resolve, reject) => {+ resolveStart = resolve;+ rejectStart = reject;+ });+ let settleStart!: () => void;+ const settled = new Promise<void>((resolve) => {+ settleStart = resolve;+ });++ // The queue is heterogeneous; each entry's T is only observed by its own+ // resolve/reject pair, so widening to unknown is safe.+ pendingStarts.push({+ sessionId,+ start,+ resolveStart,+ rejectStart,+ settleStart,+ settled,+ canceled: false,+ committed: false,+ mainStartAttempted: false,+ mainStopPromise: null,+ } as PendingStart<unknown>);+ startNext();+ return startPromise;+ };++ const cancelActiveStart = (expectedSessionId?: string | null): Promise<void> | null => {+ if (+ !activeStart ||+ activeStart.committed ||+ (expectedSessionId != null && activeStart.sessionId !== expectedSessionId)+ ) {+ return null;+ }++ activeStart.canceled = true;+ return activeStart.settled;+ };++ return { cancelActiveStart, runStart };+}++export async function teardownFailedMeetingRecordingSetup({+ stopBarrier,+ cleanup,+ stopMain,+ releaseSession,+}: {+ stopBarrier: MeetingRecordingStopBarrier;+ cleanup: () => Promise<unknown> | unknown;+ stopMain: () => Promise<unknown> | unknown;+ releaseSession: () => void;+}): Promise<void> {+ try {+ await stopBarrier.runStop(async () => {+ await cleanup();+ await stopMain();+ });+ } finally {+ releaseSession();+ }+}diff --git a/src/helpers/meetingTranscriptPersistence.ts b/src/helpers/meetingTranscriptPersistence.tsnew file mode 100644index 000000000..f60b19eca--- /dev/null+++ b/src/helpers/meetingTranscriptPersistence.ts@@ -0,0 +1,37 @@+import type { TranscriptSegment } from "../stores/meetingRecordingStore";++// The final transcript is persisted from the store's stop path, not from a+// notes-view effect: a recording can stop without the user driving it+// (auto-end, owner loss) while another view is open, and any persistence keyed+// to a mounted editor would silently drop the tail since the last periodic+// save. Delayed diarization results are handled by the store's #1495 listener.+//+// The captured segments are final the moment the stop begins, and the note+// editor swaps to the stored transcript as soon as isRecording flips — so they+// are written before the main-side stop (which can take seconds) is awaited.+// Only a segment-less recording waits for main's final transcript.+export async function persistFinalTranscriptAroundStop<T>({+ segments,+ serializeSegments,+ persist,+ stop,+ fallbackTranscript,+}: {+ segments: TranscriptSegment[];+ serializeSegments: (segments: TranscriptSegment[]) => string;+ persist: (transcript: string) => Promise<void>;+ stop: () => Promise<T>;+ fallbackTranscript: () => string;+}): Promise<T> {+ const segmentWrite = segments.length > 0 ? persist(serializeSegments(segments)) : null;++ const result = await stop();++ if (segmentWrite) {+ await segmentWrite;+ } else {+ const fallback = fallbackTranscript();+ if (fallback) await persist(fallback);+ }+ return result;+}diff --git a/src/helpers/meetingTranscriptionLifecycle.js b/src/helpers/meetingTranscriptionLifecycle.jsnew file mode 100644index 000000000..d967ba2d0--- /dev/null+++ b/src/helpers/meetingTranscriptionLifecycle.js@@ -0,0 +1,114 @@+function createMeetingTranscriptionLifecycle({ start, stop, onError = () => {} }) {+ let operationTail = Promise.resolve();+ const sessions = new Map();++ const enqueue = (operation) => {+ const pending = operationTail.then(operation, operation);+ operationTail = pending.then(+ () => undefined,+ () => undefined+ );+ return pending;+ };++ const detachOwnerListeners = (session) => {+ if (!session.ownerLossHandler) return;++ session.ownerWebContents?.removeListener?.("destroyed", session.ownerLossHandler);+ session.ownerWebContents?.removeListener?.("render-process-gone", session.ownerLossHandler);+ session.ownerLossHandler = null;+ };++ const removeSession = (session) => {+ detachOwnerListeners(session);+ if (sessions.get(session.sessionId) === session) {+ sessions.delete(session.sessionId);+ }+ };++ const resolveSession = (expectedSessionId) => {+ if (expectedSessionId != null) return sessions.get(expectedSessionId) ?? null;+ return sessions.values().next().value ?? null;+ };++ const stopSession = (expectedSessionId) => {+ const session = resolveSession(expectedSessionId);+ if (!session) {+ return Promise.resolve({ success: false, reason: "stale-session" });+ }+ if (session.stopPromise) return session.stopPromise;++ session.stopRequested = true;+ session.state = "stopping";+ session.stopPromise = enqueue(async () => {+ try {+ if (!session.startSucceeded) return { success: true };+ return await stop(session.sessionId);+ } finally {+ removeSession(session);+ }+ });+ return session.stopPromise;+ };++ const startSession = ({ sessionId, ownerWebContents, options }) => {+ const operationInProgress = [...sessions.values()].some(+ (session) => session.state !== "stopping"+ );+ if (operationInProgress || sessions.has(sessionId)) {+ return Promise.resolve({ success: false, error: "Operation in progress" });+ }++ const session = {+ sessionId,+ ownerWebContents,+ state: "queued",+ startSucceeded: false,+ stopRequested: false,+ stopPromise: null,+ ownerLossHandler: null,+ };+ sessions.set(sessionId, session);++ const startPromise = enqueue(async () => {+ if (session.stopRequested) {+ removeSession(session);+ return { success: false, error: "Start canceled", reason: "canceled", sessionId };+ }++ session.state = "starting";+ try {+ const result = await start({ sessionId, ownerWebContents, options });+ session.startSucceeded = result?.success === true;+ if (!session.startSucceeded) {+ removeSession(session);+ } else if (!session.stopRequested) {+ session.state = "active";+ }+ return result;+ } catch (error) {+ removeSession(session);+ throw error;+ }+ });++ const handleOwnerLoss = () => {+ void stopSession(sessionId).catch((error) => {+ onError(error, sessionId);+ });+ };+ session.ownerLossHandler = handleOwnerLoss;+ ownerWebContents?.once?.("destroyed", handleOwnerLoss);+ ownerWebContents?.once?.("render-process-gone", handleOwnerLoss);++ if (ownerWebContents?.isDestroyed?.()) {+ handleOwnerLoss();+ }++ return startPromise;+ };++ return { startSession, stopSession };+}++module.exports = createMeetingTranscriptionLifecycle;diff --git a/src/helpers/windowConfig.js b/src/helpers/windowConfig.jsindex 192e06db8..ccb3de761 100644--- a/src/helpers/windowConfig.js+++ b/src/helpers/windowConfig.js@@ -110,6 +110,7 @@ const NOTIFICATION_WINDOW_CONFIG = {focusable: false,hasShadow: false,show: false,+ acceptFirstMouse: true,webPreferences: {preload: path.join(__dirname, "..", "..", "preload.js"),nodeIntegration: false,@@ -120,6 +121,21 @@ const NOTIFICATION_WINDOW_CONFIG = {type: FLOATING_OVERLAY_TYPE,};+const AUTO_END_NOTIFICATION_WINDOW_SIZE = {+ width: 620,+ height: 116,+};++function getMeetingNotificationWindowSize(promptData) {+ if (promptData?.kind === "auto-end") {+ return AUTO_END_NOTIFICATION_WINDOW_SIZE;+ }+ return {+ width: NOTIFICATION_WINDOW_CONFIG.width,+ height: NOTIFICATION_WINDOW_CONFIG.height,+ };+}+const TRANSCRIPTION_PREVIEW_SIZE_LIMITS = {minWidth: 400,defaultWidth: 460,@@ -191,8 +207,8 @@ class WindowPositionUtil {};}- static getNotificationPosition(display) {- const { width, height } = NOTIFICATION_WINDOW_CONFIG;+ static getNotificationPosition(display, customSize = null) {+ const { width, height } = customSize || NOTIFICATION_WINDOW_CONFIG;const MARGIN = 16;const workArea = display.workArea || display.bounds;// Same negative-origin trap as getMainWindowPosition: clamp to the display,@@ -287,6 +303,8 @@ module.exports = {CONTROL_PANEL_CONFIG,AGENT_OVERLAY_CONFIG,NOTIFICATION_WINDOW_CONFIG,+ AUTO_END_NOTIFICATION_WINDOW_SIZE,+ getMeetingNotificationWindowSize,TRANSCRIPTION_PREVIEW_CONFIG,TRANSCRIPTION_PREVIEW_SIZE_LIMITS,WINDOW_SIZES,diff --git a/src/helpers/windowManager.js b/src/helpers/windowManager.jsindex 1c397825f..782c56818 100644--- a/src/helpers/windowManager.js+++ b/src/helpers/windowManager.js@@ -9,11 +9,13 @@ const dockManager = require("./dockManager");const { i18nMain } = require("./i18nMain");const { NotificationDismissTimer, getNotificationTimeoutMs } = require("./notificationTimer");const { DEV_SERVER_PORT } = DevServerManager;+const AUTO_END_NOTIFICATION_LOAD_TIMEOUT_MS = 10_000;const {MAIN_WINDOW_CONFIG,CONTROL_PANEL_CONFIG,AGENT_OVERLAY_CONFIG,NOTIFICATION_WINDOW_CONFIG,+ getMeetingNotificationWindowSize,TRANSCRIPTION_PREVIEW_CONFIG,TRANSCRIPTION_PREVIEW_SIZE_LIMITS,WINDOW_SIZES,@@ -26,6 +28,7 @@ class WindowManager {this.controlPanelWindow = null;this.agentWindow = null;this.notificationWindow = null;+ this._notificationLoadTimeout = null;this._notificationDismissTimer = new NotificationDismissTimer(() => {if (this.meetingDetectionEngine) {this.meetingDetectionEngine.handleNotificationTimeout();@@ -1245,22 +1248,60 @@ class WindowManager {}}- async showMeetingNotification(promptData) {+ async showMeetingNotification(promptData, { autoDismiss = true } = {}) {if (this.notificationWindow && !this.notificationWindow.isDestroyed()) {- this.notificationWindow.close();+ const previousWindow = this.notificationWindow;this.notificationWindow = null;+ this._pendingNotificationData = null;+ previousWindow.close();}this._notificationDismissTimer.cancel();+ if (this._notificationLoadTimeout) {+ clearTimeout(this._notificationLoadTimeout);+ this._notificationLoadTimeout = null;+ }+ if (this._notificationReadyFallback) {+ clearTimeout(this._notificationReadyFallback);+ this._notificationReadyFallback = null;+ }const display = screen.getPrimaryDisplay();- const position = WindowPositionUtil.getNotificationPosition(display);+ const notificationSize = getMeetingNotificationWindowSize(promptData);+ const position = WindowPositionUtil.getNotificationPosition(display, notificationSize);const win = new BrowserWindow({...NOTIFICATION_WINDOW_CONFIG,+ ...notificationSize,...position,});this.notificationWindow = win;+ // "closed" fires asynchronously, so a replaced prompt's window emits it+ // after the replacement already took over the reference and the countdown.+ win.on("closed", () => {+ if (this.notificationWindow !== win) return;+ const unavailableAutoEndSessionId =+ this._pendingNotificationData?.kind === "auto-end"+ ? this._pendingNotificationData.sessionId+ : null;+ this.notificationWindow = null;+ this._pendingNotificationData = null;+ this._notificationDismissTimer.cancel();+ if (this._notificationLoadTimeout) {+ clearTimeout(this._notificationLoadTimeout);+ this._notificationLoadTimeout = null;+ }+ if (this._notificationReadyFallback) {+ clearTimeout(this._notificationReadyFallback);+ this._notificationReadyFallback = null;+ }+ if (unavailableAutoEndSessionId) {+ this.meetingDetectionEngine?.handleAutoEndNotificationUnavailable?.(+ unavailableAutoEndSessionId+ );+ }+ });+// Keep the prompt visible to the user but out of screen shares and recordings.win.setContentProtection(true);@@ -1275,49 +1316,79 @@ class WindowManager {// Everything past the load addresses `win` directly: a replacement taking// over mid-load must not have this prompt's data, countdown or force-show// applied to its window.- if (process.env.NODE_ENV === "development") {- await DevServerManager.waitForDevServer();- await win.loadURL(`${DevServerManager.DEV_SERVER_URL}?meeting-notification=true`);- } else {- const fileInfo = DevServerManager.getAppFilePath(false);- await win.loadFile(fileInfo.path, {- query: { ...fileInfo.query, "meeting-notification": "true" },- });+ let loadTimeout = null;+ try {+ const loadNotification = async () => {+ if (process.env.NODE_ENV === "development") {+ await DevServerManager.waitForDevServer();+ if (this.notificationWindow !== win) return;+ await win.loadURL(`${DevServerManager.DEV_SERVER_URL}?meeting-notification=true`);+ return;+ }++ const fileInfo = DevServerManager.getAppFilePath(false);+ await win.loadFile(fileInfo.path, {+ query: { ...fileInfo.query, "meeting-notification": "true" },+ });+ };+ const loadPromise = loadNotification();+ if (promptData?.kind === "auto-end") {+ const timeoutPromise = new Promise((_, reject) => {+ loadTimeout = setTimeout(() => {+ if (this._notificationLoadTimeout === loadTimeout) {+ this._notificationLoadTimeout = null;+ }+ reject(new Error("Meeting auto-end notification load timed out"));+ }, AUTO_END_NOTIFICATION_LOAD_TIMEOUT_MS);+ this._notificationLoadTimeout = loadTimeout;+ });+ await Promise.race([loadPromise, timeoutPromise]);+ } else {+ await loadPromise;+ }+ } catch (error) {+ // A load aborted by our own replacement or dismissal is not a failure.+ if (this.notificationWindow !== win) return;+ this.dismissMeetingNotification();+ throw error;+ } finally {+ if (loadTimeout && this._notificationLoadTimeout === loadTimeout) {+ clearTimeout(loadTimeout);+ this._notificationLoadTimeout = null;+ }}if (this.notificationWindow !== win) return;- this._notificationReadyFallback = setTimeout(() => {+ const readyFallback = setTimeout(() => {+ if (this._notificationReadyFallback !== readyFallback) return;this._notificationReadyFallback = null;- if (!win.isDestroyed()) {- debugLogger.warn(- "Notification renderer did not signal ready, force-showing",- {},- "meeting"- );- win.webContents.send("meeting-notification-data", promptData);- win.showInactive();- }+ if (this.notificationWindow !== win || win.isDestroyed()) return;+ debugLogger.warn("Notification renderer did not signal ready, force-showing", {}, "meeting");+ win.webContents.send("meeting-notification-data", promptData);+ win.showInactive();}, 3000);+ this._notificationReadyFallback = readyFallback;- this._notificationDismissTimer.start(getNotificationTimeoutMs(promptData.source));-- // "closed" fires asynchronously, so a replaced prompt's window emits it- // after the replacement already took over the reference and the countdown.- win.on("closed", () => {- if (this.notificationWindow !== win) return;- this.notificationWindow = null;- this._notificationDismissTimer.cancel();- });+ // The auto-end countdown is owned by its controller — it stays until kept,+ // canceled by fresh activity, or expired — so it never auto-dismisses.+ if (autoDismiss) {+ this._notificationDismissTimer.start(getNotificationTimeoutMs(promptData.source));+ }}- showNotificationWindow() {+ // Only the window that loaded the prompt may reveal it: a stale window's late+ // "ready" must not clear the fallback that would force-show its replacement.+ showNotificationWindow(ownerWebContents) {+ const win = this.notificationWindow;+ if (!win || win.isDestroyed() || (ownerWebContents && win.webContents !== ownerWebContents)) {+ return;+ }+if (this._notificationReadyFallback) {clearTimeout(this._notificationReadyFallback);this._notificationReadyFallback = null;}- if (this.notificationWindow && !this.notificationWindow.isDestroyed()) {- this.notificationWindow.showInactive();- }+ win.showInactive();}dismissMeetingNotification() {@@ -1327,10 +1398,30 @@ class WindowManager {this._notificationReadyFallback = null;}this._notificationDismissTimer.cancel();- if (this.notificationWindow && !this.notificationWindow.isDestroyed()) {- this.notificationWindow.close();+ if (this._notificationLoadTimeout) {+ clearTimeout(this._notificationLoadTimeout);+ this._notificationLoadTimeout = null;}+ const win = this.notificationWindow;this.notificationWindow = null;+ if (win && !win.isDestroyed()) win.close();+ }++ showMeetingAutoEndCountdown({ sessionId, expiresAt, reason }) {+ return this.showMeetingNotification(+ { kind: "auto-end", sessionId, expiresAt, reason },+ { autoDismiss: false }+ );+ }++ dismissMeetingAutoEndCountdown(sessionId) {+ if (+ this._pendingNotificationData?.kind !== "auto-end" ||+ this._pendingNotificationData.sessionId !== sessionId+ ) {+ return;+ }+ this.dismissMeetingNotification();}async showUpdateNotification(info) {diff --git a/src/locales/de/translation.json b/src/locales/de/translation.jsonindex 673970429..15b98eb1a 100644--- a/src/locales/de/translation.json+++ b/src/locales/de/translation.json@@ -29,6 +29,10 @@"speakerDetection": {"title": "Sprecher erkennen und beschriften","description": "Wenn deaktiviert, zeigen Transkripte „Du“ und „Andere“"+ },+ "autoEnd": {+ "title": "Vergessene Aufnahmen automatisch beenden",+ "description": "Beendet Meeting-Aufnahmen automatisch, wenn das Gespräch beendet scheint – nach einem Countdown, den Sie abbrechen können"}}},@@ -2832,7 +2836,8 @@"title": "Besprechungsnotizen","description": "Transkriptionen und strukturierte Zusammenfassungen","back": "Zurück",- "restrictedByOrg": "Die Transkription von Besprechungen ist durch Ihre Organisation eingeschränkt."+ "restrictedByOrg": "Die Transkription von Besprechungen ist durch Ihre Organisation eingeschränkt.",+ "autoEnded": "Die Aufnahme wurde nach dem Ende des Meetings automatisch beendet."},"meetingPill": {"returnToNote": "Zurück zur Aufnahme",@@ -3517,6 +3522,15 @@"underway": "Es klingt, als wäre dein Meeting schon im Gange. Notizen aufnehmen?"},"start": "Notizen aufnehmen",- "join": "Beitreten & transkribieren"+ "join": "Beitreten & transkribieren",+ "autoEnd": {+ "title": "Das Meeting könnte beendet sein",+ "body": {+ "micReleased": "Keine andere App nutzt Ihr Mikrofon. Die Aufnahme stoppt in {{seconds}} s.",+ "silence": "Kein Ton erkannt. Die Aufnahme stoppt in {{seconds}} s.",+ "processExit": "Ihre Meeting-App wurde geschlossen. Die Aufnahme stoppt in {{seconds}} s."+ },+ "keep": "Aufnahme fortsetzen"+ }}}diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex ff2bd4948..a95534445 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -29,6 +29,10 @@"speakerDetection": {"title": "Identify and label speakers","description": "When off, transcripts show \"You\" and \"Others\""+ },+ "autoEnd": {+ "title": "Auto-end forgotten recordings",+ "description": "Stop meeting recordings automatically when the call seems over, after a countdown you can cancel"}}},@@ -2832,7 +2836,8 @@"title": "Meeting Notes","description": "Transcriptions & structured summaries","back": "Back",- "restrictedByOrg": "Meeting transcription is restricted by your organization."+ "restrictedByOrg": "Meeting transcription is restricted by your organization.",+ "autoEnded": "Recording stopped automatically after your meeting ended."},"meetingPill": {"returnToNote": "Return to recording",@@ -3517,6 +3522,15 @@"underway": "It sounds like your meeting is underway. Want to take notes?"},"start": "Take notes",- "join": "Join & transcribe"+ "join": "Join & transcribe",+ "autoEnd": {+ "title": "Meeting may have ended",+ "body": {+ "micReleased": "No other app is using your microphone. Recording will stop in {{seconds}}s.",+ "silence": "No audio detected. Recording will stop in {{seconds}}s.",+ "processExit": "Your meeting app closed. Recording will stop in {{seconds}}s."+ },+ "keep": "Keep recording"+ }}}diff --git a/src/locales/es/translation.json b/src/locales/es/translation.jsonindex 40573498e..19a27c0da 100644--- a/src/locales/es/translation.json+++ b/src/locales/es/translation.json@@ -29,6 +29,10 @@"speakerDetection": {"title": "Identificar y etiquetar participantes","description": "Cuando está desactivado, las transcripciones muestran \"Tú\" y \"Otros\""+ },+ "autoEnd": {+ "title": "Finalizar grabaciones olvidadas",+ "description": "Detiene las grabaciones de reuniones automáticamente cuando la llamada parece haber terminado, tras una cuenta atrás que puedes cancelar"}}},@@ -2673,7 +2677,8 @@"title": "Notas de reunión","description": "Transcripciones y resúmenes estructurados","back": "Atrás",- "restrictedByOrg": "La transcripción de reuniones está restringida por tu organización."+ "restrictedByOrg": "La transcripción de reuniones está restringida por tu organización.",+ "autoEnded": "La grabación se detuvo automáticamente cuando terminó la reunión."},"meetingPill": {"returnToNote": "Volver a la grabación",@@ -3517,6 +3522,15 @@"underway": "Parece que tu reunión ya está en curso. ¿Quieres tomar notas?"},"start": "Tomar notas",- "join": "Unirse y transcribir"+ "join": "Unirse y transcribir",+ "autoEnd": {+ "title": "Es posible que la reunión haya terminado",+ "body": {+ "micReleased": "Ninguna otra app está usando el micrófono. La grabación se detendrá en {{seconds}}s.",+ "silence": "No se detecta audio. La grabación se detendrá en {{seconds}}s.",+ "processExit": "La app de reuniones se cerró. La grabación se detendrá en {{seconds}}s."+ },+ "keep": "Seguir grabando"+ }}}diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.jsonindex 0f059945f..7fa9c16c1 100644--- a/src/locales/fr/translation.json+++ b/src/locales/fr/translation.json@@ -29,6 +29,10 @@"speakerDetection": {"title": "Identifier et étiqueter les intervenants","description": "Lorsque désactivé, les transcriptions affichent « Vous » et « Autres »"+ },+ "autoEnd": {+ "title": "Terminer les enregistrements oubliés",+ "description": "Arrête automatiquement les enregistrements de réunion quand l'appel semble terminé, après un compte à rebours annulable"}}},@@ -2832,7 +2836,8 @@"title": "Notes de réunion","description": "Transcriptions et résumés structurés","back": "Retour",- "restrictedByOrg": "La transcription des réunions est restreinte par votre organisation."+ "restrictedByOrg": "La transcription des réunions est restreinte par votre organisation.",+ "autoEnded": "L'enregistrement s'est arrêté automatiquement à la fin de votre réunion."},"meetingPill": {"returnToNote": "Revenir à l'enregistrement",@@ -3517,6 +3522,15 @@"underway": "On dirait que votre réunion est déjà en cours. Vous voulez prendre des notes ?"},"start": "Prendre des notes",- "join": "Rejoindre et transcrire"+ "join": "Rejoindre et transcrire",+ "autoEnd": {+ "title": "La réunion est peut-être terminée",+ "body": {+ "micReleased": "Aucune autre app n'utilise votre micro. L'enregistrement s'arrêtera dans {{seconds}}s.",+ "silence": "Aucun son détecté. L'enregistrement s'arrêtera dans {{seconds}}s.",+ "processExit": "Votre app de réunion s'est fermée. L'enregistrement s'arrêtera dans {{seconds}}s."+ },+ "keep": "Continuer l’enregistrement"+ }}}diff --git a/src/locales/it/translation.json b/src/locales/it/translation.jsonindex ee4fe07e6..a35c72f64 100644--- a/src/locales/it/translation.json+++ b/src/locales/it/translation.json@@ -29,6 +29,10 @@"speakerDetection": {"title": "Identifica ed etichetta i partecipanti","description": "Se disattivato, le trascrizioni mostrano \"Tu\" e \"Altri\""+ },+ "autoEnd": {+ "title": "Termina le registrazioni dimenticate",+ "description": "Interrompe automaticamente le registrazioni delle riunioni quando la chiamata sembra finita, dopo un conto alla rovescia annullabile"}}},@@ -2625,7 +2629,8 @@"title": "Note delle riunioni","description": "Trascrizioni e riassunti strutturati","back": "Indietro",- "restrictedByOrg": "La trascrizione delle riunioni è limitata dalla tua organizzazione."+ "restrictedByOrg": "La trascrizione delle riunioni è limitata dalla tua organizzazione.",+ "autoEnded": "La registrazione si è interrotta automaticamente al termine della riunione."},"meetingPill": {"returnToNote": "Torna alla registrazione",@@ -3517,6 +3522,15 @@"underway": "Sembra che la tua riunione sia già in corso. Vuoi prendere appunti?"},"start": "Prendi appunti",- "join": "Partecipa e trascrivi"+ "join": "Partecipa e trascrivi",+ "autoEnd": {+ "title": "La riunione potrebbe essere finita",+ "body": {+ "micReleased": "Nessun'altra app sta usando il microfono. La registrazione si fermerà tra {{seconds}}s.",+ "silence": "Nessun audio rilevato. La registrazione si fermerà tra {{seconds}}s.",+ "processExit": "L'app della riunione è stata chiusa. La registrazione si fermerà tra {{seconds}}s."+ },+ "keep": "Continua a registrare"+ }}}diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.jsonindex e74a47329..56f5c1032 100644--- a/src/locales/ja/translation.json+++ b/src/locales/ja/translation.json@@ -29,6 +29,10 @@"speakerDetection": {"title": "話者を識別してラベル付け","description": "オフにすると、文字起こしには「あなた」と「他の人」と表示されます"+ },+ "autoEnd": {+ "title": "停止し忘れた録音を自動終了",+ "description": "通話が終わったと判断されると、キャンセル可能なカウントダウンの後に会議の録音を自動的に停止します"}}},@@ -2609,7 +2613,8 @@"title": "議事録","description": "文字起こしと構造化されたサマリー","back": "戻る",- "restrictedByOrg": "会議の文字起こしは組織によって制限されています。"+ "restrictedByOrg": "会議の文字起こしは組織によって制限されています。",+ "autoEnded": "会議の終了後、録音は自動的に停止しました。"},"meetingPill": {"returnToNote": "録音に戻る",@@ -3517,6 +3522,15 @@"underway": "会議はすでに進行中のようです。メモを取りますか?"},"start": "メモを取る",- "join": "参加して文字起こし"+ "join": "参加して文字起こし",+ "autoEnd": {+ "title": "会議が終了した可能性があります",+ "body": {+ "micReleased": "ほかのアプリはマイクを使用していません。録音は{{seconds}}秒後に停止します。",+ "silence": "音声が検出されません。録音は{{seconds}}秒後に停止します。",+ "processExit": "会議アプリが終了しました。録音は{{seconds}}秒後に停止します。"+ },+ "keep": "録音を続ける"+ }}}diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.jsonindex 57c883ac3..c93d71bf5 100644--- a/src/locales/pt/translation.json+++ b/src/locales/pt/translation.json@@ -29,6 +29,10 @@"speakerDetection": {"title": "Identificar e rotular participantes","description": "Quando desativado, as transcrições mostram \"Você\" e \"Outros\""+ },+ "autoEnd": {+ "title": "Encerrar gravações esquecidas",+ "description": "Para as gravações de reunião automaticamente quando a chamada parece ter terminado, após uma contagem regressiva que você pode cancelar"}}},@@ -2625,7 +2629,8 @@"title": "Notas de reunião","description": "Transcrições e resumos estruturados","back": "Voltar",- "restrictedByOrg": "A transcrição de reuniões está restrita pela sua organização."+ "restrictedByOrg": "A transcrição de reuniões está restrita pela sua organização.",+ "autoEnded": "A gravação parou automaticamente após o fim da reunião."},"meetingPill": {"returnToNote": "Voltar à gravação",@@ -3517,6 +3522,15 @@"underway": "Parece que sua reunião já está em andamento. Quer fazer anotações?"},"start": "Fazer anotações",- "join": "Entrar e transcrever"+ "join": "Entrar e transcrever",+ "autoEnd": {+ "title": "A reunião pode ter terminado",+ "body": {+ "micReleased": "Nenhum outro app está usando o microfone. A gravação vai parar em {{seconds}}s.",+ "silence": "Nenhum áudio detectado. A gravação vai parar em {{seconds}}s.",+ "processExit": "Seu app de reunião foi fechado. A gravação vai parar em {{seconds}}s."+ },+ "keep": "Continuar gravando"+ }}}diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.jsonindex 7e0627d9f..cb0c2171f 100644--- a/src/locales/ru/translation.json+++ b/src/locales/ru/translation.json@@ -29,6 +29,10 @@"speakerDetection": {"title": "Распознавать и подписывать участников","description": "Если выключено, в транскриптах отображаются «Вы» и «Другие»"+ },+ "autoEnd": {+ "title": "Автозавершение забытых записей",+ "description": "Автоматически останавливает запись встречи, когда звонок, похоже, завершён — после обратного отсчёта, который можно отменить"}}},@@ -2645,7 +2649,8 @@"title": "Заметки со встреч","description": "Транскрипции и структурированные резюме","back": "Назад",- "restrictedByOrg": "Транскрипция встреч ограничена вашей организацией."+ "restrictedByOrg": "Транскрипция встреч ограничена вашей организацией.",+ "autoEnded": "Запись автоматически остановлена после завершения встречи."},"meetingPill": {"returnToNote": "Вернуться к записи",@@ -3545,6 +3550,15 @@"underway": "Похоже, ваша встреча уже идёт. Хотите вести заметки?"},"start": "Вести заметки",- "join": "Присоединиться и вести заметки"+ "join": "Присоединиться и вести заметки",+ "autoEnd": {+ "title": "Возможно, встреча завершилась",+ "body": {+ "micReleased": "Другие приложения не используют микрофон. Запись остановится через {{seconds}} с.",+ "silence": "Звук не обнаружен. Запись остановится через {{seconds}} с.",+ "processExit": "Приложение для встреч закрыто. Запись остановится через {{seconds}} с."+ },+ "keep": "Продолжить запись"+ }}}diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.jsonindex a5821b4e5..f18e32ef5 100644--- a/src/locales/zh-CN/translation.json+++ b/src/locales/zh-CN/translation.json@@ -29,6 +29,10 @@"speakerDetection": {"title": "识别并标记发言者","description": "关闭后,转写会显示\"你\"和\"其他人\""+ },+ "autoEnd": {+ "title": "自动结束遗忘的录音",+ "description": "当通话似乎已结束时,在可取消的倒计时后自动停止会议录音"}}},@@ -2625,7 +2629,8 @@"title": "会议笔记","description": "转录与结构化摘要","back": "返回",- "restrictedByOrg": "会议转录已被您的组织限制。"+ "restrictedByOrg": "会议转录已被您的组织限制。",+ "autoEnded": "会议结束后,录音已自动停止。"},"meetingPill": {"returnToNote": "返回到录音",@@ -3517,6 +3522,15 @@"underway": "你的会议似乎已在进行中。要开始记录吗?"},"start": "开始记录",- "join": "加入并转录"+ "join": "加入并转录",+ "autoEnd": {+ "title": "会议可能已结束",+ "body": {+ "micReleased": "没有其他应用在使用麦克风。录音将在 {{seconds}} 秒后停止。",+ "silence": "未检测到音频。录音将在 {{seconds}} 秒后停止。",+ "processExit": "会议应用已关闭。录音将在 {{seconds}} 秒后停止。"+ },+ "keep": "继续录音"+ }}}diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.jsonindex 71a4acae5..a2bfef3c8 100644--- a/src/locales/zh-TW/translation.json+++ b/src/locales/zh-TW/translation.json@@ -29,6 +29,10 @@"speakerDetection": {"title": "辨識並標記發言者","description": "關閉後,逐字稿會顯示「你」和「其他人」"+ },+ "autoEnd": {+ "title": "自動結束遺忘的錄音",+ "description": "當通話似乎已結束時,在可取消的倒數後自動停止會議錄音"}}},@@ -2625,7 +2629,8 @@"title": "會議筆記","description": "轉錄與結構化摘要","back": "返回",- "restrictedByOrg": "會議轉錄已被您的組織限制。"+ "restrictedByOrg": "會議轉錄已被您的組織限制。",+ "autoEnded": "會議結束後,錄音已自動停止。"},"meetingPill": {"returnToNote": "返回到錄音",@@ -3517,6 +3522,15 @@"underway": "你的會議似乎已在進行中。要開始記錄嗎?"},"start": "開始記錄",- "join": "加入並轉錄"+ "join": "加入並轉錄",+ "autoEnd": {+ "title": "會議可能已結束",+ "body": {+ "micReleased": "沒有其他應用程式在使用麥克風。錄音將在 {{seconds}} 秒後停止。",+ "silence": "未偵測到音訊。錄音將在 {{seconds}} 秒後停止。",+ "processExit": "會議應用程式已關閉。錄音將在 {{seconds}} 秒後停止。"+ },+ "keep": "繼續錄音"+ }}}diff --git a/src/stores/meetingRecordingStore.ts b/src/stores/meetingRecordingStore.tsindex 6174c5fbe..92980866c 100644--- a/src/stores/meetingRecordingStore.ts+++ b/src/stores/meetingRecordingStore.ts@@ -41,6 +41,14 @@ import { parseTranscriptSegments } from "../utils/parseTranscriptSegments";import { resolveDiarizationTarget, selectBaseSegments } from "../utils/diarizationCompletion";import { createSerialQueue } from "../utils/serialQueue";import { reduceMeetingSegmentEvent, type MeetingSegmentEvent } from "./meetingSegmentReducer";+import {+ canStopMeetingRecordingSession,+ createMeetingRecordingStartCoordinator,+ createMeetingRecordingStopBarrier,+ createMeetingRecordingSessionId,+ teardownFailedMeetingRecordingSetup,+} from "../helpers/meetingRecordingSession";+import { persistFinalTranscriptAroundStop } from "../helpers/meetingTranscriptPersistence";export interface TranscriptSegment {id: string;@@ -418,6 +426,9 @@ let systemProcessor: AudioWorkletNode | null = null;let systemStream: MediaStream | null = null;let isRecordingFlag = false;let isStartingFlag = false;+let activeRecordingSessionId: string | null = null;+const meetingRecordingStartCoordinator = createMeetingRecordingStartCoordinator();+const meetingRecordingStopBarrier = createMeetingRecordingStopBarrier();let isPrepared = false;let segmentsRefValue: TranscriptSegment[] = [];let preparePromise: Promise<void> | null = null;@@ -464,6 +475,8 @@ function reportMeetingError(error: string, extra: Partial<MeetingRecordingState>export const getMicAnalyser = (): AnalyserNode | null => micAnalyser;+export const getActiveRecordingSessionId = (): string | null => activeRecordingSessionId;+function pushConfig(enabled: boolean, expectedCount: number, countIsExplicit: boolean) {if (pushConfigTimeout) clearTimeout(pushConfigTimeout);pushConfigTimeout = setTimeout(() => {@@ -750,8 +763,12 @@ export interface StartRecordingArgs {diarizationEnabled?: boolean | null;expectedCount?: number | null;expectedCountIsExplicit?: boolean;+ autoEndEligible: boolean;}+// Resolves false only when workspace policy refuses the recording; every other+// outcome (including setup failures, which are reported through the store) is+// "accepted" so callers don't roll back UI they didn't own.export async function startRecording(args: StartRecordingArgs): Promise<boolean> {if (isRecordingFlag || isStartingFlag) return true;if (!isTranscriptionContextAllowed(usePolicyStore.getState(), getSettings(), "meeting")) {@@ -759,83 +776,128 @@ export async function startRecording(args: StartRecordingArgs): Promise<boolean>reportMeetingError("policyRestricted");return false;}- isStartingFlag = true;-- const initialEnabled =- args.diarizationEnabled ??- (getSettings() as { speakerDiarizationEnabled?: boolean }).speakerDiarizationEnabled ??- true;- const initialCount = Math.max(- 1,- Math.min(MAX_SPEAKER_COUNT, args.expectedCount ?? DEFAULT_EXPECTED_SPEAKER_COUNT)- );- const systemAudioAccessPromise =- window.electronAPI?.checkSystemAudioAccess?.() ?? Promise.resolve(DEFAULT_SYSTEM_AUDIO_ACCESS);-- logger.info("Meeting transcription starting...", {}, "meeting");- const seed = args.seedSegments ?? [];- const locks = new Map<string, string>();- let maxSpeakerIndex = -1;- for (const s of seed) {- const idx = getSpeakerNumericIndex(s.speaker);- if (idx != null && idx > maxSpeakerIndex) maxSpeakerIndex = idx;- if (s.speakerLocked && s.speaker && s.speakerName) {- locks.set(s.speaker, s.speakerName);+ const sessionId = createMeetingRecordingSessionId();+ await meetingRecordingStartCoordinator.runStart(sessionId, async (startOperation) => {+ if (isRecordingFlag || isStartingFlag) return;++ await meetingRecordingStopBarrier.waitForPendingStop();+ if (!startOperation.isCurrent() || isRecordingFlag || isStartingFlag) return;+ isStartingFlag = true;+ activeRecordingSessionId = sessionId;+ const isCurrentStart = () =>+ startOperation.isCurrent() && activeRecordingSessionId === sessionId;++ const initialEnabled =+ args.diarizationEnabled ??+ (getSettings() as { speakerDiarizationEnabled?: boolean }).speakerDiarizationEnabled ??+ true;+ const initialCount = Math.max(+ 1,+ Math.min(MAX_SPEAKER_COUNT, args.expectedCount ?? DEFAULT_EXPECTED_SPEAKER_COUNT)+ );++ logger.info("Meeting transcription starting...", {}, "meeting");+ const seed = args.seedSegments ?? [];+ const locks = new Map<string, string>();+ let maxSpeakerIndex = -1;+ for (const s of seed) {+ const idx = getSpeakerNumericIndex(s.speaker);+ if (idx != null && idx > maxSpeakerIndex) maxSpeakerIndex = idx;+ if (s.speakerLocked && s.speaker && s.speakerName) {+ locks.set(s.speaker, s.speakerName);+ }}- }- segmentsRefValue = seed;- speakerIdentifications = [];- nextPlaceholderSpeakerIndex = maxSpeakerIndex + 1;- recentSystemSpeaker = null;- speakerLocks = locks;- systemPartialSpeakerIdValue = null;+ segmentsRefValue = seed;+ speakerIdentifications = [];+ nextPlaceholderSpeakerIndex = maxSpeakerIndex + 1;+ recentSystemSpeaker = null;+ speakerLocks = locks;+ systemPartialSpeakerIdValue = null;- useMeetingRecordingStore.setState({- isRecording: true,- isTranscribing: true,- recordingNoteId: args.noteId,- recordingNoteTitle: args.noteTitle,- recordingFolderId: args.folderId,- sessionDiarizationEnabled: initialEnabled,- sessionExpectedCount: initialCount,- userTouchedStepper: resolveInitialSpeakerCountOverride(- args.expectedCount,- args.expectedCountIsExplicit- ),- segments: seed,- transcript: buildTranscriptText(seed),- micPartial: "",- systemPartial: "",- systemPartialSpeakerId: null,- systemPartialSpeakerName: null,- diarizationSessionId: null,- completedDiarization: null,- error: null,- micCaptureStatus: "inactive",- });+ useMeetingRecordingStore.setState({+ isRecording: true,+ isTranscribing: true,+ recordingNoteId: args.noteId,+ recordingNoteTitle: args.noteTitle,+ recordingFolderId: args.folderId,+ sessionDiarizationEnabled: initialEnabled,+ sessionExpectedCount: initialCount,+ userTouchedStepper: resolveInitialSpeakerCountOverride(+ args.expectedCount,+ args.expectedCountIsExplicit+ ),+ segments: seed,+ transcript: buildTranscriptText(seed),+ micPartial: "",+ systemPartial: "",+ systemPartialSpeakerId: null,+ systemPartialSpeakerName: null,+ diarizationSessionId: null,+ completedDiarization: null,+ error: null,+ micCaptureStatus: "inactive",+ });++ isRecordingFlag = true;+ let setupMicResult: MediaStream | null = null;+ let setupSystemCaptureResult: { stream: MediaStream | null; error: Error | null } = {+ stream: null,+ error: null,+ };+ const releaseSession = () => {+ if (activeRecordingSessionId === sessionId) activeRecordingSessionId = null;+ };+ const stopScopedMainOnce = () =>+ startOperation.stopMainOnce(async () => {+ await window.electronAPI?.meetingTranscriptionStop?.(sessionId).catch(() => undefined);+ });+ const teardownStart = async () => {+ stopMediaStream(setupMicResult);+ stopMediaStream(setupSystemCaptureResult.stream);+ setupMicResult = null;+ setupSystemCaptureResult = { stream: null, error: null };+ isRecordingFlag = false;+ isStartingFlag = false;+ await teardownFailedMeetingRecordingSetup({+ stopBarrier: meetingRecordingStopBarrier,+ cleanup,+ stopMain: stopScopedMainOnce,+ releaseSession,+ });+ };- isRecordingFlag = true;+ try {+ if (preparePromise) {+ logger.debug("Waiting for in-flight prepare to finish...", {}, "meeting");+ await preparePromise;+ if (!isCurrentStart()) {+ await teardownStart();+ return;+ }+ }- if (preparePromise) {- logger.debug("Waiting for in-flight prepare to finish...", {}, "meeting");- await preparePromise;- }+ const startTime = performance.now();+ const initialSystemAudioAccess =+ (await (window.electronAPI?.checkSystemAudioAccess?.() ??+ Promise.resolve(DEFAULT_SYSTEM_AUDIO_ACCESS))) ?? getFallbackSystemAudioAccess();+ if (!isCurrentStart()) {+ await teardownStart();+ return;+ }+ const { initialSystemAudioStrategy, initialDisplayCaptureStrategy, systemCapturePromise } =+ prepareMeetingSystemAudioCapture(initialSystemAudioAccess);- try {- const startTime = performance.now();- const initialSystemAudioAccess =- (await systemAudioAccessPromise) ?? getFallbackSystemAudioAccess();- const { initialSystemAudioStrategy, initialDisplayCaptureStrategy, systemCapturePromise } =- prepareMeetingSystemAudioCapture(initialSystemAudioAccess);-- const [startResult, micResult, initialSystemCaptureResult] = await Promise.all([- window.electronAPI?.meetingTranscriptionStart?.({+ startOperation.markMainStartAttempted();+ const mainStartPromise = window.electronAPI?.meetingTranscriptionStart?.({...getMeetingTranscriptionOptions(),noteId: args.noteId ?? null,- }),- getMeetingMicConstraints().then(async (constraints) => {+ sessionId,+ autoEndEligible: args.autoEndEligible,+ });+ const micCapturePromise = getMeetingMicConstraints().then(async (constraints) => {+ if (!isCurrentStart()) return null;try {return await navigator.mediaDevices.getUserMedia(constraints);} catch (err) {@@ -843,7 +905,7 @@ export async function startRecording(args: StartRecordingArgs): Promise<boolean>typeof constraints.audio === "object" &&constraints.audio !== null &&"deviceId" in constraints.audio;- if (hasExactDevice) {+ if (hasExactDevice && isCurrentStart()) {try {const fallbackStream = await navigator.mediaDevices.getUserMedia({audio: MEETING_MIC_PRIMARY_AUDIO_CONSTRAINTS,@@ -870,478 +932,626 @@ export async function startRecording(args: StartRecordingArgs): Promise<boolean>);return null;}- }),- systemCapturePromise,- ]);- let systemCaptureResult = initialSystemCaptureResult;-- const streamsMs = performance.now() - startTime;- if (!isRecordingFlag) {- logger.info("Meeting transcription aborted during setup (stop called)", {}, "meeting");- stopMediaStream(micResult);- stopMediaStream(systemCaptureResult.stream);- isStartingFlag = false;- return true;- }+ });+ const [startOutcome, micOutcome, systemCaptureOutcome] = await Promise.allSettled([+ mainStartPromise,+ micCapturePromise,+ systemCapturePromise,+ ] as const);++ if (micOutcome.status === "fulfilled") setupMicResult = micOutcome.value;+ if (systemCaptureOutcome.status === "fulfilled") {+ setupSystemCaptureResult = systemCaptureOutcome.value;+ }+ if (startOutcome.status === "rejected") throw startOutcome.reason;+ if (micOutcome.status === "rejected") throw micOutcome.reason;+ if (systemCaptureOutcome.status === "rejected") throw systemCaptureOutcome.reason;++ const startResult = startOutcome.value;+ const micResult = setupMicResult;+ const initialSystemCaptureResult = setupSystemCaptureResult;+ let systemCaptureResult = initialSystemCaptureResult;++ const streamsMs = performance.now() - startTime;+ if (!isCurrentStart()) {+ logger.info("Meeting transcription aborted during setup (stop called)", {}, "meeting");+ await teardownStart();+ return;+ }- if (!startResult?.success) {- logger.error(- "Meeting transcription IPC start failed",- { error: startResult?.error },- "meeting"- );- reportMeetingError(startResult?.error || "Failed to start meeting transcription", {- isRecording: false,- isTranscribing: false,+ if (!startResult?.success) {+ logger.error(+ "Meeting transcription IPC start failed",+ { error: startResult?.error },+ "meeting"+ );+ reportMeetingError(startResult?.error || "Failed to start meeting transcription", {+ isRecording: false,+ isTranscribing: false,+ });+ stopMediaStream(micResult);+ stopMediaStream(systemCaptureResult.stream);+ setupMicResult = null;+ setupSystemCaptureResult = { stream: null, error: null };+ isRecordingFlag = false;+ isStartingFlag = false;+ releaseSession();+ return;+ }+ const systemAudioMode = startResult.systemAudioMode || initialSystemAudioAccess.mode;+ const systemAudioStrategy = startResult.systemAudioStrategy || initialSystemAudioStrategy;+ systemCaptureResult = await ensureRendererSystemAudioCapture({+ initialDisplayCaptureStrategy,+ systemAudioStrategy,+ systemCaptureResult,});- stopMediaStream(micResult);- stopMediaStream(systemCaptureResult.stream);- isRecordingFlag = false;- isStartingFlag = false;- return true;- }+ setupSystemCaptureResult = systemCaptureResult;+ if (!isCurrentStart()) {+ await teardownStart();+ return;+ }+ const systemAudioHandledInMain =+ systemAudioMode !== "unsupported" && !isRendererSystemAudioStrategy(systemAudioStrategy);+ if (systemAudioHandledInMain && systemCaptureResult.stream) {+ stopMediaStream(systemCaptureResult.stream);+ systemCaptureResult = { stream: null, error: null };+ setupSystemCaptureResult = systemCaptureResult;+ }+ const systemCaptureError = systemAudioHandledInMain ? null : systemCaptureResult.error;- const systemAudioMode = startResult.systemAudioMode || initialSystemAudioAccess.mode;- const systemAudioStrategy = startResult.systemAudioStrategy || initialSystemAudioStrategy;- systemCaptureResult = await ensureRendererSystemAudioCapture({- initialDisplayCaptureStrategy,- systemAudioStrategy,- systemCaptureResult,- });- const systemAudioHandledInMain =- systemAudioMode !== "unsupported" && !isRendererSystemAudioStrategy(systemAudioStrategy);- if (systemAudioHandledInMain && systemCaptureResult.stream) {- stopMediaStream(systemCaptureResult.stream);- systemCaptureResult = { stream: null, error: null };- }- const systemCaptureError = systemAudioHandledInMain ? null : systemCaptureResult.error;+ if (!micResult && (systemAudioHandledInMain || systemCaptureResult.stream)) {+ reportMeetingError("Microphone capture failed. Continuing with system audio only.");+ }- if (!micResult && (systemAudioHandledInMain || systemCaptureResult.stream)) {- reportMeetingError("Microphone capture failed. Continuing with system audio only.");- }+ if (!micResult && !systemCaptureResult.stream && !systemAudioHandledInMain) {+ logger.error("Meeting transcription has no available audio source", {}, "meeting");+ reportMeetingError(+ systemAudioMode === "unsupported"+ ? "No microphone is available and system audio capture is unsupported on this device."+ : systemCaptureError?.message ||+ "No microphone is available and system audio capture could not be started.",+ { isRecording: false, isTranscribing: false }+ );+ await teardownStart();+ return;+ }- if (!micResult && !systemCaptureResult.stream && !systemAudioHandledInMain) {- logger.error("Meeting transcription has no available audio source", {}, "meeting");- reportMeetingError(- systemAudioMode === "unsupported"- ? "No microphone is available and system audio capture is unsupported on this device."- : systemCaptureError?.message ||- "No microphone is available and system audio capture could not be started.",- { isRecording: false, isTranscribing: false }- );- await window.electronAPI?.meetingTranscriptionStop?.();- isRecordingFlag = false;- isStartingFlag = false;- return true;- }+ const segmentCleanup = window.electronAPI?.onMeetingTranscriptionSegment?.(+ (data: MeetingSegmentEvent) => {+ if (activeRecordingSessionId !== sessionId) return;+ const current = useMeetingRecordingStore.getState();+ const reduction = reduceMeetingSegmentEvent(+ {+ segments: current.segments,+ micPartial: current.micPartial,+ systemPartial: current.systemPartial,+ },+ data,+ {+ mintSegmentId: () => `seg-${++segmentCounter}`,+ // Must not call setState: `current.segments` was snapshotted before this runs and the+ // reduction inserts into that snapshot. Reads of segmentsRefValue (assignProvisionalSpeaker)+ // still see the previous segments, exactly as before the reducer extraction.+ decorateFinal: (rawSegment) => {+ let decorated = rawSegment;+ for (let i = speakerIdentifications.length - 1; i >= 0; i -= 1) {+ decorated = applySpeakerIdentification(decorated, speakerIdentifications[i]);+ }+ const provisional = assignProvisionalSpeaker(decorated);+ reserveSpeakerIndex(provisional.speaker);+ const lockedName = provisional.speaker+ ? speakerLocks.get(provisional.speaker)+ : undefined;+ return lockedName+ ? lockTranscriptSpeaker(provisional, {+ speakerName: lockedName,+ speakerIsPlaceholder: false,+ suggestedName: undefined,+ suggestedProfileId: undefined,+ })+ : provisional;+ },+ }+ );- const segmentCleanup = window.electronAPI?.onMeetingTranscriptionSegment?.(- (data: MeetingSegmentEvent) => {- const current = useMeetingRecordingStore.getState();- const reduction = reduceMeetingSegmentEvent(- {- segments: current.segments,- micPartial: current.micPartial,- systemPartial: current.systemPartial,- },- data,- {- mintSegmentId: () => `seg-${++segmentCounter}`,- // Must not call setState: `current.segments` was snapshotted before this runs and the- // reduction inserts into that snapshot. Reads of segmentsRefValue (assignProvisionalSpeaker)- // still see the previous segments, exactly as before the reducer extraction.- decorateFinal: (rawSegment) => {- let decorated = rawSegment;- for (let i = speakerIdentifications.length - 1; i >= 0; i -= 1) {- decorated = applySpeakerIdentification(decorated, speakerIdentifications[i]);+ if (reduction.kind === "retract") {+ segmentsRefValue = reduction.state.segments;+ useMeetingRecordingStore.setState({+ segments: reduction.state.segments,+ transcript: buildTranscriptText(reduction.state.segments),+ });+ return;+ }++ if (reduction.kind === "partial") {+ if (reduction.source === "mic") {+ useMeetingRecordingStore.setState({ micPartial: reduction.state.micPartial });+ } else {+ useMeetingRecordingStore.setState({ systemPartial: reduction.state.systemPartial });+ if (!systemPartialSpeakerIdValue) {+ // Reuse the recent system speaker before minting — the partial id is+ // cleared after every final, so always minting spawned one per utterance.+ const carried = getRecentSystemSpeaker(Date.now());+ setSystemPartialSpeakerIdentity(+ carried?.speakerId ?? mintPlaceholderSpeakerId(),+ carried?.speakerName ?? null+ );}- const provisional = assignProvisionalSpeaker(decorated);- reserveSpeakerIndex(provisional.speaker);- const lockedName = provisional.speaker- ? speakerLocks.get(provisional.speaker)- : undefined;- return lockedName- ? lockTranscriptSpeaker(provisional, {- speakerName: lockedName,- speakerIsPlaceholder: false,- suggestedName: undefined,- suggestedProfileId: undefined,- })- : provisional;- },+ }+ return;}- );- if (reduction.kind === "retract") {+ const seg = reduction.inserted;segmentsRefValue = reduction.state.segments;+ // Only the cleared partial goes in the payload (spreading both partial fields would add a+ // key the pre-reducer code never wrote), so derive it from the inserted segment's source.+ const partialPatch = seg.source === "mic" ? { micPartial: "" } : { systemPartial: "" };useMeetingRecordingStore.setState({segments: reduction.state.segments,transcript: buildTranscriptText(reduction.state.segments),+ ...partialPatch,});- return;+ if (seg.source === "system" && seg.speaker) {+ rememberSystemSpeaker(+ seg.speaker,+ seg.speakerName ?? null,+ !!seg.speakerIsPlaceholder,+ seg.timestamp ?? Date.now()+ );+ }+ if (seg.source === "system") {+ setSystemPartialSpeakerIdentity(null, null);+ }}-- if (reduction.kind === "partial") {- if (reduction.source === "mic") {- useMeetingRecordingStore.setState({ micPartial: reduction.state.micPartial });- } else {- useMeetingRecordingStore.setState({ systemPartial: reduction.state.systemPartial });- if (!systemPartialSpeakerIdValue) {- // Reuse the recent system speaker before minting — the partial id is- // cleared after every final, so always minting spawned one per utterance.- const carried = getRecentSystemSpeaker(Date.now());- setSystemPartialSpeakerIdentity(- carried?.speakerId ?? mintPlaceholderSpeakerId(),- carried?.speakerName ?? null- );+ );+ if (segmentCleanup) ipcCleanups.push(segmentCleanup);++ const speakerCleanup = window.electronAPI?.onMeetingSpeakerIdentified?.((data) => {+ if (activeRecordingSessionId !== sessionId) return;+ reserveSpeakerIndex(data.speakerId);+ setSystemPartialSpeakerIdentity(data.speakerId, data.displayName ?? null);+ rememberSystemSpeaker(data.speakerId, data.displayName ?? null, false, data.endTime);+ speakerIdentifications = [+ ...speakerIdentifications.filter(+ (id) => id.endTime >= data.endTime - SPEAKER_IDENTIFICATION_RETENTION_MS+ ),+ data,+ ];+ const next = useMeetingRecordingStore+ .getState()+ .segments.map((segment) => applySpeakerIdentification(segment, data));+ segmentsRefValue = next;+ useMeetingRecordingStore.setState({ segments: next });+ });+ if (speakerCleanup) ipcCleanups.push(speakerCleanup);++ const mergeCleanup = window.electronAPI?.onMeetingSpeakersMerged?.((merges) => {+ if (activeRecordingSessionId !== sessionId) return;+ let next = useMeetingRecordingStore.getState().segments;+ for (const { keep, remove, displayName } of merges) {+ next = next.map((seg) => {+ if (seg.speaker !== remove) return seg;+ // Locked segments keep their user-set name but must still move to the+ // kept cluster: the removed id no longer exists in the identifier, so+ // later merges and renames would never reach a segment left on it.+ if (seg.speakerLocked) {+ return normalizeTranscriptSegment({ ...seg, speaker: keep });}- }- return;+ return normalizeTranscriptSegment({+ ...seg,+ speaker: keep,+ speakerName: displayName ?? seg.speakerName,+ });+ });}+ segmentsRefValue = next;+ useMeetingRecordingStore.setState({ segments: next });- const seg = reduction.inserted;- segmentsRefValue = reduction.state.segments;- // Only the cleared partial goes in the payload (spreading both partial fields would add a- // key the pre-reducer code never wrote), so derive it from the inserted segment's source.- const partialPatch = seg.source === "mic" ? { micPartial: "" } : { systemPartial: "" };- useMeetingRecordingStore.setState({- segments: reduction.state.segments,- transcript: buildTranscriptText(reduction.state.segments),- ...partialPatch,- });- if (seg.source === "system" && seg.speaker) {- rememberSystemSpeaker(- seg.speaker,- seg.speakerName ?? null,- !!seg.speakerIsPlaceholder,- seg.timestamp ?? Date.now()- );+ for (const { keep, remove, displayName } of merges) {+ if (recentSystemSpeaker?.speakerId === remove) {+ recentSystemSpeaker.speakerId = keep;+ if (displayName) recentSystemSpeaker.speakerName = displayName;+ }++ for (const id of speakerIdentifications) {+ if (id.speakerId === remove) id.speakerId = keep;+ }++ const lockedName = speakerLocks.get(remove);+ if (lockedName) {+ speakerLocks.set(keep, lockedName);+ speakerLocks.delete(remove);+ }}- if (seg.source === "system") {- setSystemPartialSpeakerIdentity(null, null);+ });+ if (mergeCleanup) ipcCleanups.push(mergeCleanup);++ const errorCleanup = window.electronAPI?.onMeetingTranscriptionError?.((err) => {+ if (activeRecordingSessionId !== sessionId) return;+ reportMeetingError(err);+ logger.error("Meeting transcription stream error", { error: err }, "meeting");+ });+ if (errorCleanup) ipcCleanups.push(errorCleanup);++ const fatalErrorCleanup = window.electronAPI?.onMeetingTranscriptionFatalError?.((err) => {+ if (activeRecordingSessionId !== sessionId) return;+ reportMeetingError(err);+ logger.error(+ "Meeting transcription stopped after connection loss",+ { error: err },+ "meeting"+ );+ if (isRecordingFlag) void stopRecording(sessionId);+ });+ if (fatalErrorCleanup) ipcCleanups.push(fatalErrorCleanup);++ // Main re-derives the expected count when participants are added mid-meeting+ // (never for a count set explicitly via the stepper — main skips those).+ const speakerConfigCleanup = window.electronAPI?.onMeetingSessionSpeakerConfigUpdated?.(+ (config) => {+ if (activeRecordingSessionId !== sessionId) return;+ const clamped = Math.max(1, Math.min(MAX_SPEAKER_COUNT, config.expectedCount));+ useMeetingRecordingStore.setState({ sessionExpectedCount: clamped });}+ );+ if (speakerConfigCleanup) ipcCleanups.push(speakerConfigCleanup);++ if (startResult.oneOnOneAttendee) {+ const synthetic: SpeakerIdentification = {+ speakerId: "speaker_0",+ displayName: startResult.oneOnOneAttendee.displayName,+ startTime: 0,+ endTime: Number.MAX_SAFE_INTEGER,+ };+ reserveSpeakerIndex(synthetic.speakerId);+ setSystemPartialSpeakerIdentity(synthetic.speakerId, synthetic.displayName);+ rememberSystemSpeaker(synthetic.speakerId, synthetic.displayName, false, Date.now());+ speakerIdentifications.push(synthetic);}- );- if (segmentCleanup) ipcCleanups.push(segmentCleanup);-- const speakerCleanup = window.electronAPI?.onMeetingSpeakerIdentified?.((data) => {- reserveSpeakerIndex(data.speakerId);- setSystemPartialSpeakerIdentity(data.speakerId, data.displayName ?? null);- rememberSystemSpeaker(data.speakerId, data.displayName ?? null, false, data.endTime);- speakerIdentifications = [- ...speakerIdentifications.filter(- (id) => id.endTime >= data.endTime - SPEAKER_IDENTIFICATION_RETENTION_MS- ),- data,- ];- const next = useMeetingRecordingStore- .getState()- .segments.map((segment) => applySpeakerIdentification(segment, data));- segmentsRefValue = next;- useMeetingRecordingStore.setState({ segments: next });- });- if (speakerCleanup) ipcCleanups.push(speakerCleanup);-- const mergeCleanup = window.electronAPI?.onMeetingSpeakersMerged?.((merges) => {- let next = useMeetingRecordingStore.getState().segments;- for (const { keep, remove, displayName } of merges) {- next = next.map((seg) => {- if (seg.speaker !== remove) return seg;- // Locked segments keep their user-set name but must still move to the- // kept cluster: the removed id no longer exists in the identifier, so- // later merges and renames would never reach a segment left on it.- if (seg.speakerLocked) {- return normalizeTranscriptSegment({ ...seg, speaker: keep });++ const pendingMicChunks: ArrayBuffer[] = [];+ const pendingSystemChunks: ArrayBuffer[] = [];+ let socketReady = false;++ let micPipelinePromise: Promise<void> | null = null;+ if (micResult) {+ micStream = micResult;+ setupMicResult = null;+ const ctx = new AudioContext({ sampleRate: 24000 });+ micContext = ctx;+ await detachFromOutputDevice(ctx);+ if (!isCurrentStart()) {+ await teardownStart();+ return;+ }++ micPipelinePromise = createAudioPipeline({+ stream: micResult,+ context: ctx,+ onChunk: (chunk) => {+ if (!isRecordingFlag || activeRecordingSessionId !== sessionId) return;+ if (socketReady) {+ window.electronAPI?.meetingTranscriptionSend?.(chunk, "mic");+ return;+ }+ pendingMicChunks.push(chunk.slice(0));+ },+ }).then(async ({ source, processor }) => {+ if (!isCurrentStart()) {+ source.disconnect();+ await flushAndDisconnectProcessor(processor);+ return;}- return normalizeTranscriptSegment({- ...seg,- speaker: keep,- speakerName: displayName ?? seg.speakerName,- });+ micSource = source;+ micProcessor = processor;++ // AnalyserNode must reach the destination for Chrome's pull-based+ // renderer to update its internal buffer; route through a muted gain.+ const analyser = ctx.createAnalyser();+ analyser.fftSize = 256;+ analyser.smoothingTimeConstant = 0.4;+ const analyserSink = ctx.createGain();+ analyserSink.gain.value = 0;+ source.connect(analyser);+ analyser.connect(analyserSink);+ analyserSink.connect(ctx.destination);+ micAnalyser = analyser;++ const micTrack = micResult.getAudioTracks()[0];+ logger.info(+ "Mic capture started for meeting transcription",+ {+ label: micTrack?.label,+ settings: micTrack?.getSettings(),+ },+ "meeting"+ );});}- segmentsRefValue = next;- useMeetingRecordingStore.setState({ segments: next });- for (const { keep, remove, displayName } of merges) {- if (recentSystemSpeaker?.speakerId === remove) {- recentSystemSpeaker.speakerId = keep;- if (displayName) recentSystemSpeaker.speakerName = displayName;- }-- for (const id of speakerIdentifications) {- if (id.speakerId === remove) id.speakerId = keep;+ if (micPipelinePromise) {+ await micPipelinePromise;+ if (!isCurrentStart()) {+ await teardownStart();+ return;}-- const lockedName = speakerLocks.get(remove);- if (lockedName) {- speakerLocks.set(keep, lockedName);- speakerLocks.delete(remove);+ micRecovery = new ActiveMicRecoveryController({+ mediaDevices: navigator.mediaDevices,+ acquire: async () => {+ try {+ return await navigator.mediaDevices.getUserMedia(await getMeetingMicConstraints());+ } catch {+ return navigator.mediaDevices.getUserMedia({+ audio: MEETING_MIC_PRIMARY_AUDIO_CONSTRAINTS,+ });+ }+ },+ onStatusChange: (status) => {+ if (activeRecordingSessionId !== sessionId) return;+ useMeetingRecordingStore.setState({+ micCaptureStatus: status,+ ...(status === "active" ? {} : { currentMicLevel: 0 }),+ });+ },+ onRecovered: async (replacement, previous) => {+ if (+ !isRecordingFlag ||+ activeRecordingSessionId !== sessionId ||+ !micContext ||+ !micProcessor+ ) {+ throw new Error("Meeting recording is no longer active");+ }+ const nextSource = micContext.createMediaStreamSource(replacement);+ nextSource.connect(micProcessor);+ if (micAnalyser) nextSource.connect(micAnalyser);+ micSource?.disconnect();+ previous?.getTracks().forEach((track) => track.stop());+ micSource = nextSource;+ micStream = replacement;+ logger.info("Meeting microphone capture recovered", {}, "meeting");+ },+ });+ await micRecovery.start(micStream, {+ followDefault: followsSystemDefaultMic(getSettings()),+ });+ if (!isCurrentStart()) {+ await teardownStart();+ return;}}- });- if (mergeCleanup) ipcCleanups.push(mergeCleanup);- const errorCleanup = window.electronAPI?.onMeetingTranscriptionError?.((err) => {- reportMeetingError(err);- logger.error("Meeting transcription stream error", { error: err }, "meeting");- });- if (errorCleanup) ipcCleanups.push(errorCleanup);+ if (systemCaptureResult.stream) {+ const stream = systemCaptureResult.stream;+ systemStream = stream;+ setupSystemCaptureResult = { stream: null, error: null };- const fatalErrorCleanup = window.electronAPI?.onMeetingTranscriptionFatalError?.((err) => {- reportMeetingError(err);- logger.error(- "Meeting transcription stopped after connection loss",- { error: err },- "meeting"- );- if (isRecordingFlag) void stopRecording();- });- if (fatalErrorCleanup) ipcCleanups.push(fatalErrorCleanup);-- // Main re-derives the expected count when participants are added mid-meeting- // (never for a count set explicitly via the stepper — main skips those).- const speakerConfigCleanup = window.electronAPI?.onMeetingSessionSpeakerConfigUpdated?.(- (config) => {- const clamped = Math.max(1, Math.min(MAX_SPEAKER_COUNT, config.expectedCount));- useMeetingRecordingStore.setState({ sessionExpectedCount: clamped });- }- );- if (speakerConfigCleanup) ipcCleanups.push(speakerConfigCleanup);-- if (startResult.oneOnOneAttendee) {- const synthetic: SpeakerIdentification = {- speakerId: "speaker_0",- displayName: startResult.oneOnOneAttendee.displayName,- startTime: 0,- endTime: Number.MAX_SAFE_INTEGER,- };- reserveSpeakerIndex(synthetic.speakerId);- setSystemPartialSpeakerIdentity(synthetic.speakerId, synthetic.displayName);- rememberSystemSpeaker(synthetic.speakerId, synthetic.displayName, false, Date.now());- speakerIdentifications.push(synthetic);- }+ const ctx = new AudioContext({ sampleRate: 24000 });+ systemContext = ctx;+ await detachFromOutputDevice(ctx);+ if (!isCurrentStart()) {+ await teardownStart();+ return;+ }- const pendingMicChunks: ArrayBuffer[] = [];- const pendingSystemChunks: ArrayBuffer[] = [];- let socketReady = false;-- let micPipelinePromise: Promise<void> | null = null;- if (micResult) {- micStream = micResult;- const ctx = new AudioContext({ sampleRate: 24000 });- await detachFromOutputDevice(ctx);- micContext = ctx;-- micPipelinePromise = createAudioPipeline({- stream: micResult,- context: ctx,- onChunk: (chunk) => {- if (!isRecordingFlag) return;- if (socketReady) {- window.electronAPI?.meetingTranscriptionSend?.(chunk, "mic");- return;+ const { source, processor } = await createAudioPipeline({+ stream,+ context: ctx,+ onChunk: (chunk) => {+ if (!isRecordingFlag || activeRecordingSessionId !== sessionId) return;+ if (socketReady) {+ window.electronAPI?.meetingTranscriptionSend?.(chunk, "system");+ return;+ }+ pendingSystemChunks.push(chunk.slice(0));+ },+ });+ if (!isCurrentStart()) {+ source.disconnect();+ await flushAndDisconnectProcessor(processor);+ await teardownStart();+ return;+ }+ systemSource = source;+ systemProcessor = processor;+ } else if (systemCaptureError) {+ if (systemAudioStrategy === "loopback") {+ logger.warn(+ "System audio loopback failed, continuing with mic only",+ { error: systemCaptureError.message },+ "meeting"+ );+ if (micResult) {+ reportMeetingError("System audio capture failed. Continuing with microphone only.");}- pendingMicChunks.push(chunk.slice(0));- },- }).then(({ source, processor }) => {- micSource = source;- micProcessor = processor;-- // AnalyserNode must reach the destination for Chrome's pull-based- // renderer to update its internal buffer; route through a muted gain.- const analyser = ctx.createAnalyser();- analyser.fftSize = 256;- analyser.smoothingTimeConstant = 0.4;- const analyserSink = ctx.createGain();- analyserSink.gain.value = 0;- source.connect(analyser);- analyser.connect(analyserSink);- analyserSink.connect(ctx.destination);- micAnalyser = analyser;-- const micTrack = micResult.getAudioTracks()[0];+ }+ }++ if (!isCurrentStart()) {logger.info(- "Mic capture started for meeting transcription",- {- label: micTrack?.label,- settings: micTrack?.getSettings(),- },+ "Meeting transcription aborted during pipeline setup (stop called)",+ {},"meeting");- });- }-- if (micPipelinePromise) {- await micPipelinePromise;- micRecovery = new ActiveMicRecoveryController({- mediaDevices: navigator.mediaDevices,- acquire: async () => {- try {- return await navigator.mediaDevices.getUserMedia(await getMeetingMicConstraints());- } catch {- return navigator.mediaDevices.getUserMedia({- audio: MEETING_MIC_PRIMARY_AUDIO_CONSTRAINTS,- });- }- },- onStatusChange: (status) => {- useMeetingRecordingStore.setState({- micCaptureStatus: status,- ...(status === "active" ? {} : { currentMicLevel: 0 }),- });- },- onRecovered: async (replacement, previous) => {- if (!isRecordingFlag || !micContext || !micProcessor) {- throw new Error("Meeting recording is no longer active");- }- const nextSource = micContext.createMediaStreamSource(replacement);- nextSource.connect(micProcessor);- if (micAnalyser) nextSource.connect(micAnalyser);- micSource?.disconnect();- previous?.getTracks().forEach((track) => track.stop());- micSource = nextSource;- micStream = replacement;- logger.info("Meeting microphone capture recovered", {}, "meeting");- },- });- await micRecovery.start(micStream, {- followDefault: followsSystemDefaultMic(getSettings()),- });- }+ await teardownStart();+ return;+ }- if (systemCaptureResult.stream) {- const stream = systemCaptureResult.stream;- systemStream = stream;-- const ctx = new AudioContext({ sampleRate: 24000 });- await detachFromOutputDevice(ctx);- systemContext = ctx;-- await createAudioPipeline({- stream,- context: ctx,- onChunk: (chunk) => {- if (!isRecordingFlag) return;- if (socketReady) {- window.electronAPI?.meetingTranscriptionSend?.(chunk, "system");- return;- }- pendingSystemChunks.push(chunk.slice(0));- },- }).then(({ source, processor }) => {- systemSource = source;- systemProcessor = processor;- });- } else if (systemCaptureError) {- if (systemAudioStrategy === "loopback") {+ const systemAudioAvailable = systemAudioHandledInMain || systemStream !== null;+ try {+ const availabilityResult =+ await window.electronAPI?.meetingTranscriptionSetSystemAudioAvailable?.(+ sessionId,+ systemAudioAvailable+ );+ if (availabilityResult && !availabilityResult.success) {+ logger.warn(+ "Meeting auto-end system-audio confirmation was rejected",+ { sessionId, reason: availabilityResult.reason },+ "meeting"+ );+ }+ } catch (error) {+ // Recording remains usable; auto-end stays disabled for this session.logger.warn(- "System audio loopback failed, continuing with mic only",- { error: systemCaptureError.message },+ "Meeting auto-end system-audio confirmation failed",+ { sessionId, error: (error as Error).message },"meeting");- if (micResult) {- reportMeetingError("System audio capture failed. Continuing with microphone only.");- }}- }- if (!isRecordingFlag) {+ if (!isCurrentStart()) {+ await teardownStart();+ return;+ }++ startOperation.markCommitted();+ isStartingFlag = false;+ socketReady = true;++ for (const chunk of pendingMicChunks) {+ window.electronAPI?.meetingTranscriptionSend?.(chunk, "mic");+ }+ for (const chunk of pendingSystemChunks) {+ window.electronAPI?.meetingTranscriptionSend?.(chunk, "system");+ }++ const totalMs = performance.now() - startTime;logger.info(- "Meeting transcription aborted during pipeline setup (stop called)",- {},+ "Meeting transcription started successfully",+ {+ systemAudioMode,+ systemAudioStrategy,+ bufferedChunks: pendingMicChunks.length,+ bufferedSystemChunks: pendingSystemChunks.length,+ streamsMs: Math.round(streamsMs),+ totalMs: Math.round(totalMs),+ wasPrepared: isPrepared,+ },+ "meeting"+ );+ } catch (err) {+ logger.error(+ "Meeting transcription setup failed",+ { error: (err as Error).message },"meeting");+ reportMeetingError((err as Error).message, { isRecording: false, isTranscribing: false });+ isRecordingFlag = false;isStartingFlag = false;- await cleanup();- return true;- }-- isStartingFlag = false;- socketReady = true;-- for (const chunk of pendingMicChunks) {- window.electronAPI?.meetingTranscriptionSend?.(chunk, "mic");+ await teardownStart();}- for (const chunk of pendingSystemChunks) {- window.electronAPI?.meetingTranscriptionSend?.(chunk, "system");- }-- const totalMs = performance.now() - startTime;- logger.info(- "Meeting transcription started successfully",- {- systemAudioMode,- systemAudioStrategy,- bufferedChunks: pendingMicChunks.length,- bufferedSystemChunks: pendingSystemChunks.length,- streamsMs: Math.round(streamsMs),- totalMs: Math.round(totalMs),- wasPrepared: isPrepared,- },- "meeting"- );- return true;- } catch (err) {- logger.error(- "Meeting transcription setup failed",- { error: (err as Error).message },- "meeting"- );- useMeetingRecordingStore.setState({- error: (err as Error).message,- isRecording: false,- isTranscribing: false,- });- isRecordingFlag = false;- isStartingFlag = false;- await cleanup();- return true;- }+ });+ return true;}export interface StopRecordingResult {diarizationSessionId: string | null;}-export async function stopRecording(): Promise<StopRecordingResult> {- if (!isRecordingFlag) {+export async function stopRecording(expectedSessionId?: string): Promise<StopRecordingResult> {+ const canceledStart = meetingRecordingStartCoordinator.cancelActiveStart(expectedSessionId);+ if (canceledStart) {+ isRecordingFlag = false;+ isStartingFlag = false;+ useMeetingRecordingStore.setState({ isRecording: false, isTranscribing: false });+ await canceledStart;+ useMeetingRecordingStore.setState({+ micPartial: "",+ systemPartial: "",+ systemPartialSpeakerId: null,+ systemPartialSpeakerName: null,+ currentMicLevel: 0,+ });return { diarizationSessionId: null };}- isRecordingFlag = false;- isStartingFlag = false;- useMeetingRecordingStore.setState({ isRecording: false, isTranscribing: false });-- await cleanup();+ await meetingRecordingStopBarrier.waitForPendingStop();+ if (!canStopMeetingRecordingSession(activeRecordingSessionId, expectedSessionId)) {+ return { diarizationSessionId: null };+ }+ if (!isRecordingFlag) {+ return { diarizationSessionId: null };+ }- let diarizationSessionId: string | null = null;- try {- const result = await window.electronAPI?.meetingTranscriptionStop?.();- if (result?.diarizationSessionId) {- diarizationSessionId = result.diarizationSessionId;- useMeetingRecordingStore.setState({ diarizationSessionId });+ return meetingRecordingStopBarrier.runStop(async () => {+ if (!canStopMeetingRecordingSession(activeRecordingSessionId, expectedSessionId)) {+ return { diarizationSessionId: null };}- if (result?.success && result.transcript) {- useMeetingRecordingStore.setState({ transcript: result.transcript });- } else if (result?.error) {- reportMeetingError(result.error);+ if (!isRecordingFlag) {+ return { diarizationSessionId: null };}- } catch (err) {- reportMeetingError((err as Error).message);- logger.error("Meeting transcription stop failed", { error: (err as Error).message }, "meeting");- }- useMeetingRecordingStore.setState({- micPartial: "",- systemPartial: "",- systemPartialSpeakerId: null,- systemPartialSpeakerName: null,- currentMicLevel: 0,- });+ const sessionId = activeRecordingSessionId;+ activeRecordingSessionId = null;+ isRecordingFlag = false;+ isStartingFlag = false;+ useMeetingRecordingStore.setState({ isRecording: false, isTranscribing: false });++ // Persist here, not in a notes-view effect: an auto-end stop can fire while+ // that view is unmounted, and any view-scoped saver dies with it. (Delayed+ // diarization results are persisted by the module-level listener below.)+ const { recordingNoteId, segments: finalSegments } = useMeetingRecordingStore.getState();+ const persistTranscript = async (transcript: string) => {+ if (recordingNoteId == null) return;+ try {+ await window.electronAPI?.updateNote?.(recordingNoteId, { transcript });+ } catch (err) {+ logger.error(+ "Failed to persist final meeting transcript",+ { error: (err as Error).message, noteId: recordingNoteId },+ "meeting"+ );+ }+ };- logger.info("Meeting transcription stopped", {}, "meeting");- return { diarizationSessionId };+ const diarizationSessionId = await persistFinalTranscriptAroundStop({+ segments: finalSegments,+ serializeSegments: serializeTranscriptSegments,+ persist: persistTranscript,+ fallbackTranscript: () => useMeetingRecordingStore.getState().transcript,+ stop: async () => {+ await cleanup();++ let stoppedDiarizationSessionId: string | null = null;+ try {+ const result = await window.electronAPI?.meetingTranscriptionStop?.(+ sessionId ?? undefined+ );+ if (result?.diarizationSessionId) {+ stoppedDiarizationSessionId = result.diarizationSessionId;+ useMeetingRecordingStore.setState({+ diarizationSessionId: stoppedDiarizationSessionId,+ });+ }+ if (result?.success && result.transcript) {+ useMeetingRecordingStore.setState({ transcript: result.transcript });+ } else if (result?.error) {+ reportMeetingError(result.error);+ }+ } catch (err) {+ reportMeetingError((err as Error).message);+ logger.error(+ "Meeting transcription stop failed",+ { error: (err as Error).message },+ "meeting"+ );+ }+ return stoppedDiarizationSessionId;+ },+ });++ useMeetingRecordingStore.setState({+ micPartial: "",+ systemPartial: "",+ systemPartialSpeakerId: null,+ systemPartialSpeakerName: null,+ currentMicLevel: 0,+ });++ logger.info("Meeting transcription stopped", {}, "meeting");+ return { diarizationSessionId };+ });}export function lockSpeaker(speakerId: string, displayName: string): void {diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.tsindex 490d9dc76..054f2fc04 100644--- a/src/stores/settingsStore.ts+++ b/src/stores/settingsStore.ts@@ -260,6 +260,7 @@ const BOOLEAN_SETTINGS = new Set(["floatingIconAutoHide","startMinimized","meetingProcessDetection",+ "meetingAutoEndEnabled","speakerDiarizationEnabled","dictationSileroEnabled","noteRecordingSileroEnabled",@@ -593,6 +594,7 @@ export interface SettingsStatemcalPrimaryOnly: boolean;appleCalendarConnected: boolean;meetingProcessDetection: boolean;+ meetingAutoEndEnabled: boolean;speakerDiarizationEnabled: boolean;dictationSileroEnabled: boolean;noteRecordingSileroEnabled: boolean;@@ -891,6 +893,7 @@ export interface SettingsStatesetMcalPrimaryOnly: (value: boolean) => void;setAppleCalendarConnected: (value: boolean) => void;setMeetingProcessDetection: (value: boolean) => void;+ setMeetingAutoEndEnabled: (value: boolean) => void;setSpeakerDiarizationEnabled: (value: boolean) => void;setDictationSileroEnabled: (value: boolean) => void;setNoteRecordingSileroEnabled: (value: boolean) => void;@@ -1316,6 +1319,7 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({mcalPrimaryOnly: readBoolean("mcalPrimaryOnly", true),appleCalendarConnected: readBoolean("appleCalendarConnected", false),meetingProcessDetection: readBoolean("meetingProcessDetection", true),+ meetingAutoEndEnabled: readBoolean("meetingAutoEndEnabled", true),speakerDiarizationEnabled: readBoolean("speakerDiarizationEnabled", true),// Off by default: VAD on pause-heavy dictations can strip the speech and make// Whisper hallucinate the dictionary prompt as the transcript (#1454).@@ -2074,6 +2078,14 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({},setAppleCalendarConnected: createBooleanSetter("appleCalendarConnected"),setMeetingProcessDetection: createBooleanSetter("meetingProcessDetection"),+ setMeetingAutoEndEnabled: (value: boolean) => {+ if (isBrowser) localStorage.setItem("meetingAutoEndEnabled", String(value));+ useSettingsStore.setState({ meetingAutoEndEnabled: value });+ // Takes effect immediately — a live countdown is dismissed when turned off.+ if (isBrowser) {+ window.electronAPI?.meetingDetectionSetPreferences?.({ autoEnd: value });+ }+ },setSpeakerDiarizationEnabled: (value: boolean) => {if (isBrowser) localStorage.setItem("speakerDiarizationEnabled", String(value));useSettingsStore.setState({ speakerDiarizationEnabled: value });@@ -3134,11 +3146,12 @@ export async function initializeSettings(): Promise<void> {}// Audio detection is derived from the meeting-notification toggle in- // sync-notification-preferences, so only process detection is sent here.+ // sync-notification-preferences, so it is not sent here.try {const currentState = useSettingsStore.getState();await window.electronAPI.meetingDetectionSetPreferences?.({processDetection: currentState.meetingProcessDetection,+ autoEnd: currentState.meetingAutoEndEnabled,});} catch (err) {logger.warn(diff --git a/src/types/electron.ts b/src/types/electron.tsindex e94699d18..771ef09bb 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -71,6 +71,36 @@ export type TranscriptionErrorCode =| "CUSTOM_ENDPOINT_INVALID"| null;+export type MeetingPromptVariant = "detected" | "starting" | "underway";++export interface MeetingDetectionNotificationData {+ kind: "detection";+ detectionId: string;+ source: string;+ key: string;+ event: { summary?: string | null } | null;+ variant: MeetingPromptVariant;+ joinUrl: string | null;+}++/** Why auto-end concluded the meeting is over. */+export type MeetingAutoEndReason = "mic-released" | "silence" | "process-exit";++export interface MeetingAutoEndNotificationData {+ kind: "auto-end";+ sessionId: string;+ expiresAt: number;+ reason?: MeetingAutoEndReason;+}++export type MeetingNotificationData =+ MeetingDetectionNotificationData | MeetingAutoEndNotificationData;++export interface MeetingAutoEndRequest {+ sessionId: string;+ reason?: MeetingAutoEndReason;+}+/*** Proxied-transcription IPC results. `ipcMain.handle` drops custom error props on* rejection, so these handlers resolve with a serialized error instead of throwing.@@ -2340,20 +2370,29 @@ declare global {model?: string;language?: string;noteId?: number | null;+ sessionId: string;+ autoEndEligible: boolean;}) => Promise<{success: boolean;+ sessionId?: string;+ error?: string;systemAudioMode?: SystemAudioMode;systemAudioStrategy?: SystemAudioStrategy;oneOnOneAttendee?: { displayName: string; email: string | null } | null;} & PolicyFailureMetadata>;meetingTranscriptionSend?: (buffer: ArrayBuffer, source: "mic" | "system") => void;- meetingTranscriptionStop?: () => Promise<{+ meetingTranscriptionSetSystemAudioAvailable?: (+ sessionId: string,+ available: boolean+ ) => Promise<{ success: boolean; reason?: "stale-session" }>;+ meetingTranscriptionStop?: (expectedSessionId?: string) => Promise<{success: boolean;transcript?: string;diarizationSessionId?: string;error?: string;+ reason?: "stale-session";}>;meetingTranscriptionCancel?: () => Promise<{success: boolean;@@ -2565,8 +2604,16 @@ declare global {speechPadMs?: number;samplesOverlap?: number;}) => Promise<{ success: boolean; config?: Record<string, unknown>; error?: string }>;- onMeetingNotificationData?: (callback: (data: any) => void) => () => void;- getMeetingNotificationData?: () => Promise<any>;+ onMeetingNotificationData?: (callback: (data: MeetingNotificationData) => void) => () => void;+ onMeetingAutoEndRequested?: (+ callback: (request: MeetingAutoEndRequest) => void+ ) => () => void;+ meetingAutoEndKeep?: (sessionId: string) => Promise<{+ success: boolean;+ reason?: "invalid-session" | "stale-session";+ error?: string;+ }>;+ getMeetingNotificationData?: () => Promise<MeetingNotificationData | null>;meetingNotificationReady?: () => Promise<void>;meetingNotificationRespond?: (detectionId: string,diff --git a/src/utils/audioUtils.js b/src/utils/audioUtils.jsindex b7c4677ae..769a206ee 100644--- a/src/utils/audioUtils.js+++ b/src/utils/audioUtils.js@@ -44,8 +44,42 @@ function pcm16ToFloat32(pcmBuffer) {return output;}+// Energy floors below which a meeting channel is treated as silent. Shared by+// the echo-leak detector and the auto-end activity monitor so both agree on+// what "audible" means.+const MEETING_MIC_ACTIVITY_RMS = 0.006;+const MEETING_SYSTEM_ACTIVITY_RMS = 0.004;++// RMS of raw s16le PCM in [0, 1]. Tolerates the odd-length and unaligned+// buffers that helper stdout reads produce (an Int16Array view would throw on+// an odd byteOffset), which is why it doesn't reuse pcm16ToFloat32.+function computePcm16Rms(pcmBuffer) {+ if (!pcmBuffer || pcmBuffer.length < 2) return 0;++ const sampleCount = pcmBuffer.length >> 1;+ let sumSquares = 0;++ if ((pcmBuffer.byteOffset & 1) === 0) {+ const samples = new Int16Array(pcmBuffer.buffer, pcmBuffer.byteOffset, sampleCount);+ for (let i = 0; i < sampleCount; i++) {+ const sample = samples[i] / 32768;+ sumSquares += sample * sample;+ }+ } else {+ for (let i = 0; i < sampleCount; i++) {+ const sample = pcmBuffer.readInt16LE(i * 2) / 32768;+ sumSquares += sample * sample;+ }+ }++ return Math.sqrt(sumSquares / sampleCount);+}+module.exports = {downsample24kTo16k,pcm16ToWav,pcm16ToFloat32,+ computePcm16Rms,+ MEETING_MIC_ACTIVITY_RMS,+ MEETING_SYSTEM_ACTIVITY_RMS,};diff --git a/test/helpers/audioActivityDetector.test.js b/test/helpers/audioActivityDetector.test.jsindex a5746130a..5cfd60061 100644--- a/test/helpers/audioActivityDetector.test.js+++ b/test/helpers/audioActivityDetector.test.js@@ -4,6 +4,9 @@ const assert = require("node:assert/strict");const Module = require("node:module");const { EventEmitter } = require("node:events");const childProcess = require("node:child_process");+const fs = require("node:fs");+const os = require("node:os");+const path = require("node:path");const detectorModulePath = require.resolve("../../src/helpers/audioActivityDetector");const originalLoad = Module._load;@@ -17,7 +20,7 @@ function setPlatform(platform) {afterEach(() => setPlatform(originalPlatform));-function loadDetector(platform, spawn, ownPids) {+function loadDetector(platform, spawn, exec) {delete require.cache[detectorModulePath];setPlatform(platform);@@ -26,7 +29,7 @@ function loadDetector(platform, spawn, ownPids) {return { info() {}, warn() {}, debug() {}, error() {} };}if (request === "child_process") {- return { ...childProcess, spawn };+ return { ...childProcess, exec, spawn };}// Binary resolution hits the real filesystem, so without this the platform// under test would be decided by which listener binaries happen to be built@@ -34,11 +37,6 @@ function loadDetector(platform, spawn, ownPids) {if (request === "./binaryResolver") {return { resolveBundledBinary: (name) => `/fake/bin/${name}` };}- // Outside Electron the real module can only see the main pid, so the- // child-process PIDs that matter for #1392 have to be injected.- if (request === "./ownProcessPids" && ownPids) {- return { getOwnProcessPids: () => new Set(ownPids) };- }return originalLoad.call(this, request, parent, isMain);};@@ -68,9 +66,30 @@ function createFakeChild(spawnError) {return child;}-function createDetector(platform, { spawnError, ownPids } = {}) {+// `ownPids` is the #1392 spelling of the same injection: outside Electron the+// real provider can only see the main pid, so child-process PIDs are supplied+// here. Both spellings feed the detector's excluded-pid provider.+function createDetector(+ platform,+ { excludedProcessIds, ownPids, execResponses = [], spawnError } = {}+) {+ const getExcludedProcessIds =+ excludedProcessIds ?? (ownPids ? () => [...ownPids] : () => [process.pid]);const children = [];const calls = [];+ const execCalls = [];+ const fakeExec = () => {};+ fakeExec[Symbol.for("nodejs.util.promisify.custom")] = async (command, options) => {+ execCalls.push({ command, options });+ const response = execResponses.shift();+ if (!response || response.error) {+ throw response?.error || new Error("exec unavailable in test");+ }+ if (response.promise) {+ return response.promise;+ }+ return { stdout: response.stdout, stderr: response.stderr || "" };+ };const AudioActivityDetector = loadDetector(platform,(command, args, options) => {@@ -79,15 +98,24 @@ function createDetector(platform, { spawnError, ownPids } = {}) {children.push(child);return child;},- ownPids+ fakeExec);- const detector = new AudioActivityDetector();+ const detector = new AudioActivityDetector(getExcludedProcessIds);detector._isMicActive = async () => false;- return { detector, children, calls };+ return { detector, children, calls, execCalls };}const flush = () => new Promise((resolve) => setTimeout(resolve, 0));+const createDeferred = () => {+ let resolve;+ let reject;+ const promise = new Promise((resolvePromise, rejectPromise) => {+ resolve = resolvePromise;+ reject = rejectPromise;+ });+ return { promise, reject, resolve };+};const PLATFORMS = ["darwin", "win32", "linux"];for (const platform of PLATFORMS) {@@ -169,12 +197,12 @@ test("darwin: MIC_ACTIVE then MIC_INACTIVE drives the sustained timer", async ()detector.stop();});-test("win32: mic-listener spawns hidden, keeps stdin piped, and excludes its own pid", async () => {+test("win32: mic-listener spawns hidden, keeps stdin piped, and emits every pid", async () => {const { detector, calls } = createDetector("win32");await detector.start();- assert.deepEqual(calls[0].args, ["--exclude-pid", String(process.pid)]);+ assert.deepEqual(calls[0].args, []);assert.equal(calls[0].options.windowsHide, true, "no console window may flash");assert.deepEqual(calls[0].options.stdio,@@ -239,6 +267,444 @@ test("unsupported platforms poll without spawning a listener", async () => {detector.stop();});+test("darwin: PID events exclude current OpenWhispr processes and continue during recording", async () => {+ let excludedProcessIds = [101, 102];+ const { detector, children } = createDetector("darwin", {+ excludedProcessIds: () => excludedProcessIds,+ });+ const externalStates = [];+ detector.on("external-mic-state-changed", (state) => externalStates.push(state));++ await detector.start();+ detector.setUserRecording(true);+ children[0].stdout.emit("data", "CAPABILITY PID\nMIC_START 101\nMIC_START 201\n");+ children[0].stdout.emit("data", "MIC_START 202\nMIC_STOP 201\n");++ assert.deepEqual(detector.getExternalMicState(), {+ reliable: true,+ externalMicActive: true,+ });+ assert.deepEqual(externalStates, [+ { reliable: true, externalMicActive: false },+ { reliable: true, externalMicActive: true },+ ]);+ assert.equal(detector._sustainedTimer, null, "recording must still suppress meeting prompts");+ assert.deepEqual([...detector._activeMicPids], [202], "own pids never enter the set");++ // The exclusion list is read live: a helper that spawned after start() is+ // excluded from its first MIC_START.+ excludedProcessIds = [101, 102, 103];+ children[0].stdout.emit("data", "MIC_START 103\nMIC_STOP 202\n");++ assert.deepEqual(detector.getExternalMicState(), {+ reliable: true,+ externalMicActive: false,+ });+ assert.deepEqual([...detector._activeMicPids], []);+ assert.deepEqual(externalStates, [+ { reliable: true, externalMicActive: false },+ { reliable: true, externalMicActive: true },+ { reliable: true, externalMicActive: false },+ ]);+ detector.stop();+});++test("darwin: aggregate fallback remains prompt-only and unreliable", async () => {+ const { detector, children } = createDetector("darwin");+ const externalStates = [];+ detector.on("external-mic-state-changed", (state) => externalStates.push(state));++ await detector.start();+ children[0].stdout.emit("data", "CAPABILITY AGGREGATE\nMIC_ACTIVE\n");++ assert.deepEqual(detector.getExternalMicState(), {+ reliable: false,+ externalMicActive: false,+ });+ assert.deepEqual(externalStates, []);+ assert.notEqual(detector._sustainedTimer, null, "aggregate activity must still drive prompts");+ detector.stop();+});++test("darwin: losing PID capability emits an unreliable external-mic snapshot", async () => {+ const { detector, children } = createDetector("darwin");+ const externalStates = [];+ detector.on("external-mic-state-changed", (state) => externalStates.push(state));++ await detector.start();+ children[0].stdout.emit("data", "CAPABILITY PID\nMIC_START 900\nCAPABILITY AGGREGATE\n");++ assert.deepEqual(externalStates.at(-1), {+ reliable: false,+ externalMicActive: false,+ });+ detector.stop();+});++test("darwin: listener exit emits reliability loss before polling fallback", async () => {+ const { detector, children } = createDetector("darwin");+ const externalStates = [];+ detector.on("external-mic-state-changed", (state) => externalStates.push(state));++ await detector.start();+ children[0].stdout.emit("data", "CAPABILITY PID\nMIC_START 900\n");+ children[0].emit("exit", 1);++ assert.deepEqual(externalStates.at(-1), {+ reliable: false,+ externalMicActive: false,+ });+ assert.notEqual(detector.checkInterval, null);+ detector.stop();+});++test("darwin: exclusion-provider failure emits reliability loss", async () => {+ let providerFails = false;+ const { detector, children } = createDetector("darwin", {+ excludedProcessIds: () => {+ if (providerFails) throw new Error("metrics unavailable");+ return [process.pid];+ },+ });+ const externalStates = [];+ detector.on("external-mic-state-changed", (state) => externalStates.push(state));++ await detector.start();+ children[0].stdout.emit("data", "CAPABILITY PID\nMIC_START 900\n");+ providerFails = true;+ children[0].stdout.emit("data", "MIC_START 901\n");++ assert.deepEqual(externalStates.at(-1), {+ reliable: false,+ externalMicActive: false,+ });+ detector.stop();+});++test("win32: current OpenWhispr PIDs are filtered dynamically in JavaScript", async () => {+ let excludedProcessIds = [process.pid, 404];+ const { detector, children, calls } = createDetector("win32", {+ excludedProcessIds: () => excludedProcessIds,+ });+ const externalStates = [];+ detector.on("external-mic-state-changed", (state) => externalStates.push(state));++ await detector.start();+ assert.deepEqual(calls[0].args, [], "the native listener must report excluded pids too");++ children[0].stdout.emit("data", "READY\nCAPABILITY PID\nMIC_START 404\n");+ assert.deepEqual(externalStates, [{ reliable: true, externalMicActive: false }]);++ excludedProcessIds = [process.pid];+ children[0].stdout.emit("data", "MIC_START 501\n");+ children[0].stdout.emit("data", "MIC_STOP 501\nMIC_STOP 404\n");++ assert.deepEqual(externalStates, [+ { reliable: true, externalMicActive: false },+ { reliable: true, externalMicActive: true },+ { reliable: true, externalMicActive: false },+ ]);+ assert.deepEqual(detector.getExternalMicState(), {+ reliable: true,+ externalMicActive: false,+ });+ detector.stop();+});++test("win32: own microphone activity never starts or sustains the legacy prompt", async () => {+ const { detector, children } = createDetector("win32", {+ excludedProcessIds: () => [process.pid],+ });++ await detector.start();+ children[0].stdout.emit("data", `READY\nCAPABILITY PID\nMIC_START ${process.pid}\n`);+ assert.equal(detector._sustainedTimer, null, "an excluded pid must not start a prompt");++ children[0].stdout.emit("data", "MIC_START 900\n");+ assert.notEqual(detector._sustainedTimer, null, "an external pid must start a prompt");++ children[0].stdout.emit("data", "MIC_STOP 900\n");+ assert.equal(+ detector._sustainedTimer,+ null,+ "an excluded pid must not keep the external prompt active"+ );+ detector.stop();+});++test("win32: a legacy binary without CAPABILITY PID stays unreliable but still prompts", async () => {+ const { detector, children } = createDetector("win32", {+ excludedProcessIds: () => [process.pid],+ });+ const externalStates = [];+ detector.on("external-mic-state-changed", (state) => externalStates.push(state));++ await detector.start();+ // Pre-refcounting builds print READY and un-refcounted MIC events; trusting+ // them for auto-end could stop a live meeting recording.+ children[0].stdout.emit("data", "READY\nMIC_START 900\n");++ assert.deepEqual(detector.getExternalMicState(), {+ reliable: false,+ externalMicActive: false,+ });+ assert.deepEqual(externalStates, []);+ assert.notEqual(detector._sustainedTimer, null, "legacy events must still drive prompts");+ detector.stop();+});++test("win32: a mid-run coverage downgrade emits an unreliable snapshot but keeps prompting", async () => {+ const { detector, children } = createDetector("win32", {+ excludedProcessIds: () => [process.pid],+ });+ const externalStates = [];+ detector.on("external-mic-state-changed", (state) => externalStates.push(state));++ await detector.start();+ children[0].stdout.emit("data", "READY\nCAPABILITY PID\nMIC_START 900\n");+ assert.deepEqual(externalStates.at(-1), { reliable: true, externalMicActive: true });++ // The helper announces CAPABILITY AGGREGATE instead of exiting when it can+ // no longer guarantee per-PID coverage.+ children[0].stdout.emit("data", "CAPABILITY AGGREGATE\n");+ assert.deepEqual(externalStates.at(-1), {+ reliable: false,+ externalMicActive: false,+ });++ children[0].stdout.emit("data", "MIC_START 901\n");+ assert.notEqual(detector._sustainedTimer, null, "degraded events must still drive prompts");+ assert.equal(detector.getExternalMicState().reliable, false);+ detector.stop();+});++test("win32: unattributable sessions (pid 0) count as external capture", async () => {+ const { detector, children } = createDetector("win32", {+ excludedProcessIds: () => [process.pid],+ });+ const externalStates = [];+ detector.on("external-mic-state-changed", (state) => externalStates.push(state));++ await detector.start();+ children[0].stdout.emit("data", "READY\nCAPABILITY PID\nMIC_START 0\n");+ assert.deepEqual(externalStates.at(-1), { reliable: true, externalMicActive: true });++ children[0].stdout.emit("data", "MIC_STOP 0\n");+ assert.deepEqual(externalStates.at(-1), { reliable: true, externalMicActive: false });+ detector.stop();+});++test("linux: reconciles source-output ownership at startup and on events", async () => {+ const { detector, children, execCalls } = createDetector("linux", {+ excludedProcessIds: () => [700],+ execResponses: [+ {+ stdout: JSON.stringify([+ { index: 1, properties: { "application.process.id": "700" } },+ { index: 2, properties: { "application.process.id": "800" } },+ { index: 3, properties: { "application.process.id": "800" } },+ ]),+ },+ {+ stdout: JSON.stringify([{ index: 1, properties: { "application.process.id": "700" } }]),+ },+ ],+ });+ const externalStates = [];+ detector.on("external-mic-state-changed", (state) => externalStates.push(state));++ await detector.start();+ assert.deepEqual(detector.getExternalMicState(), {+ reliable: true,+ externalMicActive: true,+ });++ children[0].stdout.emit("data", "Event 'change' on source-output #1\n");+ await flush();++ assert.deepEqual(+ execCalls.map(({ command }) => command),+ ["pactl --format=json list source-outputs", "pactl --format=json list source-outputs"]+ );+ assert.deepEqual(externalStates, [+ { reliable: true, externalMicActive: true },+ { reliable: true, externalMicActive: false },+ ]);+ detector.stop();+});++test("linux: a burst of subscribe events coalesces into at most two reconciles", async () => {+ const { detector, children, execCalls } = createDetector("linux", {+ excludedProcessIds: () => [700],+ execResponses: [+ { stdout: "[]" },+ { stdout: JSON.stringify([{ index: 1, properties: { "application.process.id": "800" } }]) },+ { stdout: JSON.stringify([{ index: 1, properties: { "application.process.id": "800" } }]) },+ ],+ });++ await detector.start();+ children[0].stdout.emit(+ "data",+ [+ "Event 'new' on source-output #1",+ "Event 'new' on source-output #2",+ "Event 'change' on source-output #1",+ "Event 'remove' on source-output #2",+ "",+ ].join("\n")+ );+ await flush();++ assert.equal(+ execCalls.filter(({ command }) => command === "pactl --format=json list source-outputs").length,+ 3,+ "startup reconcile plus one running and one trailing reconcile"+ );+ assert.deepEqual(detector.getExternalMicState(), {+ reliable: true,+ externalMicActive: true,+ });+ detector.stop();+});++test("linux: module streams without a process id stay excluded without costing reliability", async () => {+ const { detector, children } = createDetector("linux", {+ excludedProcessIds: () => [700],+ execResponses: [+ { stdout: "[]" },+ {+ // module-echo-cancel/loopback streams carry no application.process.id.+ stdout: JSON.stringify([+ { index: 1, properties: { "media.name": "Echo-Cancel Source Stream" } },+ { index: 2, properties: { "application.process.id": "900" } },+ ]),+ },+ {+ stdout: JSON.stringify([+ { index: 1, properties: { "media.name": "Echo-Cancel Source Stream" } },+ ]),+ },+ ],+ });+ const externalStates = [];+ detector.on("external-mic-state-changed", (state) => externalStates.push(state));++ await detector.start();+ children[0].stdout.emit("data", "Event 'new' on source-output #2\n");+ await flush();++ assert.deepEqual(detector.getExternalMicState(), {+ reliable: true,+ externalMicActive: true,+ });++ children[0].stdout.emit("data", "Event 'remove' on source-output #2\n");+ await flush();++ assert.deepEqual(detector.getExternalMicState(), {+ reliable: true,+ externalMicActive: false,+ });+ detector.stop();+});++test("linux: ownership query failure is unreliable while aggregate events still prompt", async () => {+ const { detector, children } = createDetector("linux", {+ execResponses: [{ stdout: "[]" }, { stdout: "not-json" }],+ });+ const externalStates = [];+ detector.on("external-mic-state-changed", (state) => externalStates.push(state));++ await detector.start();+ assert.deepEqual(detector.getExternalMicState(), {+ reliable: true,+ externalMicActive: false,+ });++ children[0].stdout.emit("data", "Event 'new' on source-output #7\n");+ await flush();++ assert.deepEqual(detector.getExternalMicState(), {+ reliable: false,+ externalMicActive: false,+ });+ assert.deepEqual(externalStates, [+ { reliable: true, externalMicActive: false },+ { reliable: false, externalMicActive: false },+ ]);+ assert.notEqual(detector._sustainedTimer, null, "aggregate activity must still drive prompts");+ detector.stop();+});++test("linux: a stale startup reconciliation cannot restore reliability after listener exit", async () => {+ const ownershipQuery = createDeferred();+ const { detector, children } = createDetector("linux", {+ execResponses: [{ promise: ownershipQuery.promise }],+ });++ const starting = detector.start();+ await flush();+ children[0].emit("exit", 1);+ ownershipQuery.resolve({+ stdout: JSON.stringify([{ index: 7, properties: { "application.process.id": "900" } }]),+ stderr: "",+ });+ await starting;+ await flush();++ assert.deepEqual(detector.getExternalMicState(), {+ reliable: false,+ externalMicActive: false,+ });+ assert.deepEqual([...detector._activeMicPids], []);+ assert.notEqual(detector.checkInterval, null, "polling must take over after listener exit");+ detector.stop();+});++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");+ t.after(() => fs.rmSync(temporaryDirectory, { force: true, recursive: true }));++ const compileResult = childProcess.spawnSync(+ process.env.CC || "cc",+ [+ "-DMIC_LISTENER_STATE_TEST",+ "-std=c11",+ "-Wall",+ "-Wextra",+ "-Werror",+ path.resolve(__dirname, "../../resources/windows-mic-listener.c"),+ "-o",+ executablePath,+ ],+ { encoding: "utf8" }+ );++ if (compileResult.error?.code === "ENOENT") {+ t.skip("no C compiler is available for the portable native-state seam");+ return;+ }++ assert.equal(compileResult.status, 0, compileResult.stderr);+ const scenarios = [+ { argument: "state", output: /native state tests passed/ },+ { argument: "ownership", output: /invalid process ownership rejected/ },+ { argument: "lifecycle", output: /session lifecycle fully released/ },+ { argument: "expired-state", output: /expired state queued cleanup once/ },+ { argument: "coverage", output: /unhealthy setup rejected/ },+ ];++ for (const scenario of scenarios) {+ const runResult = childProcess.spawnSync(executablePath, [scenario.argument], {+ encoding: "utf8",+ });+ assert.equal(runResult.status, 0, runResult.stderr);+ assert.match(runResult.stdout, scenario.output);+ }+});+// The native listeners are edge-triggered: they emit only on state transitions,// so an edge swallowed by a gate is never re-delivered. The detector must// remember the last known state and re-evaluate it when the gate lifts.diff --git a/test/helpers/electronProcessIds.test.js b/test/helpers/electronProcessIds.test.jsnew file mode 100644index 000000000..de6a718e9--- /dev/null+++ b/test/helpers/electronProcessIds.test.js@@ -0,0 +1,43 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const {+ collectAudioCaptureHelperPids,+ createExcludedProcessIdProvider,+} = require("../../src/helpers/electronProcessIds");++test("combines the Electron process tree with live audio capture helper PIDs on every call", () => {+ let ownPids = new Set([11, 22]);+ let helperPids = [55];+ const getProcessIds = createExcludedProcessIdProvider(+ () => helperPids,+ () => ownPids+ );++ assert.deepEqual(getProcessIds(), [11, 22, 55]);++ ownPids = new Set([11, 33]);+ helperPids = [];+ assert.deepEqual(getProcessIds(), [11, 33]);+});++test("defaults to the shared own-process set so the main pid is always excluded", () => {+ const getProcessIds = createExcludedProcessIdProvider();++ assert.ok(getProcessIds().includes(process.pid));+});++test("collectAudioCaptureHelperPids reads only live helper processes", () => {+ const managers = [+ null,+ undefined,+ {},+ { process: null },+ { process: { pid: 77 } },+ { process: { pid: 0 } },+ { process: { pid: "88" } },+ { process: { pid: 99 } },+ ];++ assert.deepEqual(collectAudioCaptureHelperPids(managers), [77, 99]);+});diff --git a/test/helpers/meetingAudioActivityMonitor.test.js b/test/helpers/meetingAudioActivityMonitor.test.jsnew file mode 100644index 000000000..90a506990--- /dev/null+++ b/test/helpers/meetingAudioActivityMonitor.test.js@@ -0,0 +1,141 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const {+ createMeetingAudioActivityMonitor,+ MIC_ACTIVITY_TAIL_MS,+ SYSTEM_ACTIVITY_TAIL_MS,+} = require("../../src/helpers/meetingAudioActivityMonitor");+const {+ MEETING_MIC_ACTIVITY_RMS,+ MEETING_SYSTEM_ACTIVITY_RMS,+} = require("../../src/utils/audioUtils");++const START = 1_000_000;++// A constant-amplitude s16le buffer whose RMS is exactly `rms`.+function pcmAtRms(rms, sampleCount = 800) {+ const buffer = Buffer.alloc(sampleCount * 2);+ const amplitude = Math.round(rms * 32768);+ for (let i = 0; i < sampleCount; i += 1) {+ buffer.writeInt16LE(amplitude, i * 2);+ }+ return buffer;+}++function createMonitor() {+ const changes = [];+ const monitor = createMeetingAudioActivityMonitor({+ onActivityChanged: (state) => changes.push({ ...state }),+ });+ return { monitor, changes };+}++test("a chunk at the mic threshold marks the mic active on the next tick and emits once", () => {+ const { monitor, changes } = createMonitor();++ monitor.recordChunk("mic", pcmAtRms(MEETING_MIC_ACTIVITY_RMS));+ assert.deepEqual(monitor.getState(), { micActive: false, systemActive: false });++ monitor.tick(START);+ monitor.tick(START + 1000);++ assert.deepEqual(changes, [{ micActive: true, systemActive: false }]);+ assert.deepEqual(monitor.getState(), { micActive: true, systemActive: false });+});++test("chunks below their channel threshold never mark a channel active", () => {+ const { monitor, changes } = createMonitor();++ monitor.recordChunk("mic", pcmAtRms(MEETING_MIC_ACTIVITY_RMS * 0.5));+ monitor.recordChunk("system", pcmAtRms(MEETING_SYSTEM_ACTIVITY_RMS * 0.5));+ monitor.tick(START);++ assert.deepEqual(changes, []);+});++test("digital-zero system chunks (Windows loopback silence) never mark the system active", () => {+ const { monitor, changes } = createMonitor();++ for (let i = 0; i < 30; i += 1) {+ monitor.recordChunk("system", Buffer.alloc(1600));+ }+ monitor.tick(START);+ monitor.tick(START + 1000);++ assert.deepEqual(changes, []);+});++test("activity ages out after each channel's tail with a single change", () => {+ const { monitor, changes } = createMonitor();++ monitor.recordChunk("mic", pcmAtRms(0.05));+ monitor.recordChunk("system", pcmAtRms(0.05));+ monitor.tick(START);+ assert.deepEqual(changes, [{ micActive: true, systemActive: true }]);++ monitor.tick(START + MIC_ACTIVITY_TAIL_MS - 1);+ assert.equal(changes.length, 1, "still inside both tails");++ monitor.tick(START + MIC_ACTIVITY_TAIL_MS);+ assert.deepEqual(changes.at(-1), { micActive: false, systemActive: true });++ monitor.tick(START + SYSTEM_ACTIVITY_TAIL_MS);+ assert.deepEqual(changes.at(-1), { micActive: false, systemActive: false });+ assert.equal(changes.length, 3);+});++test("odd-length and unaligned buffers are measured without throwing", () => {+ const { monitor, changes } = createMonitor();++ const aligned = pcmAtRms(0.05, 801);+ const oddLength = aligned.subarray(0, aligned.length - 1);+ const unaligned = Buffer.concat([Buffer.alloc(1), aligned]).subarray(1);++ assert.doesNotThrow(() => {+ monitor.recordChunk("mic", oddLength);+ monitor.recordChunk("system", unaligned);+ monitor.recordChunk("system", Buffer.alloc(1));+ monitor.recordChunk("system", null);+ });+ monitor.tick(START);++ assert.deepEqual(changes, [{ micActive: true, systemActive: true }]);+});++test("reset clears pending and active state without emitting", () => {+ const { monitor, changes } = createMonitor();++ monitor.recordChunk("mic", pcmAtRms(0.05));+ monitor.tick(START);+ monitor.recordChunk("system", pcmAtRms(0.05));+ assert.equal(changes.length, 1);++ monitor.reset();++ assert.deepEqual(monitor.getState(), { micActive: false, systemActive: false });+ monitor.tick(START + 100);+ assert.equal(changes.length, 1, "neither the pending system chunk nor the reset emitted");+});++test("a long tick gap ages out stale activity without spurious activity", () => {+ const { monitor, changes } = createMonitor();++ monitor.recordChunk("mic", pcmAtRms(0.05));+ monitor.tick(START);+ monitor.tick(START + 8 * 60 * 60 * 1000);++ assert.deepEqual(changes, [+ { micActive: true, systemActive: false },+ { micActive: false, systemActive: false },+ ]);+});++test("unknown sources are ignored", () => {+ const { monitor, changes } = createMonitor();++ monitor.recordChunk("other", pcmAtRms(0.5));+ monitor.tick(START);++ assert.deepEqual(changes, []);+});diff --git a/test/helpers/meetingAutoEndController.test.js b/test/helpers/meetingAutoEndController.test.jsnew file mode 100644index 000000000..7968efee1--- /dev/null+++ b/test/helpers/meetingAutoEndController.test.js@@ -0,0 +1,573 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const createMeetingAutoEndController = require("../../src/helpers/meetingAutoEndController");+const {+ COUNTDOWN_MS,+ SILENCE_WINDOW_MS,+ FAST_SILENCE_MS,+ KEEP_COOLDOWN_MS,+ OWNERSHIP_MIN_ACTIVE_MS,+ TICK_GAP_MS,+} = createMeetingAutoEndController;++const START_TIME = 1_000_000;+const TICK_MS = 1_000;++// The engine ticks the controller about once a second; runFor() mirrors that so+// long spans never look like a sleep gap.+const createHarness = () => {+ let now = START_TIME;+ const countdowns = [];+ const canceledCountdowns = [];+ const stops = [];+ const controller = createMeetingAutoEndController({+ now: () => now,+ onCountdown: (countdown) => countdowns.push(countdown),+ onCountdownCanceled: (sessionId) => canceledCountdowns.push(sessionId),+ onStop: (sessionId, reason) => stops.push({ sessionId, reason }),+ });++ const runFor = (ms) => {+ let remaining = ms;+ while (remaining > 0) {+ const step = Math.min(TICK_MS, remaining);+ now += step;+ remaining -= step;+ controller.tick();+ }+ };+ const jump = (ms) => {+ now += ms;+ };++ return {+ controller,+ countdowns,+ canceledCountdowns,+ stops,+ runFor,+ jump,+ now: () => now,+ };+};++const beginOwnership = (controller, sessionId = "s1") =>+ controller.beginSession({ sessionId, eligible: true, reliable: true, externalMicActive: true });++const beginFallback = (controller, sessionId = "s1", { reliable = true } = {}) =>+ controller.beginSession({ sessionId, eligible: true, reliable, externalMicActive: false });++const micReleased = (controller, sessionId = "s1") =>+ controller.handleExternalMicState({ sessionId, reliable: true, externalMicActive: false });++const micAcquired = (controller, sessionId = "s1") =>+ controller.handleExternalMicState({ sessionId, reliable: true, externalMicActive: true });++const audio = (controller, micActive, systemActive, sessionId = "s1") =>+ controller.handleAudioActivity({ sessionId, micActive, systemActive });++// --------------------------------------------------------------------------+// Ownership mode+// --------------------------------------------------------------------------++test("ownership: mic release with a quiet system channel starts a mic-released countdown", () => {+ const h = createHarness();+ beginOwnership(h.controller);+ h.runFor(OWNERSHIP_MIN_ACTIVE_MS);++ micReleased(h.controller);++ assert.deepEqual(h.countdowns, [+ { sessionId: "s1", expiresAt: h.now() + COUNTDOWN_MS, reason: "mic-released" },+ ]);+ h.runFor(COUNTDOWN_MS - TICK_MS);+ assert.deepEqual(h.stops, []);+ h.runFor(TICK_MS);+ assert.deepEqual(h.stops, [{ sessionId: "s1", reason: "mic-released" }]);+});++test("ownership: audible system audio defers the countdown until it goes quiet", () => {+ const h = createHarness();+ beginOwnership(h.controller);+ h.runFor(OWNERSHIP_MIN_ACTIVE_MS);+ audio(h.controller, false, true);++ micReleased(h.controller);+ h.runFor(2 * COUNTDOWN_MS);+ assert.deepEqual(h.countdowns, [], "remote voices still playing — call is live");++ audio(h.controller, false, false);+ assert.equal(h.countdowns.length, 1);+ assert.equal(h.countdowns[0].reason, "mic-released");+});++test("ownership: system audio resuming cancels the countdown and quiet restarts it from 60s", () => {+ const h = createHarness();+ beginOwnership(h.controller);+ h.runFor(OWNERSHIP_MIN_ACTIVE_MS);+ micReleased(h.controller);+ h.runFor(30_000);++ audio(h.controller, false, true);+ assert.deepEqual(h.canceledCountdowns, ["s1"]);+ h.runFor(COUNTDOWN_MS);+ assert.deepEqual(h.stops, []);++ audio(h.controller, false, false);+ assert.equal(h.countdowns.length, 2);+ assert.equal(h.countdowns[1].expiresAt, h.now() + COUNTDOWN_MS, "full 60s again");+});++test("ownership: a re-acquired external mic cancels the countdown and re-arms", () => {+ const h = createHarness();+ beginOwnership(h.controller);+ h.runFor(OWNERSHIP_MIN_ACTIVE_MS);+ micReleased(h.controller);+ h.runFor(30_000);++ micAcquired(h.controller);+ assert.deepEqual(h.canceledCountdowns, ["s1"]);+ h.runFor(2 * COUNTDOWN_MS);+ assert.deepEqual(h.stops, []);++ micReleased(h.controller);+ assert.equal(h.countdowns.length, 2);+});++test("ownership: mic-channel activity does not cancel the countdown", () => {+ const h = createHarness();+ beginOwnership(h.controller);+ h.runFor(OWNERSHIP_MIN_ACTIVE_MS);+ micReleased(h.controller);++ audio(h.controller, true, false);+ h.runFor(COUNTDOWN_MS);++ assert.deepEqual(h.canceledCountdowns, []);+ assert.deepEqual(h.stops, [{ sessionId: "s1", reason: "mic-released" }]);+});++test("ownership: a hold shorter than the minimum falls back to silence instead of arming", () => {+ const h = createHarness();+ beginFallback(h.controller);+ h.runFor(20_000);+ audio(h.controller, true, false);+ micAcquired(h.controller);+ h.runFor(OWNERSHIP_MIN_ACTIVE_MS - TICK_MS);++ micReleased(h.controller);+ h.runFor(2 * COUNTDOWN_MS);++ assert.deepEqual(h.countdowns, [], "people are still talking in the room");+ audio(h.controller, false, false);+ h.runFor(SILENCE_WINDOW_MS);+ assert.equal(h.countdowns.length, 1);+ assert.equal(h.countdowns[0].reason, "silence");+});++test("ownership: a process exit is ignored", () => {+ const h = createHarness();+ beginOwnership(h.controller);+ h.runFor(OWNERSHIP_MIN_ACTIVE_MS);++ h.controller.handleMeetingProcessExit({ sessionId: "s1" });+ h.runFor(2 * SILENCE_WINDOW_MS);++ assert.deepEqual(h.countdowns, []);+});++test("ownership: keep suppresses prompts until fresh active ownership, and the cooldown still applies", () => {+ const h = createHarness();+ beginOwnership(h.controller);+ h.runFor(OWNERSHIP_MIN_ACTIVE_MS);+ micReleased(h.controller);++ assert.equal(h.controller.keepRecording("s1"), true);+ assert.deepEqual(h.canceledCountdowns, ["s1"]);+ h.runFor(2 * KEEP_COOLDOWN_MS);+ assert.equal(h.countdowns.length, 1, "no further call → never re-prompted");++ micAcquired(h.controller);+ h.runFor(OWNERSHIP_MIN_ACTIVE_MS);+ micReleased(h.controller);+ assert.equal(h.countdowns.length, 2, "a new call is fresh evidence");+});++test("ownership: a call rejoined and left again re-prompts at once, even inside the keep cooldown", () => {+ const h = createHarness();+ beginOwnership(h.controller);+ h.runFor(OWNERSHIP_MIN_ACTIVE_MS);+ micReleased(h.controller);+ h.controller.keepRecording("s1");++ h.runFor(60_000);+ micAcquired(h.controller);+ h.runFor(OWNERSHIP_MIN_ACTIVE_MS);+ micReleased(h.controller);++ assert.equal(h.countdowns.length, 2, "unambiguous evidence must not wait out the cooldown");+ assert.equal(h.countdowns[1].reason, "mic-released");+});++test("ownership: a brief rejoin inside the cooldown does not bypass it", () => {+ const h = createHarness();+ beginOwnership(h.controller);+ h.runFor(OWNERSHIP_MIN_ACTIVE_MS);+ micReleased(h.controller);+ h.controller.keepRecording("s1");+ const keptAt = h.now();++ h.runFor(60_000);+ micAcquired(h.controller);+ h.runFor(OWNERSHIP_MIN_ACTIVE_MS - TICK_MS);+ micReleased(h.controller);+ h.runFor(2 * SILENCE_WINDOW_MS);+ assert.equal(h.countdowns.length, 1, "an incidental hold is not fresh evidence");++ h.runFor(keptAt + KEEP_COOLDOWN_MS - h.now());+ h.runFor(SILENCE_WINDOW_MS);+ assert.equal(h.countdowns.length, 2, "after the cooldown, silence prompts as fallback");+ assert.equal(h.countdowns[1].reason, "silence");+});++// --------------------------------------------------------------------------+// Fallback mode+// --------------------------------------------------------------------------++test("fallback: 60s of both-channel silence prompts with reason silence", () => {+ const h = createHarness();+ beginFallback(h.controller);++ h.runFor(SILENCE_WINDOW_MS - TICK_MS);+ assert.deepEqual(h.countdowns, []);+ h.runFor(TICK_MS);++ assert.deepEqual(h.countdowns, [+ { sessionId: "s1", expiresAt: h.now() + COUNTDOWN_MS, reason: "silence" },+ ]);+ h.runFor(COUNTDOWN_MS);+ assert.deepEqual(h.stops, [{ sessionId: "s1", reason: "silence" }]);+});++test("fallback: activity on either channel resets the window and cancels the countdown", () => {+ const h = createHarness();+ beginFallback(h.controller);+ h.runFor(SILENCE_WINDOW_MS - 5_000);++ audio(h.controller, true, false);+ h.runFor(5_000);+ audio(h.controller, false, false);+ h.runFor(SILENCE_WINDOW_MS - TICK_MS);+ assert.deepEqual(h.countdowns, [], "the window restarted when the mic went quiet");+ h.runFor(TICK_MS);+ assert.equal(h.countdowns.length, 1);++ audio(h.controller, false, true);+ assert.deepEqual(h.canceledCountdowns, ["s1"]);+ h.runFor(2 * COUNTDOWN_MS);+ assert.deepEqual(h.stops, []);+});++test("fallback: process exit with no tracked app left shortens the window to 10s", () => {+ const h = createHarness();+ beginFallback(h.controller);+ h.runFor(20_000);++ h.controller.handleMeetingProcessExit({ sessionId: "s1" });+ h.runFor(FAST_SILENCE_MS - TICK_MS);+ assert.deepEqual(h.countdowns, []);+ h.runFor(TICK_MS);++ assert.equal(h.countdowns.length, 1);+ assert.equal(h.countdowns[0].reason, "process-exit");+});++test("fallback: activity after a process exit clears the fast window", () => {+ const h = createHarness();+ beginFallback(h.controller);+ h.controller.handleMeetingProcessExit({ sessionId: "s1" });+ h.runFor(5_000);++ audio(h.controller, false, true);+ h.runFor(5_000);+ audio(h.controller, false, false);+ h.runFor(FAST_SILENCE_MS);+ assert.deepEqual(h.countdowns, [], "call continued elsewhere — back to the full window");++ h.runFor(SILENCE_WINDOW_MS - FAST_SILENCE_MS);+ assert.equal(h.countdowns.length, 1);+ assert.equal(h.countdowns[0].reason, "silence");+});++test("fallback: process exit while a countdown is visible is ignored", () => {+ const h = createHarness();+ beginFallback(h.controller);+ h.runFor(SILENCE_WINDOW_MS);+ assert.equal(h.countdowns.length, 1);+ const { expiresAt } = h.countdowns[0];++ h.controller.handleMeetingProcessExit({ sessionId: "s1" });+ h.runFor(COUNTDOWN_MS);++ assert.equal(h.countdowns.length, 1);+ assert.deepEqual(h.stops, [{ sessionId: "s1", reason: "silence" }]);+ assert.equal(h.countdowns[0].expiresAt, expiresAt);+});++test("fallback: keep is honored until activity resumes and the cooldown passes", () => {+ const h = createHarness();+ beginFallback(h.controller);+ h.runFor(SILENCE_WINDOW_MS);+ assert.equal(h.controller.keepRecording("s1"), true);+ const keptAt = h.now();++ h.runFor(2 * KEEP_COOLDOWN_MS);+ assert.equal(h.countdowns.length, 1, "no fresh evidence → no re-prompt");++ audio(h.controller, true, false);+ h.runFor(2_000);+ audio(h.controller, false, false);+ h.runFor(SILENCE_WINDOW_MS);+ assert.equal(h.countdowns.length, 2, "renewed audio then silence reopened the episode");+ assert.ok(h.countdowns[1].expiresAt > keptAt + KEEP_COOLDOWN_MS);+});++test("fallback: process exit after keep reopens the episode but fires no earlier than the cooldown", () => {+ const h = createHarness();+ beginFallback(h.controller);+ h.runFor(SILENCE_WINDOW_MS);+ h.controller.keepRecording("s1");+ const keptAt = h.now();++ h.runFor(60_000);+ h.controller.handleMeetingProcessExit({ sessionId: "s1" });+ h.runFor(FAST_SILENCE_MS + TICK_MS);+ assert.equal(h.countdowns.length, 1, "inside the cooldown");++ h.runFor(keptAt + KEEP_COOLDOWN_MS - h.now());+ assert.equal(h.countdowns.length, 2);+ assert.equal(h.countdowns[1].reason, "process-exit");+});++test("fallback: a session that never sees a chunk prompts after the first window", () => {+ const h = createHarness();+ beginFallback(h.controller);++ h.runFor(SILENCE_WINDOW_MS);++ assert.equal(h.countdowns.length, 1);+ assert.equal(h.countdowns[0].reason, "silence");+});++test("fallback: unreliable ownership behaves as fallback from the start", () => {+ const h = createHarness();+ beginFallback(h.controller, "s1", { reliable: false });++ h.runFor(SILENCE_WINDOW_MS);+ assert.equal(h.countdowns.length, 1);+});++// --------------------------------------------------------------------------+// Mode transitions+// --------------------------------------------------------------------------++test("fresh active ownership switches fallback to ownership and cancels a pending fallback countdown", () => {+ const h = createHarness();+ beginFallback(h.controller);+ h.runFor(SILENCE_WINDOW_MS);+ assert.equal(h.countdowns.length, 1);++ micAcquired(h.controller);+ assert.deepEqual(h.canceledCountdowns, ["s1"]);+ h.runFor(2 * SILENCE_WINDOW_MS);+ assert.equal(h.countdowns.length, 1, "silence no longer prompts while an app holds the mic");++ micReleased(h.controller);+ assert.equal(h.countdowns.length, 2);+ assert.equal(h.countdowns[1].reason, "mic-released");+});++test("reliability loss switches to fallback, dismisses the countdown, and restarts silence from now", () => {+ const h = createHarness();+ beginOwnership(h.controller);+ h.runFor(OWNERSHIP_MIN_ACTIVE_MS);+ micReleased(h.controller);+ h.runFor(30_000);++ h.controller.handleExternalMicState({+ sessionId: "s1",+ reliable: false,+ externalMicActive: false,+ });+ assert.deepEqual(h.canceledCountdowns, ["s1"]);++ h.runFor(SILENCE_WINDOW_MS - TICK_MS);+ assert.equal(h.countdowns.length, 1);+ h.runFor(TICK_MS);+ assert.equal(h.countdowns.length, 2);+ assert.equal(h.countdowns[1].reason, "silence");+});++test("a reliable-but-inactive report after a reliability loss stays in fallback", () => {+ const h = createHarness();+ beginOwnership(h.controller);+ h.runFor(OWNERSHIP_MIN_ACTIVE_MS);+ h.controller.handleExternalMicState({+ sessionId: "s1",+ reliable: false,+ externalMicActive: false,+ });+ h.runFor(5_000);++ micReleased(h.controller);+ assert.deepEqual(+ h.countdowns,+ [],+ "no observed release → must not start a mic-released countdown"+ );++ h.runFor(SILENCE_WINDOW_MS);+ assert.equal(h.countdowns.length, 1);+ assert.equal(h.countdowns[0].reason, "silence");+});++// --------------------------------------------------------------------------+// Clock, lifecycle, and guards+// --------------------------------------------------------------------------++test("a tick gap over the sleep threshold discards accumulated silence and cancels a visible countdown without stopping", () => {+ const h = createHarness();+ beginFallback(h.controller);+ h.runFor(SILENCE_WINDOW_MS);+ assert.equal(h.countdowns.length, 1);++ h.jump(8 * 60 * 60 * 1000);+ h.controller.tick();++ assert.deepEqual(h.stops, []);+ assert.deepEqual(h.canceledCountdowns, ["s1"]);+ h.runFor(SILENCE_WINDOW_MS - TICK_MS);+ assert.equal(h.countdowns.length, 1, "silence restarted from wake");+ h.runFor(TICK_MS);+ assert.equal(h.countdowns.length, 2);+});++test("a gap observed through an activity event instead of tick() is handled the same way", () => {+ const h = createHarness();+ beginFallback(h.controller);+ h.runFor(SILENCE_WINDOW_MS);+ h.runFor(30_000);++ h.jump(TICK_GAP_MS + 1);+ audio(h.controller, false, false);++ assert.deepEqual(h.stops, []);+ assert.deepEqual(h.canceledCountdowns, ["s1"]);+});++test("countdown expiry stops exactly once and later inputs are ignored", () => {+ const h = createHarness();+ beginOwnership(h.controller);+ h.runFor(OWNERSHIP_MIN_ACTIVE_MS);+ micReleased(h.controller);+ h.runFor(COUNTDOWN_MS);+ assert.equal(h.stops.length, 1);++ h.runFor(5 * COUNTDOWN_MS);+ micAcquired(h.controller);+ micReleased(h.controller);+ audio(h.controller, true, true);+ audio(h.controller, false, false);+ h.controller.handleMeetingProcessExit({ sessionId: "s1" });+ h.runFor(5 * COUNTDOWN_MS);++ assert.equal(h.stops.length, 1);+ assert.equal(h.countdowns.length, 1);+});++test("keep recording after countdown expiry reports failure — the stop is already in flight", () => {+ const h = createHarness();+ beginOwnership(h.controller);+ h.runFor(OWNERSHIP_MIN_ACTIVE_MS);+ micReleased(h.controller);+ h.runFor(COUNTDOWN_MS);++ assert.equal(h.controller.keepRecording("s1"), false);+});++test("ending or replacing a session cancels its countdown", () => {+ const h = createHarness();+ beginOwnership(h.controller);+ h.runFor(OWNERSHIP_MIN_ACTIVE_MS);+ micReleased(h.controller);+ assert.equal(h.countdowns.length, 1);++ beginOwnership(h.controller, "s2");+ assert.deepEqual(h.canceledCountdowns, ["s1"]);+ h.runFor(2 * COUNTDOWN_MS);+ assert.deepEqual(h.stops, [], "the old countdown never fires for the new session");++ micReleased(h.controller, "s2");+ h.controller.endSession("s2");+ assert.deepEqual(h.canceledCountdowns, ["s1", "s2"]);+ h.runFor(2 * COUNTDOWN_MS);+ assert.deepEqual(h.stops, []);+});++test("ending an expired session dismisses nothing and does not stop again", () => {+ const h = createHarness();+ beginOwnership(h.controller);+ h.runFor(OWNERSHIP_MIN_ACTIVE_MS);+ micReleased(h.controller);+ h.runFor(COUNTDOWN_MS);++ h.controller.endSession("s1");+ h.runFor(COUNTDOWN_MS);++ assert.equal(h.stops.length, 1);+ assert.deepEqual(h.canceledCountdowns, []);+});++test("stale session ids and ineligible sessions ignore all inputs", () => {+ const h = createHarness();+ beginOwnership(h.controller);+ h.runFor(OWNERSHIP_MIN_ACTIVE_MS);++ micReleased(h.controller, "other");+ audio(h.controller, false, false, "other");+ h.controller.handleMeetingProcessExit({ sessionId: "other" });+ assert.equal(h.controller.keepRecording("other"), false);+ h.runFor(2 * SILENCE_WINDOW_MS);+ assert.deepEqual(h.countdowns, []);++ h.controller.beginSession({+ sessionId: "s3",+ eligible: false,+ reliable: true,+ externalMicActive: true,+ });+ micReleased(h.controller, "s3");+ h.runFor(2 * SILENCE_WINDOW_MS);+ assert.deepEqual(h.countdowns, []);+});++test("beginSession seeds the initial audio state so an already-audible system channel defers the countdown", () => {+ const h = createHarness();+ h.controller.beginSession({+ sessionId: "s1",+ eligible: true,+ reliable: true,+ externalMicActive: true,+ micActive: false,+ systemActive: true,+ });+ h.runFor(OWNERSHIP_MIN_ACTIVE_MS);++ micReleased(h.controller);+ h.runFor(COUNTDOWN_MS);+ assert.deepEqual(h.countdowns, []);++ audio(h.controller, false, false);+ assert.equal(h.countdowns.length, 1);+});diff --git a/test/helpers/meetingAutoEndKeep.test.js b/test/helpers/meetingAutoEndKeep.test.jsnew file mode 100644index 000000000..13b469a2c--- /dev/null+++ b/test/helpers/meetingAutoEndKeep.test.js@@ -0,0 +1,46 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const {+ keepMeetingRecordingSession,+ registerMeetingAutoEndKeepHandler,+} = require("../../src/helpers/meetingAutoEndKeep");++test("keep-recording IPC validation rejects invalid and stale sessions", () => {+ const requestedSessions = [];+ const engine = {+ keepRecordingSession: (sessionId) => {+ requestedSessions.push(sessionId);+ return sessionId === "meeting-2";+ },+ };++ assert.deepEqual(keepMeetingRecordingSession(engine, ""), {+ success: false,+ reason: "invalid-session",+ });+ assert.deepEqual(keepMeetingRecordingSession(engine, "meeting-1"), {+ success: false,+ reason: "stale-session",+ });+ assert.deepEqual(keepMeetingRecordingSession(engine, "meeting-2"), { success: true });+ assert.deepEqual(requestedSessions, ["meeting-1", "meeting-2"]);+});++test("main IPC registers Keep and resolves the current engine at invocation time", async () => {+ const handlers = new Map();+ const ipcMain = {+ handle: (channel, handler) => handlers.set(channel, handler),+ };+ let engine = { keepRecordingSession: () => false };+ registerMeetingAutoEndKeepHandler(ipcMain, () => engine);+ const handler = handlers.get("meeting-auto-end-keep");++ assert.deepEqual(await handler({}, "meeting-1"), {+ success: false,+ reason: "stale-session",+ });++ engine = { keepRecordingSession: (sessionId) => sessionId === "meeting-2" };+ assert.deepEqual(await handler({}, "meeting-2"), { success: true });+});diff --git a/test/helpers/meetingDetectionEngineAutoEnd.test.js b/test/helpers/meetingDetectionEngineAutoEnd.test.jsnew file mode 100644index 000000000..ae06998ef--- /dev/null+++ b/test/helpers/meetingDetectionEngineAutoEnd.test.js@@ -0,0 +1,768 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const Module = require("node:module");+const { EventEmitter } = require("node:events");++const originalLoad = Module._load;+Module._load = function loadWithElectronStub(request, parent, isMain) {+ if (request === "electron") {+ return {+ shell: { openExternal: async () => undefined },+ BrowserWindow: { getAllWindows: () => [] },+ };+ }+ return originalLoad.call(this, request, parent, isMain);+};+const MeetingDetectionEngine = require("../../src/helpers/meetingDetectionEngine");+const createMeetingAutoEndController = require("../../src/helpers/meetingAutoEndController");+Module._load = originalLoad;++const { COUNTDOWN_MS, SILENCE_WINDOW_MS, FAST_SILENCE_MS, OWNERSHIP_MIN_ACTIVE_MS } =+ createMeetingAutoEndController;++const TICK_MS = 1000;++// Fake clock with a single interval slot: the engine's 1s auto-end ticker.+// advance() steps the clock a second at a time and fires the interval so long+// spans never look like a sleep gap.+const createClock = () => {+ let now = 10_000;+ const intervals = new Map();+ let nextIntervalId = 1;++ return {+ now: () => now,+ setInterval: (callback, delay) => {+ const id = nextIntervalId;+ nextIntervalId += 1;+ intervals.set(id, { callback, delay });+ return id;+ },+ clearInterval: (id) => intervals.delete(id),+ activeIntervals: () => intervals.size,+ advance: (ms) => {+ let remaining = ms;+ while (remaining > 0) {+ const step = Math.min(TICK_MS, remaining);+ now += step;+ remaining -= step;+ for (const { callback } of [...intervals.values()]) callback();+ }+ },+ };+};++// A buffer whose RMS is unmistakably above the activity thresholds.+const LOUD_CHUNK = (() => {+ const buffer = Buffer.alloc(1600);+ for (let i = 0; i < 800; i += 1) buffer.writeInt16LE(3000, i * 2);+ return buffer;+})();++class FakeAudioActivityDetector extends EventEmitter {+ constructor() {+ super();+ this.running = false;+ this.startCount = 0;+ this.stopCount = 0;+ this.externalMicState = { reliable: true, externalMicActive: true };+ }++ async start() {+ if (this.running) return;+ this.running = true;+ this.startCount += 1;+ }++ stop() {+ if (!this.running) return;+ this.running = false;+ this.stopCount += 1;+ }++ getExternalMicState() {+ return { ...this.externalMicState };+ }++ setUserRecording() {}+ resetPrompt() {}+ dismiss() {}+}++class FakeMeetingProcessDetector extends EventEmitter {+ constructor() {+ super();+ this.running = false;+ this.detected = [];+ }++ start() {+ this.running = true;+ }++ stop() {+ this.running = false;+ }++ getDetectedProcesses() {+ return this.detected.map((processKey) => ({ processKey, appName: processKey }));+ }++ // Mirrors the real detector: the ended key is removed before the event fires.+ endProcess(processKey) {+ this.detected = this.detected.filter((key) => key !== processKey);+ this.emit("meeting-process-ended", { processKey, appName: processKey });+ }+}++function createEngine(windowManagerOverrides = {}) {+ const clock = createClock();+ const audioActivityDetector = new FakeAudioActivityDetector();+ const meetingProcessDetector = new FakeMeetingProcessDetector();+ const shownCountdowns = [];+ const dismissedCountdowns = [];+ const shownNotifications = [];+ const windowManager = {+ notificationPrefs: {},+ showMeetingAutoEndCountdown: (countdown) => shownCountdowns.push(countdown),+ dismissMeetingAutoEndCountdown: (sessionId) => dismissedCountdowns.push(sessionId),+ showMeetingNotification: (notification) => shownNotifications.push(notification),+ ...windowManagerOverrides,+ };+ const engine = new MeetingDetectionEngine(+ { getActiveMeetingState: () => ({ activeMeeting: null, upcomingEvents: [] }) },+ meetingProcessDetector,+ audioActivityDetector,+ windowManager,+ {},+ {+ now: clock.now,+ setInterval: clock.setInterval,+ clearInterval: clock.clearInterval,+ }+ );++ const micState = (reliable, externalMicActive) =>+ audioActivityDetector.emit("external-mic-state-changed", { reliable, externalMicActive });++ const owner = (messages = []) => ({+ isDestroyed: () => false,+ send: (channel, payload) => messages.push({ channel, payload }),+ });++ return {+ audioActivityDetector,+ meetingProcessDetector,+ clock,+ dismissedCountdowns,+ engine,+ shownCountdowns,+ shownNotifications,+ micState,+ owner,+ };+}++test("detection prompts retain their existing payload with a detection discriminator", () => {+ const { engine, shownNotifications } = createEngine();+ const event = {+ id: "calendar-1",+ summary: "Planning",+ start_time: new Date(9_000).toISOString(),+ };++ engine.handleCalendarReminder(event);++ assert.deepEqual(shownNotifications, [+ {+ kind: "detection",+ detectionId: "calendar:calendar-1",+ source: "calendar",+ key: "calendar-1",+ event,+ variant: "underway",+ joinUrl: null,+ },+ ]);+ engine.stop();+});++test("keeps audio ownership detection running while an eligible recording is active", async () => {+ const { audioActivityDetector, engine, owner } = createEngine();++ engine.setPreferences({ audioDetection: false });+ assert.equal(audioActivityDetector.running, false);++ await engine.beginRecordingSession({+ sessionId: "meeting-1",+ autoEndEligible: true,+ ownerWebContents: owner(),+ systemAudioAvailable: true,+ });+ assert.equal(audioActivityDetector.running, true);++ engine.setPreferences({ audioDetection: false });+ assert.equal(audioActivityDetector.running, true);++ assert.equal(engine.endRecordingSession("meeting-1"), true);+ assert.equal(audioActivityDetector.running, false);+});++test("keeps the process detector running for an eligible session while processDetection is off", async () => {+ const { meetingProcessDetector, engine, owner } = createEngine();++ engine.setPreferences({ processDetection: false });+ assert.equal(meetingProcessDetector.running, false);++ await engine.beginRecordingSession({+ sessionId: "meeting-1",+ autoEndEligible: true,+ ownerWebContents: owner(),+ systemAudioAvailable: true,+ });+ assert.equal(meetingProcessDetector.running, true);++ engine.endRecordingSession("meeting-1");+ assert.equal(meetingProcessDetector.running, false);+});++test("does not arm auto-end until system audio capture is confirmed", async () => {+ const { clock, engine, micState, owner, shownCountdowns } = createEngine();+ const ownerWebContents = owner();++ await engine.beginRecordingSession({+ sessionId: "meeting-1",+ autoEndEligible: true,+ ownerWebContents,+ });+ clock.advance(OWNERSHIP_MIN_ACTIVE_MS);+ micState(true, false);+ clock.advance(2 * COUNTDOWN_MS);++ assert.deepEqual(shownCountdowns, []);++ assert.equal(+ await engine.setRecordingSystemAudioAvailable("meeting-1", true, owner()),+ false,+ "a stale renderer must not arm another renderer's recording"+ );+ assert.equal(+ await engine.setRecordingSystemAudioAvailable("meeting-1", true, ownerWebContents),+ true+ );+ clock.advance(OWNERSHIP_MIN_ACTIVE_MS);+ micState(true, false);++ assert.equal(shownCountdowns.length, 1);+ engine.stop();+});++test("shows and dismisses the countdown from reliable external mic changes", async () => {+ const { clock, dismissedCountdowns, engine, micState, owner, shownCountdowns } = createEngine();++ await engine.beginRecordingSession({+ sessionId: "meeting-1",+ autoEndEligible: true,+ ownerWebContents: owner(),+ systemAudioAvailable: true,+ });+ clock.advance(OWNERSHIP_MIN_ACTIVE_MS);+ micState(true, false);+ micState(true, true);++ assert.deepEqual(shownCountdowns, [+ { sessionId: "meeting-1", expiresAt: clock.now() + COUNTDOWN_MS, reason: "mic-released" },+ ]);+ assert.deepEqual(dismissedCountdowns, ["meeting-1"]);+ engine.stop();+});++test("system activity from meeting chunks defers the ownership countdown until quiet", async () => {+ const { clock, engine, micState, owner, shownCountdowns } = createEngine();++ await engine.beginRecordingSession({+ sessionId: "meeting-1",+ autoEndEligible: true,+ ownerWebContents: owner(),+ systemAudioAvailable: true,+ });+ clock.advance(OWNERSHIP_MIN_ACTIVE_MS);+ engine.recordMeetingAudioChunk("system", LOUD_CHUNK);+ clock.advance(TICK_MS);++ micState(true, false);+ clock.advance(TICK_MS);+ assert.deepEqual(shownCountdowns, [], "remote audio still playing");++ // The system channel ages out once no more loud chunks arrive.+ clock.advance(5 * TICK_MS);+ assert.equal(shownCountdowns.length, 1);+ assert.equal(shownCountdowns[0].reason, "mic-released");+ engine.stop();+});++test("meeting audio chunks are ignored before the controller session begins and after it ends", async () => {+ const { clock, engine, micState, owner, shownCountdowns } = createEngine();++ // Streaming starts before beginRecordingSession is reached in main.+ engine.recordMeetingAudioChunk("system", LOUD_CHUNK);+ await engine.beginRecordingSession({+ sessionId: "meeting-1",+ autoEndEligible: true,+ ownerWebContents: owner(),+ systemAudioAvailable: true,+ });+ clock.advance(OWNERSHIP_MIN_ACTIVE_MS);+ micState(true, false);+ assert.equal(+ shownCountdowns.length,+ 1,+ "the pre-session chunk must not read as live system audio"+ );++ engine.endRecordingSession("meeting-1");+ assert.doesNotThrow(() => engine.recordMeetingAudioChunk("mic", LOUD_CHUNK));+ clock.advance(2 * SILENCE_WINDOW_MS);+ assert.equal(shownCountdowns.length, 1);+});++test("fallback silence prompts and forwards the reason to the countdown and stop request", async () => {+ const { audioActivityDetector, clock, engine, owner, shownCountdowns } = createEngine();+ const messages = [];+ audioActivityDetector.externalMicState = { reliable: true, externalMicActive: false };++ await engine.beginRecordingSession({+ sessionId: "meeting-1",+ autoEndEligible: true,+ ownerWebContents: owner(messages),+ systemAudioAvailable: true,+ });+ clock.advance(SILENCE_WINDOW_MS);++ assert.equal(shownCountdowns.length, 1);+ assert.equal(shownCountdowns[0].reason, "silence");+ clock.advance(COUNTDOWN_MS);+ assert.deepEqual(messages, [+ {+ channel: "meeting-auto-end-requested",+ payload: { sessionId: "meeting-1", reason: "silence" },+ },+ ]);+ engine.stop();+});++test("meeting-process-ended tightens the silence window only when no tracked app remains", async () => {+ const { audioActivityDetector, clock, engine, meetingProcessDetector, owner, shownCountdowns } =+ createEngine();+ audioActivityDetector.externalMicState = { reliable: false, externalMicActive: false };+ meetingProcessDetector.detected = ["zoom", "teams"];++ await engine.beginRecordingSession({+ sessionId: "meeting-1",+ autoEndEligible: true,+ ownerWebContents: owner(),+ systemAudioAvailable: true,+ });+ meetingProcessDetector.endProcess("teams");+ clock.advance(FAST_SILENCE_MS + TICK_MS);+ assert.deepEqual(shownCountdowns, [], "Zoom is still running");++ meetingProcessDetector.endProcess("zoom");+ clock.advance(FAST_SILENCE_MS);+ assert.equal(shownCountdowns.length, 1);+ assert.equal(shownCountdowns[0].reason, "process-exit");+ engine.stop();+});++test("reliability loss dismisses the countdown and prevents auto-stop", async () => {+ const { clock, dismissedCountdowns, engine, micState, owner } = createEngine();+ const messages = [];++ await engine.beginRecordingSession({+ sessionId: "meeting-1",+ autoEndEligible: true,+ ownerWebContents: owner(messages),+ systemAudioAvailable: true,+ });+ clock.advance(OWNERSHIP_MIN_ACTIVE_MS);+ micState(true, false);+ clock.advance(30_000);++ micState(false, false);+ clock.advance(COUNTDOWN_MS);++ assert.deepEqual(dismissedCountdowns, ["meeting-1"]);+ assert.deepEqual(messages, []);+ engine.stop();+});++test("countdown presentation failure keeps the recording active", async () => {+ const { clock, engine, micState, owner } = createEngine({+ showMeetingAutoEndCountdown: () => Promise.reject(new Error("notification load failed")),+ });+ const messages = [];++ await engine.beginRecordingSession({+ sessionId: "meeting-1",+ autoEndEligible: true,+ ownerWebContents: owner(messages),+ systemAudioAvailable: true,+ });+ clock.advance(OWNERSHIP_MIN_ACTIVE_MS);+ micState(true, false);+ await Promise.resolve();+ await Promise.resolve();+ clock.advance(2 * COUNTDOWN_MS);++ assert.deepEqual(messages, []);+ engine.stop();+});++test("expiry requests one stop from the renderer that owns the current session", async () => {+ const { clock, dismissedCountdowns, engine, micState, owner } = createEngine();+ const messages = [];++ await engine.beginRecordingSession({+ sessionId: "meeting-1",+ autoEndEligible: true,+ ownerWebContents: owner(messages),+ systemAudioAvailable: true,+ });+ clock.advance(OWNERSHIP_MIN_ACTIVE_MS);+ micState(true, false);+ clock.advance(3 * COUNTDOWN_MS);++ assert.deepEqual(messages, [+ {+ channel: "meeting-auto-end-requested",+ payload: { sessionId: "meeting-1", reason: "mic-released" },+ },+ ]);+ assert.deepEqual(dismissedCountdowns, ["meeting-1"]);+ engine.stop();+});++test("replacement cancels the old countdown and stale end requests preserve the new session", async () => {+ const { clock, dismissedCountdowns, engine, micState } = createEngine();+ const messages = [];++ await engine.beginRecordingSession({+ sessionId: "meeting-1",+ autoEndEligible: true,+ ownerWebContents: { isDestroyed: () => false, send: () => messages.push("meeting-1") },+ systemAudioAvailable: true,+ });+ clock.advance(OWNERSHIP_MIN_ACTIVE_MS);+ micState(true, false);++ await engine.beginRecordingSession({+ sessionId: "meeting-2",+ autoEndEligible: true,+ ownerWebContents: { isDestroyed: () => false, send: () => messages.push("meeting-2") },+ systemAudioAvailable: true,+ });+ assert.equal(engine.endRecordingSession("meeting-1"), false);+ clock.advance(OWNERSHIP_MIN_ACTIVE_MS);+ micState(true, false);+ clock.advance(2 * COUNTDOWN_MS);++ assert.deepEqual(dismissedCountdowns, ["meeting-1", "meeting-2"]);+ assert.deepEqual(messages, ["meeting-2"]);+ engine.stop();+});++test("an ineligible recording does not retain the audio detector", async () => {+ const { audioActivityDetector, clock, engine, micState, owner, shownCountdowns } = createEngine();++ engine.setPreferences({ audioDetection: false });+ await engine.beginRecordingSession({+ sessionId: "personal-1",+ autoEndEligible: false,+ ownerWebContents: owner(),+ });+ micState(true, false);+ clock.advance(2 * SILENCE_WINDOW_MS);++ assert.equal(audioActivityDetector.running, false);+ assert.deepEqual(shownCountdowns, []);+ assert.equal(engine.endRecordingSession("personal-1"), true);+});++test("keep recording suppresses prompts until fresh ownership evidence, only for the matching session", async () => {+ const { clock, dismissedCountdowns, engine, micState, owner, shownCountdowns } = createEngine();++ await engine.beginRecordingSession({+ sessionId: "meeting-1",+ autoEndEligible: true,+ ownerWebContents: owner(),+ systemAudioAvailable: true,+ });+ clock.advance(OWNERSHIP_MIN_ACTIVE_MS);+ micState(true, false);++ assert.equal(engine.keepRecordingSession("stale-session"), false);+ assert.equal(engine.keepRecordingSession("meeting-1"), true);+ assert.deepEqual(dismissedCountdowns, ["meeting-1"]);+ clock.advance(2 * COUNTDOWN_MS);+ assert.equal(shownCountdowns.length, 1, "no re-prompt without fresh evidence");++ micState(true, true);+ clock.advance(OWNERSHIP_MIN_ACTIVE_MS);+ micState(true, false);+ assert.equal(shownCountdowns.length, 2, "a rejoined-and-left call re-prompts at once");+ assert.equal(shownCountdowns[1].reason, "mic-released");+ engine.stop();+});++test("keep recording after countdown expiry reports a stale session", async () => {+ const { clock, engine, micState, owner } = createEngine();++ await engine.beginRecordingSession({+ sessionId: "meeting-1",+ autoEndEligible: true,+ ownerWebContents: owner(),+ systemAudioAvailable: true,+ });+ clock.advance(OWNERSHIP_MIN_ACTIVE_MS);+ micState(true, false);+ clock.advance(COUNTDOWN_MS);++ assert.equal(engine.keepRecordingSession("meeting-1"), false);+ engine.stop();+});++test("the autoEnd preference disables the feature mid-recording and re-enabling arms a fresh session", async () => {+ const {+ audioActivityDetector,+ clock,+ dismissedCountdowns,+ engine,+ micState,+ owner,+ shownCountdowns,+ } = createEngine();++ await engine.beginRecordingSession({+ sessionId: "meeting-1",+ autoEndEligible: true,+ ownerWebContents: owner(),+ systemAudioAvailable: true,+ });+ clock.advance(OWNERSHIP_MIN_ACTIVE_MS);+ micState(true, false);+ assert.equal(shownCountdowns.length, 1);++ engine.setPreferences({ autoEnd: false });+ assert.deepEqual(dismissedCountdowns, ["meeting-1"]);+ assert.equal(clock.activeIntervals(), 0, "ticker released while disabled");+ clock.advance(2 * COUNTDOWN_MS);+ micState(true, true);+ micState(true, false);+ assert.equal(shownCountdowns.length, 1, "nothing prompts while disabled");++ audioActivityDetector.externalMicState = { reliable: true, externalMicActive: false };+ engine.setPreferences({ autoEnd: true });+ await Promise.resolve();+ clock.advance(SILENCE_WINDOW_MS);+ assert.equal(shownCountdowns.length, 2, "re-enabled → fresh session in fallback mode");+ assert.equal(shownCountdowns[1].reason, "silence");+ engine.stop();+});++test("a session started while autoEnd is off does not arm and does not retain the detectors", async () => {+ const { audioActivityDetector, clock, engine, micState, owner, shownCountdowns } = createEngine();+ engine.setPreferences({ audioDetection: false, processDetection: false, autoEnd: false });++ await engine.beginRecordingSession({+ sessionId: "meeting-1",+ autoEndEligible: true,+ ownerWebContents: owner(),+ systemAudioAvailable: true,+ });+ micState(true, false);+ clock.advance(2 * SILENCE_WINDOW_MS);++ assert.equal(audioActivityDetector.running, false);+ assert.deepEqual(shownCountdowns, []);+ assert.equal(clock.activeIntervals(), 0);+ engine.stop();+});++test("the auto-end ticker is cleared on session end and engine stop", async () => {+ const { clock, engine, owner } = createEngine();++ await engine.beginRecordingSession({+ sessionId: "meeting-1",+ autoEndEligible: true,+ ownerWebContents: owner(),+ systemAudioAvailable: true,+ });+ assert.equal(clock.activeIntervals(), 1);+ engine.endRecordingSession("meeting-1");+ assert.equal(clock.activeIntervals(), 0);++ await engine.beginRecordingSession({+ sessionId: "meeting-2",+ autoEndEligible: true,+ ownerWebContents: owner(),+ systemAudioAvailable: true,+ });+ assert.equal(clock.activeIntervals(), 1);+ engine.stop();+ assert.equal(clock.activeIntervals(), 0);+});++test("ending with no tracked session allows teardown to proceed", async () => {+ const { engine, owner } = createEngine();++ await engine.beginRecordingSession({+ sessionId: "meeting-1",+ autoEndEligible: true,+ ownerWebContents: owner(),+ systemAudioAvailable: true,+ });+ // Quit-path engine stop clears the session while capture may still be live;+ // a scoped stop afterwards must not be treated as stale or streams leak.+ engine.stop();++ assert.equal(engine.endRecordingSession("meeting-1"), true);+});++// The user-recording flag is shared with dictation, so a dictation ending+// mid-meeting clears it while the recording is still live. Without the engine's+// own session as a gate, the next detection would bypass the queue and its+// prompt would replace a visible auto-end countdown card — the countdown then+// runs on invisibly and stops the recording without a chance to keep it.+const POST_RECORDING_COOLDOWN_MS = 2500;++const nextMeetingReminder = (clock) => ({+ id: "next",+ summary: "Next meeting",+ start_time: new Date(clock.now() + 60_000).toISOString(),+});++test("a detection during a live recording session is queued even after the user-recording flag is cleared", async (t) => {+ t.mock.timers.enable({ apis: ["setTimeout"] });+ const { clock, engine, owner, shownNotifications } = createEngine();+ engine.setUserRecording(true);+ await engine.beginRecordingSession({+ sessionId: "meeting-1",+ autoEndEligible: true,+ ownerWebContents: owner(),+ systemAudioAvailable: true,+ });++ // A dictation ended mid-meeting: the shared flag clears and its cooldown runs out.+ engine.setUserRecording(false);+ t.mock.timers.tick(POST_RECORDING_COOLDOWN_MS);++ engine.handleCalendarReminder(nextMeetingReminder(clock));+ assert.equal(shownNotifications.length, 0, "no prompt may surface while the recording is live");++ // The recording ends the way ipcHandlers ends it; the held prompt surfaces then.+ engine.endRecordingSession("meeting-1");+ engine.setUserRecording(false);+ t.mock.timers.tick(POST_RECORDING_COOLDOWN_MS);+ assert.equal(shownNotifications.length, 1);+ assert.equal(shownNotifications[0].detectionId, "calendar:next");+ engine.stop();+});++test("a post-dictation queue flush holds queued detections while the recording session is live", async (t) => {+ t.mock.timers.enable({ apis: ["setTimeout"] });+ const { clock, engine, owner, shownNotifications } = createEngine();+ engine.setUserRecording(true);+ await engine.beginRecordingSession({+ sessionId: "meeting-1",+ autoEndEligible: true,+ ownerWebContents: owner(),+ systemAudioAvailable: true,+ });++ engine.handleCalendarReminder(nextMeetingReminder(clock));+ assert.equal(shownNotifications.length, 0, "queued behind the user-recording gate");++ engine.setUserRecording(false);+ t.mock.timers.tick(POST_RECORDING_COOLDOWN_MS);+ assert.equal(shownNotifications.length, 0, "the flush must not surface it mid-recording");++ engine.endRecordingSession("meeting-1");+ engine.setUserRecording(false);+ t.mock.timers.tick(POST_RECORDING_COOLDOWN_MS);+ assert.equal(shownNotifications.length, 1);+ engine.stop();+});++// "Take notes" / the meeting hotkey / calendar Join set meeting mode when they+// create the note, and until now only the narrow layout's "Back to notes"+// button ever cleared it. In the wide layout that left every later mic,+// process, and calendar detection suppressed for the rest of the app session.+test("a detection-started recording re-enables prompts once its session ends", async (t) => {+ t.mock.timers.enable({ apis: ["setTimeout"] });+ const { audioActivityDetector, clock, engine, owner, shownNotifications } = createEngine();+ engine.setMeetingModeActive(true);+ engine.setUserRecording(true);+ await engine.beginRecordingSession({+ sessionId: "meeting-1",+ autoEndEligible: true,+ ownerWebContents: owner(),+ systemAudioAvailable: true,+ });++ engine.endRecordingSession("meeting-1");+ engine.setUserRecording(false);+ t.mock.timers.tick(POST_RECORDING_COOLDOWN_MS);++ audioActivityDetector.emit("sustained-audio-detected", {+ durationMs: 2000,+ detectedAt: clock.now(),+ });+ assert.equal(shownNotifications.length, 1, "the next call must prompt again");+ assert.equal(shownNotifications[0].detectionId, "audio:sustained-audio");+ engine.stop();+});++test("the next meeting's reminder prompts after a detection-started recording ends", async (t) => {+ t.mock.timers.enable({ apis: ["setTimeout"] });+ const { clock, engine, owner, shownNotifications } = createEngine();+ engine.setMeetingModeActive(true);+ engine.setUserRecording(true);+ await engine.beginRecordingSession({+ sessionId: "meeting-1",+ autoEndEligible: true,+ ownerWebContents: owner(),+ systemAudioAvailable: true,+ });++ engine.endRecordingSession("meeting-1");+ engine.setUserRecording(false);+ t.mock.timers.tick(POST_RECORDING_COOLDOWN_MS);++ engine.handleCalendarReminder(nextMeetingReminder(clock));+ assert.equal(shownNotifications.length, 1, "no longer suppressed as meeting-mode noise");+ assert.equal(shownNotifications[0].detectionId, "calendar:next");+ engine.stop();+});++test("meeting mode still suppresses prompts while the detection-started recording is live", async (t) => {+ t.mock.timers.enable({ apis: ["setTimeout"] });+ const { audioActivityDetector, clock, engine, owner, shownNotifications } = createEngine();+ engine.setMeetingModeActive(true);+ engine.setUserRecording(true);+ await engine.beginRecordingSession({+ sessionId: "meeting-1",+ autoEndEligible: true,+ ownerWebContents: owner(),+ systemAudioAvailable: true,+ });++ engine.setUserRecording(false);+ t.mock.timers.tick(POST_RECORDING_COOLDOWN_MS);+ audioActivityDetector.emit("sustained-audio-detected", {+ durationMs: 2000,+ detectedAt: clock.now(),+ });++ assert.equal(shownNotifications.length, 0);+ engine.stop();+});diff --git a/test/helpers/meetingNotificationModel.test.js b/test/helpers/meetingNotificationModel.test.jsnew file mode 100644index 000000000..aafa864ea--- /dev/null+++ b/test/helpers/meetingNotificationModel.test.js@@ -0,0 +1,155 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const load = () => import("../../src/components/meetingNotificationModel.ts");++test("auto-end presentation has countdown copy, Keep action, and no dismissal", async () => {+ const { getMeetingNotificationPresentation } = await load();++ assert.deepEqual(+ getMeetingNotificationPresentation(+ { kind: "auto-end", sessionId: "meeting-2", expiresAt: 40_001, reason: "mic-released" },+ 30+ ),+ {+ titleKey: "meetingNotification.autoEnd.title",+ bodyKey: "meetingNotification.autoEnd.body.micReleased",+ bodyValues: { seconds: 30 },+ actionKey: "meetingNotification.autoEnd.keep",+ action: "keep",+ dismissible: false,+ allowTitleWrap: true,+ }+ );+});++test("auto-end presentation picks body copy by reason and defaults to mic-released", async () => {+ const { getMeetingNotificationPresentation } = await load();+ const bodyFor = (reason) =>+ getMeetingNotificationPresentation(+ { kind: "auto-end", sessionId: "meeting-2", expiresAt: 40_001, reason },+ 5+ ).bodyKey;++ assert.equal(bodyFor("silence"), "meetingNotification.autoEnd.body.silence");+ assert.equal(bodyFor("process-exit"), "meetingNotification.autoEnd.body.processExit");+ assert.equal(bodyFor(undefined), "meetingNotification.autoEnd.body.micReleased");+ assert.equal(bodyFor("unknown-reason"), "meetingNotification.autoEnd.body.micReleased");+});++test("detection presentation preserves event title, join action, and dismissal", async () => {+ const { getMeetingNotificationPresentation } = await load();++ assert.deepEqual(+ getMeetingNotificationPresentation(+ {+ kind: "detection",+ detectionId: "calendar:event-1",+ source: "calendar",+ key: "event-1",+ event: { summary: "Weekly planning" },+ variant: "starting",+ joinUrl: "https://meet.example/event-1",+ },+ 0+ ),+ {+ title: "Weekly planning",+ bodyKey: "meetingNotification.body.starting",+ actionKey: "meetingNotification.join",+ action: "join",+ dismissible: true,+ allowTitleWrap: false,+ }+ );+});++test("countdown rounds up and emits updated seconds until expiration", async () => {+ const { subscribeMeetingAutoEndCountdown } = await load();+ let now = 10_000;+ let tick;+ let clearedTimer;+ const seconds = [];++ const unsubscribe = subscribeMeetingAutoEndCountdown(+ 12_001,+ (nextSeconds) => {+ seconds.push(nextSeconds);+ },+ {+ now: () => now,+ setInterval: (callback, delay) => {+ assert.equal(delay, 250);+ tick = callback;+ return 7;+ },+ clearInterval: (timer) => {+ clearedTimer = timer;+ },+ }+ );++ now = 10_002;+ tick();+ now = 11_002;+ tick();+ now = 12_001;+ tick();+ unsubscribe();++ assert.deepEqual(seconds, [3, 2, 1, 0]);+ assert.equal(clearedTimer, 7);+});++test("overlay initialization cleanup cancels reveal and invalidates a pending pull", async () => {+ const { initializeMeetingNotificationOverlay } = await load();+ let subscribed;+ let reveal;+ let canceledTimer;+ let resolvePendingData;+ const pendingData = new Promise((resolve) => {+ resolvePendingData = resolve;+ });+ const received = [];+ let readyCount = 0;+ let visibleCount = 0;+ let unsubscribeCount = 0;++ const cleanup = initializeMeetingNotificationOverlay({+ subscribe: (callback) => {+ subscribed = callback;+ return () => {+ unsubscribeCount += 1;+ };+ },+ getPendingData: () => pendingData,+ onData: (data) => received.push(data),+ onVisible: () => {+ visibleCount += 1;+ },+ onReady: () => {+ readyCount += 1;+ },+ setTimeout: (callback, delay) => {+ assert.equal(delay, 50);+ reveal = callback;+ return 11;+ },+ clearTimeout: (timer) => {+ canceledTimer = timer;+ },+ });++ subscribed({ kind: "auto-end", sessionId: "meeting-1", expiresAt: 70_000 });+ cleanup();+ reveal();+ resolvePendingData({ kind: "auto-end", sessionId: "meeting-2", expiresAt: 80_000 });+ await pendingData;+ await Promise.resolve();++ assert.deepEqual(received, [{ kind: "auto-end", sessionId: "meeting-1", expiresAt: 70_000 }]);+ assert.equal(canceledTimer, 11);+ assert.equal(visibleCount, 0);+ assert.equal(readyCount, 0);+ assert.equal(unsubscribeCount, 1);+});diff --git a/test/helpers/meetingRecordingSession.test.js b/test/helpers/meetingRecordingSession.test.jsnew file mode 100644index 000000000..89766c945--- /dev/null+++ b/test/helpers/meetingRecordingSession.test.js@@ -0,0 +1,329 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const load = () => import("../../src/helpers/meetingRecordingSession.ts");++function createDeferred() {+ let resolve;+ let reject;+ const promise = new Promise((resolvePromise, rejectPromise) => {+ resolve = resolvePromise;+ reject = rejectPromise;+ });+ return { promise, reject, resolve };+}++test("creates one opaque session ID for a recording start", async () => {+ const { createMeetingRecordingSessionId } = await load();+ let calls = 0;++ const sessionId = createMeetingRecordingSessionId(() => {+ calls += 1;+ return "recording-session-1";+ });++ assert.equal(sessionId, "recording-session-1");+ assert.equal(calls, 1);+});++test("accepts legacy stops but rejects an expected ID for another active session", async () => {+ const { canStopMeetingRecordingSession } = await load();++ assert.equal(canStopMeetingRecordingSession("meeting-2"), true);+ assert.equal(canStopMeetingRecordingSession("meeting-2", "meeting-2"), true);+ assert.equal(canStopMeetingRecordingSession("meeting-2", "meeting-1"), false);+ assert.equal(canStopMeetingRecordingSession(null, "meeting-1"), false);+});++test("auto-end stop requests forward only a valid expected session ID", async () => {+ const { requestMeetingRecordingAutoEnd } = await load();+ const requestedSessions = [];+ const errors = [];+ const stopRecording = async (sessionId) => {+ requestedSessions.push(sessionId);+ };+ const onError = (error, sessionId) => errors.push({ error, sessionId });++ assert.equal(+ requestMeetingRecordingAutoEnd({ sessionId: "meeting-2" }, stopRecording, onError),+ true+ );+ assert.equal(requestMeetingRecordingAutoEnd({ sessionId: "" }, stopRecording, onError), false);+ assert.equal(requestMeetingRecordingAutoEnd(null, stopRecording, onError), false);+ await Promise.resolve();++ assert.deepEqual(requestedSessions, ["meeting-2"]);+ assert.deepEqual(errors, []);+});++test("a rejected auto-end stop is reported instead of swallowed", async () => {+ const { requestMeetingRecordingAutoEnd } = await load();+ const errors = [];+ const stopFailure = new Error("stop failed");+ const stopRecording = async () => {+ throw stopFailure;+ };++ assert.equal(+ requestMeetingRecordingAutoEnd({ sessionId: "meeting-2" }, stopRecording, (error, sessionId) =>+ errors.push({ error, sessionId })+ ),+ true+ );+ await Promise.resolve();+ await Promise.resolve();++ assert.deepEqual(errors, [{ error: stopFailure, sessionId: "meeting-2" }]);+});++test("only meeting notes are eligible for automatic ending", async () => {+ const { isMeetingAutoEndEligible } = await load();++ assert.equal(isMeetingAutoEndEligible({ note_type: "meeting" }), true);+ assert.equal(isMeetingAutoEndEligible({ note_type: "personal" }), false);+ assert.equal(isMeetingAutoEndEligible({ note_type: "upload" }), false);+ assert.equal(isMeetingAutoEndEligible(null), false);+});++test("a new renderer start waits for the accepted stop to finish", async () => {+ const { createMeetingRecordingStopBarrier } = await load();+ let finishStop;+ const stopDeferred = new Promise((resolve) => {+ finishStop = resolve;+ });+ const barrier = createMeetingRecordingStopBarrier();+ let nextStartBegan = false;++ const stopPromise = barrier.runStop(() => stopDeferred);+ const nextStartPromise = barrier.waitForPendingStop().then(() => {+ nextStartBegan = true;+ });+ await Promise.resolve();++ assert.equal(nextStartBegan, false);++ finishStop("stopped");+ assert.equal(await stopPromise, "stopped");+ await nextStartPromise;+ assert.equal(nextStartBegan, true);+});++test("renderer setup failure teardown blocks retry and deduplicates concurrent stop cleanup", async () => {+ const { createMeetingRecordingStopBarrier, teardownFailedMeetingRecordingSetup } = await load();+ let finishMainStop;+ const mainStopDeferred = new Promise((resolve) => {+ finishMainStop = resolve;+ });+ let markMainStopBegan;+ const mainStopBegan = new Promise((resolve) => {+ markMainStopBegan = resolve;+ });+ const barrier = createMeetingRecordingStopBarrier();+ const events = [];+ let activeSessionId = "meeting-1";+ let retryCaptureCount = 0;++ const setupFailurePromise = teardownFailedMeetingRecordingSetup({+ stopBarrier: barrier,+ cleanup: async () => {+ events.push("cleanup");+ },+ stopMain: async () => {+ events.push("main-stop");+ markMainStopBegan();+ await mainStopDeferred;+ },+ releaseSession: () => {+ activeSessionId = null;+ events.push("release-session");+ },+ });+ const retryPromise = barrier.waitForPendingStop().then(() => {+ assert.equal(activeSessionId, null);+ retryCaptureCount += 1;+ events.push("retry-capture");+ });+ const concurrentStopPromise = barrier.runStop(async () => {+ events.push("duplicate-cleanup");+ });+ await mainStopBegan;++ assert.deepEqual(events, ["cleanup", "main-stop"]);+ assert.equal(retryCaptureCount, 0);++ finishMainStop();+ await Promise.all([setupFailurePromise, retryPromise, concurrentStopPromise]);++ assert.deepEqual(events, ["cleanup", "main-stop", "release-session", "retry-capture"]);+ assert.equal(retryCaptureCount, 1);+});++test("same-turn stop cancels an admitted start before its first continuation", async () => {+ const { createMeetingRecordingStartCoordinator } = await load();+ const coordinator = createMeetingRecordingStartCoordinator();+ const events = [];++ const firstStart = coordinator.runStart("meeting-1", async (operation) => {+ events.push(operation.isCurrent() ? "capture:meeting-1" : "canceled:meeting-1");+ });+ const canceledStart = coordinator.cancelActiveStart("meeting-1");+ const replacementStart = coordinator.runStart("meeting-2", async () => {+ events.push("capture:meeting-2");+ });++ assert.notEqual(canceledStart, null);+ await Promise.all([firstStart, canceledStart, replacementStart]);++ assert.deepEqual(events, ["canceled:meeting-1", "capture:meeting-2"]);+});++test("a committed renderer start is no longer cancelable", async () => {+ const { createMeetingRecordingStartCoordinator } = await load();+ const committed = createDeferred();+ const finishStart = createDeferred();+ const coordinator = createMeetingRecordingStartCoordinator();++ const startPromise = coordinator.runStart("meeting-1", async (operation) => {+ operation.markCommitted();+ committed.resolve();+ await finishStart.promise;+ });+ await committed.promise;++ assert.equal(coordinator.cancelActiveStart("meeting-1"), null);++ finishStart.resolve();+ await startPromise;+});++test("stop during deferred preparation cancels the old start before admitting replacement", async () => {+ const { createMeetingRecordingStartCoordinator } = await load();+ const preparation = createDeferred();+ const firstStartBegan = createDeferred();+ const coordinator = createMeetingRecordingStartCoordinator();+ const events = [];++ const firstStart = coordinator.runStart("meeting-1", async (operation) => {+ events.push("prepare:meeting-1");+ firstStartBegan.resolve();+ await preparation.promise;+ events.push(operation.isCurrent() ? "capture:meeting-1" : "canceled:meeting-1");+ });+ await firstStartBegan.promise;+ const canceledStart = coordinator.cancelActiveStart("meeting-1");+ const replacementStart = coordinator.runStart("meeting-2", async () => {+ events.push("capture:meeting-2");+ });+ await Promise.resolve();++ assert.deepEqual(events, ["prepare:meeting-1"]);++ preparation.resolve();+ await Promise.all([firstStart, canceledStart, replacementStart]);++ assert.deepEqual(events, ["prepare:meeting-1", "canceled:meeting-1", "capture:meeting-2"]);+});++test("system-audio rejection settles a canceled start before replacement", async () => {+ const { createMeetingRecordingStartCoordinator } = await load();+ const systemAudio = createDeferred();+ const systemAudioBegan = createDeferred();+ const coordinator = createMeetingRecordingStartCoordinator();+ const events = [];++ const firstStart = coordinator.runStart("meeting-1", async () => {+ events.push("system-audio:meeting-1");+ systemAudioBegan.resolve();+ await systemAudio.promise;+ });+ const firstStartRejection = assert.rejects(firstStart, /system audio denied/);+ await systemAudioBegan.promise;+ const canceledStart = coordinator.cancelActiveStart("meeting-1");+ const replacementStart = coordinator.runStart("meeting-2", async () => {+ events.push("capture:meeting-2");+ });++ systemAudio.reject(new Error("system audio denied"));+ await Promise.all([firstStartRejection, canceledStart, replacementStart]);++ assert.deepEqual(events, ["system-audio:meeting-1", "capture:meeting-2"]);+});++test("cancellation after deferred main start stops the old session once before replacement", async () => {+ const { createMeetingRecordingStartCoordinator } = await load();+ const mainStart = createDeferred();+ const mainStartBegan = createDeferred();+ const coordinator = createMeetingRecordingStartCoordinator();+ const events = [];+ let scopedStopCount = 0;++ const firstStart = coordinator.runStart("meeting-1", async (operation) => {+ operation.markMainStartAttempted();+ events.push("main-start:meeting-1");+ mainStartBegan.resolve();+ await mainStart.promise;+ if (!operation.isCurrent()) {+ const stopMain = async () => {+ scopedStopCount += 1;+ events.push("main-stop:meeting-1");+ };+ await Promise.all([operation.stopMainOnce(stopMain), operation.stopMainOnce(stopMain)]);+ events.push("canceled:meeting-1");+ }+ });+ await mainStartBegan.promise;+ const canceledStart = coordinator.cancelActiveStart("meeting-1");+ const replacementStart = coordinator.runStart("meeting-2", async () => {+ events.push("capture:meeting-2");+ });+ await Promise.resolve();++ assert.deepEqual(events, ["main-start:meeting-1"]);++ mainStart.resolve({ success: true });+ await Promise.all([firstStart, canceledStart, replacementStart]);++ assert.equal(scopedStopCount, 1);+ assert.deepEqual(events, [+ "main-start:meeting-1",+ "main-stop:meeting-1",+ "canceled:meeting-1",+ "capture:meeting-2",+ ]);+});++test("main-start rejection releases cancellation and replacement after one scoped stop", async () => {+ const { createMeetingRecordingStartCoordinator } = await load();+ const mainStart = createDeferred();+ const mainStartBegan = createDeferred();+ const coordinator = createMeetingRecordingStartCoordinator();+ const events = [];+ let scopedStopCount = 0;++ const firstStart = coordinator.runStart("meeting-1", async (operation) => {+ operation.markMainStartAttempted();+ events.push("main-start:meeting-1");+ mainStartBegan.resolve();+ try {+ await mainStart.promise;+ } catch (error) {+ await operation.stopMainOnce(async () => {+ scopedStopCount += 1;+ events.push("main-stop:meeting-1");+ });+ throw error;+ }+ });+ const firstStartRejection = assert.rejects(firstStart, /main start failed/);+ await mainStartBegan.promise;+ const canceledStart = coordinator.cancelActiveStart("meeting-1");+ const replacementStart = coordinator.runStart("meeting-2", async () => {+ events.push("capture:meeting-2");+ });++ mainStart.reject(new Error("main start failed"));+ await Promise.all([firstStartRejection, canceledStart, replacementStart]);++ assert.equal(scopedStopCount, 1);+ assert.deepEqual(events, ["main-start:meeting-1", "main-stop:meeting-1", "capture:meeting-2"]);+});diff --git a/test/helpers/meetingTranscriptPersistence.test.js b/test/helpers/meetingTranscriptPersistence.test.jsnew file mode 100644index 000000000..51d66b98f--- /dev/null+++ b/test/helpers/meetingTranscriptPersistence.test.js@@ -0,0 +1,106 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const load = () => import("../../src/helpers/meetingTranscriptPersistence.ts");++const segment = (id, text) => ({ id, text, source: "system" });+const serialize = (segments) => segments.map((s) => s.text).join("|");++// The note editor swaps from live segments to the stored transcript the moment+// isRecording flips, while the main-side stop can take seconds — so the+// captured segments must be written before that stop is awaited, or the tail+// since the last periodic save visibly disappears until the stop returns.+test("captured segments are written before the stop is awaited", async () => {+ const { persistFinalTranscriptAroundStop } = await load();+ const events = [];++ const result = await persistFinalTranscriptAroundStop({+ segments: [segment("a", "hello"), segment("b", "world")],+ serializeSegments: serialize,+ persist: async (transcript) => {+ events.push(`persist:${transcript}`);+ },+ stop: async () => {+ events.push("stop");+ return { diarizationSessionId: "diar-1" };+ },+ fallbackTranscript: () => {+ throw new Error("main's transcript must not be consulted when segments exist");+ },+ });++ assert.deepEqual(events, ["persist:hello|world", "stop"]);+ assert.deepEqual(result, { diarizationSessionId: "diar-1" });+});++test("a segment-less recording writes main's final transcript after the stop", async () => {+ const { persistFinalTranscriptAroundStop } = await load();+ const events = [];+ let stopped = false;++ await persistFinalTranscriptAroundStop({+ segments: [],+ serializeSegments: () => {+ throw new Error("must not serialize an empty segment list");+ },+ persist: async (transcript) => {+ events.push(`persist:${transcript}`);+ },+ stop: async () => {+ stopped = true;+ events.push("stop");+ return null;+ },+ // Only available once main has flushed its final text.+ fallbackTranscript: () => (stopped ? "main text" : ""),+ });++ assert.deepEqual(events, ["stop", "persist:main text"]);+});++test("nothing is written when there are neither segments nor a fallback transcript", async () => {+ const { persistFinalTranscriptAroundStop } = await load();+ let persisted = 0;++ await persistFinalTranscriptAroundStop({+ segments: [],+ serializeSegments: serialize,+ persist: async () => {+ persisted += 1;+ },+ stop: async () => null,+ fallbackTranscript: () => "",+ });++ assert.equal(persisted, 0);+});++test("the stop result is only returned once the early write has settled", async () => {+ const { persistFinalTranscriptAroundStop } = await load();+ let releaseWrite;+ const write = new Promise((resolve) => {+ releaseWrite = resolve;+ });+ let settled = false;++ const pending = persistFinalTranscriptAroundStop({+ segments: [segment("a", "hello")],+ serializeSegments: serialize,+ persist: () => write,+ stop: async () => "stopped",+ fallbackTranscript: () => "",+ }).then((value) => {+ settled = true;+ return value;+ });++ await new Promise((resolve) => setImmediate(resolve));+ assert.equal(+ settled,+ false,+ "the caller must not proceed while the transcript write is in flight"+ );++ releaseWrite();+ assert.equal(await pending, "stopped");+});diff --git a/test/helpers/meetingTranscriptionLifecycle.test.js b/test/helpers/meetingTranscriptionLifecycle.test.jsnew file mode 100644index 000000000..6890d59a9--- /dev/null+++ b/test/helpers/meetingTranscriptionLifecycle.test.js@@ -0,0 +1,189 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const { EventEmitter } = require("node:events");++const createMeetingTranscriptionLifecycle = require("../../src/helpers/meetingTranscriptionLifecycle");++function createDeferred() {+ let resolve;+ const promise = new Promise((resolvePromise) => {+ resolve = resolvePromise;+ });+ return { promise, resolve };+}++function createOwnerWebContents() {+ const ownerWebContents = new EventEmitter();+ ownerWebContents.isDestroyed = () => false;+ return ownerWebContents;+}++test("a stop requested during startup waits for startup and tears down that session", async () => {+ const startDeferred = createDeferred();+ const events = [];+ let captureActive = false;+ const lifecycle = createMeetingTranscriptionLifecycle({+ start: async ({ sessionId }) => {+ events.push(`start:${sessionId}:begin`);+ captureActive = true;+ await startDeferred.promise;+ events.push(`start:${sessionId}:end`);+ return { success: true, sessionId };+ },+ stop: async (sessionId) => {+ events.push(`stop:${sessionId}`);+ captureActive = false;+ return { success: true };+ },+ });++ const startPromise = lifecycle.startSession({+ sessionId: "meeting-1",+ ownerWebContents: createOwnerWebContents(),+ options: {},+ });+ await Promise.resolve();+ const stopPromise = lifecycle.stopSession("meeting-1");++ assert.equal(captureActive, true);+ assert.deepEqual(events, ["start:meeting-1:begin"]);++ startDeferred.resolve();+ assert.equal((await startPromise).success, true);+ assert.equal((await stopPromise).success, true);++ assert.equal(captureActive, false);+ assert.deepEqual(events, ["start:meeting-1:begin", "start:meeting-1:end", "stop:meeting-1"]);+});++test("owner loss during startup tears down after the deferred start settles", async () => {+ const startDeferred = createDeferred();+ const stopCompleted = createDeferred();+ const ownerWebContents = createOwnerWebContents();+ let captureActive = false;+ let countdownVisible = false;+ const lifecycle = createMeetingTranscriptionLifecycle({+ start: async ({ sessionId }) => {+ captureActive = true;+ countdownVisible = true;+ await startDeferred.promise;+ return { success: true, sessionId };+ },+ stop: async () => {+ captureActive = false;+ countdownVisible = false;+ stopCompleted.resolve();+ return { success: true };+ },+ });++ const startPromise = lifecycle.startSession({+ sessionId: "meeting-1",+ ownerWebContents,+ options: {},+ });+ await Promise.resolve();+ ownerWebContents.emit("destroyed");+ startDeferred.resolve();++ await startPromise;+ await stopCompleted.promise;+ await Promise.resolve();++ assert.equal(captureActive, false);+ assert.equal(countdownVisible, false);+ assert.equal(ownerWebContents.listenerCount("destroyed"), 0);+ assert.equal(ownerWebContents.listenerCount("render-process-gone"), 0);+});++for (const ownerLossEvent of ["destroyed", "render-process-gone"]) {+ test(`${ownerLossEvent} tears down an active session without renderer cooperation`, async () => {+ const stopCompleted = createDeferred();+ const ownerWebContents = createOwnerWebContents();+ let captureActive = false;+ let countdownVisible = false;+ const lifecycle = createMeetingTranscriptionLifecycle({+ start: async ({ sessionId }) => {+ captureActive = true;+ countdownVisible = true;+ return { success: true, sessionId };+ },+ stop: async () => {+ captureActive = false;+ countdownVisible = false;+ stopCompleted.resolve();+ return { success: true };+ },+ });++ await lifecycle.startSession({+ sessionId: "meeting-1",+ ownerWebContents,+ options: {},+ });+ ownerWebContents.emit(ownerLossEvent, {}, { reason: "crashed" });+ await stopCompleted.promise;+ await Promise.resolve();++ assert.equal(captureActive, false);+ assert.equal(countdownVisible, false);+ assert.equal(ownerWebContents.listenerCount("destroyed"), 0);+ assert.equal(ownerWebContents.listenerCount("render-process-gone"), 0);+ });+}++test("a replacement start waits for a deferred accepted stop to finish", async () => {+ const stopDeferred = createDeferred();+ const oldOwner = createOwnerWebContents();+ const newOwner = createOwnerWebContents();+ const starts = [];+ const stops = [];+ let activeCaptureSessionId = null;+ const lifecycle = createMeetingTranscriptionLifecycle({+ start: async ({ sessionId }) => {+ starts.push(sessionId);+ activeCaptureSessionId = sessionId;+ return { success: true, sessionId };+ },+ stop: async (sessionId) => {+ stops.push(sessionId);+ await stopDeferred.promise;+ activeCaptureSessionId = null;+ return { success: true };+ },+ });++ await lifecycle.startSession({+ sessionId: "meeting-1",+ ownerWebContents: oldOwner,+ options: {},+ });+ const stopPromise = lifecycle.stopSession("meeting-1");+ await Promise.resolve();+ const replacementPromise = lifecycle.startSession({+ sessionId: "meeting-2",+ ownerWebContents: newOwner,+ options: {},+ });+ await Promise.resolve();++ assert.deepEqual(starts, ["meeting-1"]);+ assert.deepEqual(stops, ["meeting-1"]);+ assert.equal(activeCaptureSessionId, "meeting-1");++ stopDeferred.resolve();+ await stopPromise;+ assert.equal((await replacementPromise).success, true);++ assert.deepEqual(starts, ["meeting-1", "meeting-2"]);+ assert.equal(activeCaptureSessionId, "meeting-2");+ assert.equal(oldOwner.listenerCount("destroyed"), 0);+ assert.equal(oldOwner.listenerCount("render-process-gone"), 0);+ assert.equal(newOwner.listenerCount("destroyed"), 1);+ assert.equal(newOwner.listenerCount("render-process-gone"), 1);++ oldOwner.emit("destroyed");+ await Promise.resolve();+ assert.deepEqual(stops, ["meeting-1"]);+ assert.equal(activeCaptureSessionId, "meeting-2");+});diff --git a/test/helpers/preloadAuthBridge.test.js b/test/helpers/preloadAuthBridge.test.jsindex d6aa04aee..370c8aeb8 100644--- a/test/helpers/preloadAuthBridge.test.js+++ b/test/helpers/preloadAuthBridge.test.js@@ -7,8 +7,12 @@ const vm = require("node:vm");function loadPreloadApi() {let exposedApi;const listeners = new Map();+ const invocations = [];const ipcRenderer = {- invoke: async () => undefined,+ invoke: async (...args) => {+ invocations.push(args);+ return undefined;+ },on: (channel, listener) => listeners.set(channel, listener),removeListener: (channel, listener) => {if (listeners.get(channel) === listener) listeners.delete(channel);@@ -33,7 +37,7 @@ function loadPreloadApi() {},process,});- return { api: exposedApi, listeners };+ return { api: exposedApi, invocations, listeners };}test("auth token-state listener strips the Electron event object", () => {@@ -50,3 +54,44 @@ test("auth token-state listener strips the Electron event object", () => {unsubscribe();assert.equal(listeners.has("auth-token-state-changed"), false);});++test("meeting stop forwards the optional expected recording session ID", async () => {+ const { api, invocations } = loadPreloadApi();++ await api.meetingTranscriptionStop("meeting-2");++ assert.deepEqual(invocations, [["meeting-transcription-stop", "meeting-2"]]);+});++test("meeting system-audio availability forwards the scoped session", async () => {+ const { api, invocations } = loadPreloadApi();++ await api.meetingTranscriptionSetSystemAudioAvailable("meeting-2", true);++ assert.deepEqual(invocations, [+ ["meeting-transcription-set-system-audio-available", "meeting-2", true],+ ]);+});++test("meeting auto-end listener strips the event and can unsubscribe", () => {+ const { api, listeners } = loadPreloadApi();+ const payload = { sessionId: "meeting-2" };+ let received;+ const unsubscribe = api.onMeetingAutoEndRequested((request) => {+ received = request;+ });++ listeners.get("meeting-auto-end-requested")?.({ sender: "ipc" }, payload);++ assert.equal(received, payload);+ unsubscribe();+ assert.equal(listeners.has("meeting-auto-end-requested"), false);+});++test("meeting auto-end keep forwards the recording session ID", async () => {+ const { api, invocations } = loadPreloadApi();++ await api.meetingAutoEndKeep("meeting-2");++ assert.deepEqual(invocations, [["meeting-auto-end-keep", "meeting-2"]]);+});diff --git a/test/helpers/windowConfigMeetingNotification.test.js b/test/helpers/windowConfigMeetingNotification.test.jsnew file mode 100644index 000000000..cb2ee9966--- /dev/null+++ b/test/helpers/windowConfigMeetingNotification.test.js@@ -0,0 +1,69 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const {+ AUTO_END_NOTIFICATION_WINDOW_SIZE,+ NOTIFICATION_WINDOW_CONFIG,+ WindowPositionUtil,+ getMeetingNotificationWindowSize,+} = require("../../src/helpers/windowConfig");++test("meeting notifications accept the first macOS click with Electron's documented option", () => {+ assert.equal(NOTIFICATION_WINDOW_CONFIG.acceptFirstMouse, true);+ assert.equal(Object.hasOwn(NOTIFICATION_WINDOW_CONFIG, "acceptsFirstMouse"), false);+});++test("auto-end uses a larger positioned window while detection keeps its existing size", () => {+ const detectionSize = getMeetingNotificationWindowSize({ kind: "detection" });+ const autoEndSize = getMeetingNotificationWindowSize({ kind: "auto-end" });+ const display = { workArea: { x: 100, y: 50, width: 1400, height: 900 } };++ assert.deepEqual(detectionSize, { width: 392, height: 92 });+ assert.deepEqual(autoEndSize, AUTO_END_NOTIFICATION_WINDOW_SIZE);+ assert.ok(autoEndSize.width >= 620);+ assert.ok(autoEndSize.height >= 116);+ assert.deepEqual(WindowPositionUtil.getNotificationPosition(display, autoEndSize), {+ x: 864,+ y: 66,+ width: autoEndSize.width,+ height: autoEndSize.height,+ });+});++test("auto-end dimensions fit every supported localized title, body, and action", () => {+ const locales = ["en", "es", "fr", "de", "pt", "it", "ru", "ja", "zh-CN", "zh-TW"];+ const translations = locales.map(+ (locale) => require(`../../src/locales/${locale}/translation.json`).meetingNotification.autoEnd+ );+ const displayColumns = (value) =>+ [...value].reduce(+ (columns, character) =>+ columns ++ (/\p{Script=Han}|\p{Script=Hiragana}|\p{Script=Katakana}/u.test(character) ? 2 : 1),+ 0+ );+ const longestActionColumns = Math.max(...translations.map(({ keep }) => displayColumns(keep)));++ // Reserve the card's outer padding, icon/gaps, and the full non-wrapping action.+ const actionWidth = longestActionColumns * 6 + 20;+ const textWidth = AUTO_END_NOTIFICATION_WINDOW_SIZE.width - 24 - 20 - 26 - 20 - actionWidth;+ const columnsPerLine = Math.floor(textWidth / 6);+ // Every reason-specific body must fit, not just the longest per locale.+ const worstCase = translations.flatMap(({ title, body }, index) =>+ Object.entries(body).map(([reason, text]) => ({+ locale: locales[index],+ reason,+ lines:+ Math.ceil(displayColumns(title) / columnsPerLine) ++ Math.ceil(displayColumns(text) / columnsPerLine),+ }))+ );+ const maximumTextLines = Math.max(...worstCase.map(({ lines }) => lines));+ const requiredHeight = 24 + 20 + maximumTextLines * 14;++ assert.ok(columnsPerLine > 0);+ assert.ok(+ requiredHeight <= AUTO_END_NOTIFICATION_WINDOW_SIZE.height,+ `overflow: ${JSON.stringify(worstCase.filter(({ lines }) => lines === maximumTextLines))}`+ );+});diff --git a/test/helpers/windowManagerMeetingNotification.test.js b/test/helpers/windowManagerMeetingNotification.test.jsnew file mode 100644index 000000000..aa734ab15--- /dev/null+++ b/test/helpers/windowManagerMeetingNotification.test.js@@ -0,0 +1,355 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const { EventEmitter } = require("node:events");+const Module = require("node:module");++function createDeferred() {+ let resolve;+ let reject;+ const promise = new Promise((resolvePromise, rejectPromise) => {+ resolve = resolvePromise;+ reject = rejectPromise;+ });+ return { promise, reject, resolve };+}++const createdWindows = [];+let devServerWaitPromise = Promise.resolve();++class FakeBrowserWindow extends EventEmitter {+ constructor(options) {+ super();+ this.options = options;+ this.destroyed = false;+ this.loadDeferred = createDeferred();+ this.messages = [];+ this.loadUrlCount = 0;+ this.showCount = 0;+ this.webContents = {+ send: (channel, payload) => this.messages.push({ channel, payload }),+ };+ createdWindows.push(this);+ }++ setContentProtection() {}++ setIgnoreMouseEvents() {}++ loadFile() {+ return this.loadDeferred.promise;+ }++ loadURL() {+ this.loadUrlCount += 1;+ return Promise.resolve();+ }++ close() {+ if (this.destroyed) return;+ this.destroyed = true;+ this.emit("closed");+ }++ isDestroyed() {+ return this.destroyed;+ }++ showInactive() {+ this.showCount += 1;+ }+}++class FakeHotkeyManager {+ unregisterAll() {}+}+FakeHotkeyManager.isGlobeLikeHotkey = () => false;++class FakeDragManager {+ cleanup() {}+}++const originalLoad = Module._load;+Module._load = function loadWindowManagerWithStubs(request, parent, isMain) {+ if (request === "electron") {+ return {+ app: { on: () => undefined },+ screen: { getPrimaryDisplay: () => ({}) },+ BrowserWindow: FakeBrowserWindow,+ shell: {},+ dialog: {},+ };+ }+ if (request === "./debugLogger") return { warn: () => undefined };+ if (request === "./hotkeyManager") return FakeHotkeyManager;+ if (request === "./dragManager") return FakeDragManager;+ if (request === "./menuManager") return {};+ if (request === "./devServerManager") {+ return {+ DEV_SERVER_PORT: 5173,+ DEV_SERVER_URL: "http://localhost:5173",+ getAppFilePath: () => ({ path: "/app/index.html", query: {} }),+ waitForDevServer: () => devServerWaitPromise,+ };+ }+ if (request === "./dockManager") return {};+ if (request === "./i18nMain") return { i18nMain: { t: (key) => key } };+ if (request === "./windowConfig") {+ const detectionSize = { width: 392, height: 92 };+ const autoEndSize = { width: 620, height: 116 };+ return {+ MAIN_WINDOW_CONFIG: {},+ CONTROL_PANEL_CONFIG: {},+ AGENT_OVERLAY_CONFIG: {},+ NOTIFICATION_WINDOW_CONFIG: { ...detectionSize, acceptFirstMouse: true },+ AUTO_END_NOTIFICATION_WINDOW_SIZE: autoEndSize,+ getMeetingNotificationWindowSize: (data) =>+ data?.kind === "auto-end" ? autoEndSize : detectionSize,+ TRANSCRIPTION_PREVIEW_CONFIG: {},+ TRANSCRIPTION_PREVIEW_SIZE_LIMITS: {},+ WINDOW_SIZES: {},+ WindowPositionUtil: {+ getNotificationPosition: (_display, size = detectionSize) => ({+ ...size,+ x: 1000 - size.width,+ y: 16,+ }),+ setupAlwaysOnTop: () => undefined,+ },+ };+ }+ return originalLoad.call(this, request, parent, isMain);+};+const WindowManager = require("../../src/helpers/windowManager");+Module._load = originalLoad;++function installFakeTimers() {+ const originalSetTimeout = global.setTimeout;+ const originalClearTimeout = global.clearTimeout;+ let nextTimerId = 1;+ const timers = new Map();++ global.setTimeout = (callback) => {+ const timerId = nextTimerId;+ nextTimerId += 1;+ timers.set(timerId, callback);+ return timerId;+ };+ global.clearTimeout = (timerId) => timers.delete(timerId);++ return {+ pendingCount: () => timers.size,+ runAll: () => {+ for (const [timerId, callback] of [...timers]) {+ timers.delete(timerId);+ callback();+ }+ },+ restore: () => {+ global.setTimeout = originalSetTimeout;+ global.clearTimeout = originalClearTimeout;+ },+ };+}++test.beforeEach(() => {+ createdWindows.length = 0;+});++test("window creation uses the auto-end dimensions and variant-aware position", async () => {+ const manager = new WindowManager();++ try {+ const showPromise = manager.showMeetingAutoEndCountdown({+ sessionId: "meeting-1",+ expiresAt: 70_000,+ reason: "silence",+ });+ const notificationWindow = createdWindows[0];++ assert.deepEqual(+ {+ acceptFirstMouse: notificationWindow.options.acceptFirstMouse,+ width: notificationWindow.options.width,+ height: notificationWindow.options.height,+ x: notificationWindow.options.x,+ y: notificationWindow.options.y,+ },+ { acceptFirstMouse: true, width: 620, height: 116, x: 380, y: 16 }+ );+ // The reason rides along in the pending payload the overlay will fetch.+ assert.deepEqual(manager._pendingNotificationData, {+ kind: "auto-end",+ sessionId: "meeting-1",+ expiresAt: 70_000,+ reason: "silence",+ });++ notificationWindow.loadDeferred.resolve();+ await showPromise;+ } finally {+ manager.dismissMeetingNotification();+ }+});++test("unexpected auto-end window closure suppresses that countdown", async () => {+ const manager = new WindowManager();+ const unavailableSessions = [];+ manager.meetingDetectionEngine = {+ handleAutoEndNotificationUnavailable: (sessionId) => unavailableSessions.push(sessionId),+ };++ const showPromise = manager.showMeetingAutoEndCountdown({+ sessionId: "meeting-1",+ expiresAt: 70_000,+ reason: "silence",+ });+ const notificationWindow = createdWindows[0];+ notificationWindow.loadDeferred.resolve();+ await showPromise;++ notificationWindow.close();++ assert.deepEqual(unavailableSessions, ["meeting-1"]);+});++test("auto-end notification loading has a fail-safe timeout", async () => {+ const timers = installFakeTimers();+ const manager = new WindowManager();+ const showPromise = manager.showMeetingAutoEndCountdown({+ sessionId: "meeting-1",+ expiresAt: 70_000,+ reason: "silence",+ });+ const notificationWindow = createdWindows[0];++ try {+ assert.equal(timers.pendingCount(), 1);+ timers.runAll();++ await assert.rejects(showPromise, /timed out/i);+ assert.equal(notificationWindow.isDestroyed(), true);+ assert.equal(manager.notificationWindow, null);+ } finally {+ manager.dismissMeetingNotification();+ notificationWindow.loadDeferred.resolve();+ await showPromise.catch(() => undefined);+ timers.restore();+ }+});++test("a replaced deferred notification cannot send its payload to the newer window", async () => {+ const timers = installFakeTimers();+ const manager = new WindowManager();+ let secondShowPromise;++ try {+ const firstShowPromise = manager.showMeetingNotification(+ { detectionId: "first" },+ { autoDismiss: false }+ );+ const firstWindow = createdWindows[0];+ secondShowPromise = manager.showMeetingNotification(+ { detectionId: "second" },+ { autoDismiss: false }+ );+ const secondWindow = createdWindows[1];++ firstWindow.loadDeferred.resolve();+ await firstShowPromise;+ timers.runAll();++ assert.deepEqual(secondWindow.messages, []);+ assert.equal(secondWindow.showCount, 0);+ } finally {+ createdWindows[1]?.loadDeferred.resolve();+ await secondShowPromise?.catch(() => undefined);+ manager.dismissMeetingNotification();+ timers.restore();+ }+});++test("canceling during a deferred load prevents later timers and timeout callbacks", async () => {+ const timers = installFakeTimers();+ const manager = new WindowManager();+ let timeoutCount = 0;+ manager.meetingDetectionEngine = {+ handleNotificationTimeout: () => {+ timeoutCount += 1;+ },+ };+ const showPromise = manager.showMeetingNotification({ detectionId: "first" });+ const notificationWindow = createdWindows[0];++ try {+ manager.dismissMeetingNotification();+ notificationWindow.loadDeferred.reject(new Error("ERR_ABORTED"));++ await assert.doesNotReject(showPromise);+ timers.runAll();++ assert.equal(timeoutCount, 0);+ assert.deepEqual(notificationWindow.messages, []);+ assert.equal(notificationWindow.showCount, 0);+ assert.equal(manager.notificationWindow, null);+ } finally {+ await showPromise.catch(() => undefined);+ manager.dismissMeetingNotification();+ timers.restore();+ }+});++test("canceling while waiting for the dev server never loads the stale window", async () => {+ const timers = installFakeTimers();+ const manager = new WindowManager();+ const originalNodeEnv = process.env.NODE_ENV;+ const devServerWait = createDeferred();+ devServerWaitPromise = devServerWait.promise;+ process.env.NODE_ENV = "development";++ try {+ const showPromise = manager.showMeetingNotification({ detectionId: "first" });+ const notificationWindow = createdWindows[0];+ manager.dismissMeetingNotification();+ devServerWait.resolve();++ await assert.doesNotReject(showPromise);+ assert.equal(notificationWindow.loadUrlCount, 0);+ } finally {+ process.env.NODE_ENV = originalNodeEnv;+ devServerWaitPromise = Promise.resolve();+ manager.dismissMeetingNotification();+ timers.restore();+ }+});++test("a stale ready callback cannot show the replacement notification window", async () => {+ const timers = installFakeTimers();+ const manager = new WindowManager();++ try {+ const firstShowPromise = manager.showMeetingNotification(+ { detectionId: "first" },+ { autoDismiss: false }+ );+ const firstWindow = createdWindows[0];+ firstWindow.loadDeferred.resolve();+ await firstShowPromise;++ const secondShowPromise = manager.showMeetingNotification(+ { detectionId: "second" },+ { autoDismiss: false }+ );+ const secondWindow = createdWindows[1];+ secondWindow.loadDeferred.resolve();+ await secondShowPromise;++ manager.showNotificationWindow(firstWindow.webContents);+ assert.equal(secondWindow.showCount, 0);++ manager.showNotificationWindow(secondWindow.webContents);+ assert.equal(secondWindow.showCount, 1);+ } finally {+ manager.dismissMeetingNotification();+ timers.restore();+ }+});diff --git a/test/helpers/windowsHelperSpawnHide.test.js b/test/helpers/windowsHelperSpawnHide.test.jsindex 327268301..8edb8a322 100644--- a/test/helpers/windowsHelperSpawnHide.test.js+++ b/test/helpers/windowsHelperSpawnHide.test.js@@ -22,6 +22,6 @@ test("text edit monitor spawns set windowsHide", () => {test("Windows mic-listener spawn sets windowsHide", () => {assert.match(read("src/helpers/audioActivityDetector.js"),- /args: \["--exclude-pid"[^{}]*\{[^{}]*windowsHide: true/+ /args: \[\][^{}]*options: \{ stdio: \["pipe", "pipe", "pipe"\], windowsHide: true \}/);});