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(hotkeys): let Linux reach the native listener for modifier-only and right-side hotkeys (#2048)
folks-samuel-cbe5b0a599f037
diff --git a/main.js b/main.jsindex 83a746e82..991125da3 100644--- a/main.js+++ b/main.js@@ -531,6 +531,9 @@ function initializeCoreManagers() {windowManager.selectionManager = selectionManager;windowManager.windowsKeyManager = windowsKeyManager;windowManager.linuxKeyManager = linuxKeyManager;+ if (process.platform === "linux") {+ windowManager.hotkeyManager.nativeListenerProbe = () => linuxKeyManager.checkAvailability();+ }// IPC handlers must be registered before window content loadsipcHandlers = new IPCHandlers({@@ -1782,8 +1785,15 @@ async function startApp() {debugLogger.warn("[Push-to-Talk] Linux key listener has no permission to access input devices");- if (isLiveWindow(windowManager.mainWindow)) {- windowManager.mainWindow.webContents.send("linux-ptt-permission-denied");+ // GNOME, KDE and Hyprland run this listener only as a spare release+ // source in Hold; their own shortcut still presses and releases.+ if (!hotkeyManager.reliesOnLinuxKeyListener()) return;+ // Settings owns the recovery (toast, Hold disabled, back to Tap) and it+ // renders in the control panel, not the pill this event used to reach.+ for (const browserWindow of BrowserWindow.getAllWindows()) {+ if (!browserWindow.isDestroyed()) {+ browserWindow.webContents.send("linux-ptt-permission-denied");+ }}});}diff --git a/src/components/OnboardingFlow.tsx b/src/components/OnboardingFlow.tsxindex 76886e793..93c54b43b 100644--- a/src/components/OnboardingFlow.tsx+++ b/src/components/OnboardingFlow.tsx@@ -207,6 +207,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {const {supportsPushToTalk,pushToTalkUnavailableReason,+ linuxInputAccessDenied,loaded: hotkeyModeLoaded,} = useHotkeyModeInfo("onboarding", dictationHotkey);const { activationMode, setActivationMode } = settings;@@ -1011,8 +1012,8 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {}/></div>- {platform === "linux" && activationMode === "push" && (- <LinuxPttSetupInfo isAvailable={supportsPushToTalk} />+ {platform === "linux" && (activationMode === "push" || linuxInputAccessDenied) && (+ <LinuxPttSetupInfo isAvailable={!linuxInputAccessDenied && supportsPushToTalk} />)}</div>)}diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsxindex 434f7cb47..f6231174f 100644--- a/src/components/SettingsPage.tsx+++ b/src/components/SettingsPage.tsx@@ -1581,6 +1581,7 @@ export default function SettingsPage({hyprlandConfigStatus,supportsPushToTalk,pushToTalkUnavailableReason,+ linuxInputAccessDenied,} = useHotkeyModeInfo("settings", dictationKey);const [effectiveDefaultHotkey, setEffectiveDefaultHotkey] = useState<string | null>(null);const [linuxPttAvailable, setLinuxPttAvailable] = useState(true);@@ -4034,9 +4035,12 @@ EOF`,}/></div>- {getCachedPlatform() === "linux" && activationMode === "push" && (- <LinuxPttSetupInfo isAvailable={linuxPttAvailable} />- )}+ {getCachedPlatform() === "linux" &&+ (activationMode === "push" || linuxInputAccessDenied) && (+ <LinuxPttSetupInfo+ isAvailable={!linuxInputAccessDenied && linuxPttAvailable}+ />+ )}</SettingsPanelRow>)}</SettingsPanel>diff --git a/src/components/onboarding/hotkeyPresentation.ts b/src/components/onboarding/hotkeyPresentation.tsindex a005c483a..8eed06d7b 100644--- a/src/components/onboarding/hotkeyPresentation.ts+++ b/src/components/onboarding/hotkeyPresentation.ts@@ -147,8 +147,11 @@ export const resolveOnboardingAssistantHotkey = (savedHotkey: string): string =>/*** One-key picks lead where the platform has a spare key: right Option on macOS,- * right Ctrl on Windows (right Alt is AltGr on many layouts). Linux stays on what- * main could register, since a lone right modifier needs input-device access.+ * right Ctrl on Windows (right Alt is AltGr on many layouts). Linux offers the+ * 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.*/export const getRecommendedDictationHotkeys = (platform: Platform,diff --git a/src/helpers/gnomeShortcut.js b/src/helpers/gnomeShortcut.jsindex dc7082133..7e26c4f62 100644--- a/src/helpers/gnomeShortcut.js+++ b/src/helpers/gnomeShortcut.js@@ -549,9 +549,11 @@ class GnomeShortcutManager {.split("+").map((part) => part.trim()).filter(Boolean);+ // The side is stripped because a lone "RightControl" is modifier-only too, and+ // the portal cannot bind a trigger that has no base key.if (parts.length === 0 ||- parts.every((part) => PORTAL_MODIFIER_NAMES.has(part.toLowerCase()))+ parts.every((part) => PORTAL_MODIFIER_NAMES.has(part.toLowerCase().replace(/^right/, "")))) {return "";}diff --git a/src/helpers/hotkeyManager.js b/src/helpers/hotkeyManager.jsindex cf7154415..15e02f509 100644--- a/src/helpers/hotkeyManager.js+++ b/src/helpers/hotkeyManager.js@@ -34,7 +34,7 @@ function isRightSideModifier(hotkey) {}// Modifier-only combos (e.g. "Control+Super") bypass globalShortcut on Windows-// and use the native low-level keyboard hook instead.+// and Linux, and use the native low-level keyboard listener instead.const MODIFIER_NAMES = new Set(["control","ctrl",@@ -111,6 +111,9 @@ 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.+ this.nativeListenerProbe = null;}// Ensure a slot exists and return it (slots always use the list shape).@@ -209,6 +212,14 @@ class HotkeyManager extends EventEmitter {}// Native Linux backends bind only the primary hotkey.const hotkey = hotkeys[0];+ // GNOME, KDE and Hyprland shortcuts need a regular key; only the evdev+ // listener, which those desktops do not use, can watch a lone right modifier.+ if (this.isUsingNativeShortcut() && isRightSideModifier(hotkey)) {+ return {+ success: false,+ error: i18nMain.t("hotkey.errors.rightModifierNeedsListener", { hotkey }),+ };+ }if (hotkeys.length > 1 &&(((this.useGnome || this.useHyprland) && LINUX_NATIVE_TAP_SLOTS.has(slotName)) ||@@ -444,6 +455,31 @@ 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");+ }++ // GNOME, KDE and Hyprland deliver press and release themselves, so Linux+ // depends on the bundled evdev listener only once initializeHotkey has settled+ // on none of them. Startup restores the saved activation mode before that, so+ // until then nothing may be refused on the listener's account.+ reliesOnLinuxKeyListener() {+ return process.platform === "linux" && this.isInitialized && !this.isUsingNativeShortcut();+ }++ // Where Linux 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;+ const { available, reason } = this.nativeListenerProbe();+ return available ? null : this._nativeListenerFailureMessage(reason);+ }+supportsPushToTalk(hotkey = this.currentHotkey) {if (process.platform === "darwin" && hotkey && lacksMacReleaseSignal(hotkey)) {return false;@@ -451,6 +487,9 @@ class HotkeyManager extends EventEmitter {if (this.isUsingNativeShortcut() && isModifierOnlyHotkey(hotkey)) {return false;}+ if (this._pushToTalkListenerBlockReason()) {+ return false;+ }if (this.useGnome && this.gnomeManager?.supportsPushToTalk) {return this.gnomeManager.supportsPushToTalk();}@@ -464,7 +503,7 @@ class HotkeyManager extends EventEmitter {if (this.isUsingNativeShortcut() && isModifierOnlyHotkey(hotkey)) {return i18nMain.t("hotkey.errors.osReserved", { hotkey });}- return i18nMain.t("windows.pttUnavailable");+ return this._pushToTalkListenerBlockReason() ?? i18nMain.t("windows.pttUnavailable");}async setActivationMode(mode) {@@ -553,6 +592,31 @@ 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.+ _nativeListenerUnavailable(hotkey) {+ if (process.platform !== "linux" || !this.nativeListenerProbe) return null;++ const { available, reason } = this.nativeListenerProbe();+ if (available) return null;++ const deniedAccess = reason === "input_access_denied";+ return {+ success: false,+ hotkey,+ error: this._nativeListenerFailureMessage(reason),+ reason: deniedAccess ? "input_access_denied" : "native_listener_unavailable",+ // Only regular-key hotkeys avoid the listener that just failed.+ suggestions: this.getSuggestions(hotkey).filter(+ (suggestion) => !isModifierOnlyHotkey(suggestion) && !isRightSideModifier(suggestion)+ ),+ };+ }+// Register one hotkey without mutating any slot. `accelerator` is null for// hotkeys handled by native listeners._registerSingleHotkey(hotkey, callback) {@@ -591,16 +655,24 @@ class HotkeyManager extends EventEmitter {}if (isRightSideModifier(hotkey)) {+ const unavailable = this._nativeListenerUnavailable(hotkey);+ if (unavailable) return unavailable;debugLogger.log(`[HotkeyManager] Right-side modifier "${hotkey}" set - using native listener`);return { success: true, hotkey, accelerator: null };}- if (isModifierOnlyHotkey(hotkey) && process.platform === "win32") {- debugLogger.log(- `[HotkeyManager] Modifier-only "${hotkey}" set - using Windows native listener`- );+ // Both Windows and Linux watch modifier-only chords with a low-level+ // listener; Electron cannot build an accelerator without a regular key,+ // so registering one would fail and reject an otherwise valid hotkey.+ if (+ isModifierOnlyHotkey(hotkey) &&+ (process.platform === "win32" || process.platform === "linux")+ ) {+ const unavailable = this._nativeListenerUnavailable(hotkey);+ if (unavailable) return unavailable;+ debugLogger.log(`[HotkeyManager] Modifier-only "${hotkey}" set - using native listener`);return { success: true, hotkey, accelerator: null };}@@ -1358,6 +1430,13 @@ class HotkeyManager extends EventEmitter {};}+ if (this.isUsingNativeShortcut() && isRightSideModifier(primary)) {+ return {+ success: false,+ message: i18nMain.t("hotkey.errors.rightModifierNeedsListener", { hotkey: primary }),+ };+ }+for (const hotkey of hotkeys) {const conflict = this._findSlotConflict("dictation", hotkey);if (conflict) {diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex d39a6694b..990f5c3f0 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -4315,13 +4315,9 @@ class IPCHandlers {: hotkeyManager.getCurrentHotkey();const isUsingNativeShortcut = this.windowManager.isUsingNativeShortcutHotkeys();const supportsPushToTalk =- process.platform === "linux"- ? isUsingNativeShortcut- ? hotkeyManager.supportsPushToTalk(hotkey)- : this.linuxKeyManager?.isAvailable?.() === true- : process.platform === "darwin"- ? hotkeyManager.supportsPushToTalk(hotkey)- : !isUsingNativeShortcut;+ process.platform === "linux" || process.platform === "darwin"+ ? hotkeyManager.supportsPushToTalk(hotkey)+ : !isUsingNativeShortcut;return {isUsingGnome: this.windowManager.isUsingGnomeHotkeys(),@@ -4332,6 +4328,12 @@ class IPCHandlers {pushToTalkUnavailableReason: supportsPushToTalk? null: hotkeyManager.getPushToTalkUnavailableReason(hotkey),+ // Lets the renderer show the setup box outside push mode, where the+ // disabled-Hold tooltip is the only other place this surfaces. Desktop+ // backends see their own hotkeys, so access matters only without one.+ linuxInputAccessDenied:+ hotkeyManager.reliesOnLinuxKeyListener() &&+ hotkeyManager.nativeListenerProbe().reason === "input_access_denied",};});diff --git a/src/helpers/linuxKeyManager.js b/src/helpers/linuxKeyManager.jsindex 4a3e074ab..e803d410e 100644--- a/src/helpers/linuxKeyManager.js+++ b/src/helpers/linuxKeyManager.js@@ -4,6 +4,30 @@ const EventEmitter = require("events");const fs = require("fs");const debugLogger = require("./debugLogger");+const INPUT_DIR = "/dev/input";+const INPUT_SYSFS_DIR = "/sys/class/input";+// linux/input-event-codes.h+const EV_KEY = 1n;+const KEY_A = 30n;++// is_keyboard_device() in linux-key-listener.c, read from sysfs, where the kernel+// prints the capability bitmaps its ioctl returns: hex words, most significant+// first, so the bits wanted here sit in the last word (BigInt, since a 64-bit+// word overflows a double). When sysfs cannot say, as in a sandbox without /sys,+// the node counts as a keyboard rather than refuse a hotkey it may serve.+function couldBeKeyboard(device) {+ const capabilities = path.join(INPUT_SYSFS_DIR, device, "device", "capabilities");+ const hasBit = (bitmap, bit) => {+ const words = fs.readFileSync(path.join(capabilities, bitmap), "utf8").trim().split(" ");+ return ((BigInt(`0x${words.at(-1)}`) >> bit) & 1n) === 1n;+ };+ try {+ return hasBit("ev", EV_KEY) && hasBit("key", KEY_A);+ } catch {+ return true;+ }+}+// Key state comes from an evdev reader (resources/linux-key-listener.c) that reads// /dev/input directly, so it observes KEY_UP regardless of which window has focus// and cannot miss a release. The ceiling for a genuinely stuck key is@@ -149,8 +173,46 @@ class LinuxKeyManager extends EventEmitter {for (const key of [...this.listeners.keys()]) this._stopKey(key);}- isAvailable() {- return this.resolveListenerBinary() !== null;+ /**+ * Whether the listener could actually run right now: binary present and a+ * readable keyboard among the /dev/input/event* nodes. Mirrors the C+ * listener's own rule — it keeps only keyboards and prints NO_PERMISSION only+ * when it kept none AND at least one node returned EACCES, so an event-less+ * /dev/input is not a failure there (it waits for hotplug) and must not be+ * one here. Any other readable node proves nothing: systemd grants the+ * session user every joystick.+ * Callers ask at registration time, because a hotkey only this listener can+ * serve must not report success when the listener cannot run.+ * @returns {{available: true} | {available: false, reason: "binary_missing" | "input_access_denied" | "input_devices_unavailable"}}+ */+ checkAvailability() {+ if (!this.resolveListenerBinary()) return { available: false, reason: "binary_missing" };++ let devices;+ try {+ devices = fs.readdirSync(INPUT_DIR).filter((entry) => entry.startsWith("event"));+ } catch (error) {+ // The listener cannot watch a directory it cannot list, so it never sees a+ // keyboard, and it reports nothing: NO_PERMISSION only covers device nodes.+ const deniedAccess = error.code === "EACCES" || error.code === "EPERM";+ return {+ available: false,+ reason: deniedAccess ? "input_access_denied" : "input_devices_unavailable",+ };+ }++ let denied = false;+ for (const device of devices) {+ try {+ fs.accessSync(path.join(INPUT_DIR, device), fs.constants.R_OK);+ } catch {+ denied = true;+ continue;+ }+ if (couldBeKeyboard(device)) return { available: true };+ }++ return denied ? { available: false, reason: "input_access_denied" } : { available: true };}reportError(error) {diff --git a/src/hooks/useHotkeyModeInfo.ts b/src/hooks/useHotkeyModeInfo.tsindex dde2957b5..517aa2113 100644--- a/src/hooks/useHotkeyModeInfo.ts+++ b/src/hooks/useHotkeyModeInfo.ts@@ -11,6 +11,8 @@ export interface HotkeyModeInfo {isUsingHyprland: boolean;supportsPushToTalk: boolean;pushToTalkUnavailableReason: string | null;+ /** Linux only: the evdev listener cannot read /dev/input, which Hold needs. */+ linuxInputAccessDenied: boolean;hyprlandConfigStatus: HyprlandConfigStatus | null;/** False until main has answered; the defaults above are optimistic placeholders. */loaded: boolean;@@ -21,6 +23,7 @@ const DEFAULT_INFO: HotkeyModeInfo = {isUsingHyprland: false,supportsPushToTalk: true,pushToTalkUnavailableReason: null,+ linuxInputAccessDenied: false,hyprlandConfigStatus: null,loaded: false,};@@ -48,6 +51,7 @@ export function useHotkeyModeInfo(scope: string, hotkey?: string): HotkeyModeInfisUsingHyprland: info.isUsingHyprland,supportsPushToTalk: info.supportsPushToTalk,pushToTalkUnavailableReason: info.pushToTalkUnavailableReason,+ linuxInputAccessDenied: info.linuxInputAccessDenied ?? false,hyprlandConfigStatus,loaded: true,});diff --git a/src/locales/ar/translation.json b/src/locales/ar/translation.jsonindex a73c58c89..d9efab275 100644--- a/src/locales/ar/translation.json+++ b/src/locales/ar/translation.json@@ -3543,6 +3543,7 @@"mouseButtonOnlyMac": "اختصارات أزرار الماوس مدعومة حاليًا على نظام macOS فقط.","alreadyRegistered": "\"{{hotkey}}\" مسجل بالفعل بواسطة تطبيق آخر.","osReserved": "قد يكون \"{{hotkey}}\" محجوزًا بواسطة بيئة سطح المكتب لديك.",+ "rightModifierNeedsListener": "لا يمكن استخدام \"{{hotkey}}\" على سطح المكتب هذا، إذ تحتاج اختصاراته إلى مفتاح عادي. أضف مفتاحًا، مثل Control+Alt+Space.","holdNeedsReleaseKey": "يحتاج الضغط المستمر للتحدث إلى مفتاح يمكن لـ macOS أن يرصد تحريره: Globe، أو مفتاح جانبي أيمن مثل Option الأيمن، أو اختصار مع مفتاح تعديل. أما النقر فيعمل مع أي مفتاح.","registrationFailed": "تعذر تسجيل \"{{hotkey}}\". قد يكون قيد الاستخدام بواسطة تطبيق آخر.","updateFailedCheckFormat": "فشل تحديث الاختصار إلى \"{{hotkey}}\". تأكد من أن التنسيق صالح.",diff --git a/src/locales/de/translation.json b/src/locales/de/translation.jsonindex 889d0cb0c..184bfa47b 100644--- a/src/locales/de/translation.json+++ b/src/locales/de/translation.json@@ -121,6 +121,7 @@"mouseButtonOnlyMac": "Maustasten-Hotkeys werden derzeit nur auf macOS unterstützt.","alreadyRegistered": "\"{{hotkey}}\" ist bereits von einer anderen Anwendung registriert.","osReserved": "\"{{hotkey}}\" ist möglicherweise von Ihrer Desktop-Umgebung reserviert.",+ "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.","updateFailedCheckFormat": "Hotkey konnte nicht auf \"{{hotkey}}\" aktualisiert werden. Prüfen Sie, ob das Format gültig ist.",diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex 71452abd2..471dc5634 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -121,6 +121,7 @@"mouseButtonOnlyMac": "Mouse button hotkeys are currently supported on macOS only.","alreadyRegistered": "\"{{hotkey}}\" is already registered by another application.","osReserved": "\"{{hotkey}}\" may be reserved by your desktop environment.",+ "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.","updateFailedCheckFormat": "Failed to update hotkey to \"{{hotkey}}\". Check the format is valid.",diff --git a/src/locales/es/translation.json b/src/locales/es/translation.jsonindex a543f8061..da0e21799 100644--- a/src/locales/es/translation.json+++ b/src/locales/es/translation.json@@ -121,6 +121,7 @@"mouseButtonOnlyMac": "Los atajos con botones del ratón solo son compatibles con macOS por ahora.","alreadyRegistered": "\"{{hotkey}}\" ya está registrada por otra aplicación.","osReserved": "\"{{hotkey}}\" puede estar reservada por tu entorno de escritorio.",+ "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.","updateFailedCheckFormat": "No se pudo actualizar el atajo a \"{{hotkey}}\". Comprueba que el formato sea válido.",diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.jsonindex b1ffcbebe..9d5f91ac2 100644--- a/src/locales/fr/translation.json+++ b/src/locales/fr/translation.json@@ -121,6 +121,7 @@"mouseButtonOnlyMac": "Les raccourcis avec les boutons de la souris ne sont actuellement pris en charge que sur macOS.","alreadyRegistered": "\"{{hotkey}}\" est déjà enregistré par une autre application.","osReserved": "\"{{hotkey}}\" peut être réservé par votre environnement de bureau.",+ "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.","updateFailedCheckFormat": "Impossible de mettre à jour le raccourci vers \"{{hotkey}}\". Vérifiez que le format est valide.",diff --git a/src/locales/it/translation.json b/src/locales/it/translation.jsonindex 711887afb..7e844effe 100644--- a/src/locales/it/translation.json+++ b/src/locales/it/translation.json@@ -121,6 +121,7 @@"mouseButtonOnlyMac": "Le scorciatoie con i tasti del mouse sono attualmente supportate solo su macOS.","alreadyRegistered": "\"{{hotkey}}\" è già registrata da un'altra applicazione.","osReserved": "\"{{hotkey}}\" potrebbe essere riservata dal sistema operativo.",+ "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.","updateFailedCheckFormat": "Impossibile aggiornare la scorciatoia a \"{{hotkey}}\". Verifica che il formato sia valido.",diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.jsonindex 75ed3c7b6..ceb0f8432 100644--- a/src/locales/ja/translation.json+++ b/src/locales/ja/translation.json@@ -121,6 +121,7 @@"mouseButtonOnlyMac": "マウスボタンのホットキーは現在 macOS でのみサポートされています。","alreadyRegistered": "\"{{hotkey}}\" は別のアプリケーションで既に登録されています。","osReserved": "\"{{hotkey}}\" はデスクトップ環境で予約されている可能性があります。",+ "rightModifierNeedsListener": "\"{{hotkey}}\" はこのデスクトップでは使用できません。ショートカットには通常のキーが必要です。Control+Alt+Space のようにキーを追加してください。","holdNeedsReleaseKey": "ホールドして話すには、macOS が離したことを検知できるキーが必要です。Globe、右 Option のような右側のキー、または修飾キー付きのショートカットです。タップならどのキーでも使えます。","registrationFailed": "\"{{hotkey}}\" を登録できませんでした。別のアプリケーションで使用されている可能性があります。","updateFailedCheckFormat": "「{{hotkey}}」へのホットキーの更新に失敗しました。形式が正しいか確認してください。",diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.jsonindex f6ae5444e..acf3b2c4d 100644--- a/src/locales/pt/translation.json+++ b/src/locales/pt/translation.json@@ -121,6 +121,7 @@"mouseButtonOnlyMac": "Atalhos com botões do mouse atualmente são compatíveis apenas no macOS.","alreadyRegistered": "\"{{hotkey}}\" já está registrada por outro aplicativo.","osReserved": "\"{{hotkey}}\" pode estar reservada pelo seu ambiente de desktop.",+ "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.","updateFailedCheckFormat": "Não foi possível atualizar o atalho para \"{{hotkey}}\". Verifique se o formato é válido.",diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.jsonindex 5249c88e6..421818a97 100644--- a/src/locales/ru/translation.json+++ b/src/locales/ru/translation.json@@ -121,6 +121,7 @@"mouseButtonOnlyMac": "Горячие клавиши на кнопках мыши в настоящее время поддерживаются только на macOS.","alreadyRegistered": "«{{hotkey}}» уже зарегистрирована другим приложением.","osReserved": "«{{hotkey}}» может быть зарезервирована вашей операционной системой.",+ "rightModifierNeedsListener": "«{{hotkey}}» нельзя использовать в этой среде рабочего стола: её сочетаниям клавиш нужна обычная клавиша. Добавьте клавишу, например Control+Alt+Space.","holdNeedsReleaseKey": "Для удержания нужна клавиша, отпускание которой macOS может заметить: Globe, правая клавиша вроде правого Option или сочетание с модификатором. Нажатие работает с любой клавишей.","registrationFailed": "Не удалось зарегистрировать «{{hotkey}}». Возможно, она используется другим приложением.","updateFailedCheckFormat": "Не удалось обновить горячую клавишу на «{{hotkey}}». Проверьте правильность формата.",diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.jsonindex b0829fd4f..936a69c0b 100644--- a/src/locales/zh-CN/translation.json+++ b/src/locales/zh-CN/translation.json@@ -121,6 +121,7 @@"mouseButtonOnlyMac": "鼠标按键快捷键目前仅在 macOS 上受支持。","alreadyRegistered": "\"{{hotkey}}\" 已被其他应用注册。","osReserved": "\"{{hotkey}}\" 可能被系统保留。",+ "rightModifierNeedsListener": "\"{{hotkey}}\" 无法在此桌面上使用,其快捷键需要包含一个普通按键。请添加一个按键,例如 Control+Alt+Space。","holdNeedsReleaseKey": "按住说话需要 macOS 能检测到松开的按键:Globe、右侧 Option 之类的右侧按键,或带修饰键的快捷键。点按可用于任何按键。","registrationFailed": "无法注册 \"{{hotkey}}\",该快捷键可能已被其他应用占用。","updateFailedCheckFormat": "无法将快捷键更新为 \"{{hotkey}}\",请检查格式是否有效。",diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.jsonindex 05fef41f4..53ce5b758 100644--- a/src/locales/zh-TW/translation.json+++ b/src/locales/zh-TW/translation.json@@ -121,6 +121,7 @@"mouseButtonOnlyMac": "滑鼠按鍵快捷鍵目前僅在 macOS 上受支援。","alreadyRegistered": "\"{{hotkey}}\" 已被其他應用程式註冊。","osReserved": "\"{{hotkey}}\" 可能被你的作業系統保留。",+ "rightModifierNeedsListener": "\"{{hotkey}}\" 無法在此桌面上使用,其快捷鍵需要包含一個一般按鍵。請加入一個按鍵,例如 Control+Alt+Space。","holdNeedsReleaseKey": "按住說話需要 macOS 能偵測到放開的按鍵:Globe、右側 Option 之類的右側按鍵,或帶修飾鍵的快速鍵。點按可用於任何按鍵。","registrationFailed": "無法註冊「{{hotkey}}」。可能已被其他應用程式使用。","updateFailedCheckFormat": "無法將快速鍵更新為「{{hotkey}}」。請檢查格式是否有效。",diff --git a/src/types/electron.ts b/src/types/electron.tsindex a82f859d1..c2f6b260f 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -2024,6 +2024,7 @@ declare global {isUsingNativeShortcut: boolean;supportsPushToTalk: boolean;pushToTalkUnavailableReason: string | null;+ linuxInputAccessDenied?: boolean;}>;getHyprlandConfigStatus?: () => Promise<{ canWrite: boolean; path: string } | null>;diff --git a/src/utils/hotkeyValidator.ts b/src/utils/hotkeyValidator.tsindex aa008c0a8..f6cde2199 100644--- a/src/utils/hotkeyValidator.ts+++ b/src/utils/hotkeyValidator.ts@@ -659,9 +659,9 @@ export function validateHotkey(const modifierCount = parts.filter((part) => normalizeModifier(part, platform) !== null).length;const hasBaseKey = parts.length > modifierCount;- // Only Windows routes a modifier-only chord to a native low-level hook. macOS- // has no equivalent — the Globe listener reports Fn, right-side modifiers and- // mouse buttons, nothing else — and Electron cannot register an accelerator+ // Windows and Linux route a modifier-only chord to a native low-level listener;+ // macOS has no equivalent — the Globe listener reports Fn, right-side modifiers+ // and mouse buttons, nothing else — and Electron cannot register an accelerator// without a key, so the chord would be accepted here and then fail to bind.if (!hasBaseKey && modifierCount >= 2 && platform === "darwin") {return {@@ -684,15 +684,6 @@ export function validateHotkey(errorCode: "LEFT_MODIFIER_ONLY",};}- // Right-side single modifiers require native listeners (not available on Linux)- if (platform === "linux") {- return {- valid: false,- error:- "Right-side single modifier hotkeys are not supported on Linux. Use two modifiers (e.g., Control+Alt) instead.",- errorCode: "LEFT_MODIFIER_ONLY",- };- }}const normalizedHotkey = normalizeHotkey(hotkey, platform);diff --git a/test/helpers/gnomeShortcutFormat.test.js b/test/helpers/gnomeShortcutFormat.test.jsindex 6c06b49f9..d874a1e96 100644--- a/test/helpers/gnomeShortcutFormat.test.js+++ b/test/helpers/gnomeShortcutFormat.test.js@@ -73,6 +73,15 @@ test("portal shortcuts use the XDG modifier syntax", () => {assert.equal(GnomeShortcutManager.convertToPortalFormat("Control+Super"), "");});+test("lone right-side modifiers have no portal trigger", () => {+ assert.equal(GnomeShortcutManager.convertToPortalFormat("RightControl"), "");+ assert.equal(GnomeShortcutManager.convertToPortalFormat("RightAlt"), "");+ assert.equal(GnomeShortcutManager.convertToPortalFormat("RightShift"), "");+ assert.equal(GnomeShortcutManager.convertToPortalFormat("RightSuper"), "");+ assert.equal(GnomeShortcutManager.convertToPortalFormat("Control+Shift+K"), "CTRL+SHIFT+k");+ assert.equal(GnomeShortcutManager.convertToPortalFormat("F8"), "F8");+});+test("failed portal registration restores the working GNOME tap binding", async () => {const manager = new GnomeShortcutManager();const registrations = [];diff --git a/test/helpers/hotkeyActivationMode.test.js b/test/helpers/hotkeyActivationMode.test.jsindex 22dcacadf..508036617 100644--- a/test/helpers/hotkeyActivationMode.test.js+++ b/test/helpers/hotkeyActivationMode.test.js@@ -23,7 +23,7 @@ function withPlatform(platform, run) {const original = Object.getOwnPropertyDescriptor(process, "platform");Object.defineProperty(process, "platform", { value: platform, configurable: true });try {- run();+ return run();} finally {Object.defineProperty(process, "platform", original);}@@ -72,3 +72,119 @@ test("a failed activation-mode registration preserves Tap and notifies the user"assert.equal(failures.length, 1);assert.equal(failures[0].hotkey, "Alt+R");});++// Off a desktop-native backend, Linux Hold runs through the bundled evdev+// listener, so the same probe that refuses to register its hotkeys must also+// report Hold unavailable — otherwise Settings offers a mode that cannot work.+// 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", () => {+ const manager = new HotkeyManager();+ manager.isInitialized = true;+ manager.nativeListenerProbe = denyProbe("input_access_denied");++ assert.equal(manager.supportsPushToTalk("F8"), false);+ assert.match(manager.getPushToTalkUnavailableReason("F8"), /usermod/);+ });+});++test("linux Hold reports the generic message when the listener binary is missing", () => {+ withPlatform("linux", () => {+ const manager = new HotkeyManager();+ 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"+ );+ });+});++test("linux Hold stays available when the listener can run, or when nothing probed", () => {+ withPlatform("linux", () => {+ const manager = new HotkeyManager();+ manager.isInitialized = true;+ manager.nativeListenerProbe = () => ({ available: true });+ assert.equal(manager.supportsPushToTalk("F8"), true);++ const unprobed = new HotkeyManager();+ unprobed.isInitialized = true;+ assert.equal(unprobed.supportsPushToTalk("F8"), true);+ });+});++test("a desktop-native backend answers for Hold even when the probe fails", () => {+ withPlatform("linux", () => {+ const manager = new HotkeyManager();+ manager.isInitialized = true;+ manager.useKDE = true;+ manager.nativeListenerProbe = denyProbe("input_access_denied");++ assert.equal(manager.supportsPushToTalk("Control+Super"), false);+ assert.equal(manager.supportsPushToTalk("F8"), true);+ });+});++test("switching to Hold without input access is refused and keeps Tap", async () => {+ const manager = new HotkeyManager();+ const failures = [];+ manager.isInitialized = true;+ manager.activationMode = "tap";+ manager.currentHotkey = "F8";+ 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);+ assert.equal(manager.activationMode, "tap");+ assert.equal(failures.length, 1);+ assert.match(failures[0].result.error, /usermod/);+});++// main.js restores the saved mode before initializeHotkey has chosen a backend,+// and GNOME, KDE and Hyprland hold without the listener. Refusing that early left+// the saved setting on Hold while main ran Tap, and nothing checked it again.+test("a saved Hold is not refused before the hotkey backend is known", async () => {+ const manager = new HotkeyManager();+ manager.activationMode = "tap";+ manager.currentHotkey = "F8";+ manager.nativeListenerProbe = denyProbe("input_access_denied");++ const changed = await withPlatform("linux", () => manager.setActivationMode("push"));++ assert.equal(changed, true);+ assert.equal(manager.activationMode, "push");+});++// 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", () => {+ const manager = new HotkeyManager();+ assert.equal(manager.reliesOnLinuxKeyListener(), false, "before initializeHotkey");++ manager.isInitialized = true;+ assert.equal(manager.reliesOnLinuxKeyListener(), true);++ for (const backend of ["useGnome", "useKDE", "useHyprland"]) {+ const native = new HotkeyManager();+ native.isInitialized = true;+ native[backend] = true;+ assert.equal(native.reliesOnLinuxKeyListener(), false, backend);+ }+ });++ withPlatform("win32", () => {+ const manager = new HotkeyManager();+ manager.isInitialized = true;+ assert.equal(manager.reliesOnLinuxKeyListener(), false);+ });+});diff --git a/test/helpers/hotkeyModeInfoIpc.test.js b/test/helpers/hotkeyModeInfoIpc.test.jsnew file mode 100644index 000000000..150b60cb1--- /dev/null+++ b/test/helpers/hotkeyModeInfoIpc.test.js@@ -0,0 +1,140 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const Module = require("node:module");++const handlersModulePath = require.resolve("../../src/helpers/ipcHandlers");+const originalLoad = Module._load;+const handlers = new Map();++const electronStub = {+ app: {+ getPath: () => "/tmp",+ getName: () => "test",+ getVersion: () => "0.0.0",+ isPackaged: false,+ on: () => {},+ requestSingleInstanceLock: () => true,+ },+ ipcMain: {+ handle: (channel, handler) => handlers.set(channel, handler),+ on: () => {},+ removeHandler: () => {},+ },+ net: { fetch: async () => ({ ok: true, status: 200, json: async () => ({}) }) },+ BrowserWindow: class BrowserWindow {+ static getAllWindows() {+ return [];+ }++ static fromWebContents() {+ return null;+ }+ },+ shell: {},+ dialog: {},+ screen: { getPrimaryDisplay: () => ({ workAreaSize: { width: 0, height: 0 } }) },+ systemPreferences: { getMediaAccessStatus: () => "granted" },+ session: { fromPartition: () => ({}) },+ clipboard: {},+ nativeImage: {},+ globalShortcut: {},+ utilityProcess: {},+ MessageChannelMain: class {},+};++Module._load = function loadWithMocks(request, parent, isMain) {+ if (request === "electron") return electronStub;+ if (+ parent?.filename === handlersModulePath &&+ (request.startsWith("./") || request.startsWith("../"))+ ) {+ return anything();+ }+ return originalLoad.call(this, request, parent, isMain);+};++function anything() {+ return new Proxy(function () {}, {+ get: (_target, property) => {+ if (property === Symbol.toPrimitive || property === "toString") return () => "";+ if (property === "then") return undefined;+ return anything();+ },+ apply: () => anything(),+ });+}++// A real HotkeyManager answers for Hold; only its backend and the listener+// probe are faked.+const HotkeyManager = require("../../src/helpers/hotkeyManager");++const inputDenied = () => ({ available: false, reason: "input_access_denied" });+let hotkeyManager;++test.before(() => {+ delete require.cache[handlersModulePath];+ const IPCHandlers = require(handlersModulePath);+ const target = {+ windowManager: {+ get hotkeyManager() {+ return hotkeyManager;+ },+ isUsingGnomeHotkeys: () => hotkeyManager.isUsingGnome(),+ isUsingHyprlandHotkeys: () => hotkeyManager.isUsingHyprland(),+ isUsingKDEHotkeys: () => hotkeyManager.isUsingKDE(),+ isUsingNativeShortcutHotkeys: () => hotkeyManager.isUsingNativeShortcut(),+ },+ };+ IPCHandlers.prototype.setupHandlers.call(+ new Proxy(target, {+ get: (value, property) => (property in value ? value[property] : anything()),+ })+ );+});++test.after(() => {+ Module._load = originalLoad;+});++// The handler decides everything before its first await, so the patched+// platform covers the whole answer.+function hotkeyModeInfo(backend) {+ hotkeyManager = Object.assign(new HotkeyManager(), {+ isInitialized: true,+ nativeListenerProbe: inputDenied,+ ...backend,+ });+ const original = Object.getOwnPropertyDescriptor(process, "platform");+ Object.defineProperty(process, "platform", { value: "linux", configurable: true });+ try {+ return handlers.get("get-hotkey-mode-info")({}, "F8");+ } finally {+ Object.defineProperty(process, "platform", original);+ }+}++// GNOME (portal), KDE and Hyprland deliver press and release themselves, so a+// user without /dev/input access can still hold, and the setup box would send+// them to run sudo for nothing.+const DESKTOP_BACKENDS = {+ GNOME: { useGnome: true, gnomeManager: { supportsPushToTalk: () => true } },+ KDE: { useKDE: true },+ Hyprland: { useHyprland: true },+};++for (const [desktop, backend] of Object.entries(DESKTOP_BACKENDS)) {+ test(`${desktop} holds without the evdev listener, so no input setup is shown`, async () => {+ const info = await hotkeyModeInfo(backend);++ assert.equal(info.supportsPushToTalk, true);+ assert.equal(info.linuxInputAccessDenied, false);+ });+}++test("without a desktop backend, denied input access reaches the renderer", async () => {+ const info = await hotkeyModeInfo({});++ assert.equal(info.supportsPushToTalk, false);+ assert.equal(info.linuxInputAccessDenied, true);+ assert.match(info.pushToTalkUnavailableReason, /usermod/);+});diff --git a/test/helpers/hotkeyModifierOnlyNative.test.js b/test/helpers/hotkeyModifierOnlyNative.test.jsnew file mode 100644index 000000000..76c37059e--- /dev/null+++ b/test/helpers/hotkeyModifierOnlyNative.test.js@@ -0,0 +1,149 @@+const test = require("node:test");+const assert = require("node:assert/strict");++// A modifier-only chord has no regular key, so Electron cannot build an+// accelerator for it. Registering one always fails; the low-level listener is+// what actually watches these on Windows and Linux. Any register() call reaching+// this stub for such a hotkey is the bug this guards against.+const registered = new Map();+require.cache[require.resolve("electron")] = {+ exports: {+ globalShortcut: {+ register(accelerator, callback) {+ registered.set(accelerator, callback);+ return true;+ },+ unregister(accelerator) {+ registered.delete(accelerator);+ },+ isRegistered(accelerator) {+ return registered.has(accelerator);+ },+ unregisterAll() {+ registered.clear();+ },+ },+ BrowserWindow: class {},+ },+};++const HotkeyManager = require("../../src/helpers/hotkeyManager.js");++const noop = () => {};+const originalPlatform = Object.getOwnPropertyDescriptor(process, "platform");+const setPlatform = (value) =>+ Object.defineProperty(process, "platform", { value, configurable: true });++test.beforeEach(() => registered.clear());+test.after(() => Object.defineProperty(process, "platform", originalPlatform));++for (const platform of ["win32", "linux"]) {+ test(`modifier-only chords skip globalShortcut on ${platform} and go to the native listener`, async () => {+ setPlatform(platform);+ const mgr = new HotkeyManager();++ const result = await mgr.registerSlot("dictation", "Control+Super", noop);++ assert.equal(result.success, true);+ assert.deepEqual(mgr.getSlotHotkeys("dictation"), ["Control+Super"]);+ assert.equal(registered.size, 0, "globalShortcut must not be used for a modifier-only chord");+ assert.deepEqual(mgr.getNativeListenerKeys("tap"), ["Control+Super"]);+ });+}++test("a right-side single modifier also reaches the native listener on linux", async () => {+ setPlatform("linux");+ const mgr = new HotkeyManager();++ const result = await mgr.registerSlot("dictation", "RightControl", noop);++ assert.equal(result.success, true);+ assert.equal(registered.size, 0);+ assert.deepEqual(mgr.getNativeListenerKeys("tap"), ["RightControl"]);+});++// The listener backing those hotkeys needs its binary and read access to+// /dev/input. When it cannot run, registration must fail like a refused+// globalShortcut.register so the startup fallback, the Settings error and the+// slot rollback all still happen. The managers stay uninitialized on purpose: a+// saved hotkey registers from .env inside initializeHotkey, before isInitialized+// is set, and must be refused there too.+const denyProbe = (reason) => () => ({ available: false, reason });++for (const hotkey of ["Control+Super", "Control+Alt", "RightControl"]) {+ test(`linux refuses "${hotkey}" when the listener has no input access`, async () => {+ setPlatform("linux");+ const mgr = new HotkeyManager();+ mgr.nativeListenerProbe = denyProbe("input_access_denied");++ const result = await mgr.registerSlot("dictation", hotkey, noop);++ assert.equal(result.success, false);+ assert.equal(registered.size, 0, "a refused hotkey must not fall back to globalShortcut");+ assert.match(result.error, /usermod/, "the error must tell the user how to fix it");+ for (const suggestion of result.suggestions) {+ assert.equal(+ HotkeyManager.isModifierOnlyHotkey(suggestion) ||+ HotkeyManager.isRightSideModifier(suggestion),+ false,+ `"${suggestion}" needs the same listener`+ );+ }+ });+}++test("a refused listener hotkey leaves the slot on its previous binding", async () => {+ setPlatform("linux");+ const mgr = new HotkeyManager();++ await mgr.registerSlot("dictation", "F8", noop);+ mgr.nativeListenerProbe = denyProbe("input_access_denied");+ const result = await mgr.registerSlot("dictation", "Control+Super", noop);++ assert.equal(result.success, false);+ assert.deepEqual(mgr.getSlotHotkeys("dictation"), ["F8"]);+ assert.equal(registered.has("F8"), true, "the previous accelerator must stay registered");+});++test("a missing listener binary reports the push-to-talk unavailable message", async () => {+ setPlatform("linux");+ const mgr = new HotkeyManager();+ mgr.nativeListenerProbe = denyProbe("binary_missing");++ const result = await mgr.registerSlot("dictation", "Control+Super", noop);++ assert.equal(result.success, false);+ // setupShortcuts appends "Try: <suggestions>" to whatever the failure carried.+ assert.equal(result.error.startsWith("Push-to-Talk native listener not available"), true);+});++test("a failing probe is ignored off linux", async () => {+ setPlatform("win32");+ const mgr = new HotkeyManager();+ mgr.nativeListenerProbe = denyProbe("input_access_denied");++ const result = await mgr.registerSlot("dictation", "Control+Super", noop);++ assert.equal(result.success, true);+ assert.deepEqual(mgr.getSlotHotkeys("dictation"), ["Control+Super"]);+});++// GNOME, KDE and Hyprland register through their own shortcut systems, which+// need a regular key and never start the listener in Tap. A lone right modifier+// must be refused with a reason instead of failing there as a format error.+for (const backend of ["useGnome", "useKDE", "useHyprland"]) {+ test(`a right-side single modifier is refused with a reason when ${backend} is active`, async () => {+ setPlatform("linux");+ const mgr = new HotkeyManager();+ mgr[backend] = true;++ const slotResult = await mgr.registerSlot("voiceAgent", "RightControl", noop);+ const updateResult = await mgr.updateHotkey("RightControl", noop);++ assert.equal(slotResult.success, false);+ assert.match(slotResult.error, /regular key/);+ assert.equal(updateResult.success, false);+ assert.match(updateResult.message, /regular key/);+ assert.equal(registered.size, 0);+ });+}diff --git a/test/helpers/hotkeyValidation.test.js b/test/helpers/hotkeyValidation.test.jsindex 6346b1074..45d537438 100644--- a/test/helpers/hotkeyValidation.test.js+++ b/test/helpers/hotkeyValidation.test.js@@ -64,7 +64,7 @@ test("mixing left and right versions of the same modifier is rejected", async ()assert.equal(result.errorCode, "LEFT_RIGHT_MIX");});-test("a single left-side modifier cannot be a hotkey, but a right-side one can (except on Linux)", async () => {+test("a single left-side modifier cannot be a hotkey, but a right-side one can", async () => {const { validateHotkey } = await load();const left = validateHotkey("Control", "win32");@@ -74,10 +74,10 @@ test("a single left-side modifier cannot be a hotkey, but a right-side one can (assert.equal(validateHotkey("RightOption", "darwin").valid, true);assert.equal(validateHotkey("RightAlt", "win32").valid, true);- // Right-side single modifiers need native listeners, which don't exist on Linux.- const linux = validateHotkey("RightAlt", "linux");- assert.equal(linux.valid, false);- assert.equal(linux.errorCode, "LEFT_MODIFIER_ONLY");+ // Linux included: linux-key-listener watches right-side modifiers, and+ // getNativeListenerKeys() routes them to it.+ assert.equal(validateHotkey("RightAlt", "linux").valid, true);+ assert.equal(validateHotkey("RightControl", "linux").valid, true);});test("two-modifier combos without a base key are valid", async () => {diff --git a/test/helpers/linuxKeyManager.test.js b/test/helpers/linuxKeyManager.test.jsindex 6573580ce..ed705c81f 100644--- a/test/helpers/linuxKeyManager.test.js+++ b/test/helpers/linuxKeyManager.test.js@@ -4,6 +4,7 @@ const assert = require("node:assert/strict");const Module = require("node:module");const { EventEmitter } = require("node:events");const childProcess = require("node:child_process");+const fs = require("node:fs");const managerModulePath = require.resolve("../../src/helpers/linuxKeyManager");const originalLoad = Module._load;@@ -133,3 +134,190 @@ test("dropping a key kills its listener process and stops tracking it", () => {assert.equal(child.killed, true);assert.equal(manager.listeners.size, 0);});++// checkAvailability mirrors the C listener's NO_PERMISSION rule, so these pin+// the states it has to tell apart. loadManager's `fs` stub only carries+// statSync, so these load the manager against the real fs and patch it per test.+function loadManagerWithRealFs() {+ delete require.cache[managerModulePath];+ setPlatform("linux");++ Module._load = function loadWithMocks(request, parent, isMain) {+ if (request === "./debugLogger") {+ return { info() {}, warn() {}, debug() {}, error() {} };+ }+ return originalLoad(request, parent, isMain);+ };++ try {+ return require(managerModulePath);+ } finally {+ Module._load = originalLoad;+ }+}++const enoent = () => Object.assign(new Error("ENOENT"), { code: "ENOENT" });+const eacces = () => Object.assign(new Error("EACCES"), { code: "EACCES" });++// sysfs capability bitmaps as the kernel prints them: hex words, most+// significant first, unpadded. A laptop keyboard's lowest key word has every bit+// but KEY_RESERVED set, a value a double cannot hold exactly.+const KEYBOARD_CAPABILITIES = {+ ev: "120013",+ key: "402000000 3803078f800d001 feffffdfffefffff fffffffffffffffe",+};+const GAMEPAD_CAPABILITIES = { ev: "20000b", key: "7cdb000000000000 0 0 0 0" };++// Patch only the paths under test; everything else keeps the real behaviour so+// node:test's own fs use is untouched.+function stubBinaryFound(t, found) {+ const real = fs.statSync;+ t.mock.method(fs, "statSync", (target, ...rest) => {+ if (!String(target).includes("linux-key-listener")) return real.call(fs, target, ...rest);+ if (!found) throw enoent();+ return { isFile: () => true };+ });+}++function stubInputDir(+ t,+ { entries, listError = enoent, readable = [], keyboards = readable, sysfs = true }+) {+ const realReaddir = fs.readdirSync;+ t.mock.method(fs, "readdirSync", (target, ...rest) => {+ if (String(target) !== "/dev/input") return realReaddir.call(fs, target, ...rest);+ if (!entries) throw listError();+ return entries;+ });++ const realAccess = fs.accessSync;+ t.mock.method(fs, "accessSync", (target, ...rest) => {+ if (!String(target).startsWith("/dev/input/")) return realAccess.call(fs, target, ...rest);+ if (!readable.includes(String(target))) throw eacces();+ });++ // Every /sys/class/input read is answered here, so a Linux runner's own+ // devices never leak into the result.+ const realReadFile = fs.readFileSync;+ t.mock.method(fs, "readFileSync", (target, ...rest) => {+ if (!String(target).startsWith("/sys/class/input/")) {+ return realReadFile.call(fs, target, ...rest);+ }+ const match = /^\/sys\/class\/input\/(event\d+)\/device\/capabilities\/(ev|key)$/.exec(+ String(target)+ );+ if (!sysfs || !match) throw enoent();+ const [, node, bitmap] = match;+ const isKeyboard = keyboards.includes(`/dev/input/${node}`);+ return `${(isKeyboard ? KEYBOARD_CAPABILITIES : GAMEPAD_CAPABILITIES)[bitmap]}\n`;+ });+}++test("checkAvailability reports a missing listener binary", (t) => {+ const LinuxKeyManager = loadManagerWithRealFs();+ stubBinaryFound(t, false);++ assert.deepEqual(new LinuxKeyManager().checkAvailability(), {+ available: false,+ reason: "binary_missing",+ });+});++test("checkAvailability reports denied access when no event node is readable", (t) => {+ const LinuxKeyManager = loadManagerWithRealFs();+ stubBinaryFound(t, true);+ stubInputDir(t, { entries: ["event0", "event1", "mice"] });++ assert.deepEqual(new LinuxKeyManager().checkAvailability(), {+ available: false,+ reason: "input_access_denied",+ });+});++test("checkAvailability is available when a single event node is readable", (t) => {+ const LinuxKeyManager = loadManagerWithRealFs();+ stubBinaryFound(t, true);+ stubInputDir(t, { entries: ["event0", "event1"], readable: ["/dev/input/event1"] });++ assert.deepEqual(new LinuxKeyManager().checkAvailability(), { available: true });+});++// The C listener watches /dev/input for hotplug, so an empty directory is a wait,+// not a failure.+test("checkAvailability does not block when /dev/input holds no event nodes", (t) => {+ const LinuxKeyManager = loadManagerWithRealFs();+ stubBinaryFound(t, true);+ stubInputDir(t, { entries: ["mice"] });++ assert.deepEqual(new LinuxKeyManager().checkAvailability(), { available: true });+});++// A /dev/input it cannot list, it cannot watch either: the listener stays silent+// and never recovers. A Flatpak without input devices has no /dev/input at all.+test("checkAvailability reports the listener unavailable without /dev/input", (t) => {+ const LinuxKeyManager = loadManagerWithRealFs();+ stubBinaryFound(t, true);+ stubInputDir(t, { entries: null });++ assert.deepEqual(new LinuxKeyManager().checkAvailability(), {+ available: false,+ reason: "input_devices_unavailable",+ });+});++test("checkAvailability denies access when /dev/input itself is unreadable", (t) => {+ const LinuxKeyManager = loadManagerWithRealFs();+ stubBinaryFound(t, true);+ stubInputDir(t, { entries: null, listError: eacces });++ assert.deepEqual(new LinuxKeyManager().checkAvailability(), {+ available: false,+ reason: "input_access_denied",+ });+});++// systemd's uaccess rule (rules.d/70-uaccess.rules.in) grants the session user+// every joystick node, so a gamepad is readable where keyboards are not. The C+// listener skips it as a non-keyboard and prints NO_PERMISSION; the probe must+// reach the same verdict.+test("checkAvailability denies access when only a gamepad node is readable", (t) => {+ const LinuxKeyManager = loadManagerWithRealFs();+ stubBinaryFound(t, true);+ stubInputDir(t, {+ entries: ["event0", "event1"],+ readable: ["/dev/input/event1"],+ keyboards: [],+ });++ assert.deepEqual(new LinuxKeyManager().checkAvailability(), {+ available: false,+ reason: "input_access_denied",+ });+});++test("checkAvailability finds a readable keyboard past a readable gamepad", (t) => {+ const LinuxKeyManager = loadManagerWithRealFs();+ stubBinaryFound(t, true);+ stubInputDir(t, {+ entries: ["event0", "event1", "event2"],+ readable: ["/dev/input/event0", "/dev/input/event2"],+ keyboards: ["/dev/input/event2"],+ });++ assert.deepEqual(new LinuxKeyManager().checkAvailability(), { available: true });+});++// Without /sys (some sandboxes) a readable node might be a keyboard, and a false+// "denied" would refuse a hotkey the listener can serve.+test("checkAvailability trusts a readable node when sysfs cannot describe it", (t) => {+ const LinuxKeyManager = loadManagerWithRealFs();+ stubBinaryFound(t, true);+ stubInputDir(t, {+ entries: ["event0", "event1"],+ readable: ["/dev/input/event1"],+ keyboards: [],+ sysfs: false,+ });++ assert.deepEqual(new LinuxKeyManager().checkAvailability(), { available: true });+});