Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

fix(hotkeys): make modifier-only hotkeys work simultaneously on Windows/Linux (#1001)

Gabriel Stein4e4004bf9593
diff --git a/main.js b/main.js
index fc1519cb6..285681c0c 100644
--- a/main.js
+++ b/main.js
@@ -409,6 +409,8 @@ function initializeCoreManagers() {
cleanupOrphanedLinuxRestoreToken();
meetingAecManager = new MeetingAecManager();
windowManager.textEditMonitor = textEditMonitor;
+ windowManager.windowsKeyManager = windowsKeyManager;
+ windowManager.linuxKeyManager = linuxKeyManager;
// IPC handlers must be registered before window content loads
ipcHandlers = new IPCHandlers({
@@ -904,6 +906,7 @@ async function startApp() {
ipcMain.handle("register-meeting-hotkey", async (_event, hotkey) => {
if (hotkey) {
const result = await hotkeyManager.registerSlot("meeting", hotkey, meetingHotkeyCallback);
+ windowManager.reconcileNativeKeyListeners();
if (result.success) {
environmentManager.saveMeetingKey(hotkey);
return { success: true };
@@ -912,6 +915,7 @@ async function startApp() {
} else {
hotkeyManager.unregisterSlot("meeting");
environmentManager.saveMeetingKey("");
+ windowManager.reconcileNativeKeyListeners();
return { success: true };
}
});
@@ -1320,49 +1324,55 @@ async function startApp() {
});
}
- if (process.platform === "win32") {
- debugLogger.debug("[Push-to-Talk] Windows Push-to-Talk setup starting");
-
- const {
- isGlobeLikeHotkey: isGlobeLike,
- isModifierOnlyHotkey,
- } = require("./src/helpers/hotkeyManager");
- const isValidHotkey = (hotkey) => hotkey && !isGlobeLike(hotkey);
-
- const isRightSideMod = (hotkey) =>
- /^Right(Control|Ctrl|Alt|Option|Shift|Super|Win|Meta|Command|Cmd)$/i.test(hotkey);
-
- const needsNativeListener = (hotkey, mode) => {
- if (!isValidHotkey(hotkey)) return false;
- if (mode === "push") return true;
- return isRightSideMod(hotkey) || isModifierOnlyHotkey(hotkey);
- };
-
- windowsKeyManager.on("key-down", (_key) => {
- if (!isLiveWindow(windowManager.mainWindow)) return;
-
- const activationMode = windowManager.getActivationMode();
- if (activationMode === "push") {
- windowManager.startWindowsPushToTalk();
- } else if (activationMode === "tap") {
- windowManager.sendToggleDictation();
+ // Windows and Linux share the same native low-level key listener model: one hook
+ // process per watched key (Electron globalShortcut can't see modifier-only or
+ // right-side-modifier combos), routed to the owning slot here. macOS is handled
+ // separately above via globeKeyManager.
+ if (process.platform === "win32" || process.platform === "linux") {
+ const isWindows = process.platform === "win32";
+ const nativeKeyManager = isWindows ? windowsKeyManager : linuxKeyManager;
+ debugLogger.debug("[Push-to-Talk] Native key listener setup starting");
+
+ // Dictation supports push-to-talk and needs the overlay window; agent/meeting
+ // drive other windows (matching their globalShortcut callbacks and macOS).
+ const dispatchNativeKeyDown = (key) => {
+ if (key === hotkeyManager.getCurrentHotkey()) {
+ if (!isLiveWindow(windowManager.mainWindow)) return;
+ if (windowManager.getActivationMode() === "push") {
+ windowManager.startWindowsPushToTalk();
+ } else {
+ windowManager.sendToggleDictation();
+ }
+ return;
}
- });
+ if (key === hotkeyManager.getSlotHotkey("voiceAgent")) {
+ windowManager.sendToggleVoiceAgent();
+ } else if (key === hotkeyManager.getSlotHotkey("agent")) {
+ if (!hotkeyManager.isInListeningMode()) windowManager.toggleAgentOverlay();
+ } else if (key === hotkeyManager.getSlotHotkey("meeting")) {
+ if (!hotkeyManager.isInListeningMode()) meetingDetectionEngine?.startManualMeeting();
+ }
+ };
- windowsKeyManager.on("key-up", () => {
+ // Only dictation drives push-to-talk, so only its key-up matters.
+ const dispatchNativeKeyUp = (key) => {
+ if (key !== hotkeyManager.getCurrentHotkey()) return;
if (windowManager.winPushState?.active) {
windowManager.handleWindowsPushKeyUp();
- } else if (isLiveWindow(windowManager.mainWindow)) {
- const activationMode = windowManager.getActivationMode();
- if (activationMode === "push") {
- windowManager.handleWindowsPushKeyUp();
- }
+ } else if (
+ isLiveWindow(windowManager.mainWindow) &&
+ windowManager.getActivationMode() === "push"
+ ) {
+ windowManager.handleWindowsPushKeyUp();
}
- });
+ };
+
+ nativeKeyManager.on("key-down", dispatchNativeKeyDown);
+ nativeKeyManager.on("key-up", dispatchNativeKeyUp);
- windowsKeyManager.on("error", (error) => {
- debugLogger.warn("[Push-to-Talk] Windows key listener error", { error: error.message });
- if (isLiveWindow(windowManager.mainWindow)) {
+ nativeKeyManager.on("error", (error) => {
+ debugLogger.warn("[Push-to-Talk] Native key listener error", { error: error.message });
+ if (isWindows && isLiveWindow(windowManager.mainWindow)) {
windowManager.mainWindow.webContents.send("windows-ptt-unavailable", {
reason: "error",
message: error.message,
@@ -1370,11 +1380,11 @@ async function startApp() {
}
});
- windowsKeyManager.on("unavailable", () => {
+ nativeKeyManager.on("unavailable", () => {
debugLogger.debug(
- "[Push-to-Talk] Windows key listener not available - falling back to toggle mode"
+ "[Push-to-Talk] Native key listener unavailable - falling back to toggle mode"
);
- if (isLiveWindow(windowManager.mainWindow)) {
+ if (isWindows && isLiveWindow(windowManager.mainWindow)) {
windowManager.mainWindow.webContents.send("windows-ptt-unavailable", {
reason: "binary_not_found",
message: i18nMain.t("windows.pttUnavailable"),
@@ -1382,136 +1392,32 @@ async function startApp() {
}
});
- windowsKeyManager.on("ready", () => {
- debugLogger.debug("[Push-to-Talk] WindowsKeyManager is ready and listening");
- });
-
- const startWindowsKeyListener = () => {
- if (!isLiveWindow(windowManager.mainWindow)) return;
- const activationMode = windowManager.getActivationMode();
- const currentHotkey = hotkeyManager.getCurrentHotkey();
-
- if (needsNativeListener(currentHotkey, activationMode)) {
- windowsKeyManager.start(currentHotkey);
- }
- };
-
- const STARTUP_DELAY_MS = 3000;
- setTimeout(startWindowsKeyListener, STARTUP_DELAY_MS);
-
- ipcMain.on("activation-mode-changed", (_event, mode) => {
- windowManager.resetWindowsPushState();
- const currentHotkey = hotkeyManager.getCurrentHotkey();
- if (needsNativeListener(currentHotkey, mode)) {
- windowsKeyManager.start(currentHotkey);
- } else {
- windowsKeyManager.stop();
- }
- });
-
- ipcMain.on("hotkey-changed", (_event, hotkey) => {
- if (!isLiveWindow(windowManager.mainWindow)) return;
- windowManager.resetWindowsPushState();
- const activationMode = windowManager.getActivationMode();
- windowsKeyManager.stop();
- if (needsNativeListener(hotkey, activationMode)) {
- windowsKeyManager.start(hotkey);
- }
- });
- }
-
- if (process.platform === "linux") {
- debugLogger.debug("[Push-to-Talk] Linux Push-to-Talk setup starting");
-
- const {
- isGlobeLikeHotkey: isGlobeLike,
- isModifierOnlyHotkey,
- } = require("./src/helpers/hotkeyManager");
- const isValidHotkey = (hotkey) => hotkey && !isGlobeLike(hotkey);
-
- const isRightSideMod = (hotkey) =>
- /^Right(Control|Ctrl|Alt|Option|Shift|Super|Win|Meta|Command|Cmd)$/i.test(hotkey);
-
- const needsNativeListener = (hotkey, mode) => {
- if (!isValidHotkey(hotkey)) return false;
- if (mode === "push") return true;
- return isRightSideMod(hotkey) || isModifierOnlyHotkey(hotkey);
- };
-
- linuxKeyManager.on("key-down", (_key) => {
- if (!isLiveWindow(windowManager.mainWindow)) return;
-
- const activationMode = windowManager.getActivationMode();
- if (activationMode === "push") {
- windowManager.startWindowsPushToTalk();
- } else if (activationMode === "tap") {
- windowManager.sendToggleDictation();
- }
- });
-
- linuxKeyManager.on("key-up", () => {
- if (!isLiveWindow(windowManager.mainWindow)) return;
-
- const activationMode = windowManager.getActivationMode();
- if (activationMode === "push") {
- windowManager.handleWindowsPushKeyUp();
- }
+ nativeKeyManager.on("ready", () => {
+ debugLogger.debug("[Push-to-Talk] Native key listener ready and listening");
});
- linuxKeyManager.on("permission-denied", () => {
- 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");
- }
- });
-
- linuxKeyManager.on("error", (error) => {
- debugLogger.warn("[Push-to-Talk] Linux key listener error", { error: error.message });
- });
-
- linuxKeyManager.on("unavailable", () => {
- debugLogger.debug(
- "[Push-to-Talk] Linux key listener not available - falling back to toggle mode"
- );
- });
-
- linuxKeyManager.on("ready", () => {
- debugLogger.debug("[Push-to-Talk] LinuxKeyManager is ready and listening");
- });
-
- const startLinuxKeyListener = () => {
- if (!isLiveWindow(windowManager.mainWindow)) return;
- const activationMode = windowManager.getActivationMode();
- const currentHotkey = hotkeyManager.getCurrentHotkey();
-
- if (needsNativeListener(currentHotkey, activationMode)) {
- linuxKeyManager.start(currentHotkey);
- }
- };
+ if (!isWindows) {
+ nativeKeyManager.on("permission-denied", () => {
+ 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");
+ }
+ });
+ }
const STARTUP_DELAY_MS = 3000;
- setTimeout(startLinuxKeyListener, STARTUP_DELAY_MS);
+ setTimeout(() => windowManager.reconcileNativeKeyListeners(), STARTUP_DELAY_MS);
- ipcMain.on("activation-mode-changed", (_event, mode) => {
+ ipcMain.on("activation-mode-changed", () => {
windowManager.resetWindowsPushState();
- const currentHotkey = hotkeyManager.getCurrentHotkey();
- if (needsNativeListener(currentHotkey, mode)) {
- linuxKeyManager.start(currentHotkey);
- } else {
- linuxKeyManager.stop();
- }
+ windowManager.reconcileNativeKeyListeners();
});
- ipcMain.on("hotkey-changed", (_event, hotkey) => {
- if (!isLiveWindow(windowManager.mainWindow)) return;
+ ipcMain.on("hotkey-changed", () => {
windowManager.resetWindowsPushState();
- const activationMode = windowManager.getActivationMode();
- linuxKeyManager.stop();
- if (needsNativeListener(hotkey, activationMode)) {
- linuxKeyManager.start(hotkey);
- }
+ windowManager.reconcileNativeKeyListeners();
});
}
}
diff --git a/src/helpers/hotkeyManager.js b/src/helpers/hotkeyManager.js
index b442e90d4..ced388f47 100644
--- a/src/helpers/hotkeyManager.js
+++ b/src/helpers/hotkeyManager.js
@@ -305,6 +305,26 @@ class HotkeyManager extends EventEmitter {
return this.slots.get(slotName)?.hotkey ?? null;
}
+ /**
+ * Hotkeys that must be watched by a native low-level listener (Windows/Linux)
+ * instead of globalShortcut. Modifier-only and right-side-modifier combos never
+ * register through globalShortcut, and in push-to-talk mode dictation also needs
+ * raw key-down/key-up events. Only the dictation slot supports push-to-talk;
+ * every other slot is tap-to-toggle. Globe/mouse hotkeys are macOS-only.
+ */
+ getNativeListenerKeys(activationMode) {
+ const keys = [];
+ for (const [slotName, slot] of this.slots) {
+ const hotkey = slot.hotkey;
+ if (!hotkey || isGlobeLikeHotkey(hotkey) || isMouseButtonHotkey(hotkey)) continue;
+ const pushToTalk = slotName === "dictation" && activationMode === "push";
+ if (pushToTalk || isModifierOnlyHotkey(hotkey) || isRightSideModifier(hotkey)) {
+ keys.push(hotkey);
+ }
+ }
+ return keys;
+ }
+
setupShortcuts(hotkey = "Control+Super", callback, slotName = "dictation") {
if (!callback) {
throw new Error(i18nMain.t("hotkey.errors.callbackRequired"));
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 9b6bfab63..a80a99f1a 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -2297,40 +2297,9 @@ class IPCHandlers {
}
}
- if (process.platform === "win32" && this.windowsKeyManager) {
- const activationMode = this.windowManager.getActivationMode();
- debugLogger.log(
- `[IPC] Exiting hotkey capture mode, activationMode="${activationMode}", hotkey="${effectiveHotkey}"`
- );
- const needsListener =
- effectiveHotkey &&
- !isGlobeLikeHotkey(effectiveHotkey) &&
- (activationMode === "push" ||
- isModifierOnlyHotkey(effectiveHotkey) ||
- isRightSideModifier(effectiveHotkey));
- if (needsListener) {
- debugLogger.log(`[IPC] Restarting Windows key listener for hotkey: ${effectiveHotkey}`);
- this.windowsKeyManager.start(effectiveHotkey);
- } else {
- this.windowsKeyManager.stop();
- }
- }
-
- if (process.platform === "linux" && this.linuxKeyManager) {
- const activationMode = this.windowManager.getActivationMode();
- const needsListener =
- effectiveHotkey &&
- !isGlobeLikeHotkey(effectiveHotkey) &&
- (activationMode === "push" ||
- isModifierOnlyHotkey(effectiveHotkey) ||
- isRightSideModifier(effectiveHotkey));
- if (needsListener) {
- debugLogger.log(`[IPC] Restarting Linux key listener for hotkey: ${effectiveHotkey}`);
- this.linuxKeyManager.start(effectiveHotkey);
- } else {
- this.linuxKeyManager.stop();
- }
- }
+ // Re-sync native key listeners (Windows/Linux) across all hotkey slots now
+ // that capture is done. Idempotent — reads the current slot hotkeys.
+ this.windowManager.reconcileNativeKeyListeners();
// On GNOME, re-register the keybinding with the effective hotkey
if (hotkeyManager.isUsingGnome() && hotkeyManager.gnomeManager && effectiveHotkey) {
@@ -7382,10 +7351,12 @@ class IPCHandlers {
if (!hotkey) {
hotkeyManager.unregisterSlot("agent");
this.environmentManager.saveAgentKey?.("");
+ this.windowManager.reconcileNativeKeyListeners();
return { success: true, message: "Agent hotkey cleared" };
}
const result = await hotkeyManager.registerSlot("agent", hotkey, agentCallback);
+ this.windowManager.reconcileNativeKeyListeners();
if (result.success) {
this.environmentManager.saveAgentKey?.(hotkey);
return { success: true, message: `Agent hotkey updated to: ${hotkey}` };
@@ -7407,10 +7378,12 @@ class IPCHandlers {
if (!hotkey) {
hotkeyManager.unregisterSlot("voiceAgent");
this.environmentManager.saveVoiceAgentKey?.("");
+ this.windowManager.reconcileNativeKeyListeners();
return { success: true, message: "Voice agent hotkey cleared" };
}
const result = await hotkeyManager.registerSlot("voiceAgent", hotkey, voiceAgentCallback);
+ this.windowManager.reconcileNativeKeyListeners();
if (result.success) {
this.environmentManager.saveVoiceAgentKey?.(hotkey);
return { success: true, message: `Voice agent hotkey updated to: ${hotkey}` };
diff --git a/src/helpers/linuxKeyManager.js b/src/helpers/linuxKeyManager.js
index 73b114daa..025f8db97 100644
--- a/src/helpers/linuxKeyManager.js
+++ b/src/helpers/linuxKeyManager.js
@@ -4,127 +4,96 @@ const EventEmitter = require("events");
const fs = require("fs");
const debugLogger = require("./debugLogger");
+// Force a key-up if the native listener never reports one (e.g. a missed release
+// while another window had focus), so a held key can't get stuck recording.
+const WATCHDOG_MS = 30000;
+
class LinuxKeyManager extends EventEmitter {
constructor() {
super();
- this.process = null;
this.isSupported = process.platform === "linux";
this.hasReportedError = false;
- this.currentKey = null;
- this.isReady = false;
- this.watchdogTimer = null;
+ this.hasReportedUnavailable = false;
+ this.listeners = new Map(); // key string -> { child, watchdog }
}
- handleOutputLine(line, key) {
- if (line === "READY") {
- debugLogger.debug("[LinuxKeyManager] Listener ready", { key });
- this.isReady = true;
- this.emit("ready");
- return;
- }
+ /**
+ * Reconcile the watched keys to exactly `keys`: spawn a listener for each new
+ * key, stop listeners no longer wanted. Idempotent — safe to call repeatedly.
+ */
+ setKeys(keys) {
+ if (!this.isSupported) return;
+ const desired = new Set(keys.filter(Boolean));
- if (line === "NO_PERMISSION") {
- debugLogger.warn("[LinuxKeyManager] No permission to access input devices");
- this.emit("permission-denied");
- return;
+ for (const key of [...this.listeners.keys()]) {
+ if (!desired.has(key)) this._stopKey(key);
}
- if (line === "KEY_DOWN") {
- debugLogger.debug("[LinuxKeyManager] KEY_DOWN detected", { key });
- if (this.watchdogTimer) clearTimeout(this.watchdogTimer);
- this.watchdogTimer = setTimeout(() => {
- debugLogger.warn("[LinuxKeyManager] Watchdog: no KEY_UP within 30s, forcing release");
- this.emit("key-up", this.currentKey);
- this.watchdogTimer = null;
- }, 30000);
- this.emit("key-down", key);
- return;
- }
-
- if (line === "KEY_UP") {
- debugLogger.debug("[LinuxKeyManager] KEY_UP detected", { key });
- if (this.watchdogTimer) {
- clearTimeout(this.watchdogTimer);
- this.watchdogTimer = null;
- }
- this.emit("key-up", key);
- return;
- }
-
- debugLogger.debug("[LinuxKeyManager] Unknown output", { line });
- }
-
- start(key = "`") {
- if (!this.isSupported) return;
- if (this.process && this.currentKey === key) return;
-
- this.stop();
+ if (desired.size === 0) return;
const listenerPath = this.resolveListenerBinary();
if (!listenerPath) {
- this.emit("unavailable", new Error("Linux key listener binary not found"));
+ if (!this.hasReportedUnavailable) {
+ this.hasReportedUnavailable = true;
+ this.emit("unavailable", new Error("Linux key listener binary not found"));
+ }
return;
}
- this.hasReportedError = false;
- this.isReady = false;
- this.currentKey = key;
-
- debugLogger.debug("[LinuxKeyManager] Starting key listener", {
- key,
- binaryPath: listenerPath,
- });
+ for (const key of desired) {
+ if (!this.listeners.has(key)) this._startKey(key, listenerPath);
+ }
+ }
+ _startKey(key, listenerPath) {
+ let child;
try {
- this.process = spawn(listenerPath, [key], {
- stdio: ["ignore", "pipe", "pipe"],
- });
+ child = spawn(listenerPath, [key], { stdio: ["ignore", "pipe", "pipe"] });
} catch (error) {
debugLogger.error("[LinuxKeyManager] Failed to spawn process", { error: error.message });
this.reportError(error);
return;
}
+ this.hasReportedError = false;
+ const entry = { child, watchdog: null };
+ this.listeners.set(key, entry);
+ debugLogger.debug("[LinuxKeyManager] Starting key listener", { key, binaryPath: listenerPath });
+
let lineBuffer = "";
- this.process.stdout.setEncoding("utf8");
- this.process.stdout.on("data", (chunk) => {
+ child.stdout.setEncoding("utf8");
+ child.stdout.on("data", (chunk) => {
lineBuffer += chunk;
const lines = lineBuffer.split(/\r?\n/);
lineBuffer = lines.pop();
for (const raw of lines) {
const line = raw.trim();
- if (!line) continue;
- this.handleOutputLine(line, key);
+ if (line) this.handleOutputLine(line, key);
}
});
- this.process.stderr.setEncoding("utf8");
- this.process.stderr.on("data", (data) => {
+ child.stderr.setEncoding("utf8");
+ child.stderr.on("data", (data) => {
const message = data.toString().trim();
if (message.length > 0) {
- debugLogger.debug("[LinuxKeyManager] Native stderr", { message });
+ debugLogger.debug("[LinuxKeyManager] Native stderr", { key, message });
}
});
- const proc = this.process;
-
- proc.on("error", (error) => {
- if (this.process === proc) this.process = null;
+ child.on("error", (error) => {
+ if (this.listeners.get(key) === entry) this._stopKey(key);
this.reportError(error);
});
- proc.on("exit", (code, signal) => {
+ child.on("exit", (code, signal) => {
const trailingLine = lineBuffer.trim();
- if (trailingLine) {
- this.handleOutputLine(trailingLine, key);
- lineBuffer = "";
- }
+ if (trailingLine) this.handleOutputLine(trailingLine, key);
- if (this.process === proc) {
- this.process = null;
- this.isReady = false;
- }
- if (code !== 0) {
+ // wasTracked is false for intentional stops (_stopKey deletes first), so this
+ // reports only unexpected exits — including signal crashes, where code is null.
+ const wasTracked = this.listeners.get(key) === entry;
+ if (wasTracked) this._stopKey(key);
+ if (wasTracked && (code || signal)) {
this.reportError(
new Error(
`Linux key listener exited with code ${code ?? "null"} signal ${signal ?? "null"}`
@@ -134,20 +103,65 @@ class LinuxKeyManager extends EventEmitter {
});
}
- stop() {
- if (this.watchdogTimer) {
- clearTimeout(this.watchdogTimer);
- this.watchdogTimer = null;
+ _stopKey(key) {
+ const entry = this.listeners.get(key);
+ if (!entry) return;
+ this.listeners.delete(key);
+ if (entry.watchdog) clearTimeout(entry.watchdog);
+ debugLogger.debug("[LinuxKeyManager] Stopping key listener", { key });
+ try {
+ entry.child.kill();
+ } catch {
+ // Already gone
}
- if (this.process) {
- debugLogger.debug("[LinuxKeyManager] Stopping key listener");
- try {
- this.process.kill();
- } catch {}
- this.process = null;
+ }
+
+ handleOutputLine(line, key) {
+ if (line === "READY") {
+ debugLogger.debug("[LinuxKeyManager] Listener ready", { key });
+ this.emit("ready", key);
+ return;
+ }
+
+ if (line === "NO_PERMISSION") {
+ debugLogger.warn("[LinuxKeyManager] No permission to access input devices");
+ this.emit("permission-denied");
+ return;
}
- this.isReady = false;
- this.currentKey = null;
+
+ if (line === "KEY_DOWN") {
+ debugLogger.debug("[LinuxKeyManager] KEY_DOWN detected", { key });
+ const entry = this.listeners.get(key);
+ if (entry) {
+ if (entry.watchdog) clearTimeout(entry.watchdog);
+ entry.watchdog = setTimeout(() => {
+ debugLogger.warn("[LinuxKeyManager] Watchdog: no KEY_UP within 30s, forcing release", {
+ key,
+ });
+ entry.watchdog = null;
+ this.emit("key-up", key);
+ }, WATCHDOG_MS);
+ }
+ this.emit("key-down", key);
+ return;
+ }
+
+ if (line === "KEY_UP") {
+ debugLogger.debug("[LinuxKeyManager] KEY_UP detected", { key });
+ const entry = this.listeners.get(key);
+ if (entry?.watchdog) {
+ clearTimeout(entry.watchdog);
+ entry.watchdog = null;
+ }
+ this.emit("key-up", key);
+ return;
+ }
+
+ debugLogger.debug("[LinuxKeyManager] Unknown output", { key, line });
+ }
+
+ stop() {
+ for (const key of [...this.listeners.keys()]) this._stopKey(key);
}
isAvailable() {
@@ -157,16 +171,6 @@ class LinuxKeyManager extends EventEmitter {
reportError(error) {
if (this.hasReportedError) return;
this.hasReportedError = true;
-
- if (this.process) {
- try {
- this.process.kill();
- } catch {
- } finally {
- this.process = null;
- }
- }
-
debugLogger.warn("[LinuxKeyManager] Error occurred", { error: error.message });
this.emit("error", error);
}
diff --git a/src/helpers/windowManager.js b/src/helpers/windowManager.js
index 0fe1e3ea7..0bc1c1f8b 100644
--- a/src/helpers/windowManager.js
+++ b/src/helpers/windowManager.js
@@ -494,6 +494,26 @@ class WindowManager {
this._cachedActivationMode = mode === "push" ? "push" : "tap";
}
+ /**
+ * Sync the native low-level key listeners (Windows/Linux) so every hotkey slot
+ * that needs one is watched. Call after any change to a slot hotkey or the
+ * activation mode. No-op during hotkey capture (listeners are stopped then).
+ */
+ reconcileNativeKeyListeners() {
+ if (!this.mainWindow || this.mainWindow.isDestroyed()) return;
+ if (this.hotkeyManager.isInListeningMode()) return;
+ // GNOME/KDE/Hyprland deliver hotkeys via D-Bus native shortcuts; the low-level
+ // listener would be redundant there and could double-fire, so watch nothing.
+ const keys = this.hotkeyManager.isUsingNativeShortcut()
+ ? []
+ : this.hotkeyManager.getNativeListenerKeys(this.getActivationMode());
+ if (process.platform === "win32" && this.windowsKeyManager) {
+ this.windowsKeyManager.setKeys(keys);
+ } else if (process.platform === "linux" && this.linuxKeyManager) {
+ this.linuxKeyManager.setKeys(keys);
+ }
+ }
+
setFloatingIconAutoHide(enabled) {
this._floatingIconAutoHide = Boolean(enabled);
}
diff --git a/src/helpers/windowsKeyManager.js b/src/helpers/windowsKeyManager.js
index 734668665..e5a54c567 100644
--- a/src/helpers/windowsKeyManager.js
+++ b/src/helpers/windowsKeyManager.js
@@ -1,8 +1,11 @@
/**
- * WindowsKeyManager - Handles key up/down detection for Push-to-Talk on Windows
+ * WindowsKeyManager - Detects key up/down for global hotkeys on Windows
*
- * Uses a native Windows keyboard hook to detect when specific keys are
- * pressed and released, enabling Push-to-Talk functionality.
+ * Modifier-only and right-side-modifier hotkeys can't register through Electron's
+ * globalShortcut, so each one is watched by a native low-level keyboard hook. One
+ * hook process is spawned per watched key; key-down/key-up events are emitted
+ * tagged with the key so the caller can route them to the right hotkey slot
+ * (dictation, voice agent, agent, meeting) and drive push-to-talk.
*/
const { spawn } = require("child_process");
@@ -14,71 +17,45 @@ const debugLogger = require("./debugLogger");
class WindowsKeyManager extends EventEmitter {
constructor() {
super();
- this.process = null;
this.isSupported = process.platform === "win32";
this.hasReportedError = false;
- this.currentKey = null;
- this.isReady = false;
- }
-
- handleOutputLine(line, key) {
- if (line === "READY") {
- debugLogger.debug("[WindowsKeyManager] Listener ready", { key });
- this.isReady = true;
- this.emit("ready");
- return;
- }
-
- if (line === "KEY_DOWN") {
- debugLogger.debug("[WindowsKeyManager] KEY_DOWN detected", { key });
- this.emit("key-down", key);
- return;
- }
-
- if (line === "KEY_UP") {
- debugLogger.debug("[WindowsKeyManager] KEY_UP detected", { key });
- this.emit("key-up", key);
- return;
- }
-
- debugLogger.debug("[WindowsKeyManager] Unknown output", { line });
+ this.hasReportedUnavailable = false;
+ this.listeners = new Map(); // key string -> child process
}
/**
- * Start listening for the specified key
- * @param {string} key - The key to listen for (e.g., "`", "F8", "F11", "CommandOrControl+F11")
+ * Reconcile the watched keys to exactly `keys`: spawn a listener for each new
+ * key, stop listeners no longer wanted. Idempotent — safe to call repeatedly.
*/
- start(key = "`") {
- if (!this.isSupported) {
- return;
- }
+ setKeys(keys) {
+ if (!this.isSupported) return;
+ const desired = new Set(keys.filter(Boolean));
- // If already running with the same key, do nothing
- if (this.process && this.currentKey === key) {
- return;
+ for (const key of [...this.listeners.keys()]) {
+ if (!desired.has(key)) this._stopKey(key);
}
- // Stop any existing listener
- this.stop();
+ if (desired.size === 0) return;
const listenerPath = this.resolveListenerBinary();
if (!listenerPath) {
// Binary not found - this is OK, Push-to-Talk will use fallback mode
- this.emit("unavailable", new Error("Windows key listener binary not found"));
+ if (!this.hasReportedUnavailable) {
+ this.hasReportedUnavailable = true;
+ this.emit("unavailable", new Error("Windows key listener binary not found"));
+ }
return;
}
- this.hasReportedError = false;
- this.isReady = false;
- this.currentKey = key;
-
- debugLogger.debug("[WindowsKeyManager] Starting key listener", {
- key,
- binaryPath: listenerPath,
- });
+ for (const key of desired) {
+ if (!this.listeners.has(key)) this._startKey(key, listenerPath);
+ }
+ }
+ _startKey(key, listenerPath) {
+ let child;
try {
- this.process = spawn(listenerPath, [key], {
+ child = spawn(listenerPath, [key], {
stdio: ["ignore", "pipe", "pipe"],
windowsHide: true,
});
@@ -88,47 +65,48 @@ class WindowsKeyManager extends EventEmitter {
return;
}
+ this.hasReportedError = false;
+ this.listeners.set(key, child);
+ debugLogger.debug("[WindowsKeyManager] Starting key listener", {
+ key,
+ binaryPath: listenerPath,
+ });
+
let lineBuffer = "";
- this.process.stdout.setEncoding("utf8");
- this.process.stdout.on("data", (chunk) => {
+ child.stdout.setEncoding("utf8");
+ child.stdout.on("data", (chunk) => {
lineBuffer += chunk;
const lines = lineBuffer.split(/\r?\n/);
lineBuffer = lines.pop();
for (const raw of lines) {
const line = raw.trim();
- if (!line) continue;
- this.handleOutputLine(line, key);
+ if (line) this.handleOutputLine(line, key);
}
});
- this.process.stderr.setEncoding("utf8");
- this.process.stderr.on("data", (data) => {
+ child.stderr.setEncoding("utf8");
+ child.stderr.on("data", (data) => {
const message = data.toString().trim();
if (message.length > 0) {
// Native binary logs to stderr for info messages, don't treat as error
- debugLogger.debug("[WindowsKeyManager] Native stderr", { message });
+ debugLogger.debug("[WindowsKeyManager] Native stderr", { key, message });
}
});
- const proc = this.process;
-
- proc.on("error", (error) => {
- if (this.process === proc) this.process = null;
+ child.on("error", (error) => {
+ if (this.listeners.get(key) === child) this.listeners.delete(key);
this.reportError(error);
});
- proc.on("exit", (code, signal) => {
+ child.on("exit", (code, signal) => {
const trailingLine = lineBuffer.trim();
- if (trailingLine) {
- this.handleOutputLine(trailingLine, key);
- lineBuffer = "";
- }
+ if (trailingLine) this.handleOutputLine(trailingLine, key);
- if (this.process === proc) {
- this.process = null;
- this.isReady = false;
- }
- if (code !== 0) {
+ // wasTracked is false for intentional stops (_stopKey deletes first), so this
+ // reports only unexpected exits — including signal crashes, where code is null.
+ const wasTracked = this.listeners.get(key) === child;
+ if (wasTracked) this.listeners.delete(key);
+ if (wasTracked && (code || signal)) {
this.reportError(
new Error(
`Windows key listener exited with code ${code ?? "null"} signal ${signal ?? "null"}`
@@ -138,25 +116,49 @@ class WindowsKeyManager extends EventEmitter {
});
}
+ _stopKey(key) {
+ const child = this.listeners.get(key);
+ if (!child) return;
+ this.listeners.delete(key);
+ debugLogger.debug("[WindowsKeyManager] Stopping key listener", { key });
+ try {
+ child.kill();
+ } catch {
+ // Already gone
+ }
+ }
+
+ handleOutputLine(line, key) {
+ if (line === "READY") {
+ debugLogger.debug("[WindowsKeyManager] Listener ready", { key });
+ this.emit("ready", key);
+ return;
+ }
+
+ if (line === "KEY_DOWN") {
+ debugLogger.debug("[WindowsKeyManager] KEY_DOWN detected", { key });
+ this.emit("key-down", key);
+ return;
+ }
+
+ if (line === "KEY_UP") {
+ debugLogger.debug("[WindowsKeyManager] KEY_UP detected", { key });
+ this.emit("key-up", key);
+ return;
+ }
+
+ debugLogger.debug("[WindowsKeyManager] Unknown output", { key, line });
+ }
+
/**
- * Stop the key listener
+ * Stop all key listeners.
*/
stop() {
- if (this.process) {
- debugLogger.debug("[WindowsKeyManager] Stopping key listener");
- try {
- this.process.kill();
- } catch {
- // Ignore kill errors
- }
- this.process = null;
- }
- this.isReady = false;
- this.currentKey = null;
+ for (const key of [...this.listeners.keys()]) this._stopKey(key);
}
/**
- * Check if the listener is available and ready
+ * Check if the listener binary is available
*/
isAvailable() {
return this.resolveListenerBinary() !== null;
@@ -166,21 +168,8 @@ class WindowsKeyManager extends EventEmitter {
* Report an error (only once per session to avoid log spam)
*/
reportError(error) {
- if (this.hasReportedError) {
- return;
- }
+ if (this.hasReportedError) return;
this.hasReportedError = true;
-
- if (this.process) {
- try {
- this.process.kill();
- } catch {
- // Ignore
- } finally {
- this.process = null;
- }
- }
-
debugLogger.warn("[WindowsKeyManager] Error occurred", { error: error.message });
this.emit("error", error);
}
diff --git a/test/helpers/nativeListenerKeys.test.js b/test/helpers/nativeListenerKeys.test.js
new file mode 100644
index 000000000..f8523b502
--- /dev/null
+++ b/test/helpers/nativeListenerKeys.test.js
@@ -0,0 +1,52 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const HotkeyManager = require("../../src/helpers/hotkeyManager.js");
+
+// Build a manager with an explicit set of slot hotkeys, independent of the
+// platform default so the assertions are deterministic everywhere.
+const makeManager = (slots) => {
+ const mgr = new HotkeyManager();
+ mgr.slots.clear();
+ for (const [name, hotkey] of Object.entries(slots)) {
+ mgr.slots.set(name, { hotkey, callback: null, accelerator: null });
+ }
+ return mgr;
+};
+
+test("tap mode watches modifier-only hotkeys for every slot", () => {
+ const mgr = makeManager({
+ dictation: "Control+Super",
+ voiceAgent: "Control+Alt",
+ agent: "Alt+Super",
+ });
+ assert.deepEqual(mgr.getNativeListenerKeys("tap").sort(), [
+ "Alt+Super",
+ "Control+Alt",
+ "Control+Super",
+ ]);
+});
+
+test("regular key hotkeys are left to globalShortcut in tap mode", () => {
+ const mgr = makeManager({ dictation: "F8", voiceAgent: "Control+Shift+A" });
+ assert.deepEqual(mgr.getNativeListenerKeys("tap"), []);
+});
+
+test("push mode watches the dictation key even when it is a regular key", () => {
+ const mgr = makeManager({ dictation: "F8", voiceAgent: "Control+Shift+A" });
+ assert.deepEqual(mgr.getNativeListenerKeys("push"), ["F8"]);
+});
+
+test("push mode does not push-enable non-dictation slots", () => {
+ const mgr = makeManager({ dictation: "Control+Super", agent: "F9" });
+ assert.deepEqual(mgr.getNativeListenerKeys("push"), ["Control+Super"]);
+});
+
+test("right-side modifiers use the native listener; globe/empty slots do not", () => {
+ const mgr = makeManager({
+ dictation: "GLOBE",
+ voiceAgent: "RightControl",
+ agent: "",
+ });
+ assert.deepEqual(mgr.getNativeListenerKeys("tap"), ["RightControl"]);
+});