Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 裸功能键支持按住说话
Dash158cb66b9003
diff --git a/apps/desktop/forge.config.ts b/apps/desktop/forge.config.tsindex 0e22a965b6..4d76efe010 100644--- a/apps/desktop/forge.config.ts+++ b/apps/desktop/forge.config.ts@@ -1038,6 +1038,53 @@ function buildMacVoiceInputModifierShortcutListener(platform: ForgePlatform, arcconsole.log(`[forge:prePackage] macOS voice input modifier shortcut listener (${swiftArchLabel(arch, MACOS_VOICE_HELPER_DEPLOYMENT_TARGET)}) -> ${dest} (${sizeMb} MB)`);}+function buildWindowsVoiceInputFunctionKeyListener(targetPlatform: string): void {+ if (process.platform !== 'win32' || targetPlatform !== 'win32') return;+ const sourceRoot = path.join(__dirname, 'native', 'voice-input', 'windows-function-key-listener');+ const manifest = path.join(sourceRoot, 'Cargo.toml');+ if (!fs.existsSync(manifest)) {+ throw new Error(+ `[forge] Windows voice input function key listener source missing at ${manifest}`,+ );+ }+ const cargoBin = process.env.USERPROFILE+ ? path.join(process.env.USERPROFILE, '.cargo', 'bin', 'cargo.exe')+ : 'cargo';+ const cargo = fs.existsSync(cargoBin) ? cargoBin : 'cargo';+ const result = spawnSync(cargo, ['build', '--release', '--manifest-path', manifest], {+ stdio: 'inherit',+ });+ if (result.error) {+ throw new Error(+ `[forge] failed to invoke cargo (${cargo}) for Windows function key listener: ${result.error.message}`,+ );+ }+ if (result.status !== 0) {+ throw new Error(+ `[forge] Windows function key listener cargo build failed with exit code ${result.status}`,+ );+ }+ const builtExe = path.join(+ sourceRoot,+ 'target',+ 'release',+ 'cindy-windows-function-key-listener.exe',+ );+ const destDir = path.join(__dirname, 'resources', 'tools', 'voice-input');+ const dest = path.join(destDir, 'cindy-windows-function-key-listener.exe');+ if (!fs.existsSync(builtExe)) {+ throw new Error(+ `[forge] Windows function key listener build succeeded but ${builtExe} is missing`,+ );+ }+ fs.mkdirSync(destDir, { recursive: true });+ fs.copyFileSync(builtExe, dest);+ const sizeMb = (fs.statSync(dest).size / (1024 * 1024)).toFixed(2);+ console.log(+ `[forge:prePackage] Windows voice input function key listener -> ${dest} (${sizeMb} MB)`,+ );+}+function buildMacAgentIslandHelper(platform: ForgePlatform, arch: ForgeArch): void {if (process.platform !== 'darwin' || !isMacForgePlatform(platform)) return;const src = path.join(__dirname, 'native', 'agent-island', 'macos-agent-island-helper.swift');@@ -1411,6 +1458,7 @@ const config: ForgeConfig = {}stageRipgrep(targetPlatform, targetArch);stageAndroidPlatformTools(targetPlatform, targetArch);+ buildWindowsVoiceInputFunctionKeyListener(targetPlatform);buildMacIOSSimulatorHelper(platform, arch);buildMacVoiceInputTextInsertionHelper(platform, arch);buildMacVoiceInputModifierShortcutListener(platform, arch);diff --git a/apps/desktop/native/voice-input/macos-modifier-shortcut-listener.swift b/apps/desktop/native/voice-input/macos-modifier-shortcut-listener.swiftindex 9dafa48b00..2af0297dec 100644--- a/apps/desktop/native/voice-input/macos-modifier-shortcut-listener.swift+++ b/apps/desktop/native/voice-input/macos-modifier-shortcut-listener.swift@@ -1,4 +1,5 @@import ApplicationServices+import AppKitimport Foundationfunc emitJson(_ payload: [String: Any]) {@@ -52,6 +53,29 @@ let keyCodeNames: [Int64: String] = [63: "Fn",]+let functionKeyCodeNames: [Int64: String] = [+ 64: "Function:F17",+ 79: "Function:F18",+ 80: "Function:F19",+ 90: "Function:F20",+ 96: "Function:F5",+ 97: "Function:F6",+ 98: "Function:F7",+ 99: "Function:F3",+ 100: "Function:F8",+ 101: "Function:F9",+ 103: "Function:F11",+ 105: "Function:F13",+ 106: "Function:F16",+ 107: "Function:F14",+ 109: "Function:F10",+ 111: "Function:F12",+ 113: "Function:F15",+ 118: "Function:F4",+ 120: "Function:F2",+ 122: "Function:F1",+]+let modifierGroups: [String: CGEventFlags] = ["MetaLeft": .maskCommand,"MetaRight": .maskCommand,@@ -75,6 +99,7 @@ let modifierGroupMembers: [UInt64: Set<String>] = [enum ListenerState {static var pressedKeys = Set<String>()static var lastEmittedKeys: [String] = []+ static var functionKeyNamesByKeyCode: [Int64: String] = [:]// Keep this helper intentionally dumb: it emits snapshots of keys currently// held down. Tap/hold timing and voice-input business state stay in the@@ -114,8 +139,40 @@ enum ListenerState {emitKeysIfChanged()}- static func handleNonModifierKey(keyCode: Int64, down: Bool) {- let name = "KeyCode:\(keyCode)"+ static func functionKeyName(event: CGEvent) -> String? {+ var length = 0+ var characters = [UniChar](repeating: 0, count: 4)+ event.keyboardGetUnicodeString(+ maxStringLength: characters.count,+ actualStringLength: &length,+ unicodeString: &characters+ )+ guard length == 1 else {+ return nil+ }+ let value = Int(characters[0])+ let firstFunctionKey = Int(NSF1FunctionKey)+ let lastFunctionKey = Int(NSF24FunctionKey)+ guard value >= firstFunctionKey && value <= lastFunctionKey else {+ return nil+ }+ return "Function:F\(value - firstFunctionKey + 1)"+ }++ static func handleNonModifierKey(event: CGEvent, down: Bool) {+ let keyCode = event.getIntegerValueField(.keyboardEventKeycode)+ let name: String+ if down {+ let detected = functionKeyName(event: event)+ ?? functionKeyCodeNames[keyCode]+ ?? "KeyCode:\(keyCode)"+ functionKeyNamesByKeyCode[keyCode] = detected+ name = detected+ } else {+ name = functionKeyNamesByKeyCode.removeValue(forKey: keyCode)+ ?? functionKeyName(event: event)+ ?? "KeyCode:\(keyCode)"+ }if down {pressedKeys.insert(name)} else {@@ -137,7 +194,7 @@ enum ListenerState {}} else if type == .keyDown || type == .keyUp {if keyCodeNames[keyCode] == nil {- handleNonModifierKey(keyCode: keyCode, down: type == .keyDown)+ handleNonModifierKey(event: event, down: type == .keyDown)}}return Unmanaged.passUnretained(event)diff --git a/apps/desktop/native/voice-input/windows-function-key-listener/.gitignore b/apps/desktop/native/voice-input/windows-function-key-listener/.gitignorenew file mode 100644index 0000000000..2f7896d1d1--- /dev/null+++ b/apps/desktop/native/voice-input/windows-function-key-listener/.gitignore@@ -0,0 +1 @@+target/diff --git a/apps/desktop/native/voice-input/windows-function-key-listener/Cargo.lock b/apps/desktop/native/voice-input/windows-function-key-listener/Cargo.locknew file mode 100644index 0000000000..ffed9a9351--- /dev/null+++ b/apps/desktop/native/voice-input/windows-function-key-listener/Cargo.lock@@ -0,0 +1,83 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "cindy-windows-function-key-listener"+version = "0.1.0"+dependencies = [+ "windows-sys",+]++[[package]]+name = "windows-sys"+version = "0.59.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"+dependencies = [+ "windows-targets",+]++[[package]]+name = "windows-targets"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"+dependencies = [+ "windows_aarch64_gnullvm",+ "windows_aarch64_msvc",+ "windows_i686_gnu",+ "windows_i686_gnullvm",+ "windows_i686_msvc",+ "windows_x86_64_gnu",+ "windows_x86_64_gnullvm",+ "windows_x86_64_msvc",+]++[[package]]+name = "windows_aarch64_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"++[[package]]+name = "windows_aarch64_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"++[[package]]+name = "windows_i686_gnu"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"++[[package]]+name = "windows_i686_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"++[[package]]+name = "windows_i686_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"++[[package]]+name = "windows_x86_64_gnu"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"++[[package]]+name = "windows_x86_64_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"++[[package]]+name = "windows_x86_64_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"diff --git a/apps/desktop/native/voice-input/windows-function-key-listener/Cargo.toml b/apps/desktop/native/voice-input/windows-function-key-listener/Cargo.tomlnew file mode 100644index 0000000000..08f61f4e1e--- /dev/null+++ b/apps/desktop/native/voice-input/windows-function-key-listener/Cargo.toml@@ -0,0 +1,20 @@+[package]+name = "cindy-windows-function-key-listener"+version = "0.1.0"+edition = "2021"+license = "Apache-2.0"++[dependencies]+windows-sys = { version = "0.59", features = [+ "Win32_Foundation",+ "Win32_System_LibraryLoader",+ "Win32_UI_Input_KeyboardAndMouse",+ "Win32_UI_WindowsAndMessaging",+] }++[profile.release]+panic = "abort"+codegen-units = 1+lto = true+opt-level = "s"+strip = truediff --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.rsnew file mode 100644index 0000000000..ba4155285d--- /dev/null+++ b/apps/desktop/native/voice-input/windows-function-key-listener/src/main.rs@@ -0,0 +1,171 @@+#[cfg(not(windows))]+fn main() {+ eprintln!("This helper is only supported on Windows.");+ std::process::exit(2);+}++#[cfg(windows)]+mod windows_listener {+ use std::io::{self, Write};+ use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};++ 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,+ };+ use windows_sys::Win32::UI::WindowsAndMessaging::{+ CallNextHookEx, GetMessageW, SetWindowsHookExW, UnhookWindowsHookEx, HC_ACTION,+ KBDLLHOOKSTRUCT, MSG, WH_KEYBOARD_LL, WM_KEYDOWN, WM_KEYUP, WM_SYSKEYDOWN, WM_SYSKEYUP,+ };++ static TARGET_VK: AtomicU32 = AtomicU32::new(0);+ static MODIFIERS_DOWN: AtomicU32 = AtomicU32::new(0);+ static ACTIVE: AtomicBool = AtomicBool::new(false);+ static SUPPRESS_UNTIL_RELEASE: AtomicBool = AtomicBool::new(false);++ pub fn run() -> i32 {+ let Some(function_number) = parse_function_number() else {+ emit_error("Expected exactly one argument from F1 through F24.");+ return 2;+ };+ TARGET_VK.store(VK_F1 as u32 + function_number - 1, Ordering::Relaxed);+ MODIFIERS_DOWN.store(seed_modifier_state(), Ordering::Relaxed);++ let module = unsafe { GetModuleHandleW(std::ptr::null()) };+ if module.is_null() {+ emit_error("Could not resolve the Windows function key listener module.");+ return 3;+ }+ let hook = unsafe { SetWindowsHookExW(WH_KEYBOARD_LL, Some(keyboard_hook), module, 0) };+ if hook.is_null() {+ emit_error("Could not install the Windows keyboard listener.");+ return 3;+ }++ emit_line("{\"type\":\"ready\"}");+ let mut message: MSG = unsafe { std::mem::zeroed() };+ while unsafe { GetMessageW(&mut message, std::ptr::null_mut(), 0, 0) } > 0 {}++ unsafe { UnhookWindowsHookEx(hook) };+ 0+ }++ unsafe extern "system" fn keyboard_hook(code: i32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {+ if code != HC_ACTION as i32 {+ return CallNextHookEx(std::ptr::null_mut(), code, wparam, lparam);+ }++ let event = &*(lparam as *const KBDLLHOOKSTRUCT);+ let target_vk = TARGET_VK.load(Ordering::Relaxed);+ let message = wparam as u32;+ let key_down = message == WM_KEYDOWN || message == WM_SYSKEYDOWN;+ let key_up = message == WM_KEYUP || message == WM_SYSKEYUP;+ let modifier_bit = modifier_bit(event.vkCode);++ if modifier_bit != 0 {+ if key_down {+ MODIFIERS_DOWN.fetch_or(modifier_bit, Ordering::Relaxed);+ } else if key_up {+ MODIFIERS_DOWN.fetch_and(!modifier_bit, Ordering::Relaxed);+ }+ }++ if key_down && ACTIVE.load(Ordering::Relaxed) && modifier_bit != 0 {+ ACTIVE.store(false, Ordering::Relaxed);+ emit_pressed(false);+ }++ if event.vkCode == target_vk {+ if key_down {+ if ACTIVE.load(Ordering::Relaxed) || SUPPRESS_UNTIL_RELEASE.load(Ordering::Relaxed)+ {+ return 1;+ }+ if MODIFIERS_DOWN.load(Ordering::Relaxed) == 0 {+ ACTIVE.store(true, Ordering::Relaxed);+ SUPPRESS_UNTIL_RELEASE.store(true, Ordering::Relaxed);+ emit_pressed(true);+ return 1;+ }+ } else if key_up && SUPPRESS_UNTIL_RELEASE.swap(false, Ordering::Relaxed) {+ if ACTIVE.swap(false, Ordering::Relaxed) {+ emit_pressed(false);+ }+ return 1;+ }+ }++ CallNextHookEx(std::ptr::null_mut(), code, wparam, lparam)+ }++ 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,+ VK_RSHIFT,+ VK_LCONTROL,+ VK_RCONTROL,+ VK_LMENU,+ VK_RMENU,+ VK_LWIN,+ VK_RWIN,+ ]+ .into_iter()+ .fold(0, |state, vk| {+ let is_down = unsafe { GetAsyncKeyState(vk as i32) } < 0;+ if is_down {+ state | modifier_bit(vk as u32)+ } else {+ state+ }+ })+ }++ fn emit_pressed(pressed: bool) {+ emit_line(if pressed {+ "{\"type\":\"pressed\",\"pressed\":true}"+ } else {+ "{\"type\":\"pressed\",\"pressed\":false}"+ });+ }++ fn emit_error(message: &str) {+ let escaped = message.replace('\\', "\\\\").replace('"', "\\\"");+ emit_line(&format!("{{\"type\":\"error\",\"message\":\"{escaped}\"}}"));+ }++ fn emit_line(line: &str) {+ let mut stdout = io::stdout().lock();+ let _ = writeln!(stdout, "{line}");+ let _ = stdout.flush();+ }+}++#[cfg(windows)]+fn main() {+ std::process::exit(windows_listener::run());+}diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex bff9f9ffd2..96471e4e93 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -641,6 +641,7 @@ import {} from './sessionDragPreviewHtml.js';import {isGlobalVoiceInputOverlayVisible,+ releaseActiveGlobalVoiceInputShortcut,registerGlobalVoiceInputIpc,} from './voice-input/global.js';import { ensureMainAppPresence } from './appPresence.js';@@ -7103,6 +7104,7 @@ app.on('ready', async () => {// 设备只剩隐私指示灯常亮和 idle-sleep assertion 的代价)。installVoiceInputPowerRelease({powerMonitor,+ releaseActiveShortcut: releaseActiveGlobalVoiceInputShortcut,broadcast: (channel, payload) => {broadcastVoiceInputPowerState(BrowserWindow.getAllWindows(),diff --git a/apps/desktop/src/main/voice-input/MacModifierShortcutListener.ts b/apps/desktop/src/main/voice-input/MacModifierShortcutListener.tsindex cd65d5f59b..44c63c98b4 100644--- a/apps/desktop/src/main/voice-input/MacModifierShortcutListener.ts+++ b/apps/desktop/src/main/voice-input/MacModifierShortcutListener.ts@@ -5,6 +5,7 @@ import path from 'node:path';import type { Readable } from 'node:stream';import {+ isVoiceInputBareFunctionKeyShortcut,isVoiceInputMacNativeKeyboardShortcut,isVoiceInputMacNativeKeyboardShortcutPressed,isVoiceInputMacNativeKeyboardShortcutTargetDown,@@ -12,6 +13,7 @@ import {type VoiceInputShortcut,} from '../../shared/voiceInputData.js';import { createLogger } from '../logger.js';+import { ShortcutHoldPhaseController } from './ShortcutHoldPhaseController.js';const log = createLogger('voice-input:modifier-shortcut');@@ -113,6 +115,9 @@ export class MacModifierShortcutListener {private holdThresholdReached = false;private keyboardShortcutPressed = false;private canceledUntilRelease = false;+ private readonly functionKeyPhaseController = new ShortcutHoldPhaseController({+ onTrigger: (phase) => this.options.onTrigger(phase),+ });constructor(private readonly options: MacModifierShortcutListenerOptions) {}@@ -218,6 +223,47 @@ export class MacModifierShortcutListener {this.resetState();}+ /**+ * System suspend / lock can consume the physical key-up event. End the+ * delivered push-to-talk activation now and forget the native snapshot so a+ * late release cannot leave the voice-input state stuck.+ */+ releaseActiveTrigger(): void {+ const shouldRestart = this.isReady();+ this.endActiveTriggerIfNeeded();+ this.resetState();+ if (!shouldRestart) return;++ // The helper owns the pressed-key snapshot. A suspend/lock transition can+ // consume key-up, so restart the process itself instead of leaving a stale+ // F-key in that snapshot. This also preserves a capture-only helper when a+ // shortcut recorder is open.+ this.startGeneration += 1;+ const child = this.child;+ this.child = null;+ this.ready = false;+ this.clearRestartTimer();+ this.restartAttempts = 0;+ if (child && !child.killed) child.kill();+ void this.startChildProcess({ preserveShortcutOnFailure: true })+ .then((result) => {+ if (!result.ok && !result.superseded) {+ log.warn('modifier shortcut listener did not restart after system release', {+ error: result.error,+ shortcut: this.shortcut ? getShortcutLogLabel(this.shortcut) : null,+ });+ if (this.shortcut) this.scheduleRestart(null, null);+ }+ })+ .catch((error: unknown) => {+ log.warn('modifier shortcut listener restart after system release crashed', {+ error: error instanceof Error ? error.message : String(error),+ shortcut: this.shortcut ? getShortcutLogLabel(this.shortcut) : null,+ });+ if (this.shortcut) this.scheduleRestart(null, null);+ });+ }+stop(): void {// 作废正在飞的启动:它可能还停在解析 helper 的 await 上,此刻 child 仍是 null,// 下面的 kill 够不着它。不作废的话它随后会 spawn 出一个没人管的 helper。@@ -452,6 +498,12 @@ export class MacModifierShortcutListener {}private handleMacNativeKeyboardPressedKeys(keys: string[], shortcut: VoiceInputShortcut): void {+ if (isVoiceInputBareFunctionKeyShortcut(shortcut)) {+ this.functionKeyPhaseController.setPressed(+ isVoiceInputMacNativeKeyboardShortcutPressed(keys, shortcut),+ );+ return;+ }const pressed = isVoiceInputMacNativeKeyboardShortcutPressed(keys, shortcut);const targetDown = isVoiceInputMacNativeKeyboardShortcutTargetDown(keys, shortcut);if (!pressed) {@@ -511,6 +563,7 @@ export class MacModifierShortcutListener {this.holdThresholdReached = false;this.keyboardShortcutPressed = false;this.canceledUntilRelease = false;+ this.functionKeyPhaseController.reset();}private clearStartTimer(): void {@@ -520,6 +573,7 @@ export class MacModifierShortcutListener {}private endActiveTriggerIfNeeded(): void {+ this.functionKeyPhaseController.releaseIfPressed();if (!this.triggered) return;this.triggered = false;this.options.onTrigger('end');@@ -667,7 +721,8 @@ async function runMacInputMonitoringPermissionCommand(command: string): Promise<return {ok: false,status: 'denied',- error: 'Input Monitoring permission is required for Fn and single-modifier voice input shortcuts.',+ error:+ 'Input Monitoring permission is required for Fn, F1-F24, and single-modifier voice input shortcuts.',};} catch (error) {return {diff --git a/apps/desktop/src/main/voice-input/ShortcutHoldPhaseController.ts b/apps/desktop/src/main/voice-input/ShortcutHoldPhaseController.tsnew file mode 100644index 0000000000..1c5119d974--- /dev/null+++ b/apps/desktop/src/main/voice-input/ShortcutHoldPhaseController.ts@@ -0,0 +1,66 @@+export type ShortcutHoldPhase = 'tap' | 'start' | 'end';++export interface ShortcutHoldPhaseControllerOptions {+ holdDelayMs?: number;+ onTrigger: (phase: ShortcutHoldPhase) => void;+}++const DEFAULT_HOLD_DELAY_MS = 450;++/**+ * Turns a native key-down/key-up stream into Cindy's short-tap / push-to-talk phases.+ *+ * Native helpers deliberately stay timing-free. Keeping the threshold here gives+ * macOS and Windows one tested product state machine and makes repeated key-down+ * messages harmless.+ */+export class ShortcutHoldPhaseController {+ private readonly holdDelayMs: number;+ private down = false;+ private holdThresholdReached = 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;+ if (pressed) {+ this.down = true;+ this.holdThresholdReached = false;+ this.options.onTrigger('start');+ this.holdTimer = setTimeout(() => {+ this.holdTimer = null;+ if (this.down) this.holdThresholdReached = true;+ }, this.holdDelayMs);+ return;+ }++ const shouldTap = !this.holdThresholdReached;+ this.clearHoldTimer();+ this.down = false;+ this.holdThresholdReached = false;+ this.options.onTrigger(shouldTap ? 'tap' : 'end');+ }++ releaseIfPressed(): void {+ if (!this.down) return;+ this.clearHoldTimer();+ this.down = false;+ this.holdThresholdReached = false;+ this.options.onTrigger('end');+ }++ reset(): void {+ this.clearHoldTimer();+ this.down = false;+ this.holdThresholdReached = false;+ }++ private clearHoldTimer(): void {+ if (!this.holdTimer) return;+ clearTimeout(this.holdTimer);+ this.holdTimer = null;+ }+}diff --git a/apps/desktop/src/main/voice-input/WindowsFunctionKeyShortcutListener.ts b/apps/desktop/src/main/voice-input/WindowsFunctionKeyShortcutListener.tsnew file mode 100644index 0000000000..1a358125a2--- /dev/null+++ b/apps/desktop/src/main/voice-input/WindowsFunctionKeyShortcutListener.ts@@ -0,0 +1,360 @@+import { app } from 'electron';+import { execFile, spawn, type ChildProcessByStdio } from 'node:child_process';+import fs from 'node:fs';+import path from 'node:path';+import type { Readable } from 'node:stream';++import {+ isVoiceInputBareFunctionKeyShortcut,+ type VoiceInputShortcut,+} from '../../shared/voiceInputData.js';+import { createLogger } from '../logger.js';+import {+ ShortcutHoldPhaseController,+ type ShortcutHoldPhase,+} from './ShortcutHoldPhaseController.js';++const log = createLogger('voice-input:windows-function-key-shortcut');++const RESOURCE_PATH = path.join('tools', 'voice-input', 'cindy-windows-function-key-listener.exe');+const SOURCE_RELATIVE_PATH = path.join('native', 'voice-input', 'windows-function-key-listener');+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;++export type WindowsFunctionKeyListenerStartResult =+ { ok: true } | { ok: false; error: string; superseded?: true };++type ListenerPayload = {+ type?: unknown;+ pressed?: unknown;+ message?: unknown;+};++type ListenerProcess = ChildProcessByStdio<null, Readable, Readable>;++export interface WindowsFunctionKeyShortcutListenerOptions {+ onTrigger: (phase: ShortcutHoldPhase) => void;+}++function supersededStart(): WindowsFunctionKeyListenerStartResult {+ return { ok: false, error: 'Function key listener start was superseded.', superseded: true };+}++/**+ * Owns the Windows low-level keyboard helper used for bare F1-F24 shortcuts.+ * The helper reports and suppresses only the configured key; tap/hold timing+ * stays in TypeScript so both desktop platforms share the same product semantics.+ */+export class WindowsFunctionKeyShortcutListener {+ private child: ListenerProcess | null = null;+ private ready = false;+ private shortcutCode: string | null = null;+ private startGeneration = 0;+ private restartAttempts = 0;+ private restartTimer: NodeJS.Timeout | null = null;+ private readonly phaseController: ShortcutHoldPhaseController;++ constructor(options: WindowsFunctionKeyShortcutListenerOptions) {+ this.phaseController = new ShortcutHoldPhaseController({ onTrigger: options.onTrigger });+ }++ isReady(): boolean {+ return this.ready && Boolean(this.child && !this.child.killed);+ }++ async setShortcut(shortcut: VoiceInputShortcut): Promise<WindowsFunctionKeyListenerStartResult> {+ if (!isVoiceInputBareFunctionKeyShortcut(shortcut)) {+ this.stop();+ return { ok: true };+ }+ if (this.shortcutCode === shortcut.code && this.isReady()) return { ok: true };++ this.shortcutCode = shortcut.code;+ this.restartAttempts = 0;+ this.clearRestartTimer();+ this.stopChildKeepingShortcut();+ return this.startChildProcess(shortcut.code);+ }++ releaseActiveTrigger(): void {+ const code = this.shortcutCode;+ const shouldRestart = this.isReady();+ this.phaseController.releaseIfPressed();+ this.phaseController.reset();+ if (!code || !shouldRestart) return;++ // Windows may drop the physical key-up while suspending or locking. The+ // helper also owns a suppression latch, so reset the process itself rather+ // than only clearing the TypeScript phase controller.+ this.restartAttempts = 0;+ this.clearRestartTimer();+ this.stopChildKeepingShortcut();+ void this.startChildProcess(code)+ .then((result) => {+ if (!result.ok && !result.superseded) {+ log.warn('Windows function key listener did not restart after system release', {+ code,+ error: result.error,+ });+ }+ })+ .catch((error: unknown) => {+ log.warn('Windows function key listener restart after system release crashed', {+ code,+ error: error instanceof Error ? error.message : String(error),+ });+ });+ }++ stop(): void {+ this.shortcutCode = null;+ this.restartAttempts = 0;+ this.clearRestartTimer();+ this.stopChildKeepingShortcut();+ }++ private stopChildKeepingShortcut(): void {+ this.startGeneration += 1;+ const child = this.child;+ this.child = null;+ this.ready = false;+ this.phaseController.releaseIfPressed();+ this.phaseController.reset();+ if (child && !child.killed) child.kill();+ }++ private async startChildProcess(code: string): Promise<WindowsFunctionKeyListenerStartResult> {+ const generation = ++this.startGeneration;+ let binary: string;+ try {+ binary = await resolveWindowsFunctionKeyListenerBinary();+ } catch (error) {+ if (generation !== this.startGeneration) return supersededStart();+ throw error;+ }+ if (generation !== this.startGeneration || this.shortcutCode !== code) return supersededStart();++ return new Promise((resolve) => {+ let settled = false;+ let stdoutBuffer = '';+ const child = spawn(binary, [code], {+ stdio: ['ignore', 'pipe', 'pipe'],+ windowsHide: true,+ });+ this.child = child;+ this.ready = false;++ let startTimer: NodeJS.Timeout | null = null;+ const settle = (result: WindowsFunctionKeyListenerStartResult): void => {+ if (settled) return;+ settled = true;+ if (startTimer) clearTimeout(startTimer);+ 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 && this.child === child) {+ this.child = null;+ this.ready = false;+ this.phaseController.releaseIfPressed();+ this.phaseController.reset();+ if (!child.killed) child.kill();+ }+ resolve(outcome);+ };++ startTimer = setTimeout(() => {+ settle({ ok: false, error: 'Windows function key listener did not start.' });+ }, START_TIMEOUT_MS);++ child.stdout.setEncoding('utf8');+ child.stdout.on('data', (chunk: string) => {+ stdoutBuffer += chunk;+ let newlineIndex = stdoutBuffer.indexOf('\n');+ while (newlineIndex >= 0) {+ const line = stdoutBuffer.slice(0, newlineIndex).trim();+ stdoutBuffer = stdoutBuffer.slice(newlineIndex + 1);+ if (line) this.handlePayloadLine(line, child, settle);+ newlineIndex = stdoutBuffer.indexOf('\n');+ }+ });++ child.stderr.setEncoding('utf8');+ child.stderr.on('data', (chunk: string) => {+ const text = chunk.trim();+ if (text) log.debug('Windows function key listener stderr', { text });+ });++ child.on('error', (error) => {+ if (settled) {+ log.warn('Windows function key listener process error', { error: error.message });+ return;+ }+ settle({ ok: false, error: error.message });+ });++ child.on('exit', (exitCode, signal) => {+ const wasCurrentChild = this.child === child;+ if (wasCurrentChild) {+ this.child = null;+ this.ready = false;+ this.phaseController.releaseIfPressed();+ this.phaseController.reset();+ }+ if (!settled) {+ settle({+ ok: false,+ error: `Windows function key listener exited before ready (${signal ?? exitCode ?? 'unknown'}).`,+ });+ return;+ }+ log.debug('Windows function key listener exited', { exitCode, signal });+ if (wasCurrentChild && this.shortcutCode === code)+ this.scheduleRestart(code, exitCode, signal);+ });+ });+ }++ private handlePayloadLine(+ line: string,+ child: ListenerProcess,+ settle: (result: WindowsFunctionKeyListenerStartResult) => void,+ ): void {+ let payload: ListenerPayload;+ try {+ payload = JSON.parse(line) as ListenerPayload;+ } catch {+ log.debug('Windows function key listener emitted non-json line', { line });+ return;+ }+ if (payload.type === 'ready') {+ settle({ ok: true });+ log.info('Windows function key listener ready', { code: this.shortcutCode });+ return;+ }+ if (payload.type === 'error') {+ settle({+ ok: false,+ error:+ typeof payload.message === 'string'+ ? payload.message+ : 'Windows function key listener failed.',+ });+ return;+ }+ if (+ payload.type === 'pressed' &&+ typeof payload.pressed === 'boolean' &&+ this.child === child+ ) {+ this.phaseController.setPressed(payload.pressed);+ }+ }++ private scheduleRestart(+ code: string,+ exitCode: number | null,+ signal: NodeJS.Signals | null,+ ): void {+ if (!this.shortcutCode || this.restartTimer) return;+ if (this.restartAttempts >= RESTART_MAX_ATTEMPTS) {+ log.warn('Windows function key listener restart limit reached', { code, exitCode, signal });+ return;+ }+ this.restartAttempts += 1;+ const delayMs = Math.min(+ RESTART_BASE_DELAY_MS * 2 ** (this.restartAttempts - 1),+ RESTART_MAX_DELAY_MS,+ );+ log.warn('Windows function key listener exited unexpectedly; scheduling restart', {+ code,+ exitCode,+ signal,+ attempt: this.restartAttempts,+ delayMs,+ });+ this.restartTimer = setTimeout(() => {+ this.restartTimer = null;+ if (this.shortcutCode !== code || this.child) return;+ void this.startChildProcess(code)+ .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', {+ code,+ error: error instanceof Error ? error.message : String(error),+ });+ this.scheduleRestart(code, null, null);+ });+ }, delayMs);+ }++ private clearRestartTimer(): void {+ if (!this.restartTimer) return;+ clearTimeout(this.restartTimer);+ this.restartTimer = null;+ }+}++async function resolveWindowsFunctionKeyListenerBinary(): Promise<string> {+ if (app.isPackaged) return path.join(process.resourcesPath, RESOURCE_PATH);+ if (process.platform !== 'win32') {+ throw new Error('The Windows function key listener can only run on Windows.');+ }+ const sourceRoot = resolveDevSourceRoot();+ const binary = path.join(+ sourceRoot,+ 'target',+ 'release',+ 'cindy-windows-function-key-listener.exe',+ );+ if (isDevBinaryCurrent(sourceRoot, binary)) return binary;+ await execFilePromise(+ resolveCargoExecutable(),+ ['build', '--release', '--manifest-path', path.join(sourceRoot, 'Cargo.toml')],+ 120_000,+ );+ return binary;+}++function resolveDevSourceRoot(): string {+ const appPathSource = path.join(app.getAppPath(), SOURCE_RELATIVE_PATH);+ if (fs.existsSync(appPathSource)) return appPathSource;+ return path.join(__dirname, '..', '..', SOURCE_RELATIVE_PATH);+}++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);+}++function resolveCargoExecutable(): string {+ const userProfileCargo = process.env.USERPROFILE+ ? path.join(process.env.USERPROFILE, '.cargo', 'bin', 'cargo.exe')+ : null;+ return userProfileCargo && fs.existsSync(userProfileCargo) ? userProfileCargo : 'cargo';+}++function execFilePromise(file: string, args: string[], timeoutMs: number): Promise<void> {+ return new Promise((resolve, reject) => {+ execFile(file, args, { timeout: timeoutMs, windowsHide: true }, (error, _stdout, stderr) => {+ if (error) {+ reject(new Error(stderr?.trim() || error.message));+ return;+ }+ resolve();+ });+ });+}diff --git a/apps/desktop/src/main/voice-input/__tests__/MacModifierShortcutListenerStartRace.test.ts b/apps/desktop/src/main/voice-input/__tests__/MacModifierShortcutListenerStartRace.test.tsindex 6e9b3f3094..631b215068 100644--- a/apps/desktop/src/main/voice-input/__tests__/MacModifierShortcutListenerStartRace.test.ts+++ b/apps/desktop/src/main/voice-input/__tests__/MacModifierShortcutListenerStartRace.test.ts@@ -266,4 +266,73 @@ describe('MacModifierShortcutListener start race', () => {await expect(starting).resolves.toMatchObject({ ok: false, superseded: true });expect(mocks.spawn).not.toHaveBeenCalled();});++ it('maps bare function-key snapshots to start/tap and releases an active press on helper exit', async () => {+ const { MacModifierShortcutListener } = await import('../MacModifierShortcutListener.js');+ const onTrigger = vi.fn();+ const listener = new MacModifierShortcutListener({ onTrigger });+ const shortcut = {+ trigger: 'keyboard',+ code: 'F24',+ key: 'F24',+ modifiers: { meta: false, ctrl: false, alt: false, shift: false, fn: false },+ } as const;++ const starting = listener.setShortcut(shortcut);+ await flush();+ mocks.pendingCompilations[0]();+ await flush();+ mocks.stdoutDataHandlers[0]?.('{"type":"ready"}\n');+ await expect(starting).resolves.toMatchObject({ ok: true });++ 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', 'tap']);++ onTrigger.mockClear();+ mocks.stdoutDataHandlers[0]?.('{"type":"keys","keys":["Function:F24"]}\n');+ mocks.spawnedChildren[0].get('exit')?.(1, null);+ expect(onTrigger.mock.calls.map(([phase]) => phase)).toEqual(['start', 'end']);+ listener.stop();+ });++ it('ends a held function key once and replaces the helper on a system release', async () => {+ const { MacModifierShortcutListener } = await import('../MacModifierShortcutListener.js');+ const onTrigger = vi.fn();+ const listener = new MacModifierShortcutListener({ onTrigger });+ const shortcut = {+ trigger: 'keyboard',+ code: 'F24',+ key: 'F24',+ modifiers: { meta: false, ctrl: false, alt: false, shift: false, fn: false },+ } as const;++ const starting = listener.setShortcut(shortcut);+ await flush();+ mocks.pendingCompilations[0]();+ await flush();+ mocks.stdoutDataHandlers[0]?.('{"type":"ready"}\n');+ await expect(starting).resolves.toMatchObject({ ok: true });++ mocks.stdoutDataHandlers[0]?.('{"type":"keys","keys":["Function:F24"]}\n');+ listener.releaseActiveTrigger();++ expect(onTrigger.mock.calls.map(([phase]) => phase)).toEqual(['start', 'end']);+ expect(mocks.kill).toHaveBeenCalledTimes(1);+ await flush();+ expect(mocks.pendingCompilations).toHaveLength(2);+ mocks.pendingCompilations[1]();+ await flush();+ expect(mocks.spawnedChildren).toHaveLength(2);+ mocks.stdoutDataHandlers[1]?.('{"type":"ready"}\n');+ await flush();+ expect(listener.isReady()).toBe(true);++ // The old process may report exit after its replacement is already live.+ // It must neither end the activation twice nor schedule another restart.+ mocks.spawnedChildren[0].get('exit')?.(null, 'SIGTERM');+ expect(onTrigger.mock.calls.map(([phase]) => phase)).toEqual(['start', 'end']);+ expect(mocks.pendingCompilations).toHaveLength(2);+ listener.stop();+ });});diff --git a/apps/desktop/src/main/voice-input/__tests__/ShortcutHoldPhaseController.test.ts b/apps/desktop/src/main/voice-input/__tests__/ShortcutHoldPhaseController.test.tsnew file mode 100644index 0000000000..4c7fd07620--- /dev/null+++ b/apps/desktop/src/main/voice-input/__tests__/ShortcutHoldPhaseController.test.ts@@ -0,0 +1,58 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { ShortcutHoldPhaseController } from '../ShortcutHoldPhaseController';++describe('ShortcutHoldPhaseController', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('classifies a short press as start followed by tap', () => {+ const onTrigger = vi.fn();+ const controller = new ShortcutHoldPhaseController({ onTrigger });++ controller.setPressed(true);+ vi.advanceTimersByTime(449);+ controller.setPressed(false);++ expect(onTrigger.mock.calls.map(([phase]) => phase)).toEqual(['start', 'tap']);+ });++ it('classifies a held press as start followed by end', () => {+ const onTrigger = vi.fn();+ const controller = new ShortcutHoldPhaseController({ onTrigger });++ controller.setPressed(true);+ vi.advanceTimersByTime(450);+ controller.setPressed(false);++ expect(onTrigger.mock.calls.map(([phase]) => phase)).toEqual(['start', 'end']);+ });++ it('ignores repeated key-down messages while the key is held', () => {+ const onTrigger = vi.fn();+ const controller = new ShortcutHoldPhaseController({ onTrigger });++ controller.setPressed(true);+ controller.setPressed(true);+ vi.advanceTimersByTime(500);+ controller.setPressed(false);++ expect(onTrigger.mock.calls.map(([phase]) => phase)).toEqual(['start', 'end']);+ });++ it('ends an active press when the native listener stops or the system suspends', () => {+ const onTrigger = vi.fn();+ const controller = new ShortcutHoldPhaseController({ onTrigger });++ controller.setPressed(true);+ controller.releaseIfPressed();+ controller.releaseIfPressed();++ expect(onTrigger.mock.calls.map(([phase]) => phase)).toEqual(['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.tsnew file mode 100644index 0000000000..3843ff6756--- /dev/null+++ b/apps/desktop/src/main/voice-input/__tests__/WindowsFunctionKeyShortcutListener.test.ts@@ -0,0 +1,147 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { VoiceInputShortcut } from '../../../shared/voiceInputData.js';++const mocks = vi.hoisted(() => {+ type Handler = (...args: unknown[]) => void;+ const spawnedChildren: Array<{+ args: string[];+ kill: ReturnType<typeof vi.fn>;+ stdoutData: (chunk: string) => void;+ handlers: Map<string, Handler>;+ }> = [];+ const spawn = vi.fn((_binary: string, args: string[]) => {+ const handlers = new Map<string, Handler>();+ let stdoutData: (chunk: string) => void = () => {};+ const child = {+ args,+ killed: false,+ kill: vi.fn(() => {+ child.killed = true;+ }),+ stdout: {+ setEncoding: vi.fn(),+ on: vi.fn((event: string, callback: (chunk: string) => void) => {+ if (event === 'data') stdoutData = callback;+ }),+ },+ stderr: { setEncoding: vi.fn(), on: vi.fn() },+ on: vi.fn((event: string, callback: Handler) => {+ handlers.set(event, callback);+ }),+ };+ spawnedChildren.push({+ args,+ kill: child.kill,+ stdoutData: (chunk) => stdoutData(chunk),+ handlers,+ });+ return child;+ });+ return { spawn, spawnedChildren };+});++vi.mock('electron', () => ({+ app: { isPackaged: true },+}));++vi.mock('node:child_process', () => ({+ spawn: mocks.spawn,+ execFile: vi.fn(),+}));++const originalResourcesPath = Object.getOwnPropertyDescriptor(process, 'resourcesPath');++function flush(): Promise<void> {+ return new Promise((resolve) => setImmediate(resolve));+}++const f2Shortcut: VoiceInputShortcut = {+ trigger: 'keyboard',+ code: 'F2',+ key: 'F2',+ modifiers: { meta: false, ctrl: false, alt: false, shift: false, fn: false },+};++async function startReady(listener: {+ setShortcut: (shortcut: VoiceInputShortcut) => Promise<unknown>;+}): Promise<void> {+ const starting = listener.setShortcut(f2Shortcut);+ await flush();+ const child = mocks.spawnedChildren.at(-1);+ expect(child?.args).toEqual(['F2']);+ child?.stdoutData('{"type":"ready"}\n');+ await expect(starting).resolves.toMatchObject({ ok: true });+}++describe('WindowsFunctionKeyShortcutListener', () => {+ beforeEach(() => {+ vi.resetModules();+ mocks.spawn.mockClear();+ mocks.spawnedChildren.length = 0;+ Object.defineProperty(process, 'resourcesPath', {+ value: 'C:\\Cindy\\resources',+ configurable: true,+ });+ });++ afterEach(() => {+ vi.useRealTimers();+ if (originalResourcesPath) {+ Object.defineProperty(process, 'resourcesPath', originalResourcesPath);+ } else {+ Reflect.deleteProperty(process, 'resourcesPath');+ }+ });++ it('maps helper press/release messages and ignores repeated keydown', 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":"pressed","pressed":true}\n');+ child.stdoutData('{"type":"pressed","pressed":false}\n');++ expect(onTrigger.mock.calls.map(([phase]) => phase)).toEqual(['start', 'tap']);+ listener.stop();+ });++ it('ends a held activation and restarts the helper on a system release', async () => {+ const { WindowsFunctionKeyShortcutListener } =+ await import('../WindowsFunctionKeyShortcutListener.js');+ const onTrigger = vi.fn();+ const listener = new WindowsFunctionKeyShortcutListener({ onTrigger });+ await startReady(listener);+ const first = mocks.spawnedChildren[0];+ first.stdoutData('{"type":"pressed","pressed":true}\n');++ listener.releaseActiveTrigger();+ await flush();++ expect(onTrigger.mock.calls.map(([phase]) => phase)).toEqual(['start', 'end']);+ expect(first.kill).toHaveBeenCalledTimes(1);+ expect(mocks.spawnedChildren).toHaveLength(2);+ mocks.spawnedChildren[1].stdoutData('{"type":"ready"}\n');+ await flush();+ listener.stop();+ });++ it('ends an active activation once when the helper exits unexpectedly', 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.handlers.get('exit')?.(1, null);++ expect(onTrigger.mock.calls.map(([phase]) => phase)).toEqual(['start', 'end']);+ 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 6988ecdab2..2721510869 100644--- a/apps/desktop/src/main/voice-input/__tests__/globalShortcut.test.ts+++ b/apps/desktop/src/main/voice-input/__tests__/globalShortcut.test.ts@@ -84,6 +84,7 @@ const mocks = vi.hoisted(() => {const modifierSetShortcut = vi.fn();const modifierStop = vi.fn();const modifierReleaseShortcut = vi.fn();+ const modifierReleaseActiveTrigger = vi.fn();const modifierIsRunning = vi.fn();const modifierIsReady = vi.fn();const modifierStartKeyCapture = vi.fn();@@ -91,6 +92,10 @@ const mocks = vi.hoisted(() => {const modifierPendingStartResult = vi.fn((): Promise<unknown> | null => null);const inputMonitoringSnapshot = vi.fn();const requestInputMonitoring = vi.fn();+ const windowsSetShortcut = vi.fn();+ const windowsStop = vi.fn();+ const windowsReleaseActiveTrigger = vi.fn();+ const windowsIsReady = vi.fn();const assertTrustedAppRenderer = vi.fn();const updateSettings = vi.fn();// 存盘里的快捷键。global-shortcut:set 只负责「让运行期对上存盘」,所以非 null 的同步@@ -114,6 +119,9 @@ const mocks = vi.hoisted(() => {onKeys?: (keys: string[]) => void;onTrigger?: (phase: 'tap' | 'start' | 'end') => void;} = {};+ const windowsListenerOptions: {+ onTrigger?: (phase: 'tap' | 'start' | 'end') => void;+ } = {};const registerShortcut = vi.fn((accelerator: string) => {void accelerator;return true;@@ -138,16 +146,22 @@ const mocks = vi.hoisted(() => {modifierSetShortcut,modifierStop,modifierReleaseShortcut,+ modifierReleaseActiveTrigger,modifierIsRunning,modifierIsReady,modifierStartKeyCapture,modifierPendingStartResult,inputMonitoringSnapshot,requestInputMonitoring,+ windowsSetShortcut,+ windowsStop,+ windowsReleaseActiveTrigger,+ windowsIsReady,assertTrustedAppRenderer,getMainWindow,ipcDeps,listenerOptions,+ windowsListenerOptions,updateSettings,getSettings,setStoredShortcut,@@ -212,27 +226,46 @@ vi.mock('../index.js', () => ({}));vi.mock('../MacModifierShortcutListener.js', () => ({- MacModifierShortcutListener: vi.fn().mockImplementation((options: {- onKeys?: (keys: string[]) => void;- onTrigger?: (phase: 'tap' | 'start' | 'end') => void;- }) => {- mocks.listenerOptions.onKeys = options?.onKeys;- mocks.listenerOptions.onTrigger = options?.onTrigger;- return {- setShortcut: mocks.modifierSetShortcut,- isRunning: mocks.modifierIsRunning,- isReady: mocks.modifierIsReady,- stop: mocks.modifierStop,- releaseShortcutKeepingCapture: mocks.modifierReleaseShortcut,- stopKeyCapture: vi.fn(),- startKeyCapture: mocks.modifierStartKeyCapture,- pendingStartResult: mocks.modifierPendingStartResult,- };- }),+ MacModifierShortcutListener: vi+ .fn()+ .mockImplementation(+ (options: {+ onKeys?: (keys: string[]) => void;+ onTrigger?: (phase: 'tap' | 'start' | 'end') => void;+ }) => {+ mocks.listenerOptions.onKeys = options?.onKeys;+ mocks.listenerOptions.onTrigger = options?.onTrigger;+ return {+ setShortcut: mocks.modifierSetShortcut,+ isRunning: mocks.modifierIsRunning,+ isReady: mocks.modifierIsReady,+ stop: mocks.modifierStop,+ releaseShortcutKeepingCapture: mocks.modifierReleaseShortcut,+ releaseActiveTrigger: mocks.modifierReleaseActiveTrigger,+ stopKeyCapture: vi.fn(),+ startKeyCapture: mocks.modifierStartKeyCapture,+ pendingStartResult: mocks.modifierPendingStartResult,+ };+ },+ ),getMacInputMonitoringPermissionSnapshot: mocks.inputMonitoringSnapshot,requestMacInputMonitoringPermission: mocks.requestInputMonitoring,}));+vi.mock('../WindowsFunctionKeyShortcutListener.js', () => ({+ WindowsFunctionKeyShortcutListener: vi+ .fn()+ .mockImplementation((options: { onTrigger?: (phase: 'tap' | 'start' | 'end') => void }) => {+ mocks.windowsListenerOptions.onTrigger = options?.onTrigger;+ return {+ setShortcut: mocks.windowsSetShortcut,+ isReady: mocks.windowsIsReady,+ stop: mocks.windowsStop,+ releaseActiveTrigger: mocks.windowsReleaseActiveTrigger,+ };+ }),+}));+vi.mock('../VoiceInputDataStore.js', () => ({voiceInputDataStore: {updateSettings: mocks.updateSettings,@@ -276,6 +309,7 @@ describe('voice input global shortcut registration', () => {mocks.modifierIsReady.mockImplementation(() => mocks.modifierIsRunning() as boolean);mocks.modifierStop.mockClear();mocks.modifierReleaseShortcut.mockClear();+ mocks.modifierReleaseActiveTrigger.mockClear();mocks.modifierStartKeyCapture.mockReset();mocks.modifierStartKeyCapture.mockResolvedValue({ ok: true });// 默认已授权:既有用例断言的是「拿得到权限时」的注册行为。@@ -283,6 +317,12 @@ describe('voice input global shortcut registration', () => {mocks.inputMonitoringSnapshot.mockResolvedValue({ ok: true, status: 'granted' });mocks.requestInputMonitoring.mockReset();mocks.requestInputMonitoring.mockResolvedValue({ ok: true, status: 'granted' });+ mocks.windowsSetShortcut.mockReset();+ mocks.windowsSetShortcut.mockResolvedValue({ ok: true });+ mocks.windowsStop.mockClear();+ mocks.windowsReleaseActiveTrigger.mockClear();+ mocks.windowsIsReady.mockReset();+ mocks.windowsIsReady.mockReturnValue(true);// 默认放行通用 sender 闸;需要验证它本身时在用例里让它抛。mocks.assertTrustedAppRenderer.mockReset();mocks.mainWindowIsDestroyed.mockReset();@@ -312,7 +352,7 @@ describe('voice input global shortcut registration', () => {setTimeoutSpy = null;});- it('registers F16 through Electron globalShortcut and routes the press to the focused renderer', async () => {+ it('uses the macOS native listener for F16 phases and Electron only to reserve the key', async () => {setPlatform('darwin');const { registerGlobalVoiceInputIpc } = await import('../global.js');registerGlobalVoiceInputIpc(mocks.ipcDeps);@@ -336,17 +376,57 @@ describe('voice input global shortcut registration', () => {mocks.setStoredShortcut(f16Shortcut);await setShortcut?.({}, f16Shortcut);- expect(mocks.modifierSetShortcut).not.toHaveBeenCalled();+ expect(mocks.modifierSetShortcut).toHaveBeenCalledWith(f16Shortcut);expect(mocks.registeredShortcuts.has('F16')).toBe(true);+ // The Electron callback only owns reservation/suppression.mocks.registeredShortcuts.get('F16')?.();+ expect(mocks.focusedWindow.webContents.send).not.toHaveBeenCalled();++ // Press/release phases come from the native listener.+ mocks.listenerOptions.onTrigger?.('start');++ expect(mocks.focusedWindow.webContents.send).toHaveBeenCalledWith(+ 'voice-input:global-shortcut-trigger',+ expect.objectContaining({ id: expect.any(String), phase: 'start' }),+ );+ });++ it('uses the Windows low-level listener for F16 without Electron registration', async () => {+ setPlatform('win32');+ 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);+ await setShortcut?.({}, f16Shortcut);++ expect(mocks.windowsSetShortcut).toHaveBeenCalledWith(f16Shortcut);+ expect(mocks.registeredShortcuts.has('F16')).toBe(false);++ mocks.windowsListenerOptions.onTrigger?.('start');expect(mocks.focusedWindow.webContents.send).toHaveBeenCalledWith('voice-input:global-shortcut-trigger',- expect.objectContaining({ id: expect.any(String) }),+ expect.objectContaining({ id: expect.any(String), phase: 'start' }),);});+ it('releases both native listener states on system power transitions', async () => {+ setPlatform('darwin');+ const { releaseActiveGlobalVoiceInputShortcut } = await import('../global.js');++ releaseActiveGlobalVoiceInputShortcut();++ expect(mocks.modifierReleaseActiveTrigger).toHaveBeenCalledTimes(1);+ expect(mocks.windowsReleaseActiveTrigger).toHaveBeenCalledTimes(1);+ });+it('does not re-register an unchanged native macOS shortcut from multiple windows', async () => {setPlatform('darwin');const { registerGlobalVoiceInputIpc } = await import('../global.js');@@ -577,13 +657,13 @@ describe('voice input global shortcut registration', () => {});// preflight 那次 await 期间用户完全可能把快捷键改成别的。拿 await 之前抓的那份去- // 注册,就会在用户的新变更之后把旧的修饰键装回去 —— 存盘/界面停在 F16,实际生效的+ // 注册,就会在用户的新变更之后把旧的修饰键装回去 —— 存盘/界面停在 Ctrl+F16,实际生效的// 却是旧那个。所以要注册的那个必须在队列里现读现校验。it('re-reads the stored shortcut inside the queue instead of using the pre-await snapshot', async () => {setPlatform('darwin');mocks.setStoredShortcut(bareRightOption);mocks.modifierIsRunning.mockReturnValue(false);- // preflight 卡住,期间用户改成了 F16(不需要 native listener)。+ // preflight 卡住,期间用户改成了 Ctrl+F16(不需要 native listener)。let settlePreflight: (snapshot: unknown) => void = () => {};mocks.inputMonitoringSnapshot.mockImplementationOnce(() => new Promise((resolve) => { settlePreflight = resolve; }),@@ -599,7 +679,7 @@ describe('voice input global shortcut registration', () => {trigger: 'keyboard',code: 'F16',key: 'F16',- modifiers: { meta: false, ctrl: false, alt: false, shift: false, fn: false },+ modifiers: { meta: false, ctrl: true, alt: false, shift: false, fn: false },});settlePreflight({ ok: true, status: 'granted' });await new Promise((resolve) => { setImmediate(resolve); });@@ -762,7 +842,7 @@ describe('voice input global shortcut registration', () => {expect(consume?.(mocks.settingsEvent)).toEqual({ failed: true });});- // preflight 期间用户把快捷键换成 F16(不需要监听权限)并成功存盘 —— 那条失败态已经被清掉,+ // preflight 期间用户把快捷键换成 Ctrl+F16(不需要监听权限)并成功存盘 —— 那条失败态已经被清掉,// 迟到的 unknown 不该再凭一个已经不存在的目标重新造一条「重启 Cindy 再试」。it('does not publish a preflight failure after the pending shortcut was replaced', async () => {setPlatform('darwin');@@ -778,15 +858,15 @@ describe('voice input global shortcut registration', () => {mocks.appListeners.get('browser-window-focus')?.();await new Promise((resolve) => { setImmediate(resolve); });- // 期间用户改成 F16 并成功存盘。- const f16: VoiceInputShortcut = {+ // 期间用户改成 Ctrl+F16 并成功存盘。+ const ctrlF16: VoiceInputShortcut = {trigger: 'keyboard',code: 'F16',key: 'F16',- modifiers: { meta: false, ctrl: false, alt: false, shift: false, fn: false },+ modifiers: { meta: false, ctrl: true, alt: false, shift: false, fn: false },};- mocks.setStoredShortcut(f16);- await mocks.handlers.get('voice-input:settings:update-shortcut')?.({}, f16);+ mocks.setStoredShortcut(ctrlF16);+ await mocks.handlers.get('voice-input:settings:update-shortcut')?.({}, ctrlF16);// preflight 这才带着 unknown 迟到返回。settlePreflight({ ok: false, status: 'unknown', error: 'helper unavailable' });@@ -1179,7 +1259,7 @@ describe('voice input global shortcut registration', () => {expect(mocks.modifierSetShortcut).not.toHaveBeenCalled();});- // 失败之后用户把快捷键换成 F16(或清空), 兜底恢复再也不会跑(没有需要监听权限的快捷键+ // 失败之后用户把快捷键换成 Ctrl+F16(或清空), 兜底恢复再也不会跑(没有需要监听权限的快捷键// 了), 这条失败就永远挂着 —— 此后每开一个应用外壳窗口都会取到它, 弹一条与当前状态无关// 的「重启 Cindy 再试」。it('clears a stale recovery failure once the user changes the shortcut', async () => {@@ -1192,13 +1272,16 @@ describe('voice input global shortcut registration', () => {await focusWindow();- // 用户改成 F16:走 Electron accelerator,压根不需要监听权限。- const update = await mocks.handlers.get('voice-input:settings:update-shortcut')?.({}, {- trigger: 'keyboard',- code: 'F16',- key: 'F16',- modifiers: { meta: false, ctrl: false, alt: false, shift: false, fn: false },- });+ // 用户改成 Ctrl+F16:走 Electron accelerator,压根不需要监听权限。+ const update = await mocks.handlers.get('voice-input:settings:update-shortcut')?.(+ {},+ {+ trigger: 'keyboard',+ code: 'F16',+ key: 'F16',+ modifiers: { meta: false, ctrl: true, alt: false, shift: false, fn: false },+ },+ );expect(update).toMatchObject({ ok: true });const consume = mocks.handlers.get('voice-input:consume-shortcut-recovery-failure');@@ -1489,6 +1572,12 @@ describe('voice input global shortcut registration', () => {key: 'F16',modifiers: { meta: false, ctrl: false, alt: false, shift: false, fn: false },};+ const ctrlF16: VoiceInputShortcut = {+ trigger: 'keyboard',+ code: 'F16',+ key: 'F16',+ modifiers: { meta: false, ctrl: true, alt: false, shift: false, fn: false },+ };// 构造真实状态: 另一个窗口在录(会话活跃), 这边提交 F16 —— 按本轮改动注册会照常发生,// 于是 accelerator 确实是注册着的。直接在挂起之后去取回调是空转断言:挂起会把 accelerator@@ -1503,7 +1592,7 @@ describe('voice input global shortcut registration', () => {expect(mocks.registeredShortcuts.has('F16')).toBe(true);}- it('drops accelerator triggers while another window is recording', async () => {+ it('drops native F-key activations while another window is recording', async () => {setPlatform('darwin');const { registerGlobalVoiceInputIpc } = await import('../global.js');registerGlobalVoiceInputIpc(mocks.ipcDeps);@@ -1511,7 +1600,7 @@ describe('voice input global shortcut registration', () => {await recordElsewhereThenCommitF16();mocks.focusedWindow.webContents.send.mockClear();- mocks.registeredShortcuts.get('F16')?.();+ mocks.listenerOptions.onTrigger?.('start');expect(mocks.focusedWindow.webContents.send).not.toHaveBeenCalledWith('voice-input:global-shortcut-trigger',@@ -1519,7 +1608,7 @@ describe('voice input global shortcut registration', () => {);});- it('resumes triggers once the recorder closes', async () => {+ it('resumes native F-key activations once the recorder closes', async () => {setPlatform('darwin');const { registerGlobalVoiceInputIpc } = await import('../global.js');registerGlobalVoiceInputIpc(mocks.ipcDeps);@@ -1528,15 +1617,15 @@ describe('voice input global shortcut registration', () => {await mocks.handlers.get('voice-input:modifier-shortcut-recording:stop')?.(mocks.settingsEvent);mocks.focusedWindow.webContents.send.mockClear();- mocks.registeredShortcuts.get('F16')?.();+ mocks.listenerOptions.onTrigger?.('start');expect(mocks.focusedWindow.webContents.send).toHaveBeenCalledWith('voice-input:global-shortcut-trigger',- expect.objectContaining({ id: expect.any(String) }),+ expect.objectContaining({ id: expect.any(String), phase: 'start' }),);});- // 同一个 helper 既服务常驻监听也服务录制页的 Fn 检测。一边提交 F16(走 accelerator 路径,+ // 同一个 helper 既服务常驻监听也服务录制页的 Fn 检测。一边提交 Ctrl+F16(走 accelerator 路径,// 会停掉 native listener)时不能把另一边的 keys 来源一起杀掉 —— 那个窗口的录制框还开着,// 却再也收不到 Fn, 只能关掉重开。it('keeps the shared capture alive for other recorders when committing an accelerator', async () => {@@ -1548,7 +1637,7 @@ describe('voice input global shortcut registration', () => {await mocks.handlers.get('voice-input:modifier-shortcut-recording:start')?.(mocks.recordingEvent);mocks.modifierStop.mockClear();- await mocks.handlers.get('voice-input:settings:update-shortcut')?.({}, f16);+ await mocks.handlers.get('voice-input:settings:update-shortcut')?.({}, ctrlF16);// 关键:没有 stop 掉共享 helper,只放弃了快捷键。expect(mocks.modifierStop).not.toHaveBeenCalled();@@ -1570,7 +1659,7 @@ describe('voice input global shortcut registration', () => {registerGlobalVoiceInputIpc(mocks.ipcDeps);mocks.modifierStop.mockClear();- await mocks.handlers.get('voice-input:settings:update-shortcut')?.({}, f16);+ await mocks.handlers.get('voice-input:settings:update-shortcut')?.({}, ctrlF16);expect(mocks.modifierStop).toHaveBeenCalled();expect(mocks.modifierReleaseShortcut).not.toHaveBeenCalled();diff --git a/apps/desktop/src/main/voice-input/__tests__/powerReleaseNotifier.test.ts b/apps/desktop/src/main/voice-input/__tests__/powerReleaseNotifier.test.tsindex 53a7ca689e..6886d5d39c 100644--- a/apps/desktop/src/main/voice-input/__tests__/powerReleaseNotifier.test.ts+++ b/apps/desktop/src/main/voice-input/__tests__/powerReleaseNotifier.test.ts@@ -26,10 +26,12 @@ describe('installVoiceInputPowerRelease', () => {it('broadcasts a release reason on suspend and lock-screen', () => {const powerMonitor = createFakePowerMonitor();const broadcast = vi.fn();+ const releaseActiveShortcut = vi.fn();installVoiceInputPowerRelease({powerMonitor,broadcast,+ releaseActiveShortcut,logger: { debug: vi.fn() },});@@ -42,6 +44,10 @@ describe('installVoiceInputPowerRelease', () => {expect(broadcast).toHaveBeenNthCalledWith(2, VOICE_INPUT_POWER_STATE_CHANNEL, {reason: 'screen_locked',});+ expect(releaseActiveShortcut).toHaveBeenCalledTimes(2);+ expect(releaseActiveShortcut.mock.invocationCallOrder[0]).toBeLessThan(+ broadcast.mock.invocationCallOrder[0],+ );});it('keeps broadcasting after one window fails mid-teardown', () => {diff --git a/apps/desktop/src/main/voice-input/global.ts b/apps/desktop/src/main/voice-input/global.tsindex abbf968164..44c076600b 100644--- a/apps/desktop/src/main/voice-input/global.ts+++ b/apps/desktop/src/main/voice-input/global.ts@@ -28,7 +28,9 @@ import {VOICE_INPUT_DICTIONARY_LEARNING_TRACK_TIMEOUT_MS,} from '../../shared/voiceInputDictionaryLearning.js';import {+ isVoiceInputBareFunctionKeyShortcut,voiceInputShortcutNeedsMacNativeListener,+ voiceInputShortcutNeedsWindowsNativeListener,type VoiceInputSettings,type VoiceInputShortcut,} from '../../shared/voiceInputData.js';@@ -38,6 +40,7 @@ import {requestMacInputMonitoringPermission,type MacInputMonitoringPermissionSnapshot,} from './MacModifierShortcutListener.js';+import { WindowsFunctionKeyShortcutListener } from './WindowsFunctionKeyShortcutListener.js';import {computeOverlayPositionRatio,isBoundsCenterOnDisplay,@@ -99,29 +102,31 @@ function hasActiveShortcutRecordingSession(): boolean {*/let nativeActivationStartDelivered = false;+function handleNativeGlobalShortcutPhase(phase: GlobalVoiceInputShortcutPhase): void {+ if (phase !== 'end' && hasActiveShortcutRecordingSession()) {+ // 挡掉 start 就等于这次激活在下游不存在,它后面那条配对的 end 也必须一起挡掉。+ if (phase === 'start') nativeActivationStartDelivered = false;+ log.debug('ignoring native global shortcut activation while recording', { phase });+ return;+ }+ if (phase === 'end' && !nativeActivationStartDelivered) {+ log.debug('ignoring native global shortcut end without a delivered start');+ return;+ }+ // tap 没有配对的 end;end 到这里就算消费掉了。两种都把配对状态清干净。+ nativeActivationStartDelivered = phase === 'start';+ log.debug('native global shortcut triggered', { phase });+ if (phase === 'tap') {+ handleGlobalVoiceInputShortcutTap();+ } else if (phase === 'start') {+ handleGlobalVoiceInputShortcut('start');+ } else {+ handleGlobalVoiceInputShortcutSubmit();+ }+}+const macModifierShortcutListener = new MacModifierShortcutListener({- onTrigger: (phase) => {- if (phase !== 'end' && hasActiveShortcutRecordingSession()) {- // 挡掉 start 就等于这次激活在下游不存在,它后面那条配对的 end 也必须一起挡掉。- if (phase === 'start') nativeActivationStartDelivered = false;- log.debug('ignoring native global shortcut activation while recording', { phase });- return;- }- if (phase === 'end' && !nativeActivationStartDelivered) {- log.debug('ignoring native global shortcut end without a delivered start');- return;- }- // tap 没有配对的 end;end 到这里就算消费掉了。两种都把配对状态清干净。- nativeActivationStartDelivered = phase === 'start';- log.debug('native global shortcut triggered', { phase });- if (phase === 'tap') {- handleGlobalVoiceInputShortcutTap();- } else if (phase === 'start') {- handleGlobalVoiceInputShortcut('start');- } else {- handleGlobalVoiceInputShortcutSubmit();- }- },+ onTrigger: handleNativeGlobalShortcutPhase,onKeys: (keys) => {for (const webContentsId of Array.from(modifierShortcutRecordingWebContentsIds)) {const window = BrowserWindow.getAllWindows()@@ -135,6 +140,15 @@ const macModifierShortcutListener = new MacModifierShortcutListener({},});+const windowsFunctionKeyShortcutListener = new WindowsFunctionKeyShortcutListener({+ onTrigger: handleNativeGlobalShortcutPhase,+});++export function releaseActiveGlobalVoiceInputShortcut(): void {+ macModifierShortcutListener.releaseActiveTrigger();+ windowsFunctionKeyShortcutListener.releaseActiveTrigger();+}+type VoiceInputGlobalResult =| { ok: true }| { ok: false; error: string; errorCode?: VoiceInputGlobalErrorCode };@@ -1495,6 +1509,7 @@ export function registerGlobalVoiceInputIpc(deps: GlobalVoiceInputIpcDeps): voidregisteredNativeShortcutLabel = null;registeredNativeShortcutKey = null;macModifierShortcutListener.stop();+ windowsFunctionKeyShortcutListener.stop();unregisterOverlayCancelShortcut();destroyOverlayWindow();});@@ -1516,7 +1531,28 @@ function stopNativeShortcutListenerPreservingCapture(): void {macModifierShortcutListener.stop();}-async function setVoiceInputGlobalShortcut(shortcut: VoiceInputShortcut | null): Promise<VoiceInputGlobalResult> {+const WINDOWS_NATIVE_LISTENER_FAILURE_MESSAGE =+ 'Could not start the Windows voice input shortcut listener.';++type WindowsNativeListenerStartResult =+ { ok: true } | { ok: false; error: string; superseded?: true };++async function startWindowsNativeListener(+ start: () => Promise<WindowsNativeListenerStartResult>,+): Promise<WindowsNativeListenerStartResult> {+ try {+ return await start();+ } catch (error) {+ log.warn('Windows native shortcut listener threw while starting', {+ error: stringifyError(error),+ });+ return { ok: false, error: WINDOWS_NATIVE_LISTENER_FAILURE_MESSAGE };+ }+}++async function setVoiceInputGlobalShortcut(+ shortcut: VoiceInputShortcut | null,+): Promise<VoiceInputGlobalResult> {if (process.platform === 'linux' && shortcut) {return {ok: false,@@ -1534,6 +1570,7 @@ async function setVoiceInputGlobalShortcut(shortcut: VoiceInputShortcut | null):registeredNativeShortcutLabel = null;registeredNativeShortcutKey = null;stopNativeShortcutListenerPreservingCapture();+ windowsFunctionKeyShortcutListener.stop();destroyOverlayWindow();log.info('global shortcut disabled');return { ok: true };@@ -1544,6 +1581,28 @@ async function setVoiceInputGlobalShortcut(shortcut: VoiceInputShortcut | null):return { ok: false, error: 'Function/modifier voice input shortcuts are only available on macOS.' };}const nativeShortcutKey = stableVoiceInputShortcutKey(shortcut);+ const reservationAccelerator = isVoiceInputBareFunctionKeyShortcut(shortcut)+ ? toElectronAccelerator(shortcut)+ : null;+ if (isVoiceInputBareFunctionKeyShortcut(shortcut) && !reservationAccelerator) {+ return { ok: false, error: 'Unsupported voice input shortcut.' };+ }+ const reservedNewAccelerator = Boolean(+ reservationAccelerator && registeredAccelerator !== reservationAccelerator,+ );+ if (+ reservedNewAccelerator &&+ !globalShortcut.register(reservationAccelerator as string, () => {+ // Native key snapshots own start/tap/end. Electron only reserves the+ // bare F-key so it does not also reach the foreground application.+ })+ ) {+ log.warn('global shortcut reservation failed', { accelerator: reservationAccelerator });+ return {+ ok: false,+ error: `Global shortcut is already in use: ${reservationAccelerator}`,+ };+ }// 复用已注册的那次要求**已就绪**,不是「进程在跑」。scheduleRestart 起的替补不经过// setShortcut,所以 registeredNativeShortcutKey 一直是旧值:替补还没报 ready 时用 isRunning// 判断就会在这里返回成功,而此刻没人在监听。两处后果:@@ -1556,11 +1615,21 @@ async function setVoiceInputGlobalShortcut(shortcut: VoiceInputShortcut | null):// 落到这里之后走 setShortcut:child 还在但没就绪时它会等那次启动的真实落点// (MacModifierShortcutListener.awaitInFlightChild),所以这里不会凭空多 spawn 一个 helper。// 兜底恢复的 pendingNativeShortcutRecoveryTarget 用的也是 isReady,两条路口径至此一致。- if (registeredNativeShortcutKey === nativeShortcutKey && macModifierShortcutListener.isReady()) {+ if (+ registeredNativeShortcutKey === nativeShortcutKey &&+ macModifierShortcutListener.isReady()+ ) {+ if (reservedNewAccelerator && reservationAccelerator) {+ if (registeredAccelerator) globalShortcut.unregister(registeredAccelerator);+ registeredAccelerator = reservationAccelerator;+ }return { ok: true };}const result = await startMacNativeListener(() => macModifierShortcutListener.setShortcut(shortcut));if (!result.ok && result.superseded) {+ if (reservedNewAccelerator && reservationAccelerator) {+ globalShortcut.unregister(reservationAccelerator);+ }// 被更晚的一轮顶掉:那一轮才决定最终注册结果,这里既不回滚(会踩掉它刚建立的// 状态)也不报故障(这次调用已经过时)。调用方按 'superseded' 静默丢弃即可。log.debug('native global shortcut registration superseded', { code: shortcut.code });@@ -1590,9 +1659,13 @@ async function setVoiceInputGlobalShortcut(shortcut: VoiceInputShortcut | null):registeredShortcut = shortcut;registeredNativeShortcutLabel = getNativeShortcutLogLabel(shortcut);registeredNativeShortcutKey = nativeShortcutKey;+ if (reservationAccelerator) registeredAccelerator = reservationAccelerator;return { ok: true };}}+ if (reservedNewAccelerator && reservationAccelerator) {+ globalShortcut.unregister(reservationAccelerator);+ }const errorCode = await classifyMacNativeListenerFailure();log.warn('native global shortcut registration failed', {code: shortcut.code,@@ -1604,10 +1677,11 @@ async function setVoiceInputGlobalShortcut(shortcut: VoiceInputShortcut | null):// 带着 helper 源码/二进制的内部路径,不能过 IPC 边界。return { ok: false, error: MAC_NATIVE_LISTENER_FAILURE_MESSAGE, errorCode };}- if (registeredAccelerator) {+ if (registeredAccelerator && registeredAccelerator !== reservationAccelerator) {globalShortcut.unregister(registeredAccelerator);- registeredAccelerator = null;}+ registeredAccelerator = reservationAccelerator;+ windowsFunctionKeyShortcutListener.stop();registeredShortcut = shortcut;registeredNativeShortcutLabel = getNativeShortcutLogLabel(shortcut);registeredNativeShortcutKey = nativeShortcutKey;@@ -1621,6 +1695,60 @@ async function setVoiceInputGlobalShortcut(shortcut: VoiceInputShortcut | null):return { ok: true };}+ if (voiceInputShortcutNeedsWindowsNativeListener(shortcut, process.platform)) {+ const nativeShortcutKey = stableVoiceInputShortcutKey(shortcut);+ if (+ registeredNativeShortcutKey === nativeShortcutKey &&+ windowsFunctionKeyShortcutListener.isReady()+ ) {+ return { ok: true };+ }+ const previousShortcut = registeredShortcut;+ const result = await startWindowsNativeListener(() =>+ windowsFunctionKeyShortcutListener.setShortcut(shortcut),+ );+ if (!result.ok && result.superseded) {+ return { ok: false, error: result.error, errorCode: 'superseded' };+ }+ if (!result.ok) {+ if (+ previousShortcut &&+ voiceInputShortcutNeedsWindowsNativeListener(previousShortcut, process.platform)+ ) {+ const restored = await startWindowsNativeListener(() =>+ windowsFunctionKeyShortcutListener.setShortcut(previousShortcut),+ );+ if (restored.ok && stableVoiceInputShortcutKey(previousShortcut) === nativeShortcutKey) {+ registeredShortcut = shortcut;+ registeredNativeShortcutLabel = getNativeShortcutLogLabel(shortcut);+ registeredNativeShortcutKey = nativeShortcutKey;+ return { ok: true };+ }+ }+ log.warn('Windows native global shortcut registration failed', {+ code: shortcut.code,+ error: result.error,+ });+ return {+ ok: false,+ error: WINDOWS_NATIVE_LISTENER_FAILURE_MESSAGE,+ errorCode: 'failed',+ };+ }+ if (registeredAccelerator) {+ globalShortcut.unregister(registeredAccelerator);+ registeredAccelerator = null;+ }+ registeredShortcut = shortcut;+ registeredNativeShortcutLabel = getNativeShortcutLogLabel(shortcut);+ registeredNativeShortcutKey = nativeShortcutKey;+ stopNativeShortcutListenerPreservingCapture();+ log.info('Windows native global shortcut registered', { code: shortcut.code });+ void prewarmVoiceInputProvider();+ setTimeout(() => prewarmGlobalVoiceInputOverlay(), 1500);+ return { ok: true };+ }+const accelerator = toElectronAccelerator(shortcut);if (!accelerator) {return { ok: false, error: 'Unsupported voice input shortcut.' };@@ -1645,6 +1773,7 @@ async function setVoiceInputGlobalShortcut(shortcut: VoiceInputShortcut | null):registeredNativeShortcutLabel = null;registeredNativeShortcutKey = null;stopNativeShortcutListenerPreservingCapture();+ windowsFunctionKeyShortcutListener.stop();log.info('global shortcut registered', { accelerator });// First-press warmup: read auth.json now so the very first shortcut press// does not pay for it on the critical path.diff --git a/apps/desktop/src/main/voice-input/powerReleaseNotifier.ts b/apps/desktop/src/main/voice-input/powerReleaseNotifier.tsindex 9f0f5bf1ad..9bdec55d16 100644--- a/apps/desktop/src/main/voice-input/powerReleaseNotifier.ts+++ b/apps/desktop/src/main/voice-input/powerReleaseNotifier.ts@@ -28,6 +28,8 @@ export interface VoicePowerMonitorLike {export interface VoiceInputPowerReleaseDeps {powerMonitor: VoicePowerMonitorLike;+ /** End a global push-to-talk press before the OS can lose its key-up event. */+ releaseActiveShortcut?: () => void;/** 把 payload 送到所有 renderer;注入以便单测断言广播内容。 */broadcast: (channel: string, payload: VoiceInputPowerStatePayload) => void;logger?: Pick<typeof log, 'debug'>;@@ -73,6 +75,7 @@ export function installVoiceInputPowerRelease(deps: VoiceInputPowerReleaseDeps):const logger = deps.logger ?? log;const emit = (reason: VoiceInputPowerReleaseReason): void => {logger.debug('voice input keep-alive release broadcast', { reason });+ deps.releaseActiveShortcut?.();deps.broadcast(VOICE_INPUT_POWER_STATE_CHANNEL, { reason });};diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex a6d8621d7e..81fbca1fe0 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -979,7 +979,7 @@},"inputMonitoring": {"label": "Shortcut listener",- "tooltip": "Used to listen for Fn, standalone Command / Option / Control, and Fn-based voice input shortcuts. Regular key combinations and standalone F1-F24 keys usually do not need it. Granted means the currently running app can listen for shortcuts; dev builds may be authorized through Terminal."+ "tooltip": "Used to listen for Fn, standalone Command / Option / Control, Fn-based shortcuts, and standalone F1-F24 push-to-talk release events. Regular key combinations do not need it. Granted means the currently running app can listen for shortcuts; dev builds may be authorized through Terminal."},"accessibility": {"label": "Automatic input",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 4e6f602b02..8a808f97e6 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -979,7 +979,7 @@},"inputMonitoring": {"label": "ショートカット監視",- "tooltip": "Fn、単独の Command / Option / Control、Fn を含む音声入力ショートカットを検出するために使います。通常の組み合わせキーや F1-F24 単独キーでは多くの場合不要です。許可済みは、現在実行中のアプリがショートカットを監視できることを意味します。開発版では Terminal 経由で許可される場合があります。"+ "tooltip": "Fn、単独の Command / Option / Control、Fn を含むショートカット、および F1-F24 単独キーの長押し音声入力でキーを放したことを検出するために使います。通常の組み合わせキーには不要です。許可済みは、現在実行中のアプリがショートカットを監視できることを意味します。開発版では Terminal 経由で許可される場合があります。"},"accessibility": {"label": "自動入力",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 9e41f0d2a0..3098bb96a7 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -979,7 +979,7 @@},"inputMonitoring": {"label": "단축키 감지 권한",- "tooltip": "Fn, 단독 Command / Option / Control, Fn이 포함된 음성 입력 단축키를 감지하는 데 사용됩니다. 일반 조합 단축키와 F1-F24 단일 키에는 보통 필요하지 않습니다. 허용됨은 현재 실행 중인 앱이 단축키를 감지할 수 있다는 뜻이며, 개발 빌드에서는 Terminal을 통해 권한이 부여될 수 있습니다."+ "tooltip": "Fn, 단독 Command / Option / Control, Fn이 포함된 단축키, 그리고 F1-F24 단일 키의 길게 눌러 말하기에서 키를 놓는 시점을 감지하는 데 사용됩니다. 일반 조합 단축키에는 필요하지 않습니다. 허용됨은 현재 실행 중인 앱이 단축키를 감지할 수 있다는 뜻이며, 개발 빌드에서는 Terminal을 통해 권한이 부여될 수 있습니다."},"accessibility": {"label": "자동 입력",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex ca6b5a97d2..61290dcc98 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -979,7 +979,7 @@},"inputMonitoring": {"label": "监听权限",- "tooltip": "用于监听 Fn、单独 Command / Option / Control 以及带 Fn 的语音输入快捷键。普通组合键和 F1-F24 单键通常不需要。已授权表示当前运行中的 App 可以监听快捷键;开发版可能由 Terminal 承载授权。"+ "tooltip": "用于监听 Fn、单独 Command / Option / Control、带 Fn 的快捷键,以及 F1-F24 单键按住说话的松键事件。普通组合键不需要。已授权表示当前运行中的 App 可以监听快捷键;开发版可能由 Terminal 承载授权。"},"accessibility": {"label": "自动输入",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex de580c2078..9566b6e0dd 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -979,7 +979,7 @@},"inputMonitoring": {"label": "監聽權限",- "tooltip": "用於監聽 Fn、單獨 Command / Option / Control 以及帶 Fn 的語音輸入快捷鍵。普通組合鍵和 F1-F24 單鍵通常不需要。已授權表示當前執行中的 App 可以監聽快捷鍵;開發版可能由 Terminal 承載授權。"+ "tooltip": "用於監聽 Fn、單獨 Command / Option / Control、帶 Fn 的快捷鍵,以及 F1-F24 單鍵按住說話的放開事件。普通組合鍵不需要。已授權表示目前執行中的 App 可以監聽快捷鍵;開發版可能由 Terminal 承載授權。"},"accessibility": {"label": "自動輸入",diff --git a/apps/desktop/src/renderer/voice-input/__tests__/voiceInputData.test.ts b/apps/desktop/src/renderer/voice-input/__tests__/voiceInputData.test.tsindex 686b0b674f..10c7a8fd47 100644--- a/apps/desktop/src/renderer/voice-input/__tests__/voiceInputData.test.ts+++ b/apps/desktop/src/renderer/voice-input/__tests__/voiceInputData.test.ts@@ -3,12 +3,14 @@ import { describe, expect, it } from 'vitest';import {createVoiceInputShortcutFromMacNativeKeys,getDefaultVoiceInputSettings,+ isVoiceInputBareFunctionKeyShortcut,isVoiceInputMacNativeKeyboardShortcutPressed,isVoiceInputMacNativeKeyboardShortcutTargetDown,isVoiceInputModifierShortcut,normalizeVoiceInputSettings,normalizeVoiceInputShortcut,voiceInputShortcutNeedsMacNativeListener,+ voiceInputShortcutNeedsWindowsNativeListener,} from '../../../shared/voiceInputData';import {createVoiceInputModifierShortcut,@@ -199,7 +201,7 @@ describe('voice input shortcut recording helpers', () => {expect(isVoiceInputMacNativeKeyboardShortcutPressed(['Fn', 'ShiftRight', 'KeyCode:19'], shortcut!)).toBe(false);});- it('keeps macOS function-key shortcuts on Electron globalShortcut unless Fn is involved', () => {+ it('routes standalone F1-F24 shortcuts through native press/release listeners', () => {const shortcut = normalizeVoiceInputShortcut({trigger: 'keyboard',code: 'F16',@@ -214,12 +216,40 @@ describe('voice input shortcut recording helpers', () => {});expect(shortcut).not.toBeNull();- expect(voiceInputShortcutNeedsMacNativeListener(shortcut, 'darwin')).toBe(false);+ expect(isVoiceInputBareFunctionKeyShortcut(shortcut)).toBe(true);+ expect(voiceInputShortcutNeedsMacNativeListener(shortcut, 'darwin')).toBe(true);expect(voiceInputShortcutNeedsMacNativeListener(shortcut, 'win32')).toBe(false);- expect(isVoiceInputMacNativeKeyboardShortcutPressed(['KeyCode:106'], shortcut!)).toBe(false);- expect(isVoiceInputMacNativeKeyboardShortcutPressed(['Fn', 'KeyCode:106'], shortcut!)).toBe(false);- expect(isVoiceInputMacNativeKeyboardShortcutPressed(['ShiftLeft', 'KeyCode:106'], shortcut!)).toBe(false);- expect(isVoiceInputMacNativeKeyboardShortcutTargetDown(['ShiftLeft', 'KeyCode:106'], shortcut!)).toBe(false);- expect(isVoiceInputMacNativeKeyboardShortcutTargetDown(['KeyCode:105'], shortcut!)).toBe(false);+ expect(voiceInputShortcutNeedsWindowsNativeListener(shortcut, 'win32')).toBe(true);+ expect(isVoiceInputMacNativeKeyboardShortcutPressed(['Function:F16'], shortcut!)).toBe(true);+ expect(isVoiceInputMacNativeKeyboardShortcutPressed(['Fn', 'Function:F16'], shortcut!)).toBe(+ false,+ );+ expect(+ isVoiceInputMacNativeKeyboardShortcutPressed(['ShiftLeft', 'Function:F16'], shortcut!),+ ).toBe(false);+ expect(+ isVoiceInputMacNativeKeyboardShortcutTargetDown(['ShiftLeft', 'Function:F16'], shortcut!),+ ).toBe(true);+ expect(isVoiceInputMacNativeKeyboardShortcutTargetDown(['Function:F15'], shortcut!)).toBe(+ false,+ );++ const f24 = normalizeVoiceInputShortcut({+ trigger: 'keyboard',+ code: 'F24',+ key: 'F24',+ modifiers: { meta: false, ctrl: false, alt: false, shift: false, fn: false },+ });+ expect(isVoiceInputMacNativeKeyboardShortcutPressed(['Function:F24'], f24!)).toBe(true);++ const modified = normalizeVoiceInputShortcut({+ trigger: 'keyboard',+ code: 'F16',+ key: 'F16',+ modifiers: { meta: false, ctrl: true, alt: false, shift: false, fn: false },+ });+ expect(isVoiceInputBareFunctionKeyShortcut(modified)).toBe(false);+ expect(voiceInputShortcutNeedsMacNativeListener(modified, 'darwin')).toBe(false);+ expect(voiceInputShortcutNeedsWindowsNativeListener(modified, 'win32')).toBe(false);});});diff --git a/apps/desktop/src/shared/voiceInputData.ts b/apps/desktop/src/shared/voiceInputData.tsindex 52880fe206..577f5c24fd 100644--- a/apps/desktop/src/shared/voiceInputData.ts+++ b/apps/desktop/src/shared/voiceInputData.ts@@ -228,6 +228,8 @@ export const VOICE_INPUT_CODE_TO_MAC_NATIVE_KEY_CODE: Readonly<Record<string, nuObject.entries(MAC_NATIVE_KEY_CODE_TO_VOICE_INPUT_KEY).map(([keyCode, value]) => [value.code, Number(keyCode)]),);+const VOICE_INPUT_FUNCTION_KEY_CODE_PATTERN = /^F(?:[1-9]|1[0-9]|2[0-4])$/;+export const DEFAULT_VOICE_INPUT_REFINEMENT_INSTRUCTIONS = ['让文本清楚自然,不明显改写;保留我的语气,不改成公文或客服话术。','保留技术词、模型名、产品名、变量、路径、命令和大小写。',@@ -320,25 +322,47 @@ export function isVoiceInputModifierShortcut(return Boolean(shortcut?.trigger === 'modifier' && isVoiceInputModifierShortcutCode(shortcut.code));}+export function isVoiceInputBareFunctionKeyShortcut(+ shortcut: VoiceInputShortcut | null | undefined,+): shortcut is VoiceInputShortcut & { trigger: 'keyboard' } {+ if (!shortcut || shortcut.trigger === 'modifier') return false;+ return (+ VOICE_INPUT_FUNCTION_KEY_CODE_PATTERN.test(shortcut.code) &&+ !shortcut.modifiers.meta &&+ !shortcut.modifiers.ctrl &&+ !shortcut.modifiers.alt &&+ !shortcut.modifiers.shift &&+ !shortcut.modifiers.fn+ );+}+export function isVoiceInputMacNativeKeyboardShortcut(shortcut: VoiceInputShortcut | null | undefined,): shortcut is VoiceInputShortcut & { trigger: 'keyboard' } {if (!shortcut || shortcut.trigger === 'modifier') return false;- if (!(shortcut.code in VOICE_INPUT_CODE_TO_MAC_NATIVE_KEY_CODE)) return false;- // Only Fn-based keyboard shortcuts need the listen-only native helper.- // Plain function keys such as F16 can be registered by Electron's- // globalShortcut without prompting for macOS Input Monitoring permission.- return Boolean(shortcut.modifiers.fn);+ if (isVoiceInputBareFunctionKeyShortcut(shortcut)) return true;+ if (!shortcut.modifiers.fn) return false;+ return (+ shortcut.code in VOICE_INPUT_CODE_TO_MAC_NATIVE_KEY_CODE ||+ VOICE_INPUT_FUNCTION_KEY_CODE_PATTERN.test(shortcut.code)+ );}export function voiceInputShortcutNeedsMacNativeListener(shortcut: VoiceInputShortcut | null | undefined,platform: string,): boolean {+ if (platform !== 'darwin') return false;if (isVoiceInputModifierShortcut(shortcut)) return true;if (!shortcut || shortcut.trigger === 'modifier') return false;- if (shortcut.modifiers.fn) return isVoiceInputMacNativeKeyboardShortcut(shortcut);- return platform === 'darwin' && isVoiceInputMacNativeKeyboardShortcut(shortcut);+ return isVoiceInputMacNativeKeyboardShortcut(shortcut);+}++export function voiceInputShortcutNeedsWindowsNativeListener(+ shortcut: VoiceInputShortcut | null | undefined,+ platform: string,+): boolean {+ return platform === 'win32' && isVoiceInputBareFunctionKeyShortcut(shortcut);}export function createVoiceInputShortcutFromMacNativeKeys(keys: readonly string[]): VoiceInputShortcut | null {@@ -360,10 +384,21 @@ export function createVoiceInputShortcutFromMacNativeKeys(keys: readonly string[};}- const nonModifierKeys = keys.filter((key) => key.startsWith('KeyCode:'));+ const nonModifierKeys = keys.filter(+ (key) => key.startsWith('KeyCode:') || key.startsWith('Function:'),+ );if (nonModifierKeys.length !== 1) return null;- const keyCode = Number(nonModifierKeys[0].slice('KeyCode:'.length));- const mapped = MAC_NATIVE_KEY_CODE_TO_VOICE_INPUT_KEY[keyCode];+ const nativeKey = nonModifierKeys[0];+ const functionCode = nativeKey.startsWith('Function:')+ ? nativeKey.slice('Function:'.length)+ : null;+ const keyCode = nativeKey.startsWith('KeyCode:')+ ? Number(nativeKey.slice('KeyCode:'.length))+ : Number.NaN;+ const mapped =+ functionCode && VOICE_INPUT_FUNCTION_KEY_CODE_PATTERN.test(functionCode)+ ? { code: functionCode, key: functionCode }+ : MAC_NATIVE_KEY_CODE_TO_VOICE_INPUT_KEY[keyCode];if (!mapped) return null;return {@@ -386,10 +421,12 @@ export function isVoiceInputMacNativeKeyboardShortcutPressed(): boolean {if (!isVoiceInputMacNativeKeyboardShortcut(shortcut)) return false;const keySet = new Set(keys);- const expectedKeyCode = VOICE_INPUT_CODE_TO_MAC_NATIVE_KEY_CODE[shortcut.code];- if (typeof expectedKeyCode !== 'number') return false;- const nonModifierKeys = keys.filter((key) => key.startsWith('KeyCode:'));- if (nonModifierKeys.length !== 1 || nonModifierKeys[0] !== `KeyCode:${expectedKeyCode}`) return false;+ const expectedNativeKey = getMacNativeShortcutKey(shortcut);+ if (!expectedNativeKey) return false;+ const nonModifierKeys = keys.filter(+ (key) => key.startsWith('KeyCode:') || key.startsWith('Function:'),+ );+ if (nonModifierKeys.length !== 1 || nonModifierKeys[0] !== expectedNativeKey) return false;return (keySet.has('Fn') === shortcut.modifiers.fn &&@@ -405,8 +442,16 @@ export function isVoiceInputMacNativeKeyboardShortcutTargetDown(shortcut: VoiceInputShortcut,): boolean {if (!isVoiceInputMacNativeKeyboardShortcut(shortcut)) return false;+ const expectedNativeKey = getMacNativeShortcutKey(shortcut);+ return Boolean(expectedNativeKey && keys.includes(expectedNativeKey));+}++function getMacNativeShortcutKey(shortcut: VoiceInputShortcut): string | null {+ if (VOICE_INPUT_FUNCTION_KEY_CODE_PATTERN.test(shortcut.code)) {+ return `Function:${shortcut.code}`;+ }const expectedKeyCode = VOICE_INPUT_CODE_TO_MAC_NATIVE_KEY_CODE[shortcut.code];- return typeof expectedKeyCode === 'number' && keys.includes(`KeyCode:${expectedKeyCode}`);+ return typeof expectedKeyCode === 'number' ? `KeyCode:${expectedKeyCode}` : null;}export function getDefaultVoiceInputSettings(diff --git a/docs/legal/notices/desktop-win.txt b/docs/legal/notices/desktop-win.txtindex c9eddf527a..84a4be025d 100644--- a/docs/legal/notices/desktop-win.txt+++ b/docs/legal/notices/desktop-win.txt@@ -13,7 +13,7 @@ We are grateful to all open source authors and maintainers.------------------------------------------------------------------------------SCOPE NOTES:- - 包含 Rust/Tauri updater 运行时 crate 闭包和随包 Android Platform-Tools。+ - 包含 Rust/Tauri updater、Windows 功能键监听器的运行时 crate 闭包和随包 Android Platform-Tools。受限或专有第三方组件不列入开源包数量,另见配套的 THIRD-PARTY-RESTRICTED.txt。Restricted or proprietary components are disclosed in the companion file.diff --git a/scripts/generate-third-party-notices.mjs b/scripts/generate-third-party-notices.mjsindex af98bfc013..f2c43b8276 100644--- a/scripts/generate-third-party-notices.mjs+++ b/scripts/generate-third-party-notices.mjs@@ -32,12 +32,16 @@ const DESKTOP_DIR = path.join(REPO_ROOT, "apps", "desktop");const MOBILE_DIR = path.join(REPO_ROOT, "apps", "mobile");const NOTICES_DIR = path.join(REPO_ROOT, "docs", "legal", "notices");const SBOM_DIR = path.join(NOTICES_DIR, "sbom");-const CARGO_MANIFEST = path.join(- DESKTOP_DIR,- "cindy-updater",- "src-tauri",- "Cargo.toml",-);+const CARGO_MANIFESTS = [+ path.join(DESKTOP_DIR, "cindy-updater", "src-tauri", "Cargo.toml"),+ path.join(+ DESKTOP_DIR,+ "native",+ "voice-input",+ "windows-function-key-listener",+ "Cargo.toml",+ ),+];/** 与 pnpm-workspace.yaml 的客户端 workspace 范围保持一致。 */function discoverWorkspaceDirs() {@@ -461,8 +465,8 @@ function cargoExecutable() {return candidate && fs.existsSync(candidate) ? candidate : "cargo";}-/** 收集 Windows updater 的运行时依赖闭包,跳过根包的 build/dev dependency。 */-function collectCargoClosure() {+/** 收集单个 Windows Rust 二进制的运行时依赖闭包,跳过根包的 build/dev dependency。 */+function collectCargoClosure(manifest) {const raw = execFileSync(cargoExecutable(),[@@ -473,7 +477,7 @@ function collectCargoClosure() {"--filter-platform","x86_64-pc-windows-msvc","--manifest-path",- CARGO_MANIFEST,+ manifest,],{ encoding: "utf8", maxBuffer: 64 * 1024 * 1024 },).replace(/^\uFEFF/, "");@@ -1097,7 +1101,9 @@ function stableCreationTime() {"--format=%cI","--","pnpm-lock.yaml",- path.relative(REPO_ROOT, CARGO_MANIFEST),+ ...CARGO_MANIFESTS.map((manifest) =>+ path.relative(REPO_ROOT, manifest),+ ),],{ cwd: REPO_ROOT, encoding: "utf8" },).trim();@@ -1347,10 +1353,12 @@ function assertTrackedBinariesRegistered() {assertNativeDeclarations();assertProjectPodspecLicenses();assertTrackedBinariesRegistered();-if (!fs.existsSync(path.join(path.dirname(CARGO_MANIFEST), "Cargo.lock"))) {- throw new Error(- "cindy-updater Cargo.lock is required for deterministic license generation",- );+for (const manifest of CARGO_MANIFESTS) {+ if (!fs.existsSync(path.join(path.dirname(manifest), "Cargo.lock"))) {+ throw new Error(+ `${path.relative(REPO_ROOT, manifest)} requires Cargo.lock for deterministic license generation`,+ );+ }}const projectNpm = collectClosureForSupportedTargets([@@ -1381,7 +1389,9 @@ const mobileAndroidNpm = collectClosure([MOBILE_DIR], {os: "android",cpu: "arm64",});-const cargoClosure = collectCargoClosure();+const cargoClosure = mergeClosures(+ ...CARGO_MANIFESTS.map((manifest) => collectCargoClosure(manifest)),+);const apacheText =projectNpm.packages.find(@@ -1401,7 +1411,7 @@ const artifactDefinitions = {productName: "Cindy desktop application — Windows x64",description: ["Windows x64 桌面安装包的第三方开源组件声明。"],notes: [- "包含 Rust/Tauri updater 运行时 crate 闭包和随包 Android Platform-Tools。",+ "包含 Rust/Tauri updater、Windows 功能键监听器的运行时 crate 闭包和随包 Android Platform-Tools。",],},"desktop-macos": {