Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
fix(windows): stop offering hotkeys the missing key listener can't fire (#2239)
voiddb095baa9490
diff --git a/main.js b/main.jsindex 70bc0bbe5..730e17a6d 100644--- a/main.js+++ b/main.js@@ -609,6 +609,8 @@ function initializeCoreManagers() {windowManager.linuxKeyManager = linuxKeyManager;if (process.platform === "linux") {windowManager.hotkeyManager.nativeListenerProbe = () => linuxKeyManager.checkAvailability();+ } else if (process.platform === "win32") {+ windowManager.hotkeyManager.nativeListenerProbe = () => windowsKeyManager.checkAvailability();}// IPC handlers must be registered before window content loads@@ -1214,6 +1216,7 @@ async function startApp() {"hotkey");}+ hotkeyManager.notifyRestoreFailures(savedVoiceAgentKey, result);}// Set up translation hotkey (dictation cleaned up and translated into the@@ -1239,6 +1242,7 @@ async function startApp() {"hotkey");}+ hotkeyManager.notifyRestoreFailures(savedTranslationKey, result);}// Set up meeting mode hotkey@@ -1261,6 +1265,7 @@ async function startApp() {{ savedMeetingKey, ...result },"meeting");+ hotkeyManager.notifyRestoreFailures(savedMeetingKey, result);}ipcMain.handle("register-meeting-hotkey", async (_event, hotkey) => {diff --git a/src/components/OnboardingFlow.tsx b/src/components/OnboardingFlow.tsxindex 93c54b43b..cdc15a5d7 100644--- a/src/components/OnboardingFlow.tsx+++ b/src/components/OnboardingFlow.tsx@@ -512,10 +512,10 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {const confirmAssistantHotkey = useCallback(async (value: string) => {- const registered = await settings.setVoiceAgentKey(+ const result = await settings.setVoiceAgentKey(serializeHotkeyList([value, ...parseHotkeyList(settings.voiceAgentKey).slice(1)]));- return registered ? null : t("onboarding.rehaul.hotkey.inUse");+ return result.success ? null : result.message || t("onboarding.rehaul.hotkey.inUse");},[settings, t]);@@ -709,14 +709,14 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {setDictationHotkeyConfirmed(true);} else if (currentStepId === "assistant-hotkey") {if (parseHotkeyList(settings.voiceAgentKey)[0] !== assistantHotkey) {- const registered = await settings.setVoiceAgentKey(+ const result = await settings.setVoiceAgentKey(serializeHotkeyList([assistantHotkey,...parseHotkeyList(settings.voiceAgentKey).slice(1),]));- if (!registered) {- setFatalError(t("onboarding.rehaul.hotkey.inUse"));+ if (!result.success) {+ setFatalError(result.message || t("onboarding.rehaul.hotkey.inUse"));return;}}diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsxindex 339c67e9b..2f5cc57bf 100644--- a/src/components/SettingsPage.tsx+++ b/src/components/SettingsPage.tsx@@ -128,6 +128,7 @@ import {TRANSCRIPTION_ENTERPRISE_POLICY_PROVIDER_IDS,TRANSCRIPTION_POLICY_PROVIDER_IDS,useSettingsStore,+ type HotkeyRegistrationResult,} from "../stores/settingsStore";import { useWorkspaceStore } from "../stores/workspaceStore";import { highestPlan } from "../lib/usageStore";@@ -1502,17 +1503,17 @@ export default function SettingsPage({// surface it and return the result so HotkeyListInput rolls the row back.const [isAgentHotkeyCommitting, setIsAgentHotkeyCommitting] = useState(false);const commitAgentHotkey = useCallback(- async (setter: (key: string) => Promise<boolean>, key: string) => {+ async (setter: (key: string) => Promise<HotkeyRegistrationResult>, key: string) => {setIsAgentHotkeyCommitting(true);try {- const ok = await setter(key);- if (!ok) {+ const result = await setter(key);+ if (!result.success) {showAlertDialog({title: t("hooks.hotkeyRegistration.titles.notRegistered"),- description: t("hooks.hotkeyRegistration.errors.failedToRegister"),+ description: result.message || t("hooks.hotkeyRegistration.errors.failedToRegister"),});}- return ok;+ return result.success;} finally {setIsAgentHotkeyCommitting(false);}diff --git a/src/components/onboarding/hotkeyPresentation.ts b/src/components/onboarding/hotkeyPresentation.tsindex 8eed06d7b..f2adc3001 100644--- a/src/components/onboarding/hotkeyPresentation.ts+++ b/src/components/onboarding/hotkeyPresentation.ts@@ -151,13 +151,16 @@ export const resolveOnboardingAssistantHotkey = (savedHotkey: string): string =>* effective default alone by choice, not by capability: a modifier-only default* like Control+Super runs through the same native listener, so input-device* access is a shared prerequisite there rather than the price of a lone right- * modifier.+ * modifier. Right Ctrl needs the same Windows key listener as the Control+Super+ * default, so when main reports another default the listener is missing.*/export const getRecommendedDictationHotkeys = (platform: Platform,effectiveDefault: string): string[] => {if (platform === "darwin") return [MACOS_DEFAULT_ONBOARDING_HOTKEY, "GLOBE", "Control+R"];- if (platform === "win32") return ["RightControl", effectiveDefault];+ if (platform === "win32" && effectiveDefault === "Control+Super") {+ return ["RightControl", effectiveDefault];+ }return [effectiveDefault];};diff --git a/src/helpers/hotkeyManager.js b/src/helpers/hotkeyManager.jsindex 15e02f509..a5f445581 100644--- a/src/helpers/hotkeyManager.js+++ b/src/helpers/hotkeyManager.js@@ -19,6 +19,14 @@ const DEFAULT_HOTKEY = "Control+Super";// Dictation has a dedicated native path because it also supports push-to-talk.const LINUX_NATIVE_TAP_SLOTS = new Set(["meeting", "voiceAgent", "translation"]);+// Settings titles that name each slot in a conflict message, as the renderer does.+const SLOT_LABEL_KEYS = {+ dictation: "settingsPage.general.hotkey.title",+ voiceAgent: "settingsPage.general.voiceAgentHotkey.title",+ translation: "settingsPage.general.translationHotkey.title",+ meeting: "settingsPage.general.meetingHotkey.title",+};+// KDE registration failure reasons — reuse existing i18n keysconst KDE_FAILURE_REASONS = {conflict: (hotkey) => i18nMain.t("hotkey.errors.alreadyRegistered", { hotkey }),@@ -111,8 +119,8 @@ class HotkeyManager extends EventEmitter {this.hyprlandRegistrationReady = Promise.resolve();this.kdeManager = null;this.useKDE = false;- // Injected by main.js on Linux: LinuxKeyManager.checkAvailability. Kept as a- // function so this module never requires the manager it asks about.+ // Injected by main.js: LinuxKeyManager or WindowsKeyManager checkAvailability.+ // Kept as a function so this module never requires the manager it asks about.this.nativeListenerProbe = null;}@@ -197,7 +205,18 @@ class HotkeyManager extends EventEmitter {suggestions = ["Control+Super", "Control+Shift+K", "Super+Shift+R"];}- return suggestions.filter((s) => s !== failedHotkey).slice(0, 3);+ const listenerMissing = this._isWindowsKeyListenerMissing();+ // A key another slot holds would only be refused as a conflict. Slots without+ // a callback are placeholders, not registered hotkeys.+ const boundHotkeys = new Set(+ [...this.slots.values()].filter((slot) => slot.callback).flatMap((slot) => slot.hotkeys)+ );+ const isUsable = (hotkey) =>+ hotkey !== failedHotkey &&+ !boundHotkeys.has(hotkey) &&+ !(listenerMissing && isModifierOnlyHotkey(hotkey));+ const usable = suggestions.filter(isUsable);+ return (usable.length > 0 ? usable : FALLBACK_HOTKEYS.filter(isUsable)).slice(0, 3);}async registerSlot(slotName, hotkeyInput, callback, options) {@@ -455,13 +474,25 @@ class HotkeyManager extends EventEmitter {return keys;}- // What to tell the user when the Linux native listener cannot run.- _nativeListenerFailureMessage(reason) {- return reason === "input_access_denied"- ? `${i18nMain.t("settingsPage.general.hotkey.linuxPttSetupDescription")} ${i18nMain.t(- "settingsPage.general.hotkey.linuxPttPermissionDescription"- )}`- : i18nMain.t("windows.pttUnavailable");+ // What to tell the user when the native listener cannot run. Only a hotkey+ // refusal names the hotkey; Hold's reason is about the mode, not the key.+ _nativeListenerFailureMessage(reason, hotkey) {+ if (reason === "input_access_denied") {+ return `${i18nMain.t("settingsPage.general.hotkey.linuxPttSetupDescription")} ${i18nMain.t(+ "settingsPage.general.hotkey.linuxPttPermissionDescription"+ )}`;+ }+ if (process.platform === "win32" && hotkey) {+ return i18nMain.t("hotkey.errors.windowsKeyListenerMissing", { hotkey });+ }+ return i18nMain.t("windows.pttUnavailable");+ }++ // Windows builds can ship without windows-key-listener.exe (#2005). Only it sees+ // modifier-only and right-side-modifier hotkeys, so without it the defaults and+ // suggestions must be regular keys.+ _isWindowsKeyListenerMissing() {+ return process.platform === "win32" && this.nativeListenerProbe?.().available === false;}// GNOME, KDE and Hyprland deliver press and release themselves, so Linux@@ -472,10 +503,16 @@ class HotkeyManager extends EventEmitter {return process.platform === "linux" && this.isInitialized && !this.isUsingNativeShortcut();}- // Where Linux relies on the listener, a probe failure means Hold cannot work+ // Windows always holds through its listener. It waits for initialization too,+ // so a saved Hold is restored and then checked by main.js the same way as Linux.+ _holdReliesOnNativeListener() {+ return (process.platform === "win32" && this.isInitialized) || this.reliesOnLinuxKeyListener();+ }++ // Where Hold relies on the listener, a probe failure means Hold cannot work// at all. Returns the reason to show the user, or null when nothing blocks it._pushToTalkListenerBlockReason() {- if (!this.reliesOnLinuxKeyListener() || !this.nativeListenerProbe) return null;+ if (!this._holdReliesOnNativeListener() || !this.nativeListenerProbe) return null;const { available, reason } = this.nativeListenerProbe();return available ? null : this._nativeListenerFailureMessage(reason);}@@ -592,23 +629,28 @@ class HotkeyManager extends EventEmitter {return { mouseButtons: [...mouseButtons], suppressGlobeAction };}- // A hotkey only the Linux evdev listener can serve must fail registration when- // that listener cannot run (no binary, or no read access to /dev/input):- // everything that rescues the user — the FALLBACK_HOTKEYS loop plus its toast- // on startup, the inline error in Settings and onboarding, the slot rollback —- // hangs off a failed registration, so reporting success leaves dictation- // silently dead. Returns null when the hotkey can be served.+ // A hotkey only the Linux evdev listener or windows-key-listener.exe can serve+ // must fail registration when that listener cannot run (no binary, or on Linux+ // no read access to /dev/input): everything that rescues the user — the+ // FALLBACK_HOTKEYS loop plus its toast on startup, the inline error in Settings+ // and onboarding, the slot rollback — hangs off a failed registration, so+ // reporting success leaves dictation silently dead. Returns null when the+ // hotkey can be served._nativeListenerUnavailable(hotkey) {- if (process.platform !== "linux" || !this.nativeListenerProbe) return null;+ if (process.platform !== "linux" && process.platform !== "win32") return null;+ if (!this.nativeListenerProbe) return null;const { available, reason } = this.nativeListenerProbe();if (available) return null;+ debugLogger.warn(`[HotkeyManager] "${hotkey}" rejected - native key listener unavailable`, {+ reason,+ });const deniedAccess = reason === "input_access_denied";return {success: false,hotkey,- error: this._nativeListenerFailureMessage(reason),+ error: this._nativeListenerFailureMessage(reason, hotkey),reason: deniedAccess ? "input_access_denied" : "native_listener_unavailable",// Only regular-key hotkeys avoid the listener that just failed.suggestions: this.getSuggestions(hotkey).filter(@@ -699,7 +741,11 @@ class HotkeyManager extends EventEmitter {};} catch (error) {debugLogger.error("Error setting up shortcut", { error: error.message }, "hotkey");- return { success: false, hotkey, error: error.message };+ return {+ success: false,+ hotkey,+ error: i18nMain.t("hotkey.errors.registrationFailed", { hotkey }),+ };}}@@ -847,7 +893,9 @@ class HotkeyManager extends EventEmitter {return {success: false,error: i18nMain.t("hotkey.errors.slotConflict", {- slot: otherSlotName,+ slot: SLOT_LABEL_KEYS[otherSlotName]+ ? i18nMain.t(SLOT_LABEL_KEYS[otherSlotName])+ : otherSlotName,defaultValue: `This hotkey is already used for ${otherSlotName}`,}),reason: "slot_conflict",@@ -1197,6 +1245,7 @@ class HotkeyManager extends EventEmitter {}}+ let savedFailure = null;if (savedHotkey && savedHotkey.trim() !== "") {const result = this.setupShortcuts(savedHotkey, callback);if (result.success) {@@ -1205,12 +1254,16 @@ class HotkeyManager extends EventEmitter {return;}debugLogger.log(`[HotkeyManager] Saved hotkey "${savedHotkey}" failed to register`);- this.notifyHotkeyFailure(savedHotkey, result);+ savedFailure = result;}const defaultHotkey = this.getEffectiveDefaultHotkey();+ // The user knows their saved hotkey, not the default, so a replacement is+ // reported against the hotkey they chose.+ const replacedHotkey = savedFailure ? savedHotkey : defaultHotkey;if (defaultHotkey === "GLOBE") {+ if (savedFailure) this.notifyHotkeyFailure(savedHotkey, savedFailure);this.currentHotkey = "GLOBE";debugLogger.log("[HotkeyManager] Using GLOBE key as default on macOS");await this._persistHotkeyToEnvFile("GLOBE");@@ -1222,6 +1275,11 @@ class HotkeyManager extends EventEmitter {debugLogger.log(`[HotkeyManager] Default hotkey "${defaultHotkey}" registered successfully`);+ // The saved hotkey stays saved so the next launch retries it.+ if (savedFailure) {+ this.notifyActiveHotkey(defaultHotkey);+ this.notifyHotkeyFallback(savedHotkey, defaultHotkey);+ }return;}@@ -1237,12 +1295,13 @@ class HotkeyManager extends EventEmitter {// app retries it on next startup once the conflict is resolved.await this._persistHotkeyToEnvFile(fallback);this.notifyActiveHotkey(fallback);- this.notifyHotkeyFallback(defaultHotkey, fallback);+ this.notifyHotkeyFallback(replacedHotkey, fallback);return;}}debugLogger.log("[HotkeyManager] All hotkey fallbacks failed");+ if (savedFailure) this.notifyHotkeyFailure(savedHotkey, savedFailure);this.notifyHotkeyFailure(defaultHotkey, result);} catch (err) {debugLogger.error("Failed to initialize hotkey", { error: err.message }, "hotkey");@@ -1323,11 +1382,13 @@ class HotkeyManager extends EventEmitter {/*** Returns the effective default hotkey for the current platform.- * On platforms where Control+Super doesn't work (X11 modifier-only,- * GNOME gsettings requires a regular key), returns the first fallback (F8).+ * Where Control+Super doesn't work (X11 modifier-only, GNOME gsettings+ * requires a regular key, Windows without its key listener), returns the+ * first fallback (F8).*/getEffectiveDefaultHotkey() {if (process.platform === "darwin") return "GLOBE";+ if (this._isWindowsKeyListenerMissing()) return FALLBACK_HOTKEYS[0];if (process.platform !== "linux") return DEFAULT_HOTKEY;const isX11 = !GnomeShortcutManager.isWayland();@@ -1382,6 +1443,13 @@ class HotkeyManager extends EventEmitter {// Tell the renderer which hotkeys actually registered and which failed._notifyStartupRegistration(requestedHotkey, result) {this.notifyActiveHotkey(result.hotkeys ? result.hotkeys.join(",") : requestedHotkey);+ this.notifyRestoreFailures(requestedHotkey, result);+ }++ // Tell the user which saved hotkeys no longer register, so a slot never goes+ // silently dead at startup.+ notifyRestoreFailures(requestedHotkey, result) {+ if (!result.success) this.notifyHotkeyFailure(requestedHotkey, result);for (const failure of result.failures || []) {this.notifyHotkeyFailure(failure.hotkey, failure);}diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex 50e988e85..2f02c4691 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -4300,10 +4300,7 @@ class IPCHandlers {? requestedHotkey.split(",")[0].trim(): hotkeyManager.getCurrentHotkey();const isUsingNativeShortcut = this.windowManager.isUsingNativeShortcutHotkeys();- const supportsPushToTalk =- process.platform === "linux" || process.platform === "darwin"- ? hotkeyManager.supportsPushToTalk(hotkey)- : !isUsingNativeShortcut;+ const supportsPushToTalk = hotkeyManager.supportsPushToTalk(hotkey);return {isUsingGnome: this.windowManager.isUsingGnomeHotkeys(),@@ -11332,7 +11329,7 @@ class IPCHandlers {const hotkeyManager = this.windowManager.hotkeyManager;const voiceAgentCallback = this.windowManager._voiceAgentHotkeyCallback;if (!voiceAgentCallback) {- return { success: false, message: "Voice agent hotkey callback not initialized" };+ return { success: false };}if (!hotkey) {@@ -11354,10 +11351,7 @@ class IPCHandlers {return { success: true, message: `Voice agent hotkey updated to: ${hotkey}` };}- return {- success: false,- message: result.error || `Failed to update voice agent hotkey to: ${hotkey}`,- };+ return { success: false, message: result.error };});ipcMain.handle("get-voice-agent-key", async () => {@@ -11368,7 +11362,7 @@ class IPCHandlers {const hotkeyManager = this.windowManager.hotkeyManager;const translationCallback = this.windowManager._translationHotkeyCallback;if (!translationCallback) {- return { success: false, message: "Translation hotkey callback not initialized" };+ return { success: false };}if (!hotkey) {@@ -11390,10 +11384,7 @@ class IPCHandlers {return { success: true, message: `Translation hotkey updated to: ${hotkey}` };}- return {- success: false,- message: result.error || `Failed to update translation hotkey to: ${hotkey}`,- };+ return { success: false, message: result.error };});ipcMain.handle("get-translation-key", async () => {diff --git a/src/helpers/windowsKeyManager.js b/src/helpers/windowsKeyManager.jsindex f5b3236de..c4c8a77dc 100644--- a/src/helpers/windowsKeyManager.js+++ b/src/helpers/windowsKeyManager.js@@ -164,6 +164,13 @@ class WindowsKeyManager extends EventEmitter {return this.resolveListenerBinary() !== null;}+ // Same shape as LinuxKeyManager.checkAvailability, for HotkeyManager's probe.+ checkAvailability() {+ return this.isAvailable()+ ? { available: true }+ : { available: false, reason: "binary_missing" };+ }+/*** Report an error (only once per session to avoid log spam)*/diff --git a/src/hooks/useMainProcessNotifications.tsx b/src/hooks/useMainProcessNotifications.tsxindex 6db590f23..6421a1bfa 100644--- a/src/hooks/useMainProcessNotifications.tsx+++ b/src/hooks/useMainProcessNotifications.tsx@@ -28,10 +28,12 @@ export function useMainProcessNotifications({});});- const unsubscribeFailed = window.electronAPI?.onHotkeyRegistrationFailed?.((_data) => {+ // Main's translated reason names the hotkey, which matters when several slots+ // restore at startup.+ const unsubscribeFailed = window.electronAPI?.onHotkeyRegistrationFailed?.((data) => {toast({title: t("app.toasts.hotkeyUnavailable.title"),- description: t("app.toasts.hotkeyUnavailable.description"),+ description: data?.error || t("app.toasts.hotkeyUnavailable.description"),duration: 10000,});});diff --git a/src/locales/ar/translation.json b/src/locales/ar/translation.jsonindex 03a4837d4..2b19aaae7 100644--- a/src/locales/ar/translation.json+++ b/src/locales/ar/translation.json@@ -4046,6 +4046,7 @@"rightModifierNeedsListener": "لا يمكن استخدام \"{{hotkey}}\" على سطح المكتب هذا، إذ تحتاج اختصاراته إلى مفتاح عادي. أضف مفتاحًا، مثل Control+Alt+Space.","holdNeedsReleaseKey": "يحتاج الضغط المستمر للتحدث إلى مفتاح يمكن لـ macOS أن يرصد تحريره: Globe، أو مفتاح جانبي أيمن مثل Option الأيمن، أو اختصار مع مفتاح تعديل. أما النقر فيعمل مع أي مفتاح.","registrationFailed": "تعذر تسجيل \"{{hotkey}}\". قد يكون قيد الاستخدام بواسطة تطبيق آخر.",+ "windowsKeyListenerMissing": "يحتاج \"{{hotkey}}\" إلى مستمع مفاتيح Windows، وهو غير موجود في هذا التثبيت. اختر اختصارًا يتضمن مفتاحًا عاديًا.","updateFailedCheckFormat": "فشل تحديث الاختصار إلى \"{{hotkey}}\". تأكد من أن التنسيق صالح.","trySuggestions": "جرّب: {{suggestions}}","slotConflict": "هذا الاختصار مستخدم بالفعل لـ {{slot}}."diff --git a/src/locales/de/translation.json b/src/locales/de/translation.jsonindex 4ff9427b7..ab96a91fb 100644--- a/src/locales/de/translation.json+++ b/src/locales/de/translation.json@@ -124,6 +124,7 @@"rightModifierNeedsListener": "„{{hotkey}}“ kann auf diesem Desktop nicht verwendet werden, da seine Tastenkürzel eine normale Taste benötigen. Fügen Sie eine Taste hinzu, z. B. Control+Alt+Space.","holdNeedsReleaseKey": "Halten zum Sprechen braucht eine Taste, deren Loslassen macOS erkennt: Globe, eine rechte Taste wie Rechte Option oder ein Kürzel mit Modifikator. Tippen funktioniert mit jeder Taste.","registrationFailed": "\"{{hotkey}}\" konnte nicht registriert werden. Möglicherweise wird es von einer anderen Anwendung verwendet.",+ "windowsKeyListenerMissing": "\"{{hotkey}}\" benötigt den Windows-Tasten-Listener, der in dieser Installation fehlt. Wählen Sie ein Tastenkürzel mit einer normalen Taste.","updateFailedCheckFormat": "Hotkey konnte nicht auf \"{{hotkey}}\" aktualisiert werden. Prüfen Sie, ob das Format gültig ist.","trySuggestions": "Versuchen Sie: {{suggestions}}","slotConflict": "Diese Tastenkombination wird bereits für {{slot}} verwendet."diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex cdafcbf21..3ef96d276 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -124,6 +124,7 @@"rightModifierNeedsListener": "\"{{hotkey}}\" can't be used on this desktop, whose shortcuts need a regular key. Add a key, such as Control+Alt+Space.","holdNeedsReleaseKey": "Hold-to-talk needs a key macOS can see you release: Globe, a right-side key like Right Option, or a shortcut with a modifier. Tap works with any key.","registrationFailed": "Could not register \"{{hotkey}}\". It may be in use by another application.",+ "windowsKeyListenerMissing": "\"{{hotkey}}\" needs the Windows key listener, which this install is missing. Choose a shortcut with a regular key.","updateFailedCheckFormat": "Failed to update hotkey to \"{{hotkey}}\". Check the format is valid.","trySuggestions": "Try: {{suggestions}}","slotConflict": "This hotkey is already used for {{slot}}."diff --git a/src/locales/es/translation.json b/src/locales/es/translation.jsonindex ae742fee6..40d71e337 100644--- a/src/locales/es/translation.json+++ b/src/locales/es/translation.json@@ -124,6 +124,7 @@"rightModifierNeedsListener": "\"{{hotkey}}\" no se puede usar en este escritorio, cuyos atajos necesitan una tecla normal. Añade una tecla, como Control+Alt+Space.","holdNeedsReleaseKey": "Mantener para hablar necesita una tecla cuya liberación macOS pueda detectar: Globo, una tecla derecha como Opción derecha o un atajo con modificador. Pulsar funciona con cualquier tecla.","registrationFailed": "No se pudo registrar \"{{hotkey}}\". Puede estar en uso por otra aplicación.",+ "windowsKeyListenerMissing": "\"{{hotkey}}\" necesita el detector de teclas de Windows, que falta en esta instalación. Elige un atajo con una tecla normal.","updateFailedCheckFormat": "No se pudo actualizar el atajo a \"{{hotkey}}\". Comprueba que el formato sea válido.","trySuggestions": "Prueba: {{suggestions}}","slotConflict": "Este atajo ya está asignado a {{slot}}."diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.jsonindex 7c79e9220..a2e751494 100644--- a/src/locales/fr/translation.json+++ b/src/locales/fr/translation.json@@ -124,6 +124,7 @@"rightModifierNeedsListener": "« {{hotkey}} » ne peut pas être utilisé sur ce bureau, dont les raccourcis exigent une touche normale. Ajoutez une touche, par exemple Control+Alt+Space.","holdNeedsReleaseKey": "Maintenir pour parler nécessite une touche dont macOS détecte le relâchement : Globe, une touche droite comme Option droite, ou un raccourci avec modificateur. Appuyer fonctionne avec n’importe quelle touche.","registrationFailed": "Impossible d'enregistrer \"{{hotkey}}\". Il est peut-être utilisé par une autre application.",+ "windowsKeyListenerMissing": "\"{{hotkey}}\" nécessite l'écouteur de touches Windows, absent de cette installation. Choisissez un raccourci avec une touche classique.","updateFailedCheckFormat": "Impossible de mettre à jour le raccourci vers \"{{hotkey}}\". Vérifiez que le format est valide.","trySuggestions": "Essayez : {{suggestions}}","slotConflict": "Ce raccourci est déjà utilisé pour {{slot}}."diff --git a/src/locales/it/translation.json b/src/locales/it/translation.jsonindex 8a051fe7d..5bf72d42f 100644--- a/src/locales/it/translation.json+++ b/src/locales/it/translation.json@@ -124,6 +124,7 @@"rightModifierNeedsListener": "\"{{hotkey}}\" non può essere usato su questo desktop, le cui scorciatoie richiedono un tasto normale. Aggiungi un tasto, ad esempio Control+Alt+Space.","holdNeedsReleaseKey": "Tieni premuto per parlare richiede un tasto di cui macOS rilevi il rilascio: Globo, un tasto destro come Opzione destra o una scorciatoia con modificatore. Tocca funziona con qualsiasi tasto.","registrationFailed": "Impossibile registrare \"{{hotkey}}\". Potrebbe essere in uso da un'altra applicazione.",+ "windowsKeyListenerMissing": "\"{{hotkey}}\" richiede il listener di tasti di Windows, che manca in questa installazione. Scegli una scorciatoia con un tasto normale.","updateFailedCheckFormat": "Impossibile aggiornare la scorciatoia a \"{{hotkey}}\". Verifica che il formato sia valido.","trySuggestions": "Prova: {{suggestions}}","slotConflict": "Questa scorciatoia è già utilizzata per {{slot}}."diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.jsonindex f5ea3121c..e6bcd5235 100644--- a/src/locales/ja/translation.json+++ b/src/locales/ja/translation.json@@ -124,6 +124,7 @@"rightModifierNeedsListener": "\"{{hotkey}}\" はこのデスクトップでは使用できません。ショートカットには通常のキーが必要です。Control+Alt+Space のようにキーを追加してください。","holdNeedsReleaseKey": "ホールドして話すには、macOS が離したことを検知できるキーが必要です。Globe、右 Option のような右側のキー、または修飾キー付きのショートカットです。タップならどのキーでも使えます。","registrationFailed": "\"{{hotkey}}\" を登録できませんでした。別のアプリケーションで使用されている可能性があります。",+ "windowsKeyListenerMissing": "\"{{hotkey}}\" には Windows のキーリスナーが必要ですが、このインストールにはありません。通常のキーを使うショートカットを選んでください。","updateFailedCheckFormat": "「{{hotkey}}」へのホットキーの更新に失敗しました。形式が正しいか確認してください。","trySuggestions": "お試しください: {{suggestions}}","slotConflict": "このホットキーは既に{{slot}}で使用されています。"diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.jsonindex 7aa3ac997..21566dd4a 100644--- a/src/locales/pt/translation.json+++ b/src/locales/pt/translation.json@@ -124,6 +124,7 @@"rightModifierNeedsListener": "\"{{hotkey}}\" não pode ser usada neste ambiente de trabalho, cujos atalhos precisam de uma tecla normal. Adicione uma tecla, como Control+Alt+Space.","holdNeedsReleaseKey": "Segurar para falar precisa de uma tecla cuja soltura o macOS detecte: Globo, uma tecla direita como Option direita ou um atalho com modificador. Tocar funciona com qualquer tecla.","registrationFailed": "Não foi possível registrar \"{{hotkey}}\". Pode estar em uso por outro aplicativo.",+ "windowsKeyListenerMissing": "\"{{hotkey}}\" precisa do listener de teclas do Windows, que está faltando nesta instalação. Escolha um atalho com uma tecla comum.","updateFailedCheckFormat": "Não foi possível atualizar o atalho para \"{{hotkey}}\". Verifique se o formato é válido.","trySuggestions": "Tente: {{suggestions}}","slotConflict": "Este atalho já está sendo usado para {{slot}}."diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.jsonindex 25fafb0f0..7209f95ed 100644--- a/src/locales/ru/translation.json+++ b/src/locales/ru/translation.json@@ -124,6 +124,7 @@"rightModifierNeedsListener": "«{{hotkey}}» нельзя использовать в этой среде рабочего стола: её сочетаниям клавиш нужна обычная клавиша. Добавьте клавишу, например Control+Alt+Space.","holdNeedsReleaseKey": "Для удержания нужна клавиша, отпускание которой macOS может заметить: Globe, правая клавиша вроде правого Option или сочетание с модификатором. Нажатие работает с любой клавишей.","registrationFailed": "Не удалось зарегистрировать «{{hotkey}}». Возможно, она используется другим приложением.",+ "windowsKeyListenerMissing": "«{{hotkey}}» требует слушателя клавиш Windows, которого нет в этой установке. Выберите сочетание с обычной клавишей.","updateFailedCheckFormat": "Не удалось обновить горячую клавишу на «{{hotkey}}». Проверьте правильность формата.","trySuggestions": "Попробуйте: {{suggestions}}","slotConflict": "Эта горячая клавиша уже используется для {{slot}}."diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.jsonindex 305559389..97dd6b373 100644--- a/src/locales/zh-CN/translation.json+++ b/src/locales/zh-CN/translation.json@@ -124,6 +124,7 @@"rightModifierNeedsListener": "\"{{hotkey}}\" 无法在此桌面上使用,其快捷键需要包含一个普通按键。请添加一个按键,例如 Control+Alt+Space。","holdNeedsReleaseKey": "按住说话需要 macOS 能检测到松开的按键:Globe、右侧 Option 之类的右侧按键,或带修饰键的快捷键。点按可用于任何按键。","registrationFailed": "无法注册 \"{{hotkey}}\",该快捷键可能已被其他应用占用。",+ "windowsKeyListenerMissing": "\"{{hotkey}}\" 需要 Windows 按键监听器,但此安装中缺少该组件。请选择包含普通按键的快捷键。","updateFailedCheckFormat": "无法将快捷键更新为 \"{{hotkey}}\",请检查格式是否有效。","trySuggestions": "建议尝试:{{suggestions}}","slotConflict": "此快捷键已用于{{slot}}。"diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.jsonindex 482601c6f..3a9e215c8 100644--- a/src/locales/zh-TW/translation.json+++ b/src/locales/zh-TW/translation.json@@ -124,6 +124,7 @@"rightModifierNeedsListener": "\"{{hotkey}}\" 無法在此桌面上使用,其快捷鍵需要包含一個一般按鍵。請加入一個按鍵,例如 Control+Alt+Space。","holdNeedsReleaseKey": "按住說話需要 macOS 能偵測到放開的按鍵:Globe、右側 Option 之類的右側按鍵,或帶修飾鍵的快速鍵。點按可用於任何按鍵。","registrationFailed": "無法註冊「{{hotkey}}」。可能已被其他應用程式使用。",+ "windowsKeyListenerMissing": "「{{hotkey}}」需要 Windows 按鍵監聽程式,但此安裝中缺少該元件。請選擇包含一般按鍵的快捷鍵。","updateFailedCheckFormat": "無法將快速鍵更新為「{{hotkey}}」。請檢查格式是否有效。","trySuggestions": "試試看:{{suggestions}}","slotConflict": "此快捷鍵已用於{{slot}}。"diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.tsindex 6435badf6..56e73cf4f 100644--- a/src/stores/settingsStore.ts+++ b/src/stores/settingsStore.ts@@ -233,6 +233,9 @@ function readStringArray(key: string, fallback: string[]): string[] {type MicrophoneSelectionMode = "system" | "built-in" | "specific";+// `message` is main's translated reason, when it gave one.+export type HotkeyRegistrationResult = { success: boolean; message?: string };+function migrateMicrophoneSelectionMode() {if (!isBrowser) return;const current = localStorage.getItem("microphoneSelectionMode");@@ -1178,9 +1181,9 @@ export interface SettingsStatesetDictationKey: (key: string) => void;setMeetingKey: (key: string) => void;- setVoiceAgentKey: (key: string) => Promise<boolean>;+ setVoiceAgentKey: (key: string) => Promise<HotkeyRegistrationResult>;translationKey: string;- setTranslationKey: (key: string) => Promise<boolean>;+ setTranslationKey: (key: string) => Promise<HotkeyRegistrationResult>;setMeetingHotkeyLayoutMode: (mode: "side-panel" | "full-width") => void;setOnboardingUseCases: (useCases: string[]) => void;setOnboardingUseCaseNote: (note: string) => void;@@ -1303,14 +1306,13 @@ function createNumberSetter(key: string) {function createRegisteredHotkeySetter(key: "voiceAgentKey" | "translationKey",label: string,- getRegisterFn: () =>- ((hotkey: string) => Promise<{ success: boolean; message: string }>) | undefined,+ getRegisterFn: () => ((hotkey: string) => Promise<HotkeyRegistrationResult>) | undefined,fallbackSave?: (hotkey: string) => void) {- return async (hotkey: string): Promise<boolean> => {+ return async (hotkey: string): Promise<HotkeyRegistrationResult> => {if (!isBrowser) {useSettingsStore.setState({ [key]: hotkey });- return true;+ return { success: true };}const registerFn = getRegisterFn();@@ -1318,7 +1320,7 @@ function createRegisteredHotkeySetter(localStorage.setItem(key, hotkey);useSettingsStore.setState({ [key]: hotkey });fallbackSave?.(hotkey);- return true;+ return { success: true };}const previousKey = useSettingsStore.getState()[key];@@ -1329,19 +1331,19 @@ function createRegisteredHotkeySetter(localStorage.setItem(key, previousKey);useSettingsStore.setState({ [key]: previousKey });logger.warn(`Failed to update ${label}`, { hotkey, message: result?.message }, "settings");- return false;+ return { success: false, message: result?.message };}localStorage.setItem(key, hotkey);useSettingsStore.setState({ [key]: hotkey });- return true;+ return { success: true };} catch (error) {logger.warn(`Failed to update ${label}`,{ hotkey, error: error instanceof Error ? error.message : String(error) },"settings");- return false;+ return { success: false };}};}diff --git a/src/types/electron.ts b/src/types/electron.tsindex a2883eda1..0625a13b4 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -2656,9 +2656,9 @@ declare global {}>;// Agent Mode- updateVoiceAgentHotkey?: (hotkey: string) => Promise<{ success: boolean; message: string }>;+ updateVoiceAgentHotkey?: (hotkey: string) => Promise<{ success: boolean; message?: string }>;getVoiceAgentKey?: () => Promise<string>;- updateTranslationHotkey?: (hotkey: string) => Promise<{ success: boolean; message: string }>;+ updateTranslationHotkey?: (hotkey: string) => Promise<{ success: boolean; message?: string }>;getTranslationKey?: () => Promise<string>;createAgentConversation?: (title: string,diff --git a/test/components/onboardingHotkeyPresentation.test.js b/test/components/onboardingHotkeyPresentation.test.jsindex 696b1ae82..9d7dfa5da 100644--- a/test/components/onboardingHotkeyPresentation.test.js+++ b/test/components/onboardingHotkeyPresentation.test.js@@ -34,10 +34,13 @@ test("macOS recommends Right Option first, followed by Globe/Fn and Ctrl + R", a);assert.deepEqual(getRecommendedDictationHotkeys("linux", "Control+Super"), ["Control+Super"]);// Right Ctrl leads on Windows: right Alt is AltGr on many layouts.- assert.deepEqual(getRecommendedDictationHotkeys("win32", "Control+Shift+Space"), [+ assert.deepEqual(getRecommendedDictationHotkeys("win32", "Control+Super"), ["RightControl",- "Control+Shift+Space",+ "Control+Super",]);+ // Main falls back to F8 when the Windows key listener is missing (#2005), and+ // Right Ctrl needs that listener too.+ assert.deepEqual(getRecommendedDictationHotkeys("win32", "F8"), ["F8"]);assert.equal(DEFAULT_ASSISTANT_ONBOARDING_HOTKEY, "CommandOrControl+Shift+Space");assert.equal(formatRecommendedHotkey(DEFAULT_ASSISTANT_ONBOARDING_HOTKEY), "Cmd + Shift + Space");});diff --git a/test/helpers/hotkeyActivationMode.test.js b/test/helpers/hotkeyActivationMode.test.jsindex 508036617..88770d48b 100644--- a/test/helpers/hotkeyActivationMode.test.js+++ b/test/helpers/hotkeyActivationMode.test.js@@ -19,18 +19,18 @@ require.cache[require.resolve("electron")] = {const HotkeyManager = require("../../src/helpers/hotkeyManager");-function withPlatform(platform, run) {+async function withPlatform(platform, run) {const original = Object.getOwnPropertyDescriptor(process, "platform");Object.defineProperty(process, "platform", { value: platform, configurable: true });try {- return run();+ return await run();} finally {Object.defineProperty(process, "platform", original);}}-test("native push-to-talk support is hotkey-aware", () => {- withPlatform("linux", () => {+test("native push-to-talk support is hotkey-aware", async () => {+ await withPlatform("linux", () => {const manager = new HotkeyManager();manager.useKDE = true;@@ -42,8 +42,8 @@ test("native push-to-talk support is hotkey-aware", () => {// globalShortcut never reports a release and re-fires on autorepeat, so a lone// regular key held down would toggle dictation on and off. Only keys a native// listener watches, or chords whose modifier release ends the hold, can be held.-test("macOS can hold only keys it can see released", () => {- withPlatform("darwin", () => {+test("macOS can hold only keys it can see released", async () => {+ await withPlatform("darwin", () => {const manager = new HotkeyManager();assert.equal(manager.supportsPushToTalk("F8"), false);@@ -79,8 +79,8 @@ test("a failed activation-mode registration preserves Tap and notifies the user"// Only an initialized manager knows its backend, so these set isInitialized.const denyProbe = (reason) => () => ({ available: false, reason });-test("linux Hold needs the listener's input access, not just its binary", () => {- withPlatform("linux", () => {+test("linux Hold needs the listener's input access, not just its binary", async () => {+ await withPlatform("linux", () => {const manager = new HotkeyManager();manager.isInitialized = true;manager.nativeListenerProbe = denyProbe("input_access_denied");@@ -90,8 +90,8 @@ test("linux Hold needs the listener's input access, not just its binary", () =>});});-test("linux Hold reports the generic message when the listener binary is missing", () => {- withPlatform("linux", () => {+test("linux Hold reports the generic message when the listener binary is missing", async () => {+ await withPlatform("linux", () => {const manager = new HotkeyManager();manager.isInitialized = true;manager.nativeListenerProbe = denyProbe("binary_missing");@@ -104,8 +104,8 @@ test("linux Hold reports the generic message when the listener binary is missing});});-test("linux Hold stays available when the listener can run, or when nothing probed", () => {- withPlatform("linux", () => {+test("linux Hold stays available when the listener can run, or when nothing probed", async () => {+ await withPlatform("linux", () => {const manager = new HotkeyManager();manager.isInitialized = true;manager.nativeListenerProbe = () => ({ available: true });@@ -117,8 +117,8 @@ test("linux Hold stays available when the listener can run, or when nothing prob});});-test("a desktop-native backend answers for Hold even when the probe fails", () => {- withPlatform("linux", () => {+test("a desktop-native backend answers for Hold even when the probe fails", async () => {+ await withPlatform("linux", () => {const manager = new HotkeyManager();manager.isInitialized = true;manager.useKDE = true;@@ -138,8 +138,6 @@ test("switching to Hold without input access is refused and keeps Tap", async ()manager.nativeListenerProbe = denyProbe("input_access_denied");manager.notifyHotkeyFailure = (hotkey, result) => failures.push({ hotkey, result });- // setActivationMode decides the refusal before its first await, so the patched- // platform still applies when the probe is read.const changed = await withPlatform("linux", () => manager.setActivationMode("push"));assert.equal(changed, false);@@ -166,8 +164,8 @@ test("a saved Hold is not refused before the hotkey backend is known", async ()// Once initializeHotkey settles on no desktop backend, the evdev listener is the// only way Linux sees these hotkeys. GNOME, KDE and Hyprland deliver press and// release themselves, so the listener's failure there must not reach the user.-test("only an initialized non-native Linux backend relies on the evdev listener", () => {- withPlatform("linux", () => {+test("only an initialized non-native Linux backend relies on the evdev listener", async () => {+ await withPlatform("linux", () => {const manager = new HotkeyManager();assert.equal(manager.reliesOnLinuxKeyListener(), false, "before initializeHotkey");@@ -182,9 +180,185 @@ test("only an initialized non-native Linux backend relies on the evdev listener"}});- withPlatform("win32", () => {+ await withPlatform("win32", () => {const manager = new HotkeyManager();manager.isInitialized = true;assert.equal(manager.reliesOnLinuxKeyListener(), false);});});++// A Windows build can ship without windows-key-listener.exe (#2005). Hold and+// modifier-only or right-side-modifier hotkeys would then never fire, so they're+// refused and the existing Tap and F8 fallbacks take over.+test("Windows refuses listener-only hotkeys when the key listener is missing", async () => {+ await withPlatform("win32", async () => {+ const manager = new HotkeyManager();+ const callback = () => undefined;+ manager.isInitialized = true;++ manager.nativeListenerProbe = denyProbe("binary_missing");+ assert.equal(manager.supportsPushToTalk("F8"), false);+ assert.equal(+ manager.getPushToTalkUnavailableReason("F8"),+ "Push-to-Talk native listener not available"+ );+ assert.equal(await manager.setActivationMode("push"), false);+ assert.equal(manager.getEffectiveDefaultHotkey(), "F8");+ const refused = manager.setupShortcuts("Control+Super", callback);+ assert.match(refused.error, /Windows key listener/);+ assert.equal(refused.reason, "native_listener_unavailable");+ assert.equal(manager.setupShortcuts("RightControl", callback).success, false);+ assert.equal(manager.setupShortcuts("F8", callback).success, true);++ manager.nativeListenerProbe = () => ({ available: true });+ assert.equal(manager.supportsPushToTalk("F8"), true);+ assert.equal(manager.getEffectiveDefaultHotkey(), "Control+Super");+ assert.equal(manager.setupShortcuts("Control+Super", callback).success, true);+ assert.equal(manager.setupShortcuts("RightControl", callback).success, true);+ });+});++// main.js restores the saved mode before initializeHotkey runs, then drops a Hold+// that supportsPushToTalk refuses once the hotkey is registered. Refusing the+// early restore would leave the saved setting on Hold while main ran Tap.+test("a saved Windows Hold is restored first and refused once initialized", async () => {+ await withPlatform("win32", async () => {+ const manager = new HotkeyManager();+ manager.activationMode = "tap";+ manager.nativeListenerProbe = denyProbe("binary_missing");++ assert.equal(await manager.setActivationMode("push"), true);++ manager.isInitialized = true;+ assert.equal(manager.supportsPushToTalk(), false);+ });+});++// Runs startup with `savedHotkey` in localStorage and records what the user is told.+async function startWithSavedHotkey(manager, savedHotkey) {+ const savedEnvHotkey = process.env.DICTATION_KEY;+ delete process.env.DICTATION_KEY;+ const told = { failures: [], fallbacks: [], active: [] };+ manager.notifyHotkeyFailure = (hotkey) => told.failures.push(hotkey);+ manager.notifyHotkeyFallback = (original, fallback) =>+ told.fallbacks.push({ original, fallback });+ manager.notifyActiveHotkey = (hotkey) => told.active.push(hotkey);+ manager._persistHotkeyToEnvFile = async () => undefined;+ try {+ const mainWindow = { webContents: { executeJavaScript: async () => savedHotkey } };+ await manager.loadSavedHotkeyOrDefault(mainWindow, () => undefined);+ return told;+ } finally {+ if (savedEnvHotkey === undefined) delete process.env.DICTATION_KEY;+ else process.env.DICTATION_KEY = savedEnvHotkey;+ }+}++// The saved hotkey stays saved, so every launch retries it; the user is told what+// runs instead rather than being asked to pick a hotkey that already works.+test("Windows startup moves a saved modifier-only hotkey to F8 without the key listener", async () => {+ await withPlatform("win32", async () => {+ const manager = new HotkeyManager();+ manager.nativeListenerProbe = denyProbe("binary_missing");++ const told = await startWithSavedHotkey(manager, "Control+Super");++ assert.equal(manager.getCurrentHotkey(), "F8");+ assert.deepEqual(told.failures, []);+ assert.deepEqual(told.active, ["F8"]);+ assert.deepEqual(told.fallbacks, [{ original: "Control+Super", fallback: "F8" }]);+ });+});++test("startup reports a fallback against the saved hotkey when the default fails too", async () => {+ const { globalShortcut } = require("electron");+ const register = globalShortcut.register;+ globalShortcut.register = (accelerator) => accelerator === "F9";+ try {+ await withPlatform("win32", async () => {+ const manager = new HotkeyManager();+ manager.nativeListenerProbe = denyProbe("binary_missing");++ const told = await startWithSavedHotkey(manager, "Alt+F7");++ assert.equal(manager.getCurrentHotkey(), "F9");+ assert.deepEqual(told.failures, []);+ assert.deepEqual(told.fallbacks, [{ original: "Alt+F7", fallback: "F9" }]);+ });+ } finally {+ globalShortcut.register = register;+ }+});++// With the listener missing every compound suggestion on Windows is modifier-only+// or taken, so the regular fallback keys stand in rather than an empty "Try:".+test("Windows suggestions skip keys other slots hold and never come back empty", async () => {+ await withPlatform("win32", () => {+ const manager = new HotkeyManager();+ manager.nativeListenerProbe = denyProbe("binary_missing");+ assert.deepEqual(manager.getSuggestions("Control+Shift+K"), [+ "F8",+ "F9",+ "Control+Shift+Space",+ ]);++ assert.equal(manager.setupShortcuts("F8", () => undefined).success, true);+ assert.deepEqual(manager.getSuggestions("RightControl"), ["F9", "F10", "Pause"]);+ const refused = manager.setupShortcuts("RightControl", () => undefined);+ assert.doesNotMatch(refused.error, /\bF8\b/);+ });+});++// Voice Assistant, Translation and Meeting restore after dictation; a saved+// hotkey that no longer registers must reach the user, not just the log.+test("restore failures reach the user for a failed slot and for each refused hotkey", () => {+ const manager = new HotkeyManager();+ const failures = [];+ manager.notifyHotkeyFailure = (hotkey, result) => failures.push({ hotkey, error: result.error });++ manager.notifyRestoreFailures("RightControl", { success: false, error: "refused" });+ manager.notifyRestoreFailures("F9,Control+Alt", {+ success: true,+ failures: [{ hotkey: "Control+Alt", error: "listener" }],+ });+ manager.notifyRestoreFailures("F10", { success: true });++ assert.deepEqual(failures, [+ { hotkey: "RightControl", error: "refused" },+ { hotkey: "Control+Alt", error: "listener" },+ ]);+});++// The Voice Assistant and Translation dialogs show main's error as written, so an+// exception's own text (English, technical) must never be it.+test("a registration that throws reports the translated failure, not the exception", async () => {+ const { globalShortcut } = require("electron");+ const register = globalShortcut.register;+ globalShortcut.register = () => {+ throw new Error("conversion failed: bad accelerator");+ };+ try {+ const manager = new HotkeyManager();+ const result = await manager.registerSlot("voiceAgent", "Alt+F7", () => undefined, {+ atomic: true,+ });++ assert.equal(result.success, false);+ assert.match(result.error, /^Could not register "Alt\+F7"/);+ assert.doesNotMatch(result.error, /conversion failed/);+ } finally {+ globalShortcut.register = register;+ }+});++// Only Windows swaps its defaults and suggestions for regular keys; a Linux probe+// failure is answered at registration instead.+test("a Linux listener failure keeps the modifier-only suggestions", async () => {+ await withPlatform("linux", () => {+ const manager = new HotkeyManager();+ manager.isInitialized = true;+ manager.nativeListenerProbe = denyProbe("binary_missing");++ assert.ok(manager.getSuggestions("Alt+R").includes("Control+Super"));+ });+});diff --git a/test/helpers/hotkeyModeInfoIpc.test.js b/test/helpers/hotkeyModeInfoIpc.test.jsindex 150b60cb1..3201e3fbf 100644--- a/test/helpers/hotkeyModeInfoIpc.test.js+++ b/test/helpers/hotkeyModeInfoIpc.test.js@@ -98,14 +98,14 @@ test.after(() => {// The handler decides everything before its first await, so the patched// platform covers the whole answer.-function hotkeyModeInfo(backend) {+function hotkeyModeInfo(backend, platform = "linux") {hotkeyManager = Object.assign(new HotkeyManager(), {isInitialized: true,nativeListenerProbe: inputDenied,...backend,});const original = Object.getOwnPropertyDescriptor(process, "platform");- Object.defineProperty(process, "platform", { value: "linux", configurable: true });+ Object.defineProperty(process, "platform", { value: platform, configurable: true });try {return handlers.get("get-hotkey-mode-info")({}, "F8");} finally {@@ -138,3 +138,23 @@ test("without a desktop backend, denied input access reaches the renderer", asynassert.equal(info.linuxInputAccessDenied, true);assert.match(info.pushToTalkUnavailableReason, /usermod/);});++// Windows holds only through windows-key-listener.exe, which a build can lack+// (#2005). The Linux input-access setup box never applies there.+test("Windows without its key listener reports Hold unavailable", async () => {+ const info = await hotkeyModeInfo(+ { nativeListenerProbe: () => ({ available: false, reason: "binary_missing" }) },+ "win32"+ );++ assert.equal(info.supportsPushToTalk, false);+ assert.equal(info.pushToTalkUnavailableReason, "Push-to-Talk native listener not available");+ assert.equal(info.linuxInputAccessDenied, false);+});++test("Windows with its key listener still offers Hold", async () => {+ const info = await hotkeyModeInfo({ nativeListenerProbe: () => ({ available: true }) }, "win32");++ assert.equal(info.supportsPushToTalk, true);+ assert.equal(info.pushToTalkUnavailableReason, null);+});diff --git a/test/helpers/hotkeyModifierOnlyNative.test.js b/test/helpers/hotkeyModifierOnlyNative.test.jsindex 76c37059e..06281e7ab 100644--- a/test/helpers/hotkeyModifierOnlyNative.test.js+++ b/test/helpers/hotkeyModifierOnlyNative.test.js@@ -117,15 +117,17 @@ test("a missing listener binary reports the push-to-talk unavailable message", aassert.equal(result.error.startsWith("Push-to-Talk native listener not available"), true);});-test("a failing probe is ignored off linux", async () => {- setPlatform("win32");+// Windows answers through its own probe (windows-key-listener.exe); macOS watches+// right-side modifiers with the Globe listener and has none.+test("a failing probe is ignored on macOS", async () => {+ setPlatform("darwin");const mgr = new HotkeyManager();- mgr.nativeListenerProbe = denyProbe("input_access_denied");+ mgr.nativeListenerProbe = denyProbe("binary_missing");- const result = await mgr.registerSlot("dictation", "Control+Super", noop);+ const result = await mgr.registerSlot("dictation", "RightOption", noop);assert.equal(result.success, true);- assert.deepEqual(mgr.getSlotHotkeys("dictation"), ["Control+Super"]);+ assert.deepEqual(mgr.getSlotHotkeys("dictation"), ["RightOption"]);});// GNOME, KDE and Hyprland register through their own shortcut systems, whichdiff --git a/test/helpers/nativeListenerKeys.test.js b/test/helpers/nativeListenerKeys.test.jsindex 4b98f6761..3a997e329 100644--- a/test/helpers/nativeListenerKeys.test.js+++ b/test/helpers/nativeListenerKeys.test.js@@ -138,6 +138,8 @@ test("_findSlotConflict detects a hotkey already bound to another slot's list",const conflict = mgr._findSlotConflict("voiceAgent", "Control+Shift+R");assert.equal(conflict?.reason, "slot_conflict");assert.equal(conflict?.conflictSlot, "dictation");+ // The message names the slot as Settings does, never by its internal id.+ assert.equal(conflict?.error, "This hotkey is already used for Dictation Hotkey.");// A fresh hotkey does not conflict.assert.equal(mgr._findSlotConflict("voiceAgent", "F7"), null);// Re-checking a slot against its own hotkey is not a conflict.diff --git a/test/stores/registeredHotkeySetter.test.js b/test/stores/registeredHotkeySetter.test.jsnew file mode 100644index 000000000..3f6b3d9ac--- /dev/null+++ b/test/stores/registeredHotkeySetter.test.js@@ -0,0 +1,50 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const path = require("node:path");+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");++async function loadStore(t, electronAPI) {+ installBrowserGlobals(t, {+ initialStorage: { voiceAgentKey: "F9", translationKey: "F10" },+ window: { electronAPI },+ });+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-registered-hotkey-setter-test-",+ resolveAlias: { "@": path.resolve(__dirname, "../../src") },+ });+ return vite.ssrLoadModule("/stores/settingsStore.ts");+}++// Settings and onboarding show main's reason for a refused Voice Assistant or+// Translation hotkey (e.g. a missing Windows key listener), not a generic retry.+test("a refused assistant or translation hotkey reports main's reason and keeps the old key", async (t) => {+ const reason = '"Control+Super" needs the Windows key listener.';+ const { useSettingsStore } = await loadStore(t, {+ updateVoiceAgentHotkey: async () => ({ success: false, message: reason }),+ updateTranslationHotkey: async () => ({ success: false }),+ });+ const store = useSettingsStore.getState();++ assert.deepEqual(await store.setVoiceAgentKey("Control+Super"), {+ success: false,+ message: reason,+ });+ assert.deepEqual(await store.setTranslationKey("RightControl"), {+ success: false,+ message: undefined,+ });+ assert.equal(useSettingsStore.getState().voiceAgentKey, "F9");+ assert.equal(useSettingsStore.getState().translationKey, "F10");+});++test("an accepted assistant hotkey is saved", async (t) => {+ const { useSettingsStore } = await loadStore(t, {+ updateVoiceAgentHotkey: async () => ({ success: true }),+ });++ assert.deepEqual(await useSettingsStore.getState().setVoiceAgentKey("Alt+Space"), {+ success: true,+ });+ assert.equal(useSettingsStore.getState().voiceAgentKey, "Alt+Space");+ assert.equal(globalThis.localStorage.getItem("voiceAgentKey"), "Alt+Space");+});