Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 启动时采样已按下的普通键,并按全部 Rust 源判断 helper 是否过期
Dash5197249ed743
diff --git a/apps/desktop/native/voice-input/windows-function-key-listener/src/keys.rs b/apps/desktop/native/voice-input/windows-function-key-listener/src/keys.rsnew file mode 100644index 0000000000..4a3b8a0a21--- /dev/null+++ b/apps/desktop/native/voice-input/windows-function-key-listener/src/keys.rs@@ -0,0 +1,105 @@+//! Physical keyboard-set helpers shared by the hook and startup snapshot.+//!+//! The hook only sees later events. Helper start / restart must seed the same+//! sets from the current physical key state, or an already-held ordinary key+//! looks like "no other keys" and a later F-keydown is treated as a bare press.++pub fn modifier_bit(vk: u32) -> u32 {+ match vk {+ 0x10 => 1 << 0, // VK_SHIFT+ 0xA0 => 1 << 1, // VK_LSHIFT+ 0xA1 => 1 << 2, // VK_RSHIFT+ 0x11 => 1 << 3, // VK_CONTROL+ 0xA2 => 1 << 4, // VK_LCONTROL+ 0xA3 => 1 << 5, // VK_RCONTROL+ 0x12 => 1 << 6, // VK_MENU+ 0xA4 => 1 << 7, // VK_LMENU+ 0xA5 => 1 << 8, // VK_RMENU+ 0x5B => 1 << 9, // VK_LWIN+ 0x5C => 1 << 10, // VK_RWIN+ _ => 0,+ }+}++pub fn other_key_slot(vk: u32) -> Option<(usize, u64)> {+ if !is_trackable_other_key(vk) {+ return None;+ }+ Some((vk as usize / 64, 1 << (vk % 64)))+}++pub fn is_trackable_other_key(vk: u32) -> bool {+ vk < 256 && !is_mouse_button(vk) && modifier_bit(vk) == 0+}++pub fn apply_other_key(slots: &mut [u64; 4], vk: u32, down: bool) {+ let Some((index, bit)) = other_key_slot(vk) else {+ return;+ };+ if down {+ slots[index] |= bit;+ } else {+ slots[index] &= !bit;+ }+}++pub fn seed_other_key_slots(target_vk: u32, is_down: impl Fn(u32) -> bool) -> [u64; 4] {+ let mut slots = [0u64; 4];+ for vk in 0u32..256 {+ if vk == target_vk || !is_trackable_other_key(vk) {+ continue;+ }+ if is_down(vk) {+ apply_other_key(&mut slots, vk, true);+ }+ }+ slots+}++pub fn any_slot_down(slots: &[u64; 4]) -> bool {+ slots.iter().any(|slot| *slot != 0)+}++fn is_mouse_button(vk: u32) -> bool {+ matches!(vk, 0x01..=0x06)+}++#[cfg(test)]+mod tests {+ use super::*;++ const VK_A: u32 = 0x41;+ const VK_F1: u32 = 0x70;+ const VK_F16: u32 = 0x7F;+ const VK_LSHIFT: u32 = 0xA0;+ const VK_LBUTTON: u32 = 0x01;++ #[test]+ fn seed_includes_already_held_ordinary_keys() {+ let slots = seed_other_key_slots(VK_F16, |vk| vk == VK_A);+ assert!(any_slot_down(&slots));+ let mut expected = [0u64; 4];+ apply_other_key(&mut expected, VK_A, true);+ assert_eq!(slots, expected);+ }++ #[test]+ fn seed_ignores_modifiers_mouse_and_the_target_key() {+ let slots =+ seed_other_key_slots(VK_F16, |vk| matches!(vk, VK_LSHIFT | VK_LBUTTON | VK_F16));+ assert!(!any_slot_down(&slots));+ }++ #[test]+ fn seed_tracks_other_function_keys() {+ let slots = seed_other_key_slots(VK_F16, |vk| vk == VK_F1);+ assert!(any_slot_down(&slots));+ }++ #[test]+ fn mouse_buttons_are_not_trackable_other_keys() {+ assert!(other_key_slot(VK_LBUTTON).is_none());+ assert!(other_key_slot(VK_A).is_some());+ assert!(other_key_slot(VK_LSHIFT).is_none());+ }+}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 431f516692..37719d7cec 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@@ -1,4 +1,6 @@#[cfg(any(windows, test))]+mod keys;+#[cfg(any(windows, test))]mod press;#[cfg(not(windows))]@@ -12,13 +14,16 @@ mod windows_listener {use std::io::{self, Write};use std::sync::atomic::{AtomicU32, AtomicU64, AtomicU8, Ordering};- use crate::press::{on_foreign_keydown, on_target_keydown, on_target_keyup, TargetPress};+ use crate::keys::{modifier_bit, other_key_slot, seed_other_key_slots};+ use crate::press::{+ initial_target_press, on_foreign_keydown, on_target_keydown, on_target_keyup, TargetPress,+ };use windows_sys::Win32::Foundation::{LPARAM, LRESULT, WPARAM};use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW;use windows_sys::Win32::UI::Input::KeyboardAndMouse::{- GetAsyncKeyState, VK_CONTROL, VK_F1, VK_LCONTROL, VK_LMENU, VK_LSHIFT, VK_LWIN, VK_MENU,- VK_RCONTROL, VK_RMENU, VK_RSHIFT, VK_RWIN, VK_SHIFT,+ GetAsyncKeyState, VK_F1, VK_LCONTROL, VK_LMENU, VK_LSHIFT, VK_LWIN, VK_RCONTROL, VK_RMENU,+ VK_RSHIFT, VK_RWIN,};use windows_sys::Win32::UI::WindowsAndMessaging::{CallNextHookEx, GetMessageW, SetWindowsHookExW, UnhookWindowsHookEx, HC_ACTION,@@ -40,8 +45,15 @@ mod windows_listener {emit_error("Expected exactly one argument from F1 through F24.");return 2;};- TARGET_VK.store(VK_F1 as u32 + function_number - 1, Ordering::Relaxed);+ let target_vk = VK_F1 as u32 + function_number - 1;+ TARGET_VK.store(target_vk, Ordering::Relaxed);MODIFIERS_DOWN.store(seed_modifier_state(), Ordering::Relaxed);+ seed_other_key_state(target_vk);+ let target_already_down = unsafe { GetAsyncKeyState(target_vk as i32) } < 0;+ TARGET_PRESS.store(+ initial_target_press(target_already_down) as u8,+ Ordering::Relaxed,+ );let module = unsafe { GetModuleHandleW(std::ptr::null()) };if module.is_null() {@@ -122,13 +134,6 @@ mod windows_listener {CallNextHookEx(std::ptr::null_mut(), code, wparam, lparam)}- fn other_key_slot(vk: u32) -> Option<(usize, u64)> {- if vk >= 256 {- return None;- }- Some((vk as usize / 64, 1 << (vk % 64)))- }-fn set_other_key(vk: u32, down: bool) {let Some((index, bit)) = other_key_slot(vk) else {return;@@ -146,29 +151,20 @@ mod windows_listener {.any(|slot| slot.load(Ordering::Relaxed) != 0)}+ fn seed_other_key_state(target_vk: u32) {+ let slots =+ seed_other_key_slots(target_vk, |vk| unsafe { GetAsyncKeyState(vk as i32) } < 0);+ for (index, value) in slots.iter().enumerate() {+ OTHER_KEYS[index].store(*value, Ordering::Relaxed);+ }+ }+fn parse_function_number() -> Option<u32> {let value = std::env::args().nth(1)?;let number = value.strip_prefix('F')?.parse::<u32>().ok()?;(1..=24).contains(&number).then_some(number)}- fn modifier_bit(vk: u32) -> u32 {- match vk as u16 {- VK_SHIFT => 1 << 0,- VK_LSHIFT => 1 << 1,- VK_RSHIFT => 1 << 2,- VK_CONTROL => 1 << 3,- VK_LCONTROL => 1 << 4,- VK_RCONTROL => 1 << 5,- VK_MENU => 1 << 6,- VK_LMENU => 1 << 7,- VK_RMENU => 1 << 8,- VK_LWIN => 1 << 9,- VK_RWIN => 1 << 10,- _ => 0,- }- }-fn seed_modifier_state() -> u32 {[VK_LSHIFT,diff --git a/apps/desktop/native/voice-input/windows-function-key-listener/src/press.rs b/apps/desktop/native/voice-input/windows-function-key-listener/src/press.rsindex d8c4babd36..eea691848d 100644--- a/apps/desktop/native/voice-input/windows-function-key-listener/src/press.rs+++ b/apps/desktop/native/voice-input/windows-function-key-listener/src/press.rs@@ -90,6 +90,14 @@ pub fn on_foreign_keydown(current: TargetPress) -> ForeignKeydownEffect {}}+pub fn initial_target_press(target_already_down: bool) -> TargetPress {+ if target_already_down {+ TargetPress::Rejected+ } else {+ TargetPress::Idle+ }+}+pub fn on_target_keyup(current: TargetPress) -> KeyupEffect {match current {TargetPress::Idle => KeyupEffect {@@ -114,6 +122,16 @@ pub fn on_target_keyup(current: TargetPress) -> KeyupEffect {mod tests {use super::*;+ #[test]+ fn startup_with_target_already_down_is_rejected_not_idle() {+ assert_eq!(initial_target_press(false), TargetPress::Idle);+ assert_eq!(initial_target_press(true), TargetPress::Rejected);+ let repeat = on_target_keydown(initial_target_press(true), true);+ assert_eq!(repeat.next, TargetPress::Rejected);+ assert!(!repeat.swallow);+ assert_eq!(repeat.emit_pressed, None);+ }+#[test]fn from_u8_round_trips_known_states() {assert_eq!(TargetPress::from_u8(0), TargetPress::Idle);diff --git a/apps/desktop/src/main/voice-input/WindowsFunctionKeyShortcutListener.ts b/apps/desktop/src/main/voice-input/WindowsFunctionKeyShortcutListener.tsindex e782125357..b1a370d7c0 100644--- a/apps/desktop/src/main/voice-input/WindowsFunctionKeyShortcutListener.ts+++ b/apps/desktop/src/main/voice-input/WindowsFunctionKeyShortcutListener.ts@@ -360,14 +360,31 @@ function resolveDevSourceRoot(): string {return path.join(__dirname, '..', '..', SOURCE_RELATIVE_PATH);}-function isDevBinaryCurrent(sourceRoot: string, binary: string): boolean {+export function listWindowsFunctionKeyListenerSourceFiles(sourceRoot: string): string[] {+ const files = [path.join(sourceRoot, 'Cargo.toml'), path.join(sourceRoot, 'Cargo.lock')];+ const srcRoot = path.join(sourceRoot, 'src');+ collectRustSources(srcRoot, files);+ return files;+}++function collectRustSources(dir: string, files: string[]): void {+ if (!fs.existsSync(dir)) return;+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {+ const fullPath = path.join(dir, entry.name);+ if (entry.isDirectory()) {+ collectRustSources(fullPath, files);+ continue;+ }+ if (entry.isFile() && entry.name.endsWith('.rs')) files.push(fullPath);+ }+}++export function isDevBinaryCurrent(sourceRoot: string, binary: string): boolean {if (!fs.existsSync(binary)) return false;const binaryMtimeMs = fs.statSync(binary).mtimeMs;- return [- path.join(sourceRoot, 'Cargo.toml'),- path.join(sourceRoot, 'Cargo.lock'),- path.join(sourceRoot, 'src', 'main.rs'),- ].every((source) => !fs.existsSync(source) || fs.statSync(source).mtimeMs <= binaryMtimeMs);+ return listWindowsFunctionKeyListenerSourceFiles(sourceRoot).every(+ (source) => !fs.existsSync(source) || fs.statSync(source).mtimeMs <= binaryMtimeMs,+ );}function resolveCargoExecutable(): string {diff --git a/apps/desktop/src/main/voice-input/__tests__/WindowsFunctionKeyShortcutListener.test.ts b/apps/desktop/src/main/voice-input/__tests__/WindowsFunctionKeyShortcutListener.test.tsindex 1985348fa4..5caefee32f 100644--- a/apps/desktop/src/main/voice-input/__tests__/WindowsFunctionKeyShortcutListener.test.ts+++ b/apps/desktop/src/main/voice-input/__tests__/WindowsFunctionKeyShortcutListener.test.ts@@ -1,3 +1,6 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { VoiceInputShortcut } from '../../../shared/voiceInputData.js';@@ -228,4 +231,34 @@ describe('WindowsFunctionKeyShortcutListener', () => {expect(onRestartLimitReached).toHaveBeenCalledTimes(1);listener.stop();});++ it('rebuilds the helper when any Rust source is newer than the existing binary', async () => {+ const { isDevBinaryCurrent } = await import('../WindowsFunctionKeyShortcutListener.js');+ const sourceRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-win-fkey-'));+ const srcDir = path.join(sourceRoot, 'src');+ const binary = path.join(sourceRoot, 'cindy-windows-function-key-listener.exe');+ fs.mkdirSync(srcDir);+ fs.writeFileSync(path.join(sourceRoot, 'Cargo.toml'), '[package]\n');+ fs.writeFileSync(path.join(sourceRoot, 'Cargo.lock'), '');+ fs.writeFileSync(path.join(srcDir, 'main.rs'), '');+ fs.writeFileSync(path.join(srcDir, 'press.rs'), '');+ fs.writeFileSync(binary, '');+ const older = new Date(Date.now() - 60_000);+ const newer = new Date(Date.now() + 60_000);+ for (const file of [+ path.join(sourceRoot, 'Cargo.toml'),+ path.join(sourceRoot, 'Cargo.lock'),+ path.join(srcDir, 'main.rs'),+ binary,+ ]) {+ fs.utimesSync(file, older, older);+ }+ fs.utimesSync(path.join(srcDir, 'press.rs'), newer, newer);++ expect(isDevBinaryCurrent(sourceRoot, binary)).toBe(false);++ fs.utimesSync(path.join(srcDir, 'press.rs'), older, older);+ expect(isDevBinaryCurrent(sourceRoot, binary)).toBe(true);+ fs.rmSync(sourceRoot, { recursive: true, force: true });+ });});