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): 电源释放同样关闭非保活的采集流 (#383)
Dash3399769148ff
diff --git a/apps/desktop/src/renderer/voice-input/WebMicAudioEngine.ts b/apps/desktop/src/renderer/voice-input/WebMicAudioEngine.tsindex c161b1503d..58f64bebba 100644--- a/apps/desktop/src/renderer/voice-input/WebMicAudioEngine.ts+++ b/apps/desktop/src/renderer/voice-input/WebMicAudioEngine.ts@@ -131,10 +131,49 @@ const DO_NOT_REBUILD_REASONS: ReadonlySet<string> = new Set([*/let powerReleaseGeneration = 0;+/**+ * Engines capturing outside the keep-alive session (fast activation off, or a+ * cold fallback). A power release only tears down the module-level keep-alive+ * session, so without this registry those streams would keep the microphone —+ * and the privacy indicator — open until the user comes back.+ */+const liveDirectCaptureEngines = new Set<WebMicAudioEngine>();++function releaseDirectCaptureEngines(reason: string): void {+ for (const engine of [...liveDirectCaptureEngines]) {+ engine.releaseForPowerEvent(reason);+ }+}+export function currentPowerReleaseGeneration(): number {return powerReleaseGeneration;}+/**+ * Tear down everything this module instance owns, for the HMR swap.+ *+ * Bumping the generation first is what covers acquisitions that are still+ * awaiting enumeration or getUserMedia: they have not reached+ * liveDirectCaptureEngines yet, so releasing the registry alone would let them+ * resolve afterwards and register into this *disposed* module's set — where the+ * replacement module's power listener can never reach them, leaving the+ * microphone open across a later suspend.+ *+ * Exported for the tests; the dev-only `import.meta.hot` block below is the+ * real caller.+ */+export function disposeVoiceInputAudioModuleForHmr(): Promise<void> {+ powerReleaseGeneration += 1;+ keepAlivePowerReleaseUnsubscribe?.();+ keepAlivePowerReleaseUnsubscribe = undefined;+ keepAlivePowerReleaseListening = false;+ // React Fast Refresh can keep the component and its engine ref alive across+ // the swap, and the new module instance has an empty registry — so without+ // this the old direct stream stays live with nothing able to reach it.+ releaseDirectCaptureEngines('hmr');+ return disposeKeepAliveVoiceInputMicrophone('hmr');+}+export function isPowerReleaseCancellation(error: unknown): boolean {if (!isKeepAliveSessionDisposedError(error)) return false;const reason = readErrorString(error, 'reason');@@ -372,8 +411,9 @@ function ensureKeepAliveDeviceChangeListener(): void {* 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.+ * above: one process-wide subscription, never torn down. Installed lazily by+ * whichever capture starts first — the keep-alive session *or* a direct+ * (keepAlive: false) capture, which relies on it just as much.*/function ensureKeepAlivePowerReleaseListener(): void {if (keepAlivePowerReleaseListening) return;@@ -385,6 +425,7 @@ function ensureKeepAlivePowerReleaseListener(): void {// so one lock event would fan out to N stale callbacks.keepAlivePowerReleaseUnsubscribe = subscribe((payload) => {powerReleaseGeneration += 1;+ releaseDirectCaptureEngines(payload.reason);void disposeKeepAliveVoiceInputMicrophone(payload.reason);});}@@ -1036,6 +1077,14 @@ export class WebMicAudioEngine {this.interrupted = false;this.ready = false;this.lastAudioFrameAt = Date.now();+ // Also needed on this path: with fast activation off no keep-alive session+ // is ever created, so this would otherwise be the only capture in the+ // renderer and nothing would subscribe to power releases.+ ensureKeepAlivePowerReleaseListener();+ // The registry below only covers engines that finished starting. A release+ // landing mid-startup would not see this one, so snapshot the generation+ // and re-check at each point where a live device could survive.+ const powerGenerationAtStart = currentPowerReleaseGeneration();const audio = buildMediaConstraints({deviceId: this.deviceId,@@ -1051,63 +1100,106 @@ export class WebMicAudioEngine {const benchmarkFixturePromise = BENCHMARK_FIXTURE_ENABLED? prewarmVoiceInputBenchmarkFixture().catch(() => null): Promise.resolve(null);- await assertSelectedMicrophoneAvailable(this.deviceId);- const streamPromise = navigator.mediaDevices.getUserMedia({- audio,- video: false,- }).catch((error) => {+ await this.awaitDirectStartupStep(+ assertSelectedMicrophoneAvailable(this.deviceId),+ powerGenerationAtStart,+ );+ // The enumeration above passed its own check, but a release can land in the+ // gap before we ask for the device. Without this the request would be made+ // after the one-shot event and only be closed once it resolves.+ this.assertNoPowerReleaseDuringStartup(powerGenerationAtStart);+ const streamPromise = this.awaitDirectStartupStep(+ navigator.mediaDevices.getUserMedia({+ audio,+ video: false,+ }),+ powerGenerationAtStart,+ (stream) => stream.getTracks().forEach((track) => track.stop()),+ ).catch((error) => {+ // A release that won this race takes priority: suspend routinely makes+ // the pending request reject (AbortError / NotReadableError), and+ // reporting that as a device failure would make captureSession show an+ // error instead of following its silent power-cancellation path.+ if (isPowerReleaseCancellation(error)) throw error;throw normalizeMicrophoneStartError(error, this.deviceId);});- this.stream = await streamPromise;- this.stream.getAudioTracks().forEach((track) => this.watchTrack(track));- this.onStateChange?.('stream_started', {- tracks: this.stream.getAudioTracks().map((track) => ({- label: track.label,- enabled: track.enabled,- muted: track.muted,- readyState: track.readyState,- settings: track.getSettings(),- })),- });+ const directStream = await streamPromise;+ // Assigned before the guarded section so the cleanup below can reach it.+ this.stream = directStream;+ // Registered immediately, not at the end of startup: every await below+ // (context warmup, worklet module, resume) can stay pending for the whole+ // suspend, and the power callback can only traverse this registry. Failure+ // paths remove it again through stop().+ liveDirectCaptureEngines.add(this);+ try {+ this.assertNoPowerReleaseDuringStartup(powerGenerationAtStart);+ this.stream.getAudioTracks().forEach((track) => this.watchTrack(track));+ this.onStateChange?.('stream_started', {+ tracks: this.stream.getAudioTracks().map((track) => ({+ label: track.label,+ enabled: track.enabled,+ muted: track.muted,+ readyState: track.readyState,+ settings: track.getSettings(),+ })),+ });- const sharedState = await sharedContextPromise;- if (sharedState) {- this.context = sharedState.context;- this.usingSharedContext = true;- this.onStateChange?.('shared_audio_context_used', {+ const sharedState = await sharedContextPromise;+ if (sharedState) {+ this.context = sharedState.context;+ this.usingSharedContext = true;+ this.onStateChange?.('shared_audio_context_used', {+ state: this.context.state,+ sampleRate: this.context.sampleRate,+ });+ } else {+ this.context = new AudioContext();+ this.usingSharedContext = false;+ }+ this.context.onstatechange = () => {+ this.onStateChange?.('context_state_changed', {+ state: this.context?.state,+ sampleRate: this.context?.sampleRate,+ });+ if (this.ready && !this.stopped && this.context?.state !== 'running') {+ this.interrupt(`Microphone audio context stopped (${this.context?.state ?? 'unknown'}). Please try again.`);+ }+ };+ this.onStateChange?.('context_created', {state: this.context.state,sampleRate: this.context.sampleRate,});- } else {- this.context = new AudioContext();- this.usingSharedContext = false;- }- this.context.onstatechange = () => {- this.onStateChange?.('context_state_changed', {- state: this.context?.state,- sampleRate: this.context?.sampleRate,- });- if (this.ready && !this.stopped && this.context?.state !== 'running') {- this.interrupt(`Microphone audio context stopped (${this.context?.state ?? 'unknown'}). Please try again.`);++ // Benchmark mode still starts the real MediaStream above so the measurement+ // includes OS microphone permission/device startup. Only the bytes sent to+ // ASR are replaced with deterministic fixture audio, keeping latency A/B+ // runs comparable without asking a human to repeat the exact same phrase.+ const benchmarkFixture = await benchmarkFixturePromise;+ if (benchmarkFixture) {+ this.onStateChange?.('benchmark_fixture_ready', {+ path: benchmarkFixture.path,+ sourceSampleRate: benchmarkFixture.sampleRate,+ durationMs: Math.round(benchmarkFixture.durationMs),+ });+ if (this.context.state !== 'running') {+ await this.context.resume();+ }+ this.onStateChange?.('context_ready', {+ state: this.context.state,+ sampleRate: this.context.sampleRate,+ });+ this.assertNoPowerReleaseDuringStartup(powerGenerationAtStart);+ this.ready = true;+ this.startWatchdog();+ void this.playBenchmarkFixture(benchmarkFixture);+ return;}- };- this.onStateChange?.('context_created', {- state: this.context.state,- sampleRate: this.context.sampleRate,- });- // Benchmark mode still starts the real MediaStream above so the measurement- // includes OS microphone permission/device startup. Only the bytes sent to- // ASR are replaced with deterministic fixture audio, keeping latency A/B- // runs comparable without asking a human to repeat the exact same phrase.- const benchmarkFixture = await benchmarkFixturePromise;- if (benchmarkFixture) {- this.onStateChange?.('benchmark_fixture_ready', {- path: benchmarkFixture.path,- sourceSampleRate: benchmarkFixture.sampleRate,- durationMs: Math.round(benchmarkFixture.durationMs),- });+ this.sink = this.context.createGain();+ this.sink.gain.value = 0;+ this.source = this.context.createMediaStreamSource(this.stream);+ await this.connectProcessor();if (this.context.state !== 'running') {await this.context.resume();}@@ -1115,28 +1207,93 @@ export class WebMicAudioEngine {state: this.context.state,sampleRate: this.context.sampleRate,});+ this.assertNoPowerReleaseDuringStartup(powerGenerationAtStart);this.ready = true;this.startWatchdog();- void this.playBenchmarkFixture(benchmarkFixture);- return;+ } catch (error) {+ // Callers treat a power cancellation as silent, so they will never call+ // stop() themselves. Do it here: it closes the device and the non-shared+ // AudioContext, clears the track listeners, and removes this engine from+ // liveDirectCaptureEngines (which it joined right after acquisition).+ await this.stop().catch(() => undefined);+ if (currentPowerReleaseGeneration() !== powerGenerationAtStart) {+ throw powerReleaseCancellation();+ }+ throw error;}+ }- this.sink = this.context.createGain();- this.sink.gain.value = 0;- this.source = this.context.createMediaStreamSource(this.stream);- await this.connectProcessor();- if (this.context.state !== 'running') {- await this.context.resume();+ /**+ * Await one direct-startup step, letting an in-flight power release win.+ *+ * Mirrors KeepAliveMicSession.awaitStartupStep: the raw error would send the+ * caller down its device-failure paths (error surface, or automatic fallback+ * to the default microphone) after the one-shot event has already passed.+ */+ private async awaitDirectStartupStep<T>(+ step: Promise<T>,+ generationAtStart: number,+ disposeValue?: (value: T) => void,+ ): Promise<T> {+ try {+ const value = await step;+ // Fulfilled awaits matter as much as rejected ones: a successful device+ // enumeration would otherwise let us call getUserMedia *after* the+ // one-shot release, reopening the microphone while the user is away.+ if (currentPowerReleaseGeneration() !== generationAtStart) {+ disposeValue?.(value);+ throw powerReleaseCancellation();+ }+ return value;+ } catch (error) {+ if (+ currentPowerReleaseGeneration() !== generationAtStart &&+ !isPowerReleaseCancellation(error)+ ) {+ throw powerReleaseCancellation();+ }+ throw error;+ }+ }++ /**+ * Check for a release at the synchronous points no await can cover: right+ * before opening the device, and right before flipping `ready` (which is what+ * makes the release path treat this engine as an interruptible recording).+ */+ private assertNoPowerReleaseDuringStartup(generationAtStart: number): void {+ if (currentPowerReleaseGeneration() === generationAtStart) return;+ throw powerReleaseCancellation();+ }++ /**+ * Suspend / lock reached us while capturing outside the keep-alive session.+ * Interrupt the caller so it cancels its ASR run, then close the stream —+ * the keep-alive release path cannot see this one.+ */+ releaseForPowerEvent(reason: string): void {+ this.onStateChange?.('direct_capture_power_release', { reason });+ // Only a capture that actually reached `ready` is a live recording worth+ // interrupting. One still starting up is registered (so its device can be+ // closed here) but must surface as a *silent* cancellation through+ // start()'s generation check — both UIs wire onInterrupted to their+ // active-recording failure path, and that visible error cannot be undone+ // by the cancellation that follows.+ if (this.ready) {+ this.interrupt('Microphone input stopped unexpectedly. Please try again.');}- this.onStateChange?.('context_ready', {- state: this.context.state,- sampleRate: this.context.sampleRate,+ void this.stop().catch((error: unknown) => {+ // Detached on purpose (the power callback must not await teardown), so an+ // AudioContext.close() failure here would otherwise surface as an+ // unhandled rejection.+ this.onStateChange?.('direct_capture_power_release_stop_failed', {+ error: error instanceof Error ? error.message : String(error),+ });});- this.ready = true;- this.startWatchdog();}async stop(): Promise<void> {+ liveDirectCaptureEngines.delete(this);this.stopped = true;this.ready = false;this.clearWatchdog();@@ -1510,9 +1667,6 @@ function flushWorkletBufferedAudio(worklet?: AudioWorkletNode): Promise<void> {if (import.meta.hot) {import.meta.hot.dispose(() => {- keepAlivePowerReleaseUnsubscribe?.();- keepAlivePowerReleaseUnsubscribe = undefined;- keepAlivePowerReleaseListening = false;- void disposeKeepAliveVoiceInputMicrophone('hmr');+ void disposeVoiceInputAudioModuleForHmr();});}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.tsindex a2f5f1775f..3f25b72867 100644--- a/apps/desktop/src/renderer/voice-input/__tests__/WebMicAudioEngine.keepAliveIdle.test.ts+++ b/apps/desktop/src/renderer/voice-input/__tests__/WebMicAudioEngine.keepAliveIdle.test.ts@@ -436,6 +436,246 @@ describe('keep-alive microphone idle window', () => {expect(track.stopped).toBe(false);});+ it('does not open the microphone when enumeration outlives a power release', async () => {+ let resolveEnumerate: (value: unknown) => void = () => undefined;+ vi.stubGlobal('navigator', {+ mediaDevices: {+ enumerateDevices: vi.fn(() => new Promise((resolve) => {+ resolveEnumerate = resolve;+ })),+ getUserMedia,+ addEventListener: vi.fn(),+ },+ });++ const engine = new mod.WebMicAudioEngine({+ workletUrl: WORKLET_URL,+ keepAlive: false,+ deviceId: 'specific-device',+ onInterrupted: vi.fn(),+ });+ const starting = engine.start();+ await vi.advanceTimersByTimeAsync(0);+ expect(powerCallback).toBeDefined();++ powerCallback?.({ reason: 'screen_locked' });+ await vi.advanceTimersByTimeAsync(0);+ // Enumeration succeeds *after* the release, reporting the device as present.+ resolveEnumerate([{ kind: 'audioinput', deviceId: 'specific-device' }]);++ await expect(starting).rejects.toThrow(/disposed/i);+ // The one-shot event has passed; nothing may reopen the device now.+ expect(getUserMedia).not.toHaveBeenCalled();+ });++ it('does not report an error when a release hits a still-starting capture', async () => {+ let resolvePool: (value: unknown) => void = () => undefined;+ const pool = await import('../audioContextPool');+ vi.mocked(pool.prewarmVoiceInputAudio).mockReturnValue(+ new Promise((resolve) => {+ resolvePool = resolve as (value: unknown) => void;+ }) as ReturnType<typeof pool.prewarmVoiceInputAudio>,+ );+ const onInterrupted = vi.fn();++ const engine = new mod.WebMicAudioEngine({+ workletUrl: WORKLET_URL,+ keepAlive: false,+ onInterrupted,+ });+ const starting = engine.start();+ await vi.advanceTimersByTimeAsync(0);++ powerCallback?.({ reason: 'screen_locked' });+ await vi.advanceTimersByTimeAsync(0);++ // The device must be closed, but a capture that never reached `ready` has+ // to surface as a silent cancellation: both UIs route onInterrupted to+ // their active-recording failure path, and that error would outlive the+ // cancellation that follows.+ expect(track.stopped).toBe(true);+ expect(onInterrupted).not.toHaveBeenCalled();++ resolvePool({+ context: {+ currentTime: 0,+ state: 'running',+ destination,+ createGain: vi.fn(() => sink),+ createMediaStreamSource: vi.fn(() => ({ connect: vi.fn(), disconnect: vi.fn() })),+ resume: vi.fn(async () => undefined),+ },+ workletReady: Promise.resolve(),+ workletUrl: WORKLET_URL,+ });+ await expect(starting).rejects.toThrow(/disposed/i);+ });++ it('can release a stream acquired before context warmup settles', async () => {+ let resolvePool: (value: unknown) => void = () => undefined;+ const pool = await import('../audioContextPool');+ vi.mocked(pool.prewarmVoiceInputAudio).mockReturnValue(+ new Promise((resolve) => {+ resolvePool = resolve as (value: unknown) => void;+ }) as ReturnType<typeof pool.prewarmVoiceInputAudio>,+ );++ const engine = new mod.WebMicAudioEngine({+ workletUrl: WORKLET_URL,+ keepAlive: false,+ onInterrupted: vi.fn(),+ });+ const starting = engine.start();+ // getUserMedia has resolved; the shared context warmup is still pending and+ // could stay that way for the whole suspend.+ await vi.advanceTimersByTimeAsync(0);+ expect(powerCallback).toBeDefined();++ powerCallback?.({ reason: 'system_suspend' });+ await vi.advanceTimersByTimeAsync(0);++ // The device is already open, so the release must reach it now rather than+ // waiting for warmup to settle.+ expect(track.stopped).toBe(true);++ resolvePool({+ context: {+ currentTime: 0,+ state: 'running',+ destination,+ createGain: vi.fn(() => sink),+ createMediaStreamSource: vi.fn(() => ({ connect: vi.fn(), disconnect: vi.fn() })),+ resume: vi.fn(async () => undefined),+ },+ workletReady: Promise.resolve(),+ workletUrl: WORKLET_URL,+ });+ await starting.catch(() => undefined);+ });++ it('reports cancellation when direct 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: false,+ onInterrupted: vi.fn(),+ });+ const starting = engine.start();+ await vi.advanceTimersByTimeAsync(0);+ expect(powerCallback).toBeDefined();++ powerCallback?.({ reason: 'system_suspend' });+ await vi.advanceTimersByTimeAsync(0);+ // Suspend routinely makes the pending request reject rather than resolve.+ // That must read as cancellation, not as a device failure worth surfacing.+ rejectStream(Object.assign(new Error('The request is not allowed'), { name: 'AbortError' }));++ await expect(starting).rejects.toThrow(/disposed/i);+ });++ it('stops the direct stream when a later startup step fails', async () => {+ const pool = await import('../audioContextPool');+ vi.mocked(pool.prewarmVoiceInputAudio).mockResolvedValue({+ context: {+ currentTime: 0,+ state: 'suspended',+ destination,+ createGain: vi.fn(() => sink),+ createMediaStreamSource: vi.fn(() => ({ connect: vi.fn(), disconnect: vi.fn() })),+ resume: vi.fn(async () => {+ throw new Error('resume failed');+ }),+ } as unknown as AudioContext,+ workletReady: Promise.resolve(),+ workletUrl: WORKLET_URL,+ });++ const engine = new mod.WebMicAudioEngine({+ workletUrl: WORKLET_URL,+ keepAlive: false,+ onInterrupted: vi.fn(),+ });++ // The device is already open by the time this step fails. Whether or not+ // the engine reached the registry, the failure path has to close it.+ await expect(engine.start()).rejects.toThrow(/resume failed/i);+ expect(track.stopped).toBe(true);+ });++ it('aborts a direct startup interrupted 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: false,+ onInterrupted: vi.fn(),+ });+ const starting = engine.start();+ await vi.advanceTimersByTimeAsync(0);+ expect(powerCallback).toBeDefined();++ // The lock lands while the device handshake is still pending, so this+ // engine is not in the registry yet and the one-shot callback cannot see+ // it. Startup must abort itself rather than come up after the event.+ powerCallback?.({ reason: 'screen_locked' });+ await vi.advanceTimersByTimeAsync(0);+ resolveStream({ getAudioTracks: () => [track], getTracks: () => [track] });++ await expect(starting).rejects.toThrow(/disposed/i);+ expect(track.stopped).toBe(true);+ });++ it('stops a direct stream that arrives after an HMR swap', async () => {+ let resolveStream: (value: unknown) => void = () => undefined;+ getUserMedia.mockImplementationOnce(() => new Promise((resolve) => {+ resolveStream = resolve;+ }));++ const engine = new mod.WebMicAudioEngine({+ workletUrl: WORKLET_URL,+ keepAlive: false,+ onInterrupted: vi.fn(),+ });+ const starting = engine.start();+ await vi.advanceTimersByTimeAsync(0);++ // Vite swaps the module while the device handshake is still pending. The+ // engine has not reached the registry, so releasing the registry alone+ // would let the stream arrive afterwards and open the microphone inside a+ // module whose power listener is already gone.+ await mod.disposeVoiceInputAudioModuleForHmr();+ resolveStream({ getAudioTracks: () => [track], getTracks: () => [track] });++ await expect(starting).rejects.toThrow(/disposed/i);+ expect(track.stopped).toBe(true);+ });++ it('releases a direct capture stream on a power event', async () => {+ const onInterrupted = vi.fn();+ // fast activation off: this capture never touches the keep-alive session,+ // so only the direct-engine registry can close it on suspend/lock.+ const engine = new mod.WebMicAudioEngine({+ workletUrl: WORKLET_URL,+ keepAlive: false,+ onInterrupted,+ });+ await engine.start();+ expect(powerCallback).toBeDefined();++ powerCallback?.({ reason: 'system_suspend' });+ await vi.advanceTimersByTimeAsync(0);++ expect(onInterrupted).toHaveBeenCalled();+ expect(track.stopped).toBe(true);+ });+it('shares one startup between concurrent callers', async () => {let resolveStream: (value: unknown) => void = () => undefined;getUserMedia.mockImplementationOnce(() => new Promise((resolve) => {