Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 按住功能键时加入修饰键不再误触发松键
Dash19d393d3a609
diff --git a/apps/desktop/native/voice-input/windows-function-key-listener/src/main.rs b/apps/desktop/native/voice-input/windows-function-key-listener/src/main.rsindex ba4155285d..bf14dbff17 100644--- a/apps/desktop/native/voice-input/windows-function-key-listener/src/main.rs+++ b/apps/desktop/native/voice-input/windows-function-key-listener/src/main.rs@@ -72,9 +72,8 @@ mod windows_listener {}}- if key_down && ACTIVE.load(Ordering::Relaxed) && modifier_bit != 0 {- ACTIVE.store(false, Ordering::Relaxed);- emit_pressed(false);+ if key_down && ACTIVE.swap(false, Ordering::Relaxed) && modifier_bit != 0 {+ emit_canceled();}if event.vkCode == target_vk {@@ -153,6 +152,10 @@ mod windows_listener {});}+ fn emit_canceled() {+ emit_line("{\"type\":\"canceled\"}");+ }+fn emit_error(message: &str) {let escaped = message.replace('\\', "\\\\").replace('"', "\\\"");emit_line(&format!("{{\"type\":\"error\",\"message\":\"{escaped}\"}}"));diff --git a/apps/desktop/src/main/voice-input/MacModifierShortcutListener.ts b/apps/desktop/src/main/voice-input/MacModifierShortcutListener.tsindex 44c63c98b4..50024f5927 100644--- a/apps/desktop/src/main/voice-input/MacModifierShortcutListener.ts+++ b/apps/desktop/src/main/voice-input/MacModifierShortcutListener.ts@@ -501,6 +501,7 @@ export class MacModifierShortcutListener {if (isVoiceInputBareFunctionKeyShortcut(shortcut)) {this.functionKeyPhaseController.setPressed(isVoiceInputMacNativeKeyboardShortcutPressed(keys, shortcut),+ isVoiceInputMacNativeKeyboardShortcutTargetDown(keys, shortcut),);return;}diff --git a/apps/desktop/src/main/voice-input/ShortcutHoldPhaseController.ts b/apps/desktop/src/main/voice-input/ShortcutHoldPhaseController.tsindex 1c5119d974..4a8340efe3 100644--- a/apps/desktop/src/main/voice-input/ShortcutHoldPhaseController.ts+++ b/apps/desktop/src/main/voice-input/ShortcutHoldPhaseController.ts@@ -18,15 +18,23 @@ export class ShortcutHoldPhaseController {private readonly holdDelayMs: number;private down = false;private holdThresholdReached = false;+ private canceledUntilRelease = false;private holdTimer: NodeJS.Timeout | null = null;constructor(private readonly options: ShortcutHoldPhaseControllerOptions) {this.holdDelayMs = options.holdDelayMs ?? DEFAULT_HOLD_DELAY_MS;}- setPressed(pressed: boolean): void {- if (pressed === this.down) return;+ /**+ * @param pressed whether the exact configured chord is currently down+ * @param targetDown whether the target key itself is still physically held.+ * When the chord is broken by another key (e.g. F16 + Shift), callers pass+ * `pressed=false` with `targetDown=true` so this press is cancelled instead+ * of being treated as a tap or a submit.+ */+ setPressed(pressed: boolean, targetDown = pressed): void {if (pressed) {+ if (this.canceledUntilRelease || this.down) return;this.down = true;this.holdThresholdReached = false;this.options.onTrigger('start');@@ -37,18 +45,32 @@ export class ShortcutHoldPhaseController {return;}- const shouldTap = !this.holdThresholdReached;- this.clearHoldTimer();- this.down = false;- this.holdThresholdReached = false;- this.options.onTrigger(shouldTap ? 'tap' : 'end');+ if (this.down) {+ this.clearHoldTimer();+ this.down = false;+ const shouldTap = !this.holdThresholdReached;+ this.holdThresholdReached = false;+ if (targetDown) {+ this.canceledUntilRelease = true;+ return;+ }+ this.canceledUntilRelease = false;+ this.options.onTrigger(shouldTap ? 'tap' : 'end');+ return;+ }++ if (!targetDown) this.canceledUntilRelease = false;}releaseIfPressed(): void {- if (!this.down) return;+ if (!this.down) {+ this.canceledUntilRelease = false;+ return;+ }this.clearHoldTimer();this.down = false;this.holdThresholdReached = false;+ this.canceledUntilRelease = false;this.options.onTrigger('end');}@@ -56,6 +78,7 @@ export class ShortcutHoldPhaseController {this.clearHoldTimer();this.down = false;this.holdThresholdReached = false;+ this.canceledUntilRelease = false;}private clearHoldTimer(): void {diff --git a/apps/desktop/src/main/voice-input/WindowsFunctionKeyShortcutListener.ts b/apps/desktop/src/main/voice-input/WindowsFunctionKeyShortcutListener.tsindex 1a358125a2..3237585fe7 100644--- a/apps/desktop/src/main/voice-input/WindowsFunctionKeyShortcutListener.ts+++ b/apps/desktop/src/main/voice-input/WindowsFunctionKeyShortcutListener.ts@@ -22,6 +22,7 @@ const START_TIMEOUT_MS = 3_000;const RESTART_MAX_ATTEMPTS = 3;const RESTART_BASE_DELAY_MS = 1_000;const RESTART_MAX_DELAY_MS = 5_000;+const RESTART_STABLE_MS = 10_000;export type WindowsFunctionKeyListenerStartResult ={ ok: true } | { ok: false; error: string; superseded?: true };@@ -54,6 +55,7 @@ export class WindowsFunctionKeyShortcutListener {private startGeneration = 0;private restartAttempts = 0;private restartTimer: NodeJS.Timeout | null = null;+ private stableTimer: NodeJS.Timeout | null = null;private readonly phaseController: ShortcutHoldPhaseController;constructor(options: WindowsFunctionKeyShortcutListenerOptions) {@@ -74,6 +76,7 @@ export class WindowsFunctionKeyShortcutListener {this.shortcutCode = shortcut.code;this.restartAttempts = 0;this.clearRestartTimer();+ this.clearStableTimer();this.stopChildKeepingShortcut();return this.startChildProcess(shortcut.code);}@@ -90,6 +93,7 @@ export class WindowsFunctionKeyShortcutListener {// than only clearing the TypeScript phase controller.this.restartAttempts = 0;this.clearRestartTimer();+ this.clearStableTimer();this.stopChildKeepingShortcut();void this.startChildProcess(code).then((result) => {@@ -112,6 +116,7 @@ export class WindowsFunctionKeyShortcutListener {this.shortcutCode = null;this.restartAttempts = 0;this.clearRestartTimer();+ this.clearStableTimer();this.stopChildKeepingShortcut();}@@ -154,7 +159,10 @@ export class WindowsFunctionKeyShortcutListener {const stale =generation !== this.startGeneration || this.child !== child || this.shortcutCode !== code;const outcome = stale ? supersededStart() : result;- if (result.ok && !stale) this.ready = true;+ if (result.ok && !stale) {+ this.ready = true;+ this.armStableTimer();+ }if (!result.ok && this.child === child) {this.child = null;this.ready = false;@@ -200,6 +208,7 @@ export class WindowsFunctionKeyShortcutListener {if (wasCurrentChild) {this.child = null;this.ready = false;+ this.clearStableTimer();this.phaseController.releaseIfPressed();this.phaseController.reset();}@@ -244,6 +253,10 @@ export class WindowsFunctionKeyShortcutListener {});return;}+ if (payload.type === 'canceled' && this.child === child) {+ this.phaseController.setPressed(false, true);+ return;+ }if (payload.type === 'pressed' &&typeof payload.pressed === 'boolean' &&@@ -282,9 +295,7 @@ export class WindowsFunctionKeyShortcutListener {.then((result) => {if (!result.ok) {this.scheduleRestart(code, null, null);- return;}- this.restartAttempts = 0;}).catch((error: unknown) => {log.warn('Windows function key listener restart crashed', {@@ -301,6 +312,20 @@ export class WindowsFunctionKeyShortcutListener {clearTimeout(this.restartTimer);this.restartTimer = null;}++ private armStableTimer(): void {+ this.clearStableTimer();+ this.stableTimer = setTimeout(() => {+ this.stableTimer = null;+ this.restartAttempts = 0;+ }, RESTART_STABLE_MS);+ }++ private clearStableTimer(): void {+ if (!this.stableTimer) return;+ clearTimeout(this.stableTimer);+ this.stableTimer = null;+ }}async function resolveWindowsFunctionKeyListenerBinary(): Promise<string> {diff --git a/apps/desktop/src/main/voice-input/__tests__/MacModifierShortcutListenerStartRace.test.ts b/apps/desktop/src/main/voice-input/__tests__/MacModifierShortcutListenerStartRace.test.tsindex 631b215068..1454c92e56 100644--- a/apps/desktop/src/main/voice-input/__tests__/MacModifierShortcutListenerStartRace.test.ts+++ b/apps/desktop/src/main/voice-input/__tests__/MacModifierShortcutListenerStartRace.test.ts@@ -289,6 +289,13 @@ describe('MacModifierShortcutListener start race', () => {mocks.stdoutDataHandlers[0]?.('{"type":"keys","keys":[]}\n');expect(onTrigger.mock.calls.map(([phase]) => phase)).toEqual(['start', 'tap']);+ onTrigger.mockClear();+ mocks.stdoutDataHandlers[0]?.('{"type":"keys","keys":["Function:F24"]}\n');+ mocks.stdoutDataHandlers[0]?.('{"type":"keys","keys":["Function:F24","ShiftLeft"]}\n');+ mocks.stdoutDataHandlers[0]?.('{"type":"keys","keys":["Function:F24"]}\n');+ mocks.stdoutDataHandlers[0]?.('{"type":"keys","keys":[]}\n');+ expect(onTrigger.mock.calls.map(([phase]) => phase)).toEqual(['start']);+onTrigger.mockClear();mocks.stdoutDataHandlers[0]?.('{"type":"keys","keys":["Function:F24"]}\n');mocks.spawnedChildren[0].get('exit')?.(1, null);diff --git a/apps/desktop/src/main/voice-input/__tests__/ShortcutHoldPhaseController.test.ts b/apps/desktop/src/main/voice-input/__tests__/ShortcutHoldPhaseController.test.tsindex 4c7fd07620..86da73bd0b 100644--- a/apps/desktop/src/main/voice-input/__tests__/ShortcutHoldPhaseController.test.ts+++ b/apps/desktop/src/main/voice-input/__tests__/ShortcutHoldPhaseController.test.ts@@ -55,4 +55,30 @@ describe('ShortcutHoldPhaseController', () => {expect(onTrigger.mock.calls.map(([phase]) => phase)).toEqual(['start', 'end']);});++ it('cancels a held chord when another key joins, then waits for the real key-up', () => {+ const onTrigger = vi.fn();+ const controller = new ShortcutHoldPhaseController({ onTrigger });++ controller.setPressed(true, true);+ controller.setPressed(false, true);+ controller.setPressed(true, true);+ controller.setPressed(false, false);++ expect(onTrigger.mock.calls.map(([phase]) => phase)).toEqual(['start']);+ });++ it('starts a new activation only after the cancelled target key is released', () => {+ const onTrigger = vi.fn();+ const controller = new ShortcutHoldPhaseController({ onTrigger });++ controller.setPressed(true, true);+ controller.setPressed(false, true);+ controller.setPressed(false, false);+ controller.setPressed(true, true);+ vi.advanceTimersByTime(450);+ controller.setPressed(false, false);++ expect(onTrigger.mock.calls.map(([phase]) => phase)).toEqual(['start', 'start', 'end']);+ });});diff --git a/apps/desktop/src/main/voice-input/__tests__/WindowsFunctionKeyShortcutListener.test.ts b/apps/desktop/src/main/voice-input/__tests__/WindowsFunctionKeyShortcutListener.test.tsindex 3843ff6756..ec865c84f8 100644--- a/apps/desktop/src/main/voice-input/__tests__/WindowsFunctionKeyShortcutListener.test.ts+++ b/apps/desktop/src/main/voice-input/__tests__/WindowsFunctionKeyShortcutListener.test.ts@@ -110,6 +110,23 @@ describe('WindowsFunctionKeyShortcutListener', () => {listener.stop();});+ it('cancels an active press when a modifier joins and waits for the real key-up', async () => {+ const { WindowsFunctionKeyShortcutListener } =+ await import('../WindowsFunctionKeyShortcutListener.js');+ const onTrigger = vi.fn();+ const listener = new WindowsFunctionKeyShortcutListener({ onTrigger });+ await startReady(listener);+ const child = mocks.spawnedChildren[0];++ child.stdoutData('{"type":"pressed","pressed":true}\n');+ child.stdoutData('{"type":"canceled"}\n');+ child.stdoutData('{"type":"pressed","pressed":true}\n');+ child.stdoutData('{"type":"pressed","pressed":false}\n');++ expect(onTrigger.mock.calls.map(([phase]) => phase)).toEqual(['start']);+ listener.stop();+ });+it('ends a held activation and restarts the helper on a system release', async () => {const { WindowsFunctionKeyShortcutListener } =await import('../WindowsFunctionKeyShortcutListener.js');@@ -144,4 +161,27 @@ describe('WindowsFunctionKeyShortcutListener', () => {expect(onTrigger.mock.calls.map(([phase]) => phase)).toEqual(['start', 'end']);listener.stop();});++ it('stops restarting after consecutive post-ready crashes before the listener is stable', async () => {+ vi.useFakeTimers();+ const { WindowsFunctionKeyShortcutListener } =+ await import('../WindowsFunctionKeyShortcutListener.js');+ const listener = new WindowsFunctionKeyShortcutListener({ onTrigger: vi.fn() });+ const starting = listener.setShortcut(f2Shortcut);+ await vi.advanceTimersByTimeAsync(0);+ mocks.spawnedChildren.at(-1)?.stdoutData('{"type":"ready"}\n');+ await expect(starting).resolves.toMatchObject({ ok: true });++ for (let attempt = 0; attempt < 3; attempt += 1) {+ mocks.spawnedChildren.at(-1)?.handlers.get('exit')?.(1, null);+ await vi.advanceTimersByTimeAsync(5_000);+ mocks.spawnedChildren.at(-1)?.stdoutData('{"type":"ready"}\n');+ await vi.advanceTimersByTimeAsync(0);+ }++ mocks.spawnedChildren.at(-1)?.handlers.get('exit')?.(1, null);+ await vi.advanceTimersByTimeAsync(5_000);+ expect(mocks.spawn).toHaveBeenCalledTimes(4);+ listener.stop();+ });});diff --git a/apps/desktop/src/main/voice-input/__tests__/globalShortcut.test.ts b/apps/desktop/src/main/voice-input/__tests__/globalShortcut.test.tsindex 2721510869..d0d99a5408 100644--- a/apps/desktop/src/main/voice-input/__tests__/globalShortcut.test.ts+++ b/apps/desktop/src/main/voice-input/__tests__/globalShortcut.test.ts@@ -392,7 +392,7 @@ describe('voice input global shortcut registration', () => {);});- it('uses the Windows low-level listener for F16 without Electron registration', async () => {+ it('uses the Windows low-level listener for F16 and Electron only to reserve the key', async () => {setPlatform('win32');const { registerGlobalVoiceInputIpc } = await import('../global.js');registerGlobalVoiceInputIpc(mocks.ipcDeps);@@ -408,7 +408,10 @@ describe('voice input global shortcut registration', () => {await setShortcut?.({}, f16Shortcut);expect(mocks.windowsSetShortcut).toHaveBeenCalledWith(f16Shortcut);- expect(mocks.registeredShortcuts.has('F16')).toBe(false);+ expect(mocks.registeredShortcuts.has('F16')).toBe(true);++ mocks.registeredShortcuts.get('F16')?.();+ expect(mocks.focusedWindow.webContents.send).not.toHaveBeenCalled();mocks.windowsListenerOptions.onTrigger?.('start');expect(mocks.focusedWindow.webContents.send).toHaveBeenCalledWith(@@ -417,6 +420,27 @@ describe('voice input global shortcut registration', () => {);});+ it('rejects a Windows F-key that another app already owns', async () => {+ setPlatform('win32');+ mocks.registerShortcut.mockImplementationOnce(() => false);+ const { registerGlobalVoiceInputIpc } = await import('../global.js');+ registerGlobalVoiceInputIpc(mocks.ipcDeps);+ const setShortcut = mocks.handlers.get('voice-input:global-shortcut:set');+ const f16Shortcut: VoiceInputShortcut = {+ trigger: 'keyboard',+ code: 'F16',+ key: 'F16',+ modifiers: { meta: false, ctrl: false, alt: false, shift: false, fn: false },+ };++ mocks.setStoredShortcut(f16Shortcut);+ const result = await setShortcut?.({}, f16Shortcut);++ expect(result).toMatchObject({ ok: false });+ expect(mocks.windowsSetShortcut).not.toHaveBeenCalled();+ expect(mocks.registeredShortcuts.has('F16')).toBe(false);+ });+it('releases both native listener states on system power transitions', async () => {setPlatform('darwin');const { releaseActiveGlobalVoiceInputShortcut } = await import('../global.js');diff --git a/apps/desktop/src/main/voice-input/global.ts b/apps/desktop/src/main/voice-input/global.tsindex 44c076600b..1785dbe81b 100644--- a/apps/desktop/src/main/voice-input/global.ts+++ b/apps/desktop/src/main/voice-input/global.ts@@ -1697,10 +1697,29 @@ async function setVoiceInputGlobalShortcut(if (voiceInputShortcutNeedsWindowsNativeListener(shortcut, process.platform)) {const nativeShortcutKey = stableVoiceInputShortcutKey(shortcut);+ const reservationAccelerator = toElectronAccelerator(shortcut);+ if (!reservationAccelerator) {+ return { ok: false, error: 'Unsupported voice input shortcut.' };+ }+ const reservedNewAccelerator = registeredAccelerator !== reservationAccelerator;+ if (+ reservedNewAccelerator &&+ !globalShortcut.register(reservationAccelerator, () => {+ // Native press/release owns start/tap/end. Electron only reserves the+ // bare F-key so another app cannot claim it first.+ })+ ) {+ log.warn('Windows global shortcut reservation failed', { accelerator: reservationAccelerator });+ return {+ ok: false,+ error: `Global shortcut is already in use: ${reservationAccelerator}`,+ };+ }if (registeredNativeShortcutKey === nativeShortcutKey &&windowsFunctionKeyShortcutListener.isReady()) {+ if (reservedNewAccelerator) registeredAccelerator = reservationAccelerator;return { ok: true };}const previousShortcut = registeredShortcut;@@ -1708,9 +1727,11 @@ async function setVoiceInputGlobalShortcut(windowsFunctionKeyShortcutListener.setShortcut(shortcut),);if (!result.ok && result.superseded) {+ if (reservedNewAccelerator) globalShortcut.unregister(reservationAccelerator);return { ok: false, error: result.error, errorCode: 'superseded' };}if (!result.ok) {+ if (reservedNewAccelerator) globalShortcut.unregister(reservationAccelerator);if (previousShortcut &&voiceInputShortcutNeedsWindowsNativeListener(previousShortcut, process.platform)@@ -1735,10 +1756,10 @@ async function setVoiceInputGlobalShortcut(errorCode: 'failed',};}- if (registeredAccelerator) {+ if (registeredAccelerator && registeredAccelerator !== reservationAccelerator) {globalShortcut.unregister(registeredAccelerator);- registeredAccelerator = null;}+ registeredAccelerator = reservationAccelerator;registeredShortcut = shortcut;registeredNativeShortcutLabel = getNativeShortcutLogLabel(shortcut);registeredNativeShortcutKey = nativeShortcutKey;