Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(voice-input): 保活窗口按最后使用时刻计算,录音结束统一记一次使用

Leng Jingxuc43b6927c855
diff --git a/apps/desktop/src/renderer/voice-input/WebMicAudioEngine.ts b/apps/desktop/src/renderer/voice-input/WebMicAudioEngine.ts
index 4a3a2d0c81..d7276d1c8b 100644
--- a/apps/desktop/src/renderer/voice-input/WebMicAudioEngine.ts
+++ b/apps/desktop/src/renderer/voice-input/WebMicAudioEngine.ts
@@ -445,6 +445,11 @@ function ensureKeepAlivePowerReleaseListener(): void {
powerReleaseGeneration += 1;
releaseDirectCaptureEngines(payload.reason);
void disposeKeepAliveVoiceInputMicrophone(payload.reason);
+ // Suspend / lock means the user walked away, so the fast-activation window
+ // ends here as well: coming back half an hour later must not relight the
+ // microphone from a stale "last use", and stop() triggered by this release
+ // (which runs synchronously above) must not count as a fresh dictation.
+ lastVoiceInputUseAt = undefined;
});
}
@@ -1057,6 +1062,21 @@ function isWithinVoiceInputUseWindow(): boolean {
return keepAliveMonotonicNow() - lastVoiceInputUseAt <= KEEP_ALIVE_MIC_IDLE_TTL_MS;
}
+/**
+ * When does the current idle window end?
+ *
+ * Always 30 minutes after the last real dictation, never 30 minutes after
+ * "now". A session is routinely rebuilt inside the window (devicechange,
+ * automatic-fallback microphone, a stale session replaced on the next press);
+ * anchoring to `now` would hand the user a fresh window he never asked for —
+ * dictating at minute 0 and switching devices at minute 29 would keep the
+ * indicator lit until minute 59.
+ */
+function keepAliveDeadlineAfterLastUse(now: number): number {
+ const useAt = lastVoiceInputUseAt ?? now;
+ return useAt + KEEP_ALIVE_MIC_IDLE_TTL_MS;
+}
+
/**
* Arm the bounded idle window that releases the warm microphone.
*
@@ -1091,7 +1111,7 @@ function scheduleKeepAliveIdleDispose(
return;
}
if (refresh || keepAliveIdleDeadlineAt === undefined) {
- keepAliveIdleDeadlineAt = now + KEEP_ALIVE_MIC_IDLE_TTL_MS;
+ keepAliveIdleDeadlineAt = keepAliveDeadlineAfterLastUse(now);
}
const deadlineAt = keepAliveIdleDeadlineAt;
keepAliveIdleDisposeTimer = window.setTimeout(() => {
@@ -1148,6 +1168,11 @@ export class WebMicAudioEngine {
// session reuses it for fast startup.
private usingSharedContext = false;
private usingKeepAliveSession = false;
+ // Power-release generation when this capture started. A release during capture
+ // means the user walked away, so the forced stop() that follows must not be
+ // recorded as a fresh dictation (it would resurrect the use window the release
+ // listener just cleared).
+ private powerGenerationAtStart = 0;
private pcmCallback: (chunk: PcmChunk) => void = () => {};
constructor(options: WebMicAudioEngineOptions) {
@@ -1169,6 +1194,7 @@ export class WebMicAudioEngine {
async start(): Promise<void> {
if (this.context) return;
+ this.powerGenerationAtStart = currentPowerReleaseGeneration();
if (this.keepAlive) {
try {
await this.startKeepAlive();
@@ -1410,9 +1436,19 @@ export class WebMicAudioEngine {
async stop(): Promise<void> {
liveDirectCaptureEngines.delete(this);
+ const wasRecording = this.ready;
this.stopped = true;
this.ready = false;
this.clearWatchdog();
+ // A recording that actually delivered audio just ended — that is "use" on
+ // every path: the keep-alive session that stays warm, the one released after
+ // a devicechange, and direct capture. Recording this only on the
+ // keep-alive-stays branch left the other two timing from the *start* of the
+ // recording, so fast activation silently expired early for them. A capture
+ // interrupted by suspend/lock is not use: the user walked away.
+ if (wasRecording && currentPowerReleaseGeneration() === this.powerGenerationAtStart) {
+ noteVoiceInputUse();
+ }
if (this.usingKeepAliveSession) {
const session = this.keepAliveSession;
if (this.releaseAfterUse) session?.markStaleForReplacement();
@@ -1432,9 +1468,8 @@ export class WebMicAudioEngine {
} else {
// Real use just ended — this is the only event allowed to restart the
// full 30-minute window the settings copy promises. The use timestamp
- // moves with it, so "last use" and the idle deadline (which starts at
- // the *end* of a recording) never disagree about when the window ends.
- noteVoiceInputUse();
+ // has already moved in stop(), so the idle deadline and "last use"
+ // never disagree about when the window ends.
scheduleKeepAliveIdleDispose(session, 'idle_timeout_after_recording', { refresh: true });
}
}
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.ts
index 898b1146b9..80145fdb76 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
@@ -182,6 +182,47 @@ describe('keep-alive microphone idle window', () => {
expect(getUserMedia).not.toHaveBeenCalled();
});
+ it('keeps the original deadline when the session is rebuilt late in the window', async () => {
+ mod.noteVoiceInputUse();
+ await mod.prewarmVoiceInputMicrophone({ workletUrl: WORKLET_URL });
+ await vi.advanceTimersByTimeAsync(29 * 60 * 1000);
+
+ // A devicechange released the warm session 29 minutes in. The next mount may
+ // rebuild it, but the window still ends 30 minutes after the last dictation —
+ // anchoring to "now" would keep the indicator lit until minute 59 for a user
+ // who never spoke again.
+ await mod.disposeKeepAliveVoiceInputMicrophone('devicechange');
+ track.stopped = false;
+ await mod.prewarmVoiceInputMicrophone({ workletUrl: WORKLET_URL });
+ expect(getUserMedia).toHaveBeenCalledTimes(2);
+ expect(track.stopped).toBe(false);
+
+ await vi.advanceTimersByTimeAsync(59 * 1000);
+ expect(track.stopped).toBe(false);
+
+ await vi.advanceTimersByTimeAsync(2 * 1000);
+ expect(track.stopped).toBe(true);
+ });
+
+ it('refreshes the window when a direct capture recording ends', async () => {
+ mod.noteVoiceInputUse();
+ await vi.advanceTimersByTimeAsync(25 * 60 * 1000);
+
+ const engine = new mod.WebMicAudioEngine({ workletUrl: WORKLET_URL, keepAlive: false });
+ await engine.start();
+ await vi.advanceTimersByTimeAsync(10 * 60 * 1000);
+ await engine.stop();
+
+ // 35 minutes after that recording *started*, but only 20 after it ended: the
+ // window must have been refreshed by the stop, or fast activation would have
+ // silently expired. The use timestamp used to move only on the
+ // keep-alive-stays branch.
+ await vi.advanceTimersByTimeAsync(20 * 60 * 1000);
+ await mod.prewarmVoiceInputMicrophone({ workletUrl: WORKLET_URL });
+
+ expect(getUserMedia).toHaveBeenCalledTimes(2);
+ });
+
it('reopens the warm microphone from a later mount inside the use window', async () => {
mod.noteVoiceInputUse();
await mod.prewarmVoiceInputMicrophone({ workletUrl: WORKLET_URL });
diff --git a/apps/desktop/src/renderer/voice-input/__tests__/useVoiceInput.startup.test.ts b/apps/desktop/src/renderer/voice-input/__tests__/useVoiceInput.startup.test.ts
index b9b64c5f28..ef81892f06 100644
--- a/apps/desktop/src/renderer/voice-input/__tests__/useVoiceInput.startup.test.ts
+++ b/apps/desktop/src/renderer/voice-input/__tests__/useVoiceInput.startup.test.ts
@@ -188,7 +188,12 @@ describe('local voice capture independent of startup checks and cloud', () => {
await act(async () => {
await vi.advanceTimersByTimeAsync(COMPOSER_LONG_PRESS_VOICE_INPUT_MS);
});
- expect(h.api.prewarm).toHaveBeenCalledOnce();
+ // A short click never reaches the hold threshold, so neither the capture
+ // device nor the main-side prewarm runs: prepare() is only invoked after the
+ // hold is recognized (see composerLongPressGesture). The previous assertion
+ // here expected one prewarm call, which the implementation has not done since
+ // prepare() moved behind the hold threshold.
+ expect(h.api.prewarm).not.toHaveBeenCalled();
// Opening even an authorized device can switch Bluetooth headphones to call audio.
expect(mocks.prepareMicrophone).not.toHaveBeenCalled();
expect(mocks.startEngine).not.toHaveBeenCalled();