Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(voice-input): 保活麦克风 idle 窗口不再被无关事件续期 (#373)
Dashbec0510da0c4
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex a2943e0d69..365b17b610 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -235,6 +235,10 @@ import {installPowerEventDiagnostics,installWindowResponsivenessDiagnostics,} from './powerWakeDiagnostics';+import {+ broadcastVoiceInputPowerState,+ installVoiceInputPowerRelease,+} from './voice-input/powerReleaseNotifier';import { reapClaudeOrphansSync } from './claude-orphan-reaper';import { initAppBadgeService, clearAllSessionAttention } from './appBadgeService';import { initNotificationService } from './notificationService';@@ -777,6 +781,7 @@ const authBoundaryLog = createLogger('auth-boundary');// 主窗 renderer 加载失败可观测性 + dev 启动看门狗(见 renderer-boot-guard.ts 顶部注释)。const rendererGuardLog = createLogger('renderer-guard');const updatePresentationLog = createLogger('update-presentation');+const voicePowerBroadcastLog = createLogger('voice-input-power');let rendererBootGuard: RendererBootGuard | null = null;const lifecycleDbClientManager = createLifecycleDbClientManager({@@ -5556,6 +5561,20 @@ app.on('ready', async () => {// render-watchdog 的漂移/无帧日志提供时间锚点。installPowerEventDiagnostics({ powerMonitor });+ // 挂起/锁屏时通知 renderer 释放语音输入的保活麦克风(用户已离开,再占着采集+ // 设备只剩隐私指示灯常亮和 idle-sleep assertion 的代价)。+ installVoiceInputPowerRelease({+ powerMonitor,+ broadcast: (channel, payload) => {+ broadcastVoiceInputPowerState(+ BrowserWindow.getAllWindows(),+ channel,+ payload,+ voicePowerBroadcastLog,+ );+ },+ });+// ── System resume: refresh tokens after sleep/hibernate ──powerMonitor.on('resume', () => {authManager.handleResume();diff --git a/apps/desktop/src/main/voice-input/__tests__/powerReleaseNotifier.test.ts b/apps/desktop/src/main/voice-input/__tests__/powerReleaseNotifier.test.tsnew file mode 100644index 0000000000..53a7ca689e--- /dev/null+++ b/apps/desktop/src/main/voice-input/__tests__/powerReleaseNotifier.test.ts@@ -0,0 +1,81 @@+import { describe, expect, it, vi } from 'vitest';++import { VOICE_INPUT_POWER_STATE_CHANNEL } from '../../../shared/voiceInputPowerIpc';+import {+ broadcastVoiceInputPowerState,+ installVoiceInputPowerRelease,+ type VoicePowerMonitorLike,+} from '../powerReleaseNotifier';++function createFakePowerMonitor(): VoicePowerMonitorLike & { emit: (event: string) => void } {+ const listeners = new Map<string, Array<() => void>>();+ return {+ on(event: string, listener: () => void) {+ const existing = listeners.get(event) ?? [];+ existing.push(listener);+ listeners.set(event, existing);+ return this;+ },+ emit(event: string) {+ (listeners.get(event) ?? []).forEach((listener) => listener());+ },+ } as VoicePowerMonitorLike & { emit: (event: string) => void };+}++describe('installVoiceInputPowerRelease', () => {+ it('broadcasts a release reason on suspend and lock-screen', () => {+ const powerMonitor = createFakePowerMonitor();+ const broadcast = vi.fn();++ installVoiceInputPowerRelease({+ powerMonitor,+ broadcast,+ logger: { debug: vi.fn() },+ });++ powerMonitor.emit('suspend');+ powerMonitor.emit('lock-screen');++ expect(broadcast).toHaveBeenNthCalledWith(1, VOICE_INPUT_POWER_STATE_CHANNEL, {+ reason: 'system_suspend',+ });+ expect(broadcast).toHaveBeenNthCalledWith(2, VOICE_INPUT_POWER_STATE_CHANNEL, {+ reason: 'screen_locked',+ });+ });++ it('keeps broadcasting after one window fails mid-teardown', () => {+ const delivered: string[] = [];+ const makeWindow = (name: string, behaviour: 'ok' | 'destroyed' | 'throws') => ({+ isDestroyed: () => behaviour === 'destroyed',+ webContents: {+ send: () => {+ if (behaviour === 'throws') throw new Error('Object has been destroyed');+ delivered.push(name);+ },+ },+ });+ const warn = vi.fn();++ broadcastVoiceInputPowerState(+ [makeWindow('first', 'ok'), makeWindow('racing', 'throws'), makeWindow('skipped', 'destroyed'), makeWindow('owner', 'ok')],+ VOICE_INPUT_POWER_STATE_CHANNEL,+ { reason: 'screen_locked' },+ { warn },+ );++ // The one-shot release must still reach the window after the failing one —+ // that may be the renderer holding the live microphone.+ expect(delivered).toEqual(['first', 'owner']);+ expect(warn).toHaveBeenCalledTimes(1);+ });++ it('does not broadcast before a power event fires', () => {+ const powerMonitor = createFakePowerMonitor();+ const broadcast = vi.fn();++ installVoiceInputPowerRelease({ powerMonitor, broadcast, logger: { debug: vi.fn() } });++ expect(broadcast).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/voice-input/powerReleaseNotifier.ts b/apps/desktop/src/main/voice-input/powerReleaseNotifier.tsnew file mode 100644index 0000000000..9f0f5bf1ad--- /dev/null+++ b/apps/desktop/src/main/voice-input/powerReleaseNotifier.ts@@ -0,0 +1,81 @@+/**+ * 系统电源事件 → 释放语音输入保活麦克风(main 侧广播)。+ *+ * fast activation 会让麦克风在用完后继续待命一段时间(renderer 侧+ * WebMicAudioEngine 的 keep-alive session)。系统挂起或锁屏意味着用户已经离开:+ * 这时继续占着采集设备既拿不到延迟收益,又让系统隐私指示灯常亮,并通过+ * coreaudiod 持有 idle-sleep assertion,把整机拖在不睡眠的状态。+ *+ * 这里只广播事实,不做决策——哪个窗口真的持有 keep-alive session 只有 renderer+ * 知道,main 无从判断,也不应该替它判断。+ *+ * 与 powerWakeDiagnostics 分开:那个模块的契约是「只记日志,不改任何行为」,+ * 在它里面挂副作用会破坏该承诺。依赖以注入面暴露,单测不需要 Electron。+ */+import {+ VOICE_INPUT_POWER_STATE_CHANNEL,+ type VoiceInputPowerReleaseReason,+ type VoiceInputPowerStatePayload,+} from '../../shared/voiceInputPowerIpc';+import { createLogger } from '../logger';++const log = createLogger('voice-input-power');++/** powerMonitor 注入面(单测用假 emitter)。 */+export interface VoicePowerMonitorLike {+ on(event: 'suspend' | 'lock-screen', listener: () => void): unknown;+}++export interface VoiceInputPowerReleaseDeps {+ powerMonitor: VoicePowerMonitorLike;+ /** 把 payload 送到所有 renderer;注入以便单测断言广播内容。 */+ broadcast: (channel: string, payload: VoiceInputPowerStatePayload) => void;+ logger?: Pick<typeof log, 'debug'>;+}++/**+ * 订阅挂起/锁屏并广播释放信号。+ *+ * macOS 与 Windows 都会触发 suspend;lock-screen 两端语义不同(macOS 为锁屏,+ * Windows 为工作站锁定),但「用户已离开」的判断在两端一致,因此同样处理。+ * Linux 不触发 lock-screen,不影响 suspend 路径。+ */+/** 广播目标窗口的最小结构面(用结构类型,避免这里依赖 Electron)。 */+export interface VoicePowerBroadcastWindow {+ isDestroyed(): boolean;+ webContents: { send(channel: string, payload: unknown): void };+}++/**+ * 逐窗发送,单窗失败不影响其余窗口。+ *+ * 窗口可能在 isDestroyed() 与 send() 之间被销毁而抛错。这是一次性事件:循环一旦+ * 中断,后面的窗口(可能正是持有麦克风的那个)就永远收不到释放信号,只能等 idle+ * 超时。容错写法与 appBadgeService 的广播保持一致。+ */+export function broadcastVoiceInputPowerState(+ windows: readonly VoicePowerBroadcastWindow[],+ channel: string,+ payload: VoiceInputPowerStatePayload,+ logger?: Pick<typeof log, 'warn'>,+): void {+ for (const win of windows) {+ if (win.isDestroyed()) continue;+ try {+ win.webContents.send(channel, payload);+ } catch (err) {+ (logger ?? log).warn('broadcast voice input power release failed:', err);+ }+ }+}++export function installVoiceInputPowerRelease(deps: VoiceInputPowerReleaseDeps): void {+ const logger = deps.logger ?? log;+ const emit = (reason: VoiceInputPowerReleaseReason): void => {+ logger.debug('voice input keep-alive release broadcast', { reason });+ deps.broadcast(VOICE_INPUT_POWER_STATE_CHANNEL, { reason });+ };++ deps.powerMonitor.on('suspend', () => emit('system_suspend'));+ deps.powerMonitor.on('lock-screen', () => emit('screen_locked'));+}diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 7c75516fb3..2015b3afa9 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -26,6 +26,7 @@ import {} from '../shared/windowBehavior';import { SELECTION_CONTEXT_MENU_ADD_TO_CHAT_CHANNEL } from '../shared/selectionContextMenu';import { SESSION_ATTENTION_CLEARED_CHANNEL } from '../shared/sessionAttention';+import { VOICE_INPUT_POWER_STATE_CHANNEL } from '../shared/voiceInputPowerIpc';import {type ApplicationMenuCommand,isApplicationMenuCommand,@@ -335,6 +336,8 @@ const fanOutVoiceInputGlobalShortcutTrigger = createIpcFanOut('voice-input:globaconst fanOutVoiceInputGlobalOverlayCommand = createIpcFanOut('voice-input:global-overlay-command');const fanOutVoiceInputDictionaryLearningEvidence = createIpcFanOut('voice-input:dictionary-learning-evidence');const fanOutVoiceInputDataChanged = createIpcFanOut('voice-input:data-changed');+// 挂起/锁屏 → renderer 释放 fast activation 的保活麦克风(见 shared/voiceInputPowerIpc)。+const fanOutVoiceInputPowerStateChange = createIpcFanOut(VOICE_INPUT_POWER_STATE_CHANNEL);// 应用级快捷键 override 变化广播 (设置页改绑 / reset 后 main 推全量 overrides,// renderer 侧 appShortcutStore 订阅热更新)。const fanOutAppShortcutsChanged = createIpcFanOut('app-shortcuts:changed');@@ -996,6 +999,7 @@ contextBridge.exposeInMainWorld('electronAPI', {adviseDictionaryLearning: (payload: unknown): Promise<unknown> =>ipcRenderer.invoke('voice-input:dictionary-learning:advise', payload),onDictionaryLearningEvidence: fanOutVoiceInputDictionaryLearningEvidence,+ onPowerStateChange: fanOutVoiceInputPowerStateChange,notifyGlobalOverlayReady: (): void =>ipcRenderer.send('voice-input:global-overlay-ready'),pasteIntoFocusedTarget: (text: string, rawTranscriptText?: string): Promise<VoiceInputGlobalResult> =>diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 0b0df966e5..c8fa20375f 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -12,6 +12,8 @@ interface ImportMeta {type ModelAccessStatusPayload = import('../shared/modelAccess').ModelAccessStatus;type RsbWindowCommand = import('../shared/rightSidebarWindow').RsbWindowCommand;+type VoiceInputPowerStatePayload =+ import('../shared/voiceInputPowerIpc').VoiceInputPowerStatePayload;type DesktopLoginAction = import('../shared/authIpc').DesktopLoginAction;type DesktopLoginActionResult = import('../shared/authIpc').DesktopLoginActionResult;type UtilityTextFailure = import('../shared/utilityTextResult').UtilityTextFailure;@@ -1332,6 +1334,8 @@ interface ElectronAPI {onDictionaryLearningEvidence: (callback: (payload: { evidence: Pick<VoiceInputDictionaryAdviceInput, 'source' | 'rawTranscriptText' | 'beforeText' | 'afterText' | 'context'> }) => void,) => () => void;+ /** 系统挂起/锁屏 → 释放 fast activation 的保活麦克风。 */+ onPowerStateChange: (callback: (payload: VoiceInputPowerStatePayload) => void) => () => void;notifyGlobalOverlayReady: () => void;pasteIntoFocusedTarget: (text: string, rawTranscriptText?: string) => Promise<VoiceInputGlobalResult>;restoreGlobalPasteTargetFocus: () => Promise<VoiceInputGlobalResult>;diff --git a/apps/desktop/src/renderer/voice-input/VoiceInputOverlay.tsx b/apps/desktop/src/renderer/voice-input/VoiceInputOverlay.tsxindex 9d9bc06395..344957d610 100644--- a/apps/desktop/src/renderer/voice-input/VoiceInputOverlay.tsx+++ b/apps/desktop/src/renderer/voice-input/VoiceInputOverlay.tsx@@ -648,7 +648,15 @@ export function VoiceInputOverlay() {t('settings.voiceInput.microphone.errors.fallbackToAuto')), [t]);+ // 这个 overlay 订阅的是全部语音设置,但只有这两项与采集设备有关。语言、润色等+ // 变更同样会走到这里,如果不过滤,一次无关设置改动就会在保活窗口已经到期释放后+ // 重新打开麦克风,让隐私指示灯毫无理由地重新亮起。+ const lastKeepAliveConfigRef = useRef<string | null>(null);+const prewarmFastActivationIfEnabled = useCallback((settings: ReturnType<typeof getVoiceInputSettings>) => {+ const configKey = `${settings.fastActivationEnabled ? 'on' : 'off'}|${settings.microphoneDeviceId ?? ''}`;+ if (lastKeepAliveConfigRef.current === configKey) return;+ lastKeepAliveConfigRef.current = configKey;if (!settings.fastActivationEnabled) {void disposeKeepAliveVoiceInputMicrophone('setting_disabled').catch(() => undefined);return;@@ -811,6 +819,23 @@ export function VoiceInputOverlay() {elapsedMs,});if (!captureStart.ok) {+ // 电源释放(锁屏/挂起)取消了启动:走与「启动尝试已失效」相同的静默清理,+ // 不把内部错误消息推到 UI —— 用户是主动离开,不是遇到故障。+ if (captureStart.cancelled) {+ log.debug('global microphone start cancelled by power release');+ resolveStartReadyState(attemptId, { ok: false, error: captureStart.error });+ startAttemptIdRef.current += 1;+ cancelStartedRun(startResultPromise);+ suppressedStartErrorAttemptsRef.current.delete(attemptId);+ await restoreSystemAudioForRecording();+ // setVoiceState('listening') already ran, and this path owns no engine+ // or run, so no later cancel/state event will arrive to clear it.+ // Leaving it would strand the overlay in 'listening' — where the+ // stateRef.current === 'listening' guard silently swallows every+ // subsequent shortcut press.+ await closeOverlayAndReset();+ return;+ }log.warn('global microphone start failed:', captureStart.error);resolveStartReadyState(attemptId, { ok: false, error: captureStart.error });startAttemptIdRef.current += 1;@@ -863,6 +888,7 @@ export function VoiceInputOverlay() {cancelStartedRun,clearErrorCloseTimer,closeOverlay,+ closeOverlayAndReset,createStartReadyState,failRecording,formatMicrophoneFallbackMessage,diff --git a/apps/desktop/src/renderer/voice-input/WebMicAudioEngine.ts b/apps/desktop/src/renderer/voice-input/WebMicAudioEngine.tsindex c4fa0cce7f..c161b1503d 100644--- a/apps/desktop/src/renderer/voice-input/WebMicAudioEngine.ts+++ b/apps/desktop/src/renderer/voice-input/WebMicAudioEngine.ts@@ -67,6 +67,80 @@ export class VoiceInputSelectedMicrophoneUnavailableError extends Error {}}+/**+ * Startup was cancelled by an explicit release (suspend/lock/setting off) that+ * landed mid-`start()`. Distinguished from real failures so prewarm can exit+ * quietly instead of logging a warning for something the user asked for.+ */+export class KeepAliveSessionDisposedError extends Error {+ readonly reason: string;++ constructor(reason: string) {+ super(`Keep-alive microphone session was disposed (${reason}).`);+ this.name = 'KeepAliveSessionDisposedError';+ this.reason = reason;+ }+}++export function isKeepAliveSessionDisposedError(error: unknown): boolean {+ if (error instanceof KeepAliveSessionDisposedError) return true;+ return readErrorString(error, 'name') === 'KeepAliveSessionDisposedError';+}++/**+ * Reasons that mean "the user walked away", as opposed to "the setup changed".+ * Only these justify abandoning a start attempt silently; a devicechange or a+ * disabled setting must still fall through to the cold path so the dictation+ * the user is in the middle of keeps working.+ */+const POWER_RELEASE_REASONS: ReadonlySet<string> = new Set([+ 'system_suspend',+ 'screen_locked',+ // Synthesised by callers that detected a release via the generation counter+ // rather than by catching a session error (see powerReleaseCancellation).+ 'power_release',+]);++/**+ * Cancellation for a caller that noticed a power release through+ * currentPowerReleaseGeneration() — by then no in-flight session error carries+ * the reason any more, but the attempt must still be abandoned rather than+ * reopening a device after the one-shot event.+ */+export function powerReleaseCancellation(): KeepAliveSessionDisposedError {+ return new KeepAliveSessionDisposedError('power_release');+}++/**+ * Reasons after which a queued replacement must NOT be built: the user either+ * walked away or turned the feature off. Other reasons (devicechange) still+ * want a rebuild with the new setup.+ */+const DO_NOT_REBUILD_REASONS: ReadonlySet<string> = new Set([+ 'system_suspend',+ 'screen_locked',+ 'power_release',+ 'setting_disabled',+ 'hmr',+]);++/**+ * Bumped on every power-triggered release. Lets a caller that was awaiting+ * something else notice a release happened in between, even when no session+ * error carries the reason any more.+ */+let powerReleaseGeneration = 0;++export function currentPowerReleaseGeneration(): number {+ return powerReleaseGeneration;+}++export function isPowerReleaseCancellation(error: unknown): boolean {+ if (!isKeepAliveSessionDisposedError(error)) return false;+ const reason = readErrorString(error, 'reason');+ return reason !== undefined && POWER_RELEASE_REASONS.has(reason);+}+const AUDIO_FRAME_WATCHDOG_INTERVAL_MS = 1000;const AUDIO_FRAME_STALL_TIMEOUT_MS = 2500;const AUDIO_DRAIN_TIMEOUT_MS = 180;@@ -79,7 +153,15 @@ let benchmarkFixturePromise: Promise<BenchmarkFixtureAudio | null> | null = nulllet keepAliveSession: KeepAliveMicSession | null = null;let keepAliveSessionPromise: Promise<KeepAliveMicSession> | null = null;let keepAliveDeviceChangeListening = false;+let keepAlivePowerReleaseListening = false;+let keepAlivePowerReleaseUnsubscribe: (() => void) | undefined;let keepAliveIdleDisposeTimer: number | undefined;+// Expiry of the current idle window, on the monotonic clock read by+// keepAliveMonotonicNow() (performance.now(), not wall time). Kept separately+// from the timer handle: callers that merely re-assert the keep-alive intent+// (component mount, unrelated settings changes) clear and re-arm the timer, and+// must land on the original deadline instead of restarting the countdown.+let keepAliveIdleDeadlineAt: number | undefined;function isSpecificMicrophoneDeviceId(deviceId?: string): deviceId is string {return Boolean(deviceId && deviceId !== 'default');@@ -229,7 +311,7 @@ function normalizeMicrophoneStartError(error: unknown, deviceId?: string): Error* `instanceof Error` in this realm. Read the standard fields structurally so a* stale selected microphone still takes the automatic fallback path.*/-function readErrorString(error: unknown, key: 'name' | 'message'): string | undefined {+function readErrorString(error: unknown, key: 'name' | 'message' | 'reason'): string | undefined {if (typeof error !== 'object' || error === null) return undefined;const value = (error as Record<string, unknown>)[key];return typeof value === 'string' ? value : undefined;@@ -284,6 +366,29 @@ function ensureKeepAliveDeviceChangeListener(): void {});}+/**+ * Release the warm microphone when the machine suspends or the screen locks.+ *+ * Both mean the user walked away, so holding the capture device buys no+ * latency while still lighting the OS privacy indicator and holding an+ * idle-sleep assertion through coreaudiod. Mirrors the devicechange listener+ * above: one process-wide subscription, installed lazily with the first+ * keep-alive session, never torn down.+ */+function ensureKeepAlivePowerReleaseListener(): void {+ if (keepAlivePowerReleaseListening) return;+ const subscribe = window.electronAPI?.voiceInput?.onPowerStateChange;+ if (typeof subscribe !== 'function') return;+ keepAlivePowerReleaseListening = true;+ // Keep the unsubscribe: without it every dev HMR reload would add another+ // live subscription (the flag resets with the module, the listener does not),+ // so one lock event would fan out to N stale callbacks.+ keepAlivePowerReleaseUnsubscribe = subscribe((payload) => {+ powerReleaseGeneration += 1;+ void disposeKeepAliveVoiceInputMicrophone(payload.reason);+ });+}+class KeepAliveMicSession {readonly key: KeepAliveSessionKey;readonly options: KeepAliveSessionOptions;@@ -297,28 +402,103 @@ class KeepAliveMicSession {private disposed = false;private active = false;private staleAfterActiveDeviceChange = false;+ private sinkConnected = false;+ private startPromise?: Promise<void>;+ // Why this session was released, so a start attempt interrupted by it can+ // tell "user walked away" (suspend/lock) from "setup changed" (devicechange,+ // setting turned off) — only the former may abandon the attempt silently.+ private disposedReason = 'dispose';+ // Counted, not boolean: two engines (overlay + ChatInput) can share one+ // session, and a flag would let whichever finishes first clear the other's+ // claim — handing the still-live session to a replacing prewarm.+ private recordingReservations = 0;constructor(options: KeepAliveSessionOptions) {this.options = options;this.key = keepAliveKey(options);}- async start(): Promise<void> {- if (this.disposed) throw new Error('Keep-alive microphone session was disposed.');- if (this.context && this.stream && this.worklet) return;- ensureKeepAliveDeviceChangeListener();- await assertSelectedMicrophoneAvailable(this.options.deviceId);+ /**+ * Idempotent for concurrent callers.+ *+ * A recording start and a prewarm can both reach this session while it is+ * still coming up (getOrCreateKeepAliveSession awaits `start()` directly when+ * the session already exists). The early-return below only fires once stream+ * *and* worklet exist, so without a shared in-flight promise the second call+ * re-runs the whole sequence and opens a second MediaStream — the first one+ * then gets overwritten by `this.stream` and is never stopped.+ */+ start(): Promise<void> {+ if (this.disposed) return Promise.reject(new KeepAliveSessionDisposedError(this.disposedReason));+ if (this.context && this.stream && this.worklet) return Promise.resolve();+ this.startPromise ??= this.startInternal().finally(() => {+ this.startPromise = undefined;+ });+ return this.startPromise;+ }++ /**+ * Await one startup step, letting an in-flight release win either outcome.+ *+ * Both outcomes matter. On success we must not keep building on a session+ * that was torn down mid-await. On failure the raw error would send start()+ * into the cold fallback path, which reopens the microphone after the power+ * event with nothing left to close it — suspend routinely makes these+ * promises reject rather than resolve.+ *+ * Steps whose resolved value needs cleanup (getUserMedia) handle disposal+ * inline instead, so the stream can be stopped before throwing.+ */+ private async awaitStartupStep<T>(step: Promise<T>): Promise<T> {+ try {+ const value = await step;+ if (this.disposed) throw new KeepAliveSessionDisposedError(this.disposedReason);+ return value;+ } catch (error) {+ if (this.disposed && !isKeepAliveSessionDisposedError(error)) {+ throw new KeepAliveSessionDisposedError(this.disposedReason);+ }+ throw error;+ }+ }- const sharedState = await prewarmVoiceInputAudio(this.options.workletUrl);+ private async startInternal(): Promise<void> {+ ensureKeepAliveDeviceChangeListener();+ ensureKeepAlivePowerReleaseListener();+ // Also guarded: if a release lands while enumerating and the device then+ // reads as absent, the raw VoiceInputSelectedMicrophoneUnavailableError+ // would send prewarm/capture down their automatic-fallback paths and open+ // the *default* microphone after the power event.+ await this.awaitStartupStep(assertSelectedMicrophoneAvailable(this.options.deviceId));++ // A release (suspend/lock/setting off) can land while this is pending, in+ // which case bailing out avoids opening a device nothing could then close.+ const sharedState = await this.awaitStartupStep(prewarmVoiceInputAudio(this.options.workletUrl));this.context = sharedState.context;+ let stream: MediaStream;try {- this.stream = await navigator.mediaDevices.getUserMedia({+ stream = await navigator.mediaDevices.getUserMedia({audio: buildMediaConstraints(this.options),video: false,});} catch (error) {+ // A release that won this race takes priority over the device error.+ // Suspending a machine commonly makes the pending getUserMedia reject+ // (AbortError / NotReadableError); reporting that as an ordinary failure+ // sends start() down the cold fallback path, which reopens the microphone+ // after the suspend/lock event has already passed — with nothing left to+ // close it.+ if (this.disposed) throw new KeepAliveSessionDisposedError(this.disposedReason);throw normalizeMicrophoneStartError(error, this.options.deviceId);}+ // dispose() ran while getUserMedia was in flight: it could not stop a track+ // that did not exist yet, so this stream would stay live forever — mic+ // indicator on, idle-sleep assertion held, and unreachable from any session.+ if (this.disposed) {+ stream.getTracks().forEach((track) => track.stop());+ throw new KeepAliveSessionDisposedError(this.disposedReason);+ }+ this.stream = stream;this.stream.getAudioTracks().forEach((track) => this.watchTrack(track));this.sink = this.context.createGain();this.sink.gain.value = 0;@@ -344,15 +524,56 @@ class KeepAliveMicSession {this.worklet.port.postMessage({ type: 'setActive', active: false, reset: true });this.source.connect(this.worklet);this.worklet.connect(this.sink);- this.sink.connect(this.context.destination);+ // The sink stays detached until activation; see attachOutputPath.if (this.context.state !== 'running') {- await this.context.resume();+ // Last await of startup. A release landing here has already stopped the+ // track and torn down every node built above, so reporting success would+ // hand the caller a session that can never emit PCM — it would arm its+ // watchdog and surface a bogus "microphone stalled" failure instead.+ await this.awaitStartupStep(this.context.resume());}}+ /**+ * Attach the capture graph to the context destination.+ *+ * AudioWorklet.process() only runs while the node has a live path to the+ * destination, so the graph must be attached before PCM can flow. Leaving it+ * attached while merely warm is what made a keep-alive microphone also hold a+ * CoreAudio *output* stream — and, through coreaudiod, an idle-sleep+ * assertion — for the whole window. Dictation needs the input path only, so+ * the output path now follows activation rather than session lifetime.+ */+ private attachOutputPath(): void {+ if (!this.context || !this.sink || this.sinkConnected) return;+ this.sink.connect(this.context.destination);+ this.sinkConnected = true;+ }++ private detachOutputPath(): void {+ if (!this.sink || !this.sinkConnected) return;+ this.sink.disconnect();+ this.sinkConnected = false;+ }+activate(activation: KeepAliveActivation): void {+ // Defence in depth: a disposed session has no stream or worklet left, so+ // activating it would look like a successful start that never emits audio.+ if (this.disposed) throw new KeepAliveSessionDisposedError(this.disposedReason);+ // One session carries exactly one PCM callback, so two simultaneous+ // recordings cannot share it — the second would silently steal the first's+ // audio. The product keeps dictation mutually exclusive (overlay and+ // ChatInput guard on their own 'listening' state), so this is a broken+ // invariant rather than a case to support: fail loudly instead of+ // swapping the callback behind the first recording's back.+ if (this.active) {+ throw new Error('Keep-alive microphone session is already recording.');+ }this.activation = activation;this.active = true;+ // Attach before arming the worklet so the first active render quantum+ // already has a live path; the worklet drops audio until setActive lands.+ this.attachOutputPath();this.worklet?.port.postMessage({ type: 'setActive', active: true, reset: true });activation.onStateChange?.('keep_alive_activated', {tracks: this.stream?.getAudioTracks().map((track) => this.describeTrack(track)),@@ -362,8 +583,12 @@ class KeepAliveMicSession {deactivate(): void {this.worklet?.port.postMessage({ type: 'setActive', active: false, reset: true });+ this.detachOutputPath();this.activation = undefined;this.active = false;+ // Reservations are released by whoever took them (see stop()), not here:+ // deactivate() is also called by prewarm on an idle session, and by one of+ // several engines that may share this one.}drainBufferedAudio(): Promise<void> {@@ -374,6 +599,44 @@ class KeepAliveMicSession {return this.active;}+ /**+ * Recording, or on its way there.+ *+ * `active` only flips in activate(), which happens *after* start() resolves,+ * so a concurrent prewarm checking `active` alone would sail past a session a+ * recording is waiting on and hand it to the replace path — the recording+ * would then activate() a disposed session and die on the stall watchdog.+ *+ * The reservation (not merely "a startup is in flight") is what marks that+ * window: a *prewarm-only* startup has no recording waiting on it and must+ * stay replaceable, otherwise a device change during background warm-up would+ * only mark the session stale and then strand it — nothing would ever call+ * stop() to finish the deferred swap.+ */+ isBusy(): boolean {+ return this.active || this.recordingReservations > 0;+ }++ /**+ * Claim this session for an imminent activate(); see isBusy().+ *+ * Paired with releaseRecordingReservation(): the engine claims it inside+ * getOrCreateKeepAliveSession (before the first await) and releases it in+ * stop(), or on any startup path that fails after claiming.+ */+ reserveForRecording(): void {+ this.recordingReservations += 1;+ }++ releaseRecordingReservation(): void {+ this.recordingReservations = Math.max(0, this.recordingReservations - 1);+ }++ /** Someone other than the caller still needs this session live. */+ hasRecordingReservations(): boolean {+ return this.recordingReservations > 0;+ }+handleDeviceChange(): boolean {if (!this.active) return false;this.staleAfterActiveDeviceChange = true;@@ -383,6 +646,20 @@ class KeepAliveMicSession {return true;}+ /**+ * Retire this session after the current recording instead of right now.+ *+ * Used when the requested device/profile no longer matches while dictation is+ * in flight: rebuilding immediately would stop the very track the user is+ * speaking into. stop() sees isStaleAfterDeviceChange() and disposes then.+ */+ markStaleForReplacement(): void {+ this.staleAfterActiveDeviceChange = true;+ this.activation?.onStateChange?.('keep_alive_replacement_deferred', {+ reason: 'active_recording',+ });+ }+isStaleAfterDeviceChange(): boolean {return this.staleAfterActiveDeviceChange;}@@ -390,15 +667,28 @@ class KeepAliveMicSession {async dispose(reason = 'dispose'): Promise<void> {if (this.disposed) return;this.disposed = true;- this.activation?.onStateChange?.('keep_alive_disposed', { reason });+ this.disposedReason = reason;+ const activation = this.activation;+ const wasActive = this.active;+ activation?.onStateChange?.('keep_alive_disposed', { reason });this.activation = undefined;this.active = false;+ // A forced release during live dictation (suspend / lock / device removal)+ // must reach the engine. Without this the renderer stays in `listening` and+ // main keeps owning the ASR run until the audio watchdog fires — and during+ // suspend the watchdog does not run at all, so the run would stay live for+ // the entire sleep.+ if (wasActive) {+ activation?.onInterrupted?.('Microphone input stopped unexpectedly. Please try again.');+ }this.trackCleanup.splice(0).forEach((cleanup) => cleanup());this.worklet?.port.close();this.worklet?.disconnect();this.sink?.disconnect();this.source?.disconnect();this.stream?.getTracks().forEach((track) => track.stop());+ this.sinkConnected = false;+ this.recordingReservations = 0;this.worklet = undefined;this.sink = undefined;this.source = undefined;@@ -438,29 +728,76 @@ class KeepAliveMicSession {}}-async function getOrCreateKeepAliveSession(options: KeepAliveSessionOptions): Promise<KeepAliveMicSession> {+/**+ * `reserveForRecording` marks the session as claimed by an imminent recording+ * *before* the first await, so a prewarm racing on the same session sees it as+ * busy and defers instead of replacing it mid-startup. Prewarm itself never+ * reserves — a background warm-up must stay replaceable when the device changes.+ */+async function getOrCreateKeepAliveSession(+ options: KeepAliveSessionOptions,+ { reserveForRecording = false }: { reserveForRecording?: boolean } = {},+): Promise<KeepAliveMicSession> {clearKeepAliveIdleDisposeTimer();const key = keepAliveKey(options);if (keepAliveSession && keepAliveSession.key === key && !keepAliveSession.isStaleAfterDeviceChange()) {- await keepAliveSession.start();- return keepAliveSession;+ const existing = keepAliveSession;+ if (reserveForRecording) existing.reserveForRecording();+ try {+ await existing.start();+ } catch (error) {+ // Do not leave a reservation on a session that failed to start: nothing+ // would ever release it, and prewarm could never replace it again.+ if (reserveForRecording) existing.releaseRecordingReservation();+ throw error;+ }+ return existing;}- if (keepAliveSessionPromise && keepAliveSession?.key === key) {- return keepAliveSessionPromise;+ const joining = keepAliveSession;+ if (keepAliveSessionPromise && joining && joining.key === key) {+ // Joining an in-flight startup still has to claim it: without the+ // reservation a later prewarm would read isBusy() as false and dispose the+ // session out from under the recording that is waiting on this promise.+ if (!reserveForRecording) return keepAliveSessionPromise;+ joining.reserveForRecording();+ // stop() only runs for a startup that succeeded, so a rejected join has to+ // drop its own claim here or the session stays busy forever.+ return keepAliveSessionPromise.catch((error: unknown) => {+ joining.releaseRecordingReservation();+ throw error;+ });}if (keepAliveSessionPromise) {- await keepAliveSessionPromise.catch(() => undefined);+ let releasedReason: string | undefined;+ await keepAliveSessionPromise.catch((error: unknown) => {+ if (isKeepAliveSessionDisposedError(error)) {+ releasedReason = readErrorString(error, 'reason') ?? 'dispose';+ }+ });+ // The in-flight session we were queued behind was torn down. Propagate the+ // original reason so callers can still tell a power release (build nothing,+ // the one-shot event has passed) from a setup change (fall through and+ // rebuild). Building a replacement after a power release would open the+ // microphone with nothing left to close it until the idle timeout.+ if (releasedReason !== undefined && DO_NOT_REBUILD_REASONS.has(releasedReason)) {+ throw new KeepAliveSessionDisposedError(releasedReason);+ }}if (keepAliveSession) {+ // A different device/profile is a fresh warm-up, not a continuation of the+ // previous idle window.await keepAliveSession.dispose('replaced');keepAliveSession = null;+ keepAliveIdleDeadlineAt = undefined;}const session = new KeepAliveMicSession(options);+ if (reserveForRecording) session.reserveForRecording();keepAliveSession = session;keepAliveSessionPromise = session.start().then(() => session).catch((error) => {if (keepAliveSession === session) keepAliveSession = null;+ if (reserveForRecording) session.releaseRecordingReservation();throw error;}).finally(() => {@@ -470,9 +807,34 @@ async function getOrCreateKeepAliveSession(options: KeepAliveSessionOptions): Pr}export async function prewarmVoiceInputMicrophone(options: WebMicAudioEngineOptions): Promise<void> {- const session = await getOrCreateKeepAliveSession(normalizeKeepAliveOptions(options));+ const normalized = normalizeKeepAliveOptions(options);+ // Prewarm can land mid-dictation: another ChatInput mounts, or a settings+ // change fires while the overlay is recording. An active session must not be+ // touched at all — not deactivated, and not handed to+ // getOrCreateKeepAliveSession, whose replace path would dispose the very+ // track the user is speaking into when the device/profile changed. stop()+ // already owns both re-arming the idle window and honouring the new config.+ if (keepAliveSession?.isBusy()) {+ if (keepAliveSession.key !== keepAliveKey(normalized)) {+ keepAliveSession.markStaleForReplacement();+ }+ return;+ }+ let session: KeepAliveMicSession;+ try {+ session = await getOrCreateKeepAliveSession(normalized);+ } catch (error) {+ // Being released mid-startup is the user asking for it, not a failure.+ if (isKeepAliveSessionDisposedError(error)) return;+ throw error;+ }+ // Re-check after the await: a recording start racing on the *same*+ // keepAliveSessionPromise can resolve first and activate() this session.+ // Deactivating it here would send setActive=false, drop the PCM callback and+ // detach the output path while the UI still shows recording in progress.+ if (session.isActive()) return;session.deactivate();- scheduleKeepAliveIdleDispose(session, 'idle_timeout_after_prewarm');+ scheduleKeepAliveIdleDispose(session, 'idle_timeout_after_prewarm', { refresh: false });}export async function prewarmVoiceInputMicrophoneWithAutomaticFallback(@@ -495,7 +857,18 @@ export async function prewarmVoiceInputMicrophoneWithAutomaticFallback(}export async function disposeKeepAliveVoiceInputMicrophone(reason = 'dispose'): Promise<void> {+ // Turning the setting off, or a devicechange, must not throw away dictation+ // the user is in the middle of — that would turn a preference tweak into a+ // discarded recording. Mark it for replacement instead; stop() disposes it as+ // soon as the user is done. Power releases still take effect immediately:+ // there the user has already walked away.+ const active = keepAliveSession;+ if (active?.isActive() && !POWER_RELEASE_REASONS.has(reason)) {+ active.markStaleForReplacement();+ return;+ }clearKeepAliveIdleDisposeTimer();+ keepAliveIdleDeadlineAt = undefined;const session = keepAliveSession;keepAliveSession = null;keepAliveSessionPromise = null;@@ -518,18 +891,68 @@ function clearKeepAliveIdleDisposeTimer(): void {keepAliveIdleDisposeTimer = undefined;}-function scheduleKeepAliveIdleDispose(session: KeepAliveMicSession, reason: string): void {+/**+ * Monotonic clock for the idle deadline.+ *+ * The deadline is an absolute timestamp that prewarm keeps re-arming the timer+ * against, so a wall-clock jump backwards (NTP correction, manual change, DST+ * tooling) would silently stretch the remaining window and hold the microphone+ * past the 30 minutes the settings copy promises. performance.now() is immune+ * to that; Date.now() is only a fallback for environments without it.+ */+function keepAliveMonotonicNow(): number {+ return typeof performance !== 'undefined' && typeof performance.now === 'function'+ ? performance.now()+ : Date.now();+}++/**+ * Arm the bounded idle window that releases the warm microphone.+ *+ * `refresh` separates real dictation from bookkeeping. The user-facing copy+ * promises release after 30 minutes of *no use*, so only a finished recording+ * may restart the countdown. Prewarm runs on every ChatInput/overlay mount and+ * on unrelated voice settings changes; letting those extend the deadline kept+ * the microphone — and the OS privacy indicator — on forever on a machine the+ * user was simply working in.+ */+function scheduleKeepAliveIdleDispose(+ session: KeepAliveMicSession,+ reason: string,+ { refresh }: { refresh: boolean },+): void {+ // The caller may have been suspended across an await while a power release+ // (or a device change) swapped the session out. Mutating the shared timer and+ // deadline from a session that is no longer current would cancel the live+ // session's countdown and leave a deadline that outlives its owner.+ if (keepAliveSession !== session) return;clearKeepAliveIdleDisposeTimer();- // Fast activation intentionally keeps the MediaStream warm only for a bounded- // idle window. This preserves the next-use latency win without leaving the- // OS microphone indicator on indefinitely after the user stops dictating.+ const now = keepAliveMonotonicNow();+ if (!refresh && keepAliveIdleDeadlineAt !== undefined && keepAliveIdleDeadlineAt <= now) {+ // The window already elapsed; the timer just has not fired yet (renderer+ // timers are throttled in background windows). A bookkeeping call must not+ // resurrect it into another full window — release now, which is what the+ // overdue timer was about to do anyway.+ keepAliveIdleDeadlineAt = undefined;+ keepAliveSession = null;+ keepAliveSessionPromise = null;+ void session.dispose('idle_timeout_expired');+ return;+ }+ if (refresh || keepAliveIdleDeadlineAt === undefined) {+ keepAliveIdleDeadlineAt = now + KEEP_ALIVE_MIC_IDLE_TTL_MS;+ }+ const deadlineAt = keepAliveIdleDeadlineAt;keepAliveIdleDisposeTimer = window.setTimeout(() => {keepAliveIdleDisposeTimer = undefined;+ // A recording that started before the deadline keeps the session; stop()+ // re-arms with refresh so the full window starts after the user is done.if (keepAliveSession !== session || session.isActive()) return;+ keepAliveIdleDeadlineAt = undefined;keepAliveSession = null;keepAliveSessionPromise = null;void session.dispose(reason);- }, KEEP_ALIVE_MIC_IDLE_TTL_MS);+ }, Math.max(0, deadlineAt - now));}/**@@ -598,6 +1021,12 @@ export class WebMicAudioEngine {return;} catch (error) {if (isSelectedMicrophoneUnavailableError(error)) throw error;+ // Only a *power* release ends the attempt. Falling through to the cold+ // getUserMedia() below after a suspend/lock would open a brand-new+ // stream once that one-shot event has passed, with nothing left to+ // close it. Other releases (devicechange, setting turned off) must keep+ // falling through — the user is still here and still dictating.+ if (isPowerReleaseCancellation(error)) throw error;this.onStateChange?.('keep_alive_unavailable', {error: error instanceof Error ? error.message : String(error),});@@ -713,11 +1142,24 @@ export class WebMicAudioEngine {this.clearWatchdog();if (this.usingKeepAliveSession) {const session = this.keepAliveSession;- session?.deactivate();- if (session?.isStaleAfterDeviceChange()) {- await disposeKeepAliveVoiceInputMicrophone('devicechange_after_recording');- } else if (session) {- scheduleKeepAliveIdleDispose(session, 'idle_timeout_after_recording');+ // Drop the claim taken in startKeepAlive, then only tear the session down+ // if nobody else still holds one. deactivate() clears the shared PCM+ // callback, sends setActive=false and detaches the output path — doing+ // that while another engine is still recording would starve it of audio+ // and trip its stall watchdog.+ session?.releaseRecordingReservation();+ // Everything below tears down shared state, so it may only run for the+ // last holder. Disposing a stale session while another engine still has a+ // reservation would stop the very track it is recording from.+ if (session && !session.hasRecordingReservations()) {+ session.deactivate();+ if (session.isStaleAfterDeviceChange()) {+ await disposeKeepAliveVoiceInputMicrophone('devicechange_after_recording');+ } else {+ // Real use just ended — this is the only event allowed to restart the+ // full 30-minute window the settings copy promises.+ scheduleKeepAliveIdleDispose(session, 'idle_timeout_after_recording', { refresh: true });+ }}this.keepAliveSession = undefined;this.usingKeepAliveSession = false;@@ -778,20 +1220,33 @@ export class WebMicAudioEngine {chunkMs: this.chunkMs,audioProcessing: this.audioProcessing,latencyMs: this.latencyMs,- });- this.keepAliveSession = session;- this.usingKeepAliveSession = true;- this.context = session.context;- this.stream = session.stream;- clearKeepAliveIdleDisposeTimer();- session.activate({- callback: (chunk) => {- this.lastAudioFrameAt = Date.now();- this.pcmCallback(chunk);- },- onStateChange: this.onStateChange,- onInterrupted: (message) => this.interrupt(message),- });+ }, { reserveForRecording: true });+ try {+ this.keepAliveSession = session;+ this.usingKeepAliveSession = true;+ this.context = session.context;+ this.stream = session.stream;+ clearKeepAliveIdleDisposeTimer();+ session.activate({+ callback: (chunk) => {+ this.lastAudioFrameAt = Date.now();+ this.pcmCallback(chunk);+ },+ onStateChange: this.onStateChange,+ onInterrupted: (message) => this.interrupt(message),+ });+ } catch (error) {+ // activate() rejects a session disposed between the await above and here.+ // stop() will never run for this engine, so the claim has to be dropped+ // now — otherwise the session stays "busy" forever and no prewarm could+ // ever replace it.+ session.releaseRecordingReservation();+ this.keepAliveSession = undefined;+ this.usingKeepAliveSession = false;+ this.context = undefined;+ this.stream = undefined;+ throw error;+ }this.onStateChange?.('keep_alive_microphone_started', {chunkMs: this.chunkMs,contextState: this.context?.state,@@ -1055,6 +1510,9 @@ function flushWorkletBufferedAudio(worklet?: AudioWorkletNode): Promise<void> {if (import.meta.hot) {import.meta.hot.dispose(() => {+ keepAlivePowerReleaseUnsubscribe?.();+ keepAlivePowerReleaseUnsubscribe = undefined;+ keepAlivePowerReleaseListening = false;void disposeKeepAliveVoiceInputMicrophone('hmr');});}diff --git a/apps/desktop/src/renderer/voice-input/__tests__/WebMicAudioEngine.keepAliveIdle.test.ts b/apps/desktop/src/renderer/voice-input/__tests__/WebMicAudioEngine.keepAliveIdle.test.tsnew file mode 100644index 0000000000..a2f5f1775f--- /dev/null+++ b/apps/desktop/src/renderer/voice-input/__tests__/WebMicAudioEngine.keepAliveIdle.test.ts@@ -0,0 +1,484 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('../audioContextPool', () => ({+ PCM16K_WORKLET_NAME: 'pcm16k-worklet',+ prewarmVoiceInputAudio: vi.fn(),+}));++type EngineModule = typeof import('../WebMicAudioEngine');+type PowerCallback = (payload: { reason: 'system_suspend' | 'screen_locked' }) => void;++const WORKLET_URL = 'https://app.local/pcm16k-worklet.js';+const IDLE_TTL_MS = 30 * 60 * 1000;++type FakeTrack = MediaStreamTrack & { stopped: boolean };++function createFakeTrack(): FakeTrack {+ const track = {+ label: 'keep-alive microphone',+ enabled: true,+ muted: false,+ readyState: 'live',+ stopped: false,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ getSettings: () => ({ deviceId: 'default' }),+ stop: (): void => undefined,+ };+ track.stop = (): void => {+ track.stopped = true;+ };+ return track as unknown as FakeTrack;+}++/**+ * The keep-alive session is module-level state, so every case re-imports the+ * engine to start from a clean slate. Without this the process-wide power+ * listener flag would leak across cases and silently skip the subscription.+ */+describe('keep-alive microphone idle window', () => {+ let mod: EngineModule;+ let track: FakeTrack;+ let sink: { connect: ReturnType<typeof vi.fn>; disconnect: ReturnType<typeof vi.fn>; gain: { value: number } };+ let destination: object;+ let powerCallback: PowerCallback | undefined;+ let getUserMedia: ReturnType<typeof vi.fn>;++ beforeEach(async () => {+ vi.useFakeTimers();+ track = createFakeTrack();+ powerCallback = undefined;+ getUserMedia = vi.fn(async () => ({+ getAudioTracks: () => [track],+ getTracks: () => [track],+ }));+ sink = { connect: vi.fn(), disconnect: vi.fn(), gain: { value: 1 } };+ destination = { connect: vi.fn(), disconnect: vi.fn() };++ vi.stubGlobal('navigator', {+ mediaDevices: {+ enumerateDevices: vi.fn(async () => [{ kind: 'audioinput', deviceId: 'default' }]),+ getUserMedia,+ addEventListener: vi.fn(),+ },+ });+ vi.stubGlobal('window', {+ setTimeout: globalThis.setTimeout,+ clearTimeout: globalThis.clearTimeout,+ setInterval: globalThis.setInterval,+ clearInterval: globalThis.clearInterval,+ electronAPI: {+ voiceInput: {+ onPowerStateChange: (callback: PowerCallback) => {+ powerCallback = callback;+ return () => undefined;+ },+ },+ },+ });+ vi.stubGlobal('AudioWorkletNode', vi.fn().mockImplementation(() => ({+ connect: vi.fn(),+ disconnect: vi.fn(),+ port: { close: vi.fn(), postMessage: vi.fn(), onmessage: null },+ })));++ vi.resetModules();+ const pool = await import('../audioContextPool');+ vi.mocked(pool.prewarmVoiceInputAudio).mockResolvedValue({+ context: {+ currentTime: 0,+ state: 'running',+ destination,+ createGain: vi.fn(() => sink),+ createMediaStreamSource: vi.fn(() => ({ connect: vi.fn(), disconnect: vi.fn() })),+ resume: vi.fn(async () => undefined),+ } as unknown as AudioContext,+ workletReady: Promise.resolve(),+ workletUrl: WORKLET_URL,+ });+ mod = await import('../WebMicAudioEngine');+ });++ afterEach(async () => {+ await mod.disposeKeepAliveVoiceInputMicrophone('test_cleanup');+ vi.useRealTimers();+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ });++ it('releases the warm microphone once the idle window elapses', async () => {+ await mod.prewarmVoiceInputMicrophone({ workletUrl: WORKLET_URL });+ expect(track.stopped).toBe(false);++ await vi.advanceTimersByTimeAsync(IDLE_TTL_MS);++ expect(track.stopped).toBe(true);+ });++ it('does not extend the idle window when prewarm re-asserts keep-alive intent', async () => {+ await mod.prewarmVoiceInputMicrophone({ workletUrl: WORKLET_URL });++ // A ChatInput mounting (or an unrelated voice setting changing) 20 minutes+ // in must not buy the microphone another full window — that regression kept+ // the device open indefinitely on a machine the user was simply working in.+ await vi.advanceTimersByTimeAsync(20 * 60 * 1000);+ await mod.prewarmVoiceInputMicrophone({ workletUrl: WORKLET_URL });+ expect(track.stopped).toBe(false);++ await vi.advanceTimersByTimeAsync(10 * 60 * 1000);++ expect(track.stopped).toBe(true);+ });++ it('restarts the full window after real dictation ends', async () => {+ await mod.prewarmVoiceInputMicrophone({ workletUrl: WORKLET_URL });+ await vi.advanceTimersByTimeAsync(20 * 60 * 1000);++ const engine = new mod.WebMicAudioEngine({+ workletUrl: WORKLET_URL,+ keepAlive: true,+ onInterrupted: vi.fn(),+ });+ await engine.start();+ await engine.stop();++ // 20 minutes into the previous window + 25 more: only a refreshed deadline+ // keeps the device alive here.+ await vi.advanceTimersByTimeAsync(25 * 60 * 1000);+ expect(track.stopped).toBe(false);++ await vi.advanceTimersByTimeAsync(5 * 60 * 1000);+ expect(track.stopped).toBe(true);+ });++ it('releases the microphone when the machine suspends or the screen locks', async () => {+ await mod.prewarmVoiceInputMicrophone({ workletUrl: WORKLET_URL });+ expect(powerCallback).toBeDefined();++ powerCallback?.({ reason: 'screen_locked' });+ await vi.advanceTimersByTimeAsync(0);++ expect(track.stopped).toBe(true);+ });++ it('stops a stream that arrives after the session was released mid-startup', async () => {+ let resolveStream: (value: unknown) => void = () => undefined;+ getUserMedia.mockImplementationOnce(() => new Promise((resolve) => {+ resolveStream = resolve;+ }));++ const prewarming = mod.prewarmVoiceInputMicrophone({ workletUrl: WORKLET_URL });+ // Let start() reach the pending getUserMedia await.+ await vi.advanceTimersByTimeAsync(0);+ expect(powerCallback).toBeDefined();++ // Screen locks while the device handshake is still in flight: dispose()+ // cannot stop a track that does not exist yet.+ powerCallback?.({ reason: 'screen_locked' });+ await vi.advanceTimersByTimeAsync(0);++ resolveStream({ getAudioTracks: () => [track], getTracks: () => [track] });+ await prewarming;++ // The late stream must not survive as an unreachable live microphone.+ expect(track.stopped).toBe(true);+ });++ it('does not fall back to a cold stream when startup is cancelled by a power release', async () => {+ let resolveStream: (value: unknown) => void = () => undefined;+ getUserMedia.mockImplementationOnce(() => new Promise((resolve) => {+ resolveStream = resolve;+ }));++ const engine = new mod.WebMicAudioEngine({+ workletUrl: WORKLET_URL,+ keepAlive: true,+ onInterrupted: vi.fn(),+ });+ const starting = engine.start();+ await vi.advanceTimersByTimeAsync(0);+ expect(powerCallback).toBeDefined();++ powerCallback?.({ reason: 'screen_locked' });+ await vi.advanceTimersByTimeAsync(0);+ resolveStream({ getAudioTracks: () => [track], getTracks: () => [track] });++ // The release must surface as cancellation. Treating it as "keep-alive+ // unavailable" would fall through to the cold getUserMedia() path and open+ // a second stream *after* the lock event — with nothing left to close it.+ await expect(starting).rejects.toThrow(/disposed/i);+ expect(getUserMedia).toHaveBeenCalledTimes(1);+ expect(track.stopped).toBe(true);+ });++ it('keeps an in-flight recording when the microphone config changes', async () => {+ const engine = new mod.WebMicAudioEngine({+ workletUrl: WORKLET_URL,+ keepAlive: true,+ onInterrupted: vi.fn(),+ });+ await engine.start();+ expect(track.stopped).toBe(false);++ // The user switches microphone in settings while still dictating. Rebuilding+ // the session now would stop the very track they are speaking into.+ await mod.prewarmVoiceInputMicrophone({ workletUrl: WORKLET_URL, deviceId: 'another-device' });++ expect(track.stopped).toBe(false);+ expect(getUserMedia).toHaveBeenCalledTimes(1);++ // The new config is honoured once dictation actually ends.+ await engine.stop();+ expect(track.stopped).toBe(true);+ });++ it('rejects startup when a release lands during context resume', async () => {+ let resolveResume: () => void = () => undefined;+ const pool = await import('../audioContextPool');+ vi.mocked(pool.prewarmVoiceInputAudio).mockResolvedValue({+ context: {+ currentTime: 0,+ // A suspended shared context makes startup await resume() — the last+ // await before the session reports success.+ state: 'suspended',+ destination,+ createGain: vi.fn(() => sink),+ createMediaStreamSource: vi.fn(() => ({ connect: vi.fn(), disconnect: vi.fn() })),+ resume: vi.fn(() => new Promise<void>((resolve) => {+ resolveResume = () => resolve();+ })),+ } as unknown as AudioContext,+ workletReady: Promise.resolve(),+ workletUrl: WORKLET_URL,+ });++ const engine = new mod.WebMicAudioEngine({+ workletUrl: WORKLET_URL,+ keepAlive: true,+ onInterrupted: vi.fn(),+ });+ const starting = engine.start();+ await vi.advanceTimersByTimeAsync(0);+ expect(powerCallback).toBeDefined();++ powerCallback?.({ reason: 'system_suspend' });+ await vi.advanceTimersByTimeAsync(0);+ resolveResume();++ // Reporting success here would hand the caller a session whose nodes were+ // already torn down: it emits no PCM and dies on the stall watchdog.+ await expect(starting).rejects.toThrow(/disposed/i);+ expect(track.stopped).toBe(true);+ });++ it('does not replace a session a recording is still starting on', async () => {+ let resolveStream: (value: unknown) => void = () => undefined;+ getUserMedia.mockImplementationOnce(() => new Promise((resolve) => {+ resolveStream = resolve;+ }));++ const engine = new mod.WebMicAudioEngine({+ workletUrl: WORKLET_URL,+ keepAlive: true,+ onInterrupted: vi.fn(),+ });+ const starting = engine.start();+ await vi.advanceTimersByTimeAsync(0);++ // The recording has not reached activate() yet, so the session is not+ // "active" — but it is being started *for* that recording. A prewarm with a+ // different device must not send it down the replace path.+ await mod.prewarmVoiceInputMicrophone({ workletUrl: WORKLET_URL, deviceId: 'another-device' });++ resolveStream({ getAudioTracks: () => [track], getTracks: () => [track] });+ await starting;++ expect(track.stopped).toBe(false);+ expect(getUserMedia).toHaveBeenCalledTimes(1);+ });++ it('replaces a prewarm-only session when the config changes mid warm-up', async () => {+ let resolveStream: (value: unknown) => void = () => undefined;+ getUserMedia.mockImplementationOnce(() => new Promise((resolve) => {+ resolveStream = resolve;+ }));++ const first = mod.prewarmVoiceInputMicrophone({ workletUrl: WORKLET_URL });+ await vi.advanceTimersByTimeAsync(0);++ // No recording is waiting on this background warm-up, so a config change+ // must actually swap it. Deferring here would strand the old device until+ // the idle timeout while the new one never gets warmed at all.+ const second = mod.prewarmVoiceInputMicrophone({ workletUrl: WORKLET_URL, deviceId: 'default' });++ resolveStream({ getAudioTracks: () => [track], getTracks: () => [track] });+ await first;+ await second;++ expect(getUserMedia).toHaveBeenCalledTimes(2);+ });++ it('reports cancellation when getUserMedia rejects after a release', async () => {+ let rejectStream: (error: unknown) => void = () => undefined;+ getUserMedia.mockImplementationOnce(() => new Promise((_resolve, reject) => {+ rejectStream = reject;+ }));++ const engine = new mod.WebMicAudioEngine({+ workletUrl: WORKLET_URL,+ keepAlive: true,+ onInterrupted: vi.fn(),+ });+ const starting = engine.start();+ await vi.advanceTimersByTimeAsync(0);+ expect(powerCallback).toBeDefined();++ powerCallback?.({ reason: 'system_suspend' });+ await vi.advanceTimersByTimeAsync(0);++ // Suspending the machine typically makes the pending request reject rather+ // than resolve. That must still read as cancellation, not as a device+ // failure worth retrying with a fresh cold stream.+ rejectStream(Object.assign(new Error('The request is not allowed'), { name: 'AbortError' }));++ await expect(starting).rejects.toThrow(/disposed/i);+ expect(getUserMedia).toHaveBeenCalledTimes(1);+ });++ it('interrupts an active recording when a power release disposes the session', async () => {+ const onInterrupted = vi.fn();+ const engine = new mod.WebMicAudioEngine({+ workletUrl: WORKLET_URL,+ keepAlive: true,+ onInterrupted,+ });+ await engine.start();++ powerCallback?.({ reason: 'system_suspend' });+ await vi.advanceTimersByTimeAsync(0);++ // Without this the renderer stays in 'listening' and main keeps owning the+ // ASR run until the audio watchdog fires — which during suspend does not+ // happen until the machine wakes up.+ expect(onInterrupted).toHaveBeenCalledTimes(1);+ expect(track.stopped).toBe(true);+ });++ it('reports cancellation when the shared context fails after a release', async () => {+ let rejectPool: (error: unknown) => void = () => undefined;+ const pool = await import('../audioContextPool');+ vi.mocked(pool.prewarmVoiceInputAudio).mockReturnValue(+ new Promise((_resolve, reject) => {+ rejectPool = reject;+ }) as ReturnType<typeof pool.prewarmVoiceInputAudio>,+ );++ const engine = new mod.WebMicAudioEngine({+ workletUrl: WORKLET_URL,+ keepAlive: true,+ onInterrupted: vi.fn(),+ });+ const starting = engine.start();+ await vi.advanceTimersByTimeAsync(0);+ expect(powerCallback).toBeDefined();++ powerCallback?.({ reason: 'screen_locked' });+ await vi.advanceTimersByTimeAsync(0);+ // Suspend can make AudioContext/worklet init reject too, not just resolve.+ rejectPool(new Error('AudioContext unavailable'));++ await expect(starting).rejects.toThrow(/disposed/i);+ expect(getUserMedia).not.toHaveBeenCalled();+ });++ it('falls through to the cold path when a non-power release cancels startup', async () => {+ let resolveStream: (value: unknown) => void = () => undefined;+ getUserMedia.mockImplementationOnce(() => new Promise((resolve) => {+ resolveStream = resolve;+ }));++ const engine = new mod.WebMicAudioEngine({+ workletUrl: WORKLET_URL,+ keepAlive: true,+ onInterrupted: vi.fn(),+ });+ const starting = engine.start();+ await vi.advanceTimersByTimeAsync(0);++ // Turning the setting off also releases the session — but the user is still+ // here and still dictating, so this must not abandon the attempt the way a+ // suspend/lock does.+ await mod.disposeKeepAliveVoiceInputMicrophone('setting_disabled');+ resolveStream({ getAudioTracks: () => [track], getTracks: () => [track] });++ await starting;+ expect(getUserMedia).toHaveBeenCalledTimes(2);+ });++ it('does not let a second recording steal the keep-alive session', async () => {+ const engineA = new mod.WebMicAudioEngine({+ workletUrl: WORKLET_URL,+ keepAlive: true,+ onInterrupted: vi.fn(),+ });+ const engineB = new mod.WebMicAudioEngine({+ workletUrl: WORKLET_URL,+ keepAlive: true,+ onInterrupted: vi.fn(),+ });+ await engineA.start();++ // A session carries exactly one PCM callback. B must not take it over — it+ // falls back to its own cold stream instead, leaving A's audio flowing.+ await engineB.start();++ expect(getUserMedia).toHaveBeenCalledTimes(2);+ expect(track.stopped).toBe(false);+ });++ it('shares one startup between concurrent callers', async () => {+ let resolveStream: (value: unknown) => void = () => undefined;+ getUserMedia.mockImplementationOnce(() => new Promise((resolve) => {+ resolveStream = resolve;+ }));++ // A recording start and a prewarm reach the same session while it is still+ // coming up. Each one re-entering start() would open a second MediaStream;+ // the first would then be overwritten by `this.stream` and never stopped.+ const engine = new mod.WebMicAudioEngine({+ workletUrl: WORKLET_URL,+ keepAlive: true,+ onInterrupted: vi.fn(),+ });+ const starting = engine.start();+ await vi.advanceTimersByTimeAsync(0);+ const prewarming = mod.prewarmVoiceInputMicrophone({ workletUrl: WORKLET_URL });+ await vi.advanceTimersByTimeAsync(0);++ resolveStream({ getAudioTracks: () => [track], getTracks: () => [track] });+ await starting;+ await prewarming;++ expect(getUserMedia).toHaveBeenCalledTimes(1);+ });++ it('keeps the audio output path detached while merely warm', async () => {+ await mod.prewarmVoiceInputMicrophone({ workletUrl: WORKLET_URL });++ // Warm but idle: dictation needs the input path only. Staying connected to+ // the destination is what made a warm microphone also hold a CoreAudio+ // output stream for the whole window.+ expect(sink.connect).not.toHaveBeenCalled();++ const engine = new mod.WebMicAudioEngine({+ workletUrl: WORKLET_URL,+ keepAlive: true,+ onInterrupted: vi.fn(),+ });+ await engine.start();+ expect(sink.connect).toHaveBeenCalledWith(destination);++ await engine.stop();+ expect(sink.disconnect).toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/renderer/voice-input/captureSession.ts b/apps/desktop/src/renderer/voice-input/captureSession.tsindex 4adca6553e..b05480e80b 100644--- a/apps/desktop/src/renderer/voice-input/captureSession.ts+++ b/apps/desktop/src/renderer/voice-input/captureSession.ts@@ -1,7 +1,10 @@import { createLogger } from '@/lib/logger';import {WebMicAudioEngine,+ currentPowerReleaseGeneration,+ isPowerReleaseCancellation,isSelectedMicrophoneUnavailableError,+ powerReleaseCancellation,type PcmChunk,} from './WebMicAudioEngine';import { createVoiceInputAudioProfile } from './audioProfile';@@ -22,6 +25,12 @@ export type VoiceInputCaptureSessionStartResult =| {ok: false;error: string;+ /**+ * Startup was cancelled rather than broken — currently only by a power+ * release (suspend / lock) landing mid-start. Callers should clean up+ * silently instead of surfacing `error`, which is an internal message.+ */+ cancelled?: boolean;};type VoiceInputCaptureSessionOptions = {@@ -95,6 +104,7 @@ export async function startVoiceInputCaptureSession(engine = createEngine(options.deviceId);options.setEngine(engine);+ const powerGenerationAtStart = currentPowerReleaseGeneration();const startEngineWithAutomaticFallback = async (): Promise<void> => {try {@@ -113,6 +123,13 @@ export async function startVoiceInputCaptureSession(stopError instanceof Error ? stopError.message : String(stopError),);});+ // A release can land during the stop() above, and by then no session error+ // carries the power reason any more — the check below would only see the+ // earlier device error and happily open the default microphone after the+ // one-shot event.+ if (currentPowerReleaseGeneration() !== powerGenerationAtStart) {+ throw powerReleaseCancellation();+ }engine = createEngine(undefined);options.setEngine(engine);await engine.start();@@ -125,6 +142,17 @@ export async function startVoiceInputCaptureSession(log.info(message(options.label, 'microphone started'), { elapsedMs: options.elapsedMs?.() });} catch (error) {options.setEngine(null);+ // Suspend/lock cancelling startup is the user walking away on purpose, not+ // a failure worth an error surface. Report it as cancellation so callers+ // clean up quietly instead of showing an internal message.+ if (isPowerReleaseCancellation(error)) {+ log.debug(message(options.label, 'microphone start cancelled by power release'));+ return {+ ok: false,+ cancelled: true,+ error: options.formatStartError(error),+ };+ }return {ok: false,error: options.formatStartError(error),diff --git a/apps/desktop/src/renderer/voice-input/useVoiceInput.ts b/apps/desktop/src/renderer/voice-input/useVoiceInput.tsindex 3c3b20bb5f..4bdd2ba6ad 100644--- a/apps/desktop/src/renderer/voice-input/useVoiceInput.ts+++ b/apps/desktop/src/renderer/voice-input/useVoiceInput.ts@@ -1070,35 +1070,41 @@ export function useVoiceInput(refinementEnabled: voiceInputSettings.refinementEnabled,}).catch(() => undefined);void prewarmVoiceInputAudio(workletUrl).catch(() => undefined);- if (voiceInputSettings.fastActivationEnabled) {- const permission = window.electronAPI.voiceInput.getMicrophonePermissionCached();- if (permission.ok) {- void prewarmVoiceInputMicrophoneWithAutomaticFallback(- {- workletUrl,- deviceId: voiceInputSettings.microphoneDeviceId ?? undefined,- ...createVoiceInputAudioProfile(true),- },- () => {- log.warn('fast activation selected microphone unavailable, prewarming automatic microphone');- },- ).catch((error) => {- log.warn('fast activation microphone prewarm failed', {- error: error instanceof Error ? error.message : String(error),- workletUrl,- hasDeviceId: Boolean(voiceInputSettings.microphoneDeviceId),- });- });- }- } else {+ if (import.meta.env.DEV) void prewarmVoiceInputBenchmarkFixture().catch(() => undefined);+ }, [voiceInputSettings.language, voiceInputSettings.refinementEnabled]);++ // Microphone keep-alive is deliberately a separate effect: unlike the prewarm+ // above it opens a real capture device and turns on the OS privacy indicator,+ // so it must not re-run for settings unrelated to the microphone. Language and+ // refinement changes used to re-assert keep-alive intent here, which kept the+ // device warm for reasons the user never asked for.+ useEffect(() => {+ if (disabledRef.current) return;+ if (!voiceInputSettings.fastActivationEnabled) {void disposeKeepAliveVoiceInputMicrophone('setting_disabled').catch(() => undefined);+ return;}- if (import.meta.env.DEV) void prewarmVoiceInputBenchmarkFixture().catch(() => undefined);+ const permission = window.electronAPI.voiceInput.getMicrophonePermissionCached();+ if (!permission.ok) return;+ void prewarmVoiceInputMicrophoneWithAutomaticFallback(+ {+ workletUrl,+ deviceId: voiceInputSettings.microphoneDeviceId ?? undefined,+ ...createVoiceInputAudioProfile(true),+ },+ () => {+ log.warn('fast activation selected microphone unavailable, prewarming automatic microphone');+ },+ ).catch((error) => {+ log.warn('fast activation microphone prewarm failed', {+ error: error instanceof Error ? error.message : String(error),+ workletUrl,+ hasDeviceId: Boolean(voiceInputSettings.microphoneDeviceId),+ });+ });}, [voiceInputSettings.fastActivationEnabled,- voiceInputSettings.language,voiceInputSettings.microphoneDeviceId,- voiceInputSettings.refinementEnabled,]);const start = useCallback(async () => {@@ -1236,6 +1242,22 @@ export function useVoiceInput(elapsedMs,});if (!captureStart.ok) {+ // 电源释放(锁屏/挂起)取消了启动:静默回收,不显示错误态 —— 用户是主动+ // 离开,内部的 disposed 消息不该出现在界面上。+ if (captureStart.cancelled) {+ log.debug('microphone start cancelled by power release');+ resolveStartReadyState(attemptId, { ok: false, error: captureStart.error });+ invalidateStartAttempt();+ void startResultPromise.then((result) => {+ if (result.ok) {+ void window.electronAPI.voiceInput.cancel({ runId: result.runId });+ }+ });+ await restoreSystemAudioForRecording();+ setVoiceState('idle');+ restoreEditorFocusAfterVoiceInput();+ return;+ }log.warn('microphone start failed:', captureStart.error);resolveStartReadyState(attemptId, { ok: false, error: captureStart.error });invalidateStartAttempt();diff --git a/apps/desktop/src/shared/voiceInputPowerIpc.ts b/apps/desktop/src/shared/voiceInputPowerIpc.tsnew file mode 100644index 0000000000..d030108b9a--- /dev/null+++ b/apps/desktop/src/shared/voiceInputPowerIpc.ts@@ -0,0 +1,22 @@+/**+ * 语音输入保活麦克风的电源事件契约(main → renderer 单向推送)。+ *+ * 放在 shared 是因为 main 广播端、preload bridge 与 renderer 订阅端必须共用同一+ * channel 名与 payload 形状;任意一处漂移都会退化成「订阅存在但永远收不到」的+ * 静默失效,而不是编译期错误。+ */++/** main → renderer 推送 channel。 */+export const VOICE_INPUT_POWER_STATE_CHANNEL = 'voice-input:power-state-change';++/**+ * 触发释放保活麦克风的系统电源事件。+ *+ * 只收录「用户已经离开」的事件。resume / unlock-screen 不在此列:回来后是否重新+ * 预热由 renderer 既有的 prewarm 路径决定,不需要额外推送来驱动。+ */+export type VoiceInputPowerReleaseReason = 'system_suspend' | 'screen_locked';++export interface VoiceInputPowerStatePayload {+ reason: VoiceInputPowerReleaseReason;+}