Skip to content

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

feat(linux): extend native Hyprland shortcut support for voice agent, translation and meeting hotkey (#1811)

Idris Gadi906689525e7e
diff --git a/main.js b/main.js
index cf28b34dd..83a746e82 100644
--- a/main.js
+++ b/main.js
@@ -1108,6 +1108,8 @@ async function startApp() {
await flushPendingNoteDeepLink();
}
+ await hotkeyManager.hyprlandRegistrationReady;
+
// Set up voice agent hotkey (dictation routed straight to the dictation
// agent, bypassing cleanup). Tap-only slots gate autorepeat like the
// dictation toggle does.
@@ -1193,7 +1195,8 @@ async function startApp() {
}
return { success: false, message: result.error };
} else {
- hotkeyManager.unregisterSlot("meeting");
+ const removed = await hotkeyManager.unregisterSlot("meeting");
+ if (removed === false) return { success: false };
environmentManager.saveMeetingKey("");
windowManager.reconcileNativeKeyListeners();
return { success: true };
diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsx
index c10392be4..087345f38 100644
--- a/src/components/SettingsPage.tsx
+++ b/src/components/SettingsPage.tsx
@@ -4095,9 +4095,19 @@ EOF`,
<HotkeyListInput
value={meetingKey}
onChange={(list) => registerMeetingHotkey(list)}
- onClear={async () => {
- await window.electronAPI?.registerMeetingHotkey?.("");
+ onClear={async (): Promise<boolean> => {
+ const result = await window.electronAPI?.registerMeetingHotkey?.("");
+ if (!result?.success) {
+ showAlertDialog({
+ title: t("hooks.hotkeyRegistration.titles.notRegistered"),
+ description:
+ result?.message ||
+ t("hooks.hotkeyRegistration.errors.couldNotRegister"),
+ });
+ return false;
+ }
setMeetingKey("");
+ return true;
}}
validate={validateMeetingHotkey}
disabled={isMeetingHotkeyRegistering}
diff --git a/src/helpers/hotkeyManager.js b/src/helpers/hotkeyManager.js
index 73590066f..cf7154415 100644
--- a/src/helpers/hotkeyManager.js
+++ b/src/helpers/hotkeyManager.js
@@ -16,9 +16,8 @@ const FALLBACK_HOTKEYS = ["F8", "F9", "Control+Shift+Space"];
// Default hotkey for dictation if no saved value exists
const DEFAULT_HOTKEY = "Control+Super";
-// Slots routed through GNOME native gsettings (not globalShortcut).
-// Temporary slots like "cancel" stay on globalShortcut.
-const GNOME_NATIVE_SLOTS = new Set(["meeting", "voiceAgent", "translation"]);
+// Dictation has a dedicated native path because it also supports push-to-talk.
+const LINUX_NATIVE_TAP_SLOTS = new Set(["meeting", "voiceAgent", "translation"]);
// KDE registration failure reasons — reuse existing i18n keys
const KDE_FAILURE_REASONS = {
@@ -108,6 +107,8 @@ class HotkeyManager extends EventEmitter {
this.useGnome = false;
this.hyprlandManager = null;
this.useHyprland = false;
+ this.hyprlandInitializationAttempted = false;
+ this.hyprlandRegistrationReady = Promise.resolve();
this.kdeManager = null;
this.useKDE = false;
}
@@ -206,12 +207,11 @@ class HotkeyManager extends EventEmitter {
}),
};
}
- // GNOME/KDE/Hyprland bind one accelerator per slot, so they use the primary
- // (first) hotkey; the globalShortcut path below registers the whole list.
+ // Native Linux backends bind only the primary hotkey.
const hotkey = hotkeys[0];
if (
hotkeys.length > 1 &&
- ((this.useGnome && GNOME_NATIVE_SLOTS.has(slotName)) ||
+ (((this.useGnome || this.useHyprland) && LINUX_NATIVE_TAP_SLOTS.has(slotName)) ||
(this.useKDE && slotName !== "cancel"))
) {
debugLogger.log(
@@ -220,7 +220,7 @@ class HotkeyManager extends EventEmitter {
}
// On GNOME (X11 or Wayland), route named slots through native gsettings
- if (this.useGnome && this.gnomeManager && GNOME_NATIVE_SLOTS.has(slotName)) {
+ if (this.useGnome && this.gnomeManager && LINUX_NATIVE_TAP_SLOTS.has(slotName)) {
const gnomeHotkey = GnomeShortcutManager.convertToGnomeFormat(hotkey);
if (!gnomeHotkey) {
debugLogger.log(
@@ -298,6 +298,34 @@ class HotkeyManager extends EventEmitter {
return { success: true, hotkey };
}
+ if (LINUX_NATIVE_TAP_SLOTS.has(slotName) && this.useHyprland && this.hyprlandManager) {
+ const conflict = this._findSlotConflict(slotName, hotkey);
+ if (conflict) return conflict;
+
+ const success = await this.hyprlandManager.registerSlotKeybinding(hotkey, slotName, callback);
+ if (!success) {
+ return {
+ success: false,
+ error: i18nMain.t("hotkey.errors.registrationFailed", { hotkey }),
+ };
+ }
+
+ const slot = this._ensureSlot(slotName);
+ slot.hotkeys = [hotkey];
+ slot.callback = callback;
+ slot.accelerators = [];
+ this.slots.set(slotName, slot);
+ debugLogger.log(`[HotkeyManager] Hyprland slot "${slotName}" set to "${hotkey}"`);
+ return { success: true, hotkey };
+ }
+
+ if (LINUX_NATIVE_TAP_SLOTS.has(slotName) && this.hyprlandInitializationAttempted) {
+ return {
+ success: false,
+ error: i18nMain.t("hotkey.errors.registrationFailed", { hotkey }),
+ };
+ }
+
const result = this.setupShortcuts(hotkeys, callback, slotName, options);
if (result.success) {
const slot = this._ensureSlot(slotName);
@@ -325,7 +353,7 @@ class HotkeyManager extends EventEmitter {
}
// On GNOME, native slots are managed via gsettings, not globalShortcut
- if (this.useGnome && this.gnomeManager && GNOME_NATIVE_SLOTS.has(slotName)) {
+ if (this.useGnome && this.gnomeManager && LINUX_NATIVE_TAP_SLOTS.has(slotName)) {
this.gnomeManager.unregisterKeybinding(slotName).catch((err) => {
debugLogger.warn(
`[HotkeyManager] Error unregistering GNOME keybinding for slot "${slotName}":`,
@@ -337,6 +365,24 @@ class HotkeyManager extends EventEmitter {
return;
}
+ if (this.useHyprland && this.hyprlandManager && LINUX_NATIVE_TAP_SLOTS.has(slotName)) {
+ return this.hyprlandManager
+ .unregisterKeybinding(slotName)
+ .then((success) => {
+ if (!success) return false;
+ slot.hotkeys = [];
+ slot.accelerators = [];
+ return true;
+ })
+ .catch((err) => {
+ debugLogger.warn(
+ `[HotkeyManager] Error unregistering Hyprland keybinding for slot "${slotName}":`,
+ err.message
+ );
+ return false;
+ });
+ }
+
// Release what was actually registered; native-listener entries are null.
for (const accel of slot.accelerators || []) {
if (!accel) continue;
@@ -704,13 +750,24 @@ class HotkeyManager extends EventEmitter {
isModifierOnlyHotkey(hotkey)
? null
: normalizeToAccelerator(hotkey);
+ const hyprlandBinding = this.useHyprland
+ ? HyprlandShortcutManager.getCanonicalBinding(hotkey)
+ : null;
for (const [otherSlotName, otherSlot] of this.slots) {
if (otherSlotName === slotName) continue;
const otherHotkeys = otherSlot.hotkeys || [];
const otherAccelerators = otherSlot.accelerators || [];
+ const hasEquivalentHyprlandBinding =
+ hyprlandBinding &&
+ otherHotkeys.some(
+ (otherHotkey) =>
+ HyprlandShortcutManager.getCanonicalBinding(otherHotkey) === hyprlandBinding
+ );
const match =
- otherHotkeys.includes(hotkey) || (accelerator && otherAccelerators.includes(accelerator));
+ otherHotkeys.includes(hotkey) ||
+ (accelerator && otherAccelerators.includes(accelerator)) ||
+ hasEquivalentHyprlandBinding;
if (match) {
debugLogger.warn(
`[HotkeyManager] Hotkey "${hotkey}" conflicts with slot "${otherSlotName}"`
@@ -831,6 +888,7 @@ class HotkeyManager extends EventEmitter {
}
if (isHyprland) {
+ this.hyprlandInitializationAttempted = true;
if (!HyprlandShortcutManager.isHyprctlAvailable()) {
debugLogger.log("[HotkeyManager] Hyprland detected but hyprctl not available");
return false;
@@ -948,7 +1006,9 @@ class HotkeyManager extends EventEmitter {
}
};
- setTimeout(registerHyprlandHotkey, HOTKEY_REGISTRATION_DELAY_MS);
+ this.hyprlandRegistrationReady = new Promise((resolve) =>
+ setTimeout(resolve, HOTKEY_REGISTRATION_DELAY_MS)
+ ).then(registerHyprlandHotkey);
this.isInitialized = true;
return;
}
diff --git a/src/helpers/hyprlandShortcut.js b/src/helpers/hyprlandShortcut.js
index 80078ae37..dc4edf960 100644
--- a/src/helpers/hyprlandShortcut.js
+++ b/src/helpers/hyprlandShortcut.js
@@ -7,6 +7,14 @@ const debugLogger = require("./debugLogger");
const DBUS_SERVICE_NAME = "com.openwhispr.App";
const DBUS_OBJECT_PATH = "/com/openwhispr/App";
const DBUS_INTERFACE = "com.openwhispr.App";
+const DBUS_NAME_REQUEST_TIMEOUT_MS = 5000;
+
+const SLOT_TOGGLE_METHOD = {
+ dictation: "Toggle",
+ meeting: "ToggleMeeting",
+ voiceAgent: "ToggleVoiceAgent",
+ translation: "ToggleTranslation",
+};
// Map Electron modifier names to Hyprland modifier names
const ELECTRON_TO_HYPRLAND_MOD = {
@@ -74,6 +82,14 @@ function isManagedHeaderLine(line) {
return MANAGED_HEADER_VARIANTS.has(line.trim().replace(/^(#|--)\s*/, ""));
}
+function isManagedBindLine(line, format) {
+ const hasManagedCall = line.includes(
+ `--dest=${DBUS_SERVICE_NAME} ${DBUS_OBJECT_PATH} ${DBUS_INTERFACE}.`
+ );
+ if (!hasManagedCall) return false;
+ return format === "lua" ? /^hl\.bind\s*\(/.test(line) : /^bind(?:t|rt)?\s*=/.test(line);
+}
+
function buildManagedBindsContent(lines = [], format = "conf") {
const body = lines.join("\n").trim();
const comment = format === "lua" ? "--" : "#";
@@ -178,12 +194,16 @@ function getDBus() {
}
class HyprlandShortcutManager {
- constructor() {
+ constructor({ dbusNameRequestTimeoutMs = DBUS_NAME_REQUEST_TIMEOUT_MS } = {}) {
this.bus = null;
- this.callback = null;
+ this.callbacks = {};
this.isRegistered = false;
- this.currentBinding = null; // Store the current Hyprland bind string for unbinding
+ this.bindings = {};
+ this.bindingPtt = {};
+ this.desiredBinds = {};
+ this.persistencePending = false;
this.config = null;
+ this.dbusNameRequestTimeoutMs = dbusNameRequestTimeoutMs;
}
/**
@@ -220,7 +240,7 @@ class HyprlandShortcutManager {
* Reuses the same D-Bus service name/path as the GNOME integration.
*/
async initDBusService(callback) {
- this.callback = callback;
+ this.callbacks.dictation = callback;
const dbusModule = getDBus();
if (!dbusModule) {
@@ -232,38 +252,58 @@ class HyprlandShortcutManager {
// Without a listener, async socket errors (e.g. a stale
// DBUS_SESSION_BUS_ADDRESS) crash the process as an unhandled
// "error" event — sessionBus() returns before connecting.
+ let rejectNameRequest;
this.bus.connection.on("error", (err) => {
debugLogger.log("[HyprlandShortcut] D-Bus connection error:", err.message);
+ rejectNameRequest?.(err);
+ });
+ const nameReply = await new Promise((resolve, reject) => {
+ let settled = false;
+ const finish = (handler, value) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timeoutId);
+ rejectNameRequest = null;
+ handler(value);
+ };
+ rejectNameRequest = (err) => finish(reject, err);
+ const timeoutId = setTimeout(
+ () => rejectNameRequest?.(new Error("D-Bus name request timed out")),
+ this.dbusNameRequestTimeoutMs
+ );
+ this.bus.requestName(DBUS_SERVICE_NAME, 0, (err, reply) => {
+ if (err) finish(reject, err);
+ else finish(resolve, reply);
+ });
+ });
+ if (nameReply !== 1 && nameReply !== 4) {
+ throw new Error(`D-Bus name request returned ${nameReply}`);
+ }
+
+ const toggleMethods = {};
+ for (const [slot, method] of Object.entries(SLOT_TOGGLE_METHOD)) {
+ toggleMethods[method] = () => {
+ const cb = this.callbacks[slot];
+ if (typeof cb === "function") cb();
+ };
+ }
+ toggleMethods.PttDown = () => {
+ const cb = this.callbacks.dictation;
+ if (typeof cb === "function") cb(undefined, "down");
+ };
+ toggleMethods.PttUp = () => {
+ const cb = this.callbacks.dictation;
+ if (typeof cb === "function") cb(undefined, "up");
+ };
+ this.bus.exportInterface(toggleMethods, DBUS_OBJECT_PATH, {
+ name: DBUS_INTERFACE,
+ methods: Object.fromEntries(
+ [...Object.values(SLOT_TOGGLE_METHOD), "PttDown", "PttUp"].map((method) => [
+ method,
+ ["", ""],
+ ])
+ ),
});
- this.bus.requestName(DBUS_SERVICE_NAME, 0);
- this.bus.exportInterface(
- {
- Toggle: () => {
- if (this.callback) {
- this.callback();
- }
- },
- PttDown: () => {
- if (this.callback) {
- this.callback(undefined, "down");
- }
- },
- PttUp: () => {
- if (this.callback) {
- this.callback(undefined, "up");
- }
- },
- },
- DBUS_OBJECT_PATH,
- {
- name: DBUS_INTERFACE,
- methods: {
- Toggle: ["", ""],
- PttDown: ["", ""],
- PttUp: ["", ""],
- },
- }
- );
debugLogger.log("[HyprlandShortcut] D-Bus service initialized successfully");
return true;
@@ -284,6 +324,22 @@ class HyprlandShortcutManager {
return VALID_HOTKEY_PATTERN.test(hotkey);
}
+ static getCanonicalBinding(hotkey) {
+ if (isModifierOnlyHotkey(hotkey)) {
+ const modifiers = hotkey
+ .split("+")
+ .map((part) => ELECTRON_TO_HYPRLAND_MOD[part.trim().toLowerCase()])
+ .filter(Boolean);
+ return `modifier-only:${[...new Set(modifiers)].sort().join("+")}`;
+ }
+
+ const converted = HyprlandShortcutManager.convertToHyprlandFormat(hotkey);
+ if (!converted) return null;
+
+ const modifiers = converted.mods.split(/\s+/).filter(Boolean).sort().join(" ");
+ return `${modifiers}, ${converted.key.toLowerCase()}`;
+ }
+
/**
* Convert an Electron-format hotkey string to Hyprland bind format.
*
@@ -362,7 +418,7 @@ class HyprlandShortcutManager {
};
}
- _writeBindToConfig(config, bindLines) {
+ _rewriteConfig(config, desiredBinds = this.desiredBinds) {
fs.mkdirSync(path.dirname(config.bindsPath), { recursive: true });
let content = "";
@@ -372,36 +428,32 @@ class HyprlandShortcutManager {
if (err.code !== "ENOENT") throw err;
}
- const lines = content.split("\n").filter((line) => {
+ const userLines = content.split("\n").filter((line) => {
const trimmed = line.trim();
- if (!trimmed || isManagedHeaderLine(trimmed)) return false;
+ if (!trimmed) return true;
+ if (isManagedHeaderLine(trimmed)) return false;
if (trimmed.startsWith("#") || trimmed.startsWith("--")) return true;
- return !trimmed.includes(DBUS_SERVICE_NAME);
+ return !isManagedBindLine(trimmed, config.format);
});
- const managedBindLines = Array.isArray(bindLines) ? bindLines : [bindLines];
- const newContent = buildManagedBindsContent([...lines, ...managedBindLines], config.format);
+ const bindLines = [];
+ for (const slotName of Object.keys(desiredBinds)) {
+ const b = desiredBinds[slotName];
+ if (b.press) bindLines.push(b.press);
+ if (b.release) bindLines.push(b.release);
+ }
+ const newContent = buildManagedBindsContent([...userLines, ...bindLines], config.format);
fs.writeFileSync(config.bindsPath, newContent, "utf-8");
}
- _removeBindFromConfig(config) {
- let content = "";
- try {
- content = fs.readFileSync(config.bindsPath, "utf-8");
- } catch (err) {
- if (err.code === "ENOENT") return;
- throw err;
+ _persistBinds(config, desiredBinds) {
+ fs.accessSync(config.path, fs.constants.F_OK);
+ this._rewriteConfig(config, desiredBinds);
+ if (!this._ensureSourceInMainConfig(config)) {
+ throw new Error(`Hyprland config not found: ${config.path}`);
}
-
- const lines = content.split("\n").filter((line) => {
- const trimmed = line.trim();
- if (!trimmed || isManagedHeaderLine(trimmed)) return false;
- if (trimmed.startsWith("#") || trimmed.startsWith("--")) return true;
- return !trimmed.includes(DBUS_SERVICE_NAME);
- });
-
- fs.writeFileSync(config.bindsPath, buildManagedBindsContent(lines, config.format), "utf-8");
+ this._removeLegacyArtifacts(config);
}
_ensureSourceInMainConfig(config) {
@@ -452,7 +504,32 @@ class HyprlandShortcutManager {
const configDir = path.dirname(config.path);
const legacyConfigPath = path.join(configDir, "hyprland.conf");
const legacyBindsPath = path.join(configDir, BINDS_FILENAMES.conf);
+ let removeLegacySource = false;
+
+ try {
+ const content = fs.readFileSync(legacyBindsPath, "utf-8");
+ const lines = content.split("\n");
+ const hasManagedArtifacts = lines.some((line) => {
+ const trimmed = line.trim();
+ return isManagedHeaderLine(trimmed) || isManagedBindLine(trimmed, "conf");
+ });
+ if (!hasManagedArtifacts) return;
+
+ const remainingLines = lines.filter((line) => {
+ const trimmed = line.trim();
+ return !isManagedHeaderLine(trimmed) && !isManagedBindLine(trimmed, "conf");
+ });
+ if (remainingLines.join("\n").trim()) {
+ fs.writeFileSync(legacyBindsPath, remainingLines.join("\n"), "utf-8");
+ } else {
+ removeLegacySource = true;
+ }
+ } catch (err) {
+ if (err.code !== "ENOENT") throw err;
+ return;
+ }
+ if (!removeLegacySource) return;
try {
const content = fs.readFileSync(legacyConfigPath, "utf-8");
const newContent = content
@@ -466,15 +543,8 @@ class HyprlandShortcutManager {
} catch (err) {
if (err.code !== "ENOENT") throw err;
}
-
- try {
- const content = fs.readFileSync(legacyBindsPath, "utf-8");
- if (content.includes(MANAGED_HEADER_TEXT[0]) || content.includes(DBUS_SERVICE_NAME)) {
- fs.unlinkSync(legacyBindsPath);
- }
- } catch (err) {
- if (err.code !== "ENOENT") throw err;
- }
+ // Keep the source target intact if removing its load directive fails.
+ fs.unlinkSync(legacyBindsPath);
}
_getConfig() {
@@ -538,46 +608,54 @@ class HyprlandShortcutManager {
}
static getHyprlandConfigStatus() {
- const mainConfig = getHyprlandConfig().path;
+ const config = getHyprlandConfig();
+ const mainConfig = config.path;
+ const configDir = path.dirname(mainConfig);
const status = {
path: mainConfig,
canWrite: false,
};
try {
- fs.accessSync(mainConfig, fs.constants.F_OK);
- try {
- fs.accessSync(mainConfig, fs.constants.W_OK);
- status.canWrite = true;
- } catch {
- debugLogger.log("[HyprlandShortcut] Hyprland config is not writable:", mainConfig);
+ fs.accessSync(mainConfig, fs.constants.F_OK | fs.constants.W_OK);
+ if (!fs.statSync(mainConfig).isFile()) {
+ throw new Error(`Hyprland config is not a file: ${mainConfig}`);
}
- } catch {
- debugLogger.log("[HyprlandShortcut] Hyprland config not found:", mainConfig);
+ fs.accessSync(configDir, fs.constants.W_OK);
+ if (fs.existsSync(config.bindsPath)) {
+ fs.accessSync(config.bindsPath, fs.constants.W_OK);
+ if (!fs.statSync(config.bindsPath).isFile()) {
+ throw new Error(`Managed binds path is not a file: ${config.bindsPath}`);
+ }
+ }
+ status.canWrite = true;
+ } catch (err) {
+ debugLogger.log(
+ "[HyprlandShortcut] Hyprland config or managed binds path is not writable:",
+ err.message
+ );
}
return status;
}
- /**
- * Register a keybinding using the runtime API for the active config provider.
- * The binding executes a dbus-send command that calls our Toggle() method.
- *
- * Also writes the bind to a format-specific config file so it survives
- * `hyprctl reload`.
- */
- async registerKeybinding(hotkey, isPushToTalk = false) {
+ async _registerForSlot(hotkey, slotName, callback, isPtt) {
if (!HyprlandShortcutManager.isHyprland()) {
debugLogger.log("[HyprlandShortcut] Not running on Hyprland, skipping registration");
return false;
}
-
if (!HyprlandShortcutManager.isValidHotkey(hotkey)) {
debugLogger.log(`[HyprlandShortcut] Invalid hotkey format: "${hotkey}"`);
return false;
}
- if (isPushToTalk && isModifierOnlyHotkey(hotkey)) {
+ const method = SLOT_TOGGLE_METHOD[slotName];
+ if (!method) {
+ debugLogger.log(`[HyprlandShortcut] Unknown slot "${slotName}"`);
+ return false;
+ }
+
+ if (isPtt && isModifierOnlyHotkey(hotkey)) {
debugLogger.log(
`[HyprlandShortcut] Modifier-only hotkey "${hotkey}" does not support push-to-talk`
);
@@ -590,107 +668,165 @@ class HyprlandShortcutManager {
return false;
}
+ let config;
try {
- const config = this._getConfig();
- const runtimeBinding = config.format === "lua" ? converted.luaKeys : converted.bindKey;
-
- // First unregister any existing OpenWhispr binding if the hotkey changed.
- if (this.currentBinding && this.currentBinding !== runtimeBinding) {
- const unregistered = await this.unregisterKeybinding();
- if (!unregistered) return false;
+ config = this._getConfig();
+ } catch (err) {
+ debugLogger.log("[HyprlandShortcut] Failed to read Hyprland config:", err.message);
+ return false;
+ }
+ const runtimeBinding = config.format === "lua" ? converted.luaKeys : converted.bindKey;
+ const previousBinding = this.bindings[slotName];
+ const previousIsPtt = this.bindingPtt[slotName] ?? false;
+ if (previousBinding === runtimeBinding && previousIsPtt === isPtt) {
+ if (typeof callback === "function") this.callbacks[slotName] = callback;
+ if (this.persistencePending) {
+ try {
+ this._persistBinds(config, this.desiredBinds);
+ this.persistencePending = false;
+ } catch (err) {
+ debugLogger.log(
+ `[HyprlandShortcut] Keybinding "${hotkey}" is active but still cannot persist:`,
+ err.message
+ );
+ }
}
+ return true;
+ }
- const pressCommand = `dbus-send --session --type=method_call --dest=${DBUS_SERVICE_NAME} ${DBUS_OBJECT_PATH} ${DBUS_INTERFACE}.${isPushToTalk ? "PttDown" : "Toggle"}`;
- const releaseCommand = `dbus-send --session --type=method_call --dest=${DBUS_SERVICE_NAME} ${DBUS_OBJECT_PATH} ${DBUS_INTERFACE}.PttUp`;
-
+ const pressCommand = `dbus-send --session --type=method_call --dest=${DBUS_SERVICE_NAME} ${DBUS_OBJECT_PATH} ${DBUS_INTERFACE}.${isPtt ? "PttDown" : method}`;
+ const releaseCommand = `dbus-send --session --type=method_call --dest=${DBUS_SERVICE_NAME} ${DBUS_OBJECT_PATH} ${DBUS_INTERFACE}.PttUp`;
+ const persistedPressBind =
+ config.format === "lua"
+ ? buildLuaBindExpression(
+ converted.luaKeys,
+ pressCommand,
+ isPtt ? "{ transparent = true }" : ""
+ )
+ : `${isPtt ? "bindt" : "bind"} = ${converted.bindKey}, exec, ${pressCommand}`;
+ const persistedReleaseBind = !isPtt
+ ? null
+ : config.format === "lua"
+ ? buildLuaBindExpression(
+ converted.luaKeys,
+ releaseCommand,
+ "{ release = true, transparent = true }"
+ )
+ : `bindrt = ${converted.bindKey}, exec, ${releaseCommand}`;
+ const nextDesiredBinds = {
+ ...this.desiredBinds,
+ [slotName]: { press: persistedPressBind, release: persistedReleaseBind },
+ };
+ try {
try {
this._unbindRuntime(config, runtimeBinding);
} catch (err) {
debugLogger.log(
- `[HyprlandShortcut] Pre-bind unbind for "${runtimeBinding}" failed, continuing:`,
+ `[HyprlandShortcut] Pre-bind unbind for "${runtimeBinding}" failed:`,
err.message
);
}
+ this._bindRuntime(config, converted, isPtt, pressCommand, releaseCommand);
+ } catch (err) {
+ if (previousBinding === runtimeBinding) {
+ try {
+ const previousPress = `dbus-send --session --type=method_call --dest=${DBUS_SERVICE_NAME} ${DBUS_OBJECT_PATH} ${DBUS_INTERFACE}.${previousIsPtt ? "PttDown" : method}`;
+ this._bindRuntime(config, converted, previousIsPtt, previousPress, releaseCommand);
+ } catch {}
+ }
+ debugLogger.log("[HyprlandShortcut] Failed to register keybinding:", err.message);
+ return false;
+ }
- this._bindRuntime(config, converted, isPushToTalk, pressCommand, releaseCommand);
-
- this.currentBinding = runtimeBinding;
- this.isRegistered = true;
-
+ if (previousBinding && previousBinding !== runtimeBinding) {
try {
- const persistedPressBind =
- config.format === "lua"
- ? buildLuaBindExpression(
- converted.luaKeys,
- pressCommand,
- isPushToTalk ? "{ transparent = true }" : ""
- )
- : `${isPushToTalk ? "bindt" : "bind"} = ${converted.bindKey}, exec, ${pressCommand}`;
- const persistedReleaseBind = !isPushToTalk
- ? null
- : config.format === "lua"
- ? buildLuaBindExpression(
- converted.luaKeys,
- releaseCommand,
- "{ release = true, transparent = true }"
- )
- : `bindrt = ${converted.bindKey}, exec, ${releaseCommand}`;
- this._writeBindToConfig(config, [persistedPressBind, persistedReleaseBind].filter(Boolean));
- const mainConfigFound = this._ensureSourceInMainConfig(config);
- if (mainConfigFound) this._removeLegacyArtifacts(config);
+ this._unbindRuntime(config, previousBinding);
} catch (err) {
- debugLogger.log(
- "[HyprlandShortcut] Failed to persist keybinding; runtime bind is still active:",
- err.message
- );
+ try {
+ this._unbindRuntime(config, runtimeBinding);
+ } catch {}
+ debugLogger.log("[HyprlandShortcut] Failed to replace keybinding:", err.message);
+ return false;
}
+ }
+ this.bindings[slotName] = runtimeBinding;
+ this.bindingPtt[slotName] = isPtt;
+ this.isRegistered = true;
+ if (typeof callback === "function") this.callbacks[slotName] = callback;
+ this.desiredBinds = nextDesiredBinds;
+ this.persistencePending = true;
+ try {
+ this._persistBinds(config, nextDesiredBinds);
+ this.persistencePending = false;
+ } catch (err) {
debugLogger.log(
- `[HyprlandShortcut] Keybinding "${hotkey}" (${runtimeBinding}) registered successfully`
+ `[HyprlandShortcut] Keybinding "${hotkey}" is active for this session but will not persist:`,
+ err.message
);
- return true;
- } catch (err) {
- debugLogger.log("[HyprlandShortcut] Failed to register keybinding:", err.message);
- return false;
}
+ debugLogger.log(
+ `[HyprlandShortcut] Keybinding "${hotkey}" (${runtimeBinding}) registered for slot "${slotName}"`
+ );
+ return true;
}
- /**
- * Update the keybinding to a new hotkey.
- */
- async updateKeybinding(hotkey, isPushToTalk = false) {
- // Just unregister old and register new
+ registerKeybinding(hotkey, isPushToTalk = false) {
+ return this._registerForSlot(hotkey, "dictation", null, isPushToTalk);
+ }
+
+ registerSlotKeybinding(hotkey, slotName, callback) {
+ return this._registerForSlot(hotkey, slotName, callback, false);
+ }
+
+ updateKeybinding(hotkey, isPushToTalk = false) {
return this.registerKeybinding(hotkey, isPushToTalk);
}
- /**
- * Unregister the current keybinding from Hyprland.
- */
- async unregisterKeybinding() {
- if (!this.currentBinding) {
- this.isRegistered = false;
- return true;
+ // Unregister one slot, or all slots on teardown.
+ async unregisterKeybinding(slotName) {
+ if (!slotName) {
+ const removals = Object.keys(this.bindings).map((slot) => this.unregisterKeybinding(slot));
+ const success = (await Promise.all(removals)).every(Boolean);
+ if (success) this.isRegistered = false;
+ return success;
}
- const binding = this.currentBinding;
- const config = this._getConfig();
+ let config;
+ try {
+ config = this._getConfig();
+ } catch (err) {
+ debugLogger.log("[HyprlandShortcut] Failed to read Hyprland config:", err.message);
+ return false;
+ }
+ const binding = this.bindings[slotName];
try {
- this._unbindRuntime(config, binding);
+ if (binding) this._unbindRuntime(config, binding);
} catch (err) {
- debugLogger.log(`[HyprlandShortcut] Runtime unbind for "${binding}" failed:`, err.message);
+ debugLogger.log("[HyprlandShortcut] Failed to unregister keybinding:", err.message);
return false;
}
+ const nextDesiredBinds = { ...this.desiredBinds };
+ delete nextDesiredBinds[slotName];
+ this.desiredBinds = nextDesiredBinds;
+ this.persistencePending = true;
try {
- this._removeBindFromConfig(config);
+ this._persistBinds(config, nextDesiredBinds);
+ this.persistencePending = false;
} catch (err) {
- debugLogger.log("[HyprlandShortcut] Failed to remove persisted keybinding:", err.message);
+ debugLogger.log(
+ `[HyprlandShortcut] Runtime binding "${slotName}" removed but config was unchanged:`,
+ err.message
+ );
}
- debugLogger.log(`[HyprlandShortcut] Keybinding "${binding}" unregistered successfully`);
- this.currentBinding = null;
- this.isRegistered = false;
+ delete this.bindings[slotName];
+ delete this.bindingPtt[slotName];
+ if (slotName !== "dictation") delete this.callbacks[slotName];
+ if (Object.keys(this.bindings).length === 0) this.isRegistered = false;
+ debugLogger.log(`[HyprlandShortcut] Keybinding "${slotName}" unregistered successfully`);
return true;
}
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 833672d48..e2b10f6dc 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -4193,9 +4193,15 @@ class IPCHandlers {
// On Hyprland Wayland, unregister the keybinding during capture
if (hotkeyManager.isUsingHyprland() && hotkeyManager.hyprlandManager) {
debugLogger.log("[IPC] Unregistering Hyprland keybinding for hotkey capture mode");
- await hotkeyManager.hyprlandManager.unregisterKeybinding().catch((err) => {
- debugLogger.warn("[IPC] Failed to unregister Hyprland keybinding:", err.message);
- });
+ const unregistered = await hotkeyManager.hyprlandManager
+ .unregisterKeybinding()
+ .catch((err) => {
+ debugLogger.warn("[IPC] Failed to unregister Hyprland keybinding:", err.message);
+ return false;
+ });
+ if (!unregistered) {
+ debugLogger.warn("[IPC] Hyprland keybinding remained active during capture");
+ }
}
} else {
// Exiting capture mode - re-register globalShortcut if not already registered
@@ -4280,9 +4286,15 @@ class IPCHandlers {
debugLogger.log(
`[IPC] Re-registering slot "${slot}" ("${hotkeys.join(", ")}") after capture mode`
);
- await hotkeyManager.registerSlot(slot, hotkeys, info.callback).catch((err) => {
- debugLogger.warn(`[IPC] Failed to re-register slot "${slot}":`, err.message);
- });
+ const result = await hotkeyManager
+ .registerSlot(slot, hotkeys, info.callback)
+ .catch((err) => {
+ debugLogger.warn(`[IPC] Failed to re-register slot "${slot}":`, err.message);
+ return { success: false };
+ });
+ if (!result.success) {
+ debugLogger.warn(`[IPC] Slot "${slot}" was not restored after capture`);
+ }
}
}
@@ -11127,7 +11139,8 @@ class IPCHandlers {
}
if (!hotkey) {
- hotkeyManager.unregisterSlot("voiceAgent");
+ const removed = await hotkeyManager.unregisterSlot("voiceAgent");
+ if (removed === false) return { success: false };
this.environmentManager.saveVoiceAgentKey?.("");
this.windowManager.reconcileNativeKeyListeners();
this._notifyHotkeyChanged("");
@@ -11162,7 +11175,8 @@ class IPCHandlers {
}
if (!hotkey) {
- hotkeyManager.unregisterSlot("translation");
+ const removed = await hotkeyManager.unregisterSlot("translation");
+ if (removed === false) return { success: false };
this.environmentManager.saveTranslationKey?.("");
this.windowManager.reconcileNativeKeyListeners();
this._notifyHotkeyChanged("");
diff --git a/test/components/meetingHotkeyClear.test.js b/test/components/meetingHotkeyClear.test.js
new file mode 100644
index 000000000..59a00221a
--- /dev/null
+++ b/test/components/meetingHotkeyClear.test.js
@@ -0,0 +1,70 @@
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const path = require("node:path");
+const test = require("node:test");
+const vm = require("node:vm");
+const ts = require("typescript");
+
+// Exercise the actual Settings callback without loading unrelated settings panels.
+const filename = path.join(__dirname, "../../src/components/SettingsPage.tsx");
+const source = ts.createSourceFile(
+ filename,
+ fs.readFileSync(filename, "utf8"),
+ ts.ScriptTarget.Latest,
+ true,
+ ts.ScriptKind.TSX
+);
+let clearCallback;
+function visit(node) {
+ if (ts.isJsxSelfClosingElement(node) && node.tagName.getText(source) === "HotkeyListInput") {
+ const attributes = node.attributes.properties;
+ const value = attributes.find((attribute) => attribute.name?.getText(source) === "value");
+ if (value?.initializer?.expression?.getText(source) === "meetingKey") {
+ clearCallback = attributes
+ .find((attribute) => attribute.name?.getText(source) === "onClear")
+ .initializer.expression.getText(source);
+ }
+ }
+ ts.forEachChild(node, visit);
+}
+visit(source);
+assert.ok(clearCallback, "meeting shortcut must expose its clear callback");
+
+for (const [label, response] of [
+ ["failed removal", { success: false }],
+ ["unavailable IPC", undefined],
+ ["successful removal", { success: true }],
+]) {
+ test(`meeting shortcut clear handles ${label}`, async () => {
+ let meetingKey = "F7";
+ const alerts = [];
+ const registerMeetingHotkey = async (hotkey) => {
+ assert.equal(hotkey, "");
+ return response;
+ };
+ const context = {
+ window: { electronAPI: { registerMeetingHotkey } },
+ setMeetingKey: (hotkey) => {
+ meetingKey = hotkey;
+ },
+ showAlertDialog: (alert) => alerts.push(alert),
+ t: (key) => key,
+ };
+ const { outputText } = ts.transpileModule(`const clear = ${clearCallback};`, {
+ compilerOptions: { target: ts.ScriptTarget.ES2022 },
+ });
+ const clear = vm.runInNewContext(`${outputText}\nclear;`, context);
+
+ const result = await clear();
+
+ if (response?.success) {
+ assert.equal(result, true);
+ assert.equal(meetingKey, "");
+ assert.equal(alerts.length, 0);
+ } else {
+ assert.equal(result, false, "HotkeyListInput needs false to roll back the removed row");
+ assert.equal(meetingKey, "F7");
+ assert.equal(alerts.length, 1);
+ }
+ });
+}
diff --git a/test/helpers/hotkeyHyprlandSlots.test.js b/test/helpers/hotkeyHyprlandSlots.test.js
new file mode 100644
index 000000000..a372458e3
--- /dev/null
+++ b/test/helpers/hotkeyHyprlandSlots.test.js
@@ -0,0 +1,134 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const registered = new Map();
+require.cache[require.resolve("electron")] = {
+ exports: {
+ globalShortcut: {
+ register(accelerator, callback) {
+ if (registered.has(accelerator)) return false;
+ 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 hyprlandTest = process.platform === "linux" ? test : test.skip;
+
+async function withHyprland(fn) {
+ const saved = {
+ XDG_SESSION_TYPE: process.env.XDG_SESSION_TYPE,
+ HYPRLAND_INSTANCE_SIGNATURE: process.env.HYPRLAND_INSTANCE_SIGNATURE,
+ };
+ process.env.XDG_SESSION_TYPE = "wayland";
+ process.env.HYPRLAND_INSTANCE_SIGNATURE = "test";
+ try {
+ await fn();
+ } finally {
+ for (const [key, value] of Object.entries(saved)) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+ registered.clear();
+ }
+}
+
+hyprlandTest("Hyprland optional slots do not fall back when registration fails", async () => {
+ await withHyprland(async () => {
+ const calls = [];
+ const manager = new HotkeyManager();
+ manager.useHyprland = true;
+ manager.hyprlandManager = {
+ async registerSlotKeybinding(hotkey) {
+ calls.push(hotkey);
+ return false;
+ },
+ };
+
+ const result = await manager.registerSlot("meeting", "F7", () => {});
+ assert.equal(result.success, false);
+ assert.deepEqual(calls, ["F7"]);
+ assert.deepEqual(manager.getSlotHotkeys("meeting"), []);
+ assert.equal(registered.size, 0);
+ });
+});
+
+hyprlandTest("Hyprland slots reject equivalent modifier aliases and ordering", async () => {
+ await withHyprland(async () => {
+ const calls = [];
+ let releaseRemoval;
+ const manager = new HotkeyManager();
+ manager.useHyprland = true;
+ manager.hyprlandManager = {
+ async registerSlotKeybinding(...args) {
+ calls.push(args);
+ return true;
+ },
+ unregisterKeybinding() {
+ return new Promise((resolve) => {
+ releaseRemoval = resolve;
+ });
+ },
+ };
+
+ const callback = () => {};
+ const registeredSlot = await manager.registerSlot("meeting", "Ctrl+Shift+F8", callback);
+ assert.equal(registeredSlot.success, true);
+ assert.deepEqual(manager.getSlotHotkeys("meeting"), ["Ctrl+Shift+F8"]);
+
+ const conflict = await manager.registerSlot("translation", "Shift+Control+F8", () => {});
+ assert.equal(conflict.success, false);
+ assert.equal(conflict.reason, "slot_conflict");
+ assert.deepEqual(calls, [["Ctrl+Shift+F8", "meeting", callback]]);
+
+ const removal = manager.unregisterSlot("meeting");
+ assert.deepEqual(manager.getSlotHotkeys("meeting"), ["Ctrl+Shift+F8"]);
+ releaseRemoval(true);
+ assert.equal(await removal, true);
+ assert.deepEqual(manager.getSlotHotkeys("meeting"), []);
+ });
+});
+
+hyprlandTest("Hyprland slots reject reversed modifier-only chords", async () => {
+ await withHyprland(async () => {
+ const calls = [];
+ const manager = new HotkeyManager();
+ manager.useHyprland = true;
+ manager.hyprlandManager = {
+ async registerSlotKeybinding(hotkey) {
+ calls.push(hotkey);
+ return true;
+ },
+ };
+
+ assert.equal((await manager.registerSlot("meeting", "Alt+Super", () => {})).success, true);
+ const conflict = await manager.registerSlot("translation", "Super+Alt", () => {});
+
+ assert.equal(conflict.success, false);
+ assert.equal(conflict.reason, "slot_conflict");
+ assert.deepEqual(calls, ["Alt+Super"]);
+ });
+});
+
+hyprlandTest("failed Hyprland initialization does not fall back to globalShortcut", async () => {
+ await withHyprland(async () => {
+ const manager = new HotkeyManager();
+ manager.hyprlandInitializationAttempted = true;
+
+ const result = await manager.registerSlot("meeting", "F7", () => {});
+ assert.equal(result.success, false);
+ assert.equal(registered.size, 0);
+ });
+});
diff --git a/test/helpers/hyprlandShortcut.test.js b/test/helpers/hyprlandShortcut.test.js
index d68b16d84..56e4544fe 100644
--- a/test/helpers/hyprlandShortcut.test.js
+++ b/test/helpers/hyprlandShortcut.test.js
@@ -23,6 +23,19 @@ function loadManager(execFileSync) {
}
}
+async function withDbusMock(dbusModule, fn) {
+ const previousLoad = Module._load;
+ Module._load = function loadDbusMock(request, parent, isMain) {
+ if (request === "@homebridge/dbus-native") return dbusModule;
+ return previousLoad.call(this, request, parent, isMain);
+ };
+ try {
+ await fn();
+ } finally {
+ Module._load = previousLoad;
+ }
+}
+
function withTempHyprConfig(fn) {
return async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-hyprland-test-"));
@@ -59,6 +72,94 @@ function successfulHyprctl(provider) {
const DBUS_COMMAND =
"dbus-send --session --type=method_call --dest=com.openwhispr.App /com/openwhispr/App com.openwhispr.App.Toggle";
+test("exports every Hyprland D-Bus toggle", async () => {
+ let exported;
+ const dbusModule = {
+ sessionBus() {
+ return {
+ connection: { on() {}, end() {} },
+ requestName(_name, _flags, callback) {
+ callback(null, 1);
+ },
+ exportInterface(methods, _path, iface) {
+ exported = { methods, iface };
+ },
+ };
+ },
+ };
+ const HyprlandShortcutManager = loadManager(() => "ok\n");
+ await withDbusMock(dbusModule, async () => {
+ const calls = [];
+ const manager = new HyprlandShortcutManager();
+
+ assert.equal(await manager.initDBusService(() => calls.push("dictation")), true);
+ manager.callbacks.meeting = () => calls.push("meeting");
+ manager.callbacks.voiceAgent = () => calls.push("voiceAgent");
+ manager.callbacks.translation = () => calls.push("translation");
+
+ assert.deepEqual(Object.keys(exported.iface.methods).sort(), [
+ "PttDown",
+ "PttUp",
+ "Toggle",
+ "ToggleMeeting",
+ "ToggleTranslation",
+ "ToggleVoiceAgent",
+ ]);
+ exported.methods.Toggle();
+ exported.methods.ToggleMeeting();
+ exported.methods.ToggleVoiceAgent();
+ exported.methods.ToggleTranslation();
+ assert.deepEqual(calls, ["dictation", "meeting", "voiceAgent", "translation"]);
+ });
+});
+
+test("fails D-Bus initialization when the connection errors before RequestName replies", async () => {
+ let onError;
+ const dbusModule = {
+ sessionBus() {
+ return {
+ connection: {
+ on(event, callback) {
+ if (event === "error") onError = callback;
+ },
+ end() {},
+ },
+ requestName() {
+ onError(new Error("disconnected"));
+ },
+ };
+ },
+ };
+ const HyprlandShortcutManager = loadManager(() => "ok\n");
+ await withDbusMock(dbusModule, async () => {
+ assert.equal(await new HyprlandShortcutManager().initDBusService(() => {}), false);
+ });
+});
+
+test("times out D-Bus initialization when RequestName never replies", async () => {
+ let ended = false;
+ const dbusModule = {
+ sessionBus() {
+ return {
+ connection: {
+ on() {},
+ end() {
+ ended = true;
+ },
+ },
+ requestName() {},
+ };
+ },
+ };
+ const HyprlandShortcutManager = loadManager(() => "ok\n");
+ await withDbusMock(dbusModule, async () => {
+ const manager = new HyprlandShortcutManager({ dbusNameRequestTimeoutMs: 10 });
+ assert.equal(await manager.initDBusService(() => {}), false);
+ assert.equal(ended, true);
+ assert.equal(manager.bus, null);
+ });
+});
+
test(
"persists a legacy binding through hyprland.conf",
withTempHyprConfig(async (configDir) => {
@@ -93,6 +194,71 @@ test(
})
);
+test(
+ "keeps runtime binds active when the Hyprland config cannot be persisted",
+ withTempHyprConfig(async (configDir) => {
+ fs.mkdirSync(configDir, { recursive: true });
+ const hyprctl = successfulHyprctl("hyprlang");
+ const HyprlandShortcutManager = loadManager(hyprctl.execFileSync);
+ const manager = new HyprlandShortcutManager();
+
+ assert.equal(await manager.registerKeybinding("Control+Shift+Enter"), true);
+ assert.equal(await manager.registerSlotKeybinding("Alt+F9", "meeting", () => {}), true);
+ assert.equal(manager.persistencePending, true);
+ assert.deepEqual(Object.keys(manager.desiredBinds).sort(), ["dictation", "meeting"]);
+ assert.deepEqual(Object.keys(manager.bindings).sort(), ["dictation", "meeting"]);
+ assert.equal(fs.existsSync(path.join(configDir, "openwhispr-binds.conf")), false);
+ })
+);
+
+test(
+ "retries the same desired bind after persistence recovers",
+ withTempHyprConfig(async (configDir) => {
+ fs.mkdirSync(configDir, { recursive: true });
+ const configPath = path.join(configDir, "hyprland.conf");
+ const hyprctl = successfulHyprctl("hyprlang");
+ const HyprlandShortcutManager = loadManager(hyprctl.execFileSync);
+ const manager = new HyprlandShortcutManager();
+
+ assert.equal(await manager.registerKeybinding("F8"), true);
+ fs.writeFileSync(configPath, "# config\n");
+ assert.equal(await manager.registerKeybinding("F8"), true);
+
+ assert.match(fs.readFileSync(configPath, "utf8"), /openwhispr-binds\.conf/);
+ assert.match(readBinds(configDir), /bind = , F8, exec/);
+ })
+);
+
+test(
+ "retries the latest desired binds after persistence recovers",
+ withTempHyprConfig(async (configDir) => {
+ fs.mkdirSync(configDir, { recursive: true });
+ fs.writeFileSync(path.join(configDir, "hyprland.conf"), "# config\n");
+ const hyprctl = successfulHyprctl("hyprlang");
+ const HyprlandShortcutManager = loadManager(hyprctl.execFileSync);
+ const manager = new HyprlandShortcutManager();
+
+ assert.equal(await manager.registerKeybinding("Control+Shift+Enter"), true);
+ const persistBinds = manager._persistBinds.bind(manager);
+ let failNextPersist = true;
+ manager._persistBinds = (...args) => {
+ if (failNextPersist) {
+ failNextPersist = false;
+ throw new Error("disk unavailable");
+ }
+ return persistBinds(...args);
+ };
+
+ assert.equal(await manager.updateKeybinding("Alt+F9"), true);
+ assert.equal(await manager.registerSlotKeybinding("Alt+F10", "meeting", () => {}), true);
+
+ const binds = readBinds(configDir);
+ assert.doesNotMatch(binds, /CTRL SHIFT, Return/);
+ assert.match(binds, /ALT, F9, exec/);
+ assert.match(binds, /ALT, F10, exec/);
+ })
+);
+
test(
"prefers Hyprland's active Lua config when both formats exist",
withTempHyprConfig(async (configDir) => {
@@ -225,9 +391,9 @@ test(
assert.deepEqual(evalExpressions, [
'hl.unbind("CTRL + SHIFT + RETURN")',
`hl.bind("CTRL + SHIFT + RETURN", hl.dsp.exec_cmd(${JSON.stringify(DBUS_COMMAND)}))`,
- 'hl.unbind("CTRL + SHIFT + RETURN")',
'hl.unbind("ALT + PAGE_UP")',
`hl.bind("ALT + PAGE_UP", hl.dsp.exec_cmd(${JSON.stringify(DBUS_COMMAND)}))`,
+ 'hl.unbind("CTRL + SHIFT + RETURN")',
'hl.unbind("ALT + PAGE_UP")',
]);
})
@@ -248,7 +414,7 @@ test(
const manager = new HyprlandShortcutManager();
assert.equal(await manager.registerKeybinding("Control+Shift+Enter"), false);
assert.equal(manager.isRegistered, false);
- assert.equal(manager.currentBinding, null);
+ assert.equal(manager.bindings.dictation, undefined);
assert.equal(fs.existsSync(path.join(configDir, "openwhispr-binds.lua")), false);
})
);
@@ -272,11 +438,36 @@ test(
rejectUnbind = true;
assert.equal(await manager.unregisterKeybinding(), false);
- assert.equal(manager.currentBinding, "CTRL + SHIFT + RETURN");
+ assert.equal(manager.bindings.dictation, "CTRL + SHIFT + RETURN");
assert.equal(manager.isRegistered, true);
})
);
+test(
+ "keeps a slot binding when its replacement fails",
+ withTempHyprConfig(async (configDir) => {
+ fs.mkdirSync(configDir, { recursive: true });
+ fs.writeFileSync(path.join(configDir, "hyprland.conf"), "# config\n");
+ let failReplacement = false;
+ const HyprlandShortcutManager = loadManager((command, args) => {
+ if (args[0] === "systeminfo") return "configProvider: hyprlang\n";
+ if (failReplacement && command === "hyprctl" && args[1] === "bind") {
+ return "bind failed\n";
+ }
+ return "ok\n";
+ });
+ const manager = new HyprlandShortcutManager();
+ const callback = () => {};
+
+ assert.equal(await manager.registerSlotKeybinding("F8", "meeting", callback), true);
+ failReplacement = true;
+ assert.equal(await manager.registerSlotKeybinding("Alt+F9", "meeting", () => {}), false);
+ assert.equal(manager.bindings.meeting, ", F8");
+ assert.equal(manager.callbacks.meeting, callback);
+ assert.match(readBinds(configDir), /bind = , F8, exec, .*ToggleMeeting/);
+ })
+);
+
test(
"uses HYPRLAND_CONFIG for a Lua config without spawning systeminfo",
withTempHyprConfig(async (configDir) => {
@@ -365,6 +556,37 @@ test(
})
);
+test(
+ "preserves user-authored lines that merely mention the D-Bus service",
+ withTempHyprConfig(async (configDir) => {
+ const configPath = path.join(configDir, "hyprland.conf");
+ const bindsPath = path.join(configDir, "openwhispr-binds.conf");
+ fs.mkdirSync(configDir, { recursive: true });
+ fs.writeFileSync(configPath, "# legacy config\n");
+ fs.writeFileSync(bindsPath, "exec-once = notify-send com.openwhispr.App\n");
+ const hyprctl = successfulHyprctl("hyprlang");
+ const HyprlandShortcutManager = loadManager(hyprctl.execFileSync);
+
+ assert.equal(await new HyprlandShortcutManager().registerKeybinding("F8"), true);
+
+ const content = fs.readFileSync(bindsPath, "utf8");
+ assert.match(content, /exec-once = notify-send com\.openwhispr\.App/);
+ assert.match(content, /bind = , F8, exec, dbus-send/);
+ })
+);
+
+test(
+ "reports persistence unavailable when the managed binds path is not a file",
+ withTempHyprConfig(async (configDir) => {
+ fs.mkdirSync(configDir, { recursive: true });
+ fs.writeFileSync(path.join(configDir, "hyprland.conf"), "# legacy config\n");
+ fs.mkdirSync(path.join(configDir, "openwhispr-binds.conf"));
+ const HyprlandShortcutManager = loadManager(successfulHyprctl("hyprlang").execFileSync);
+
+ assert.equal(HyprlandShortcutManager.getHyprlandConfigStatus().canWrite, false);
+ })
+);
+
test(
"removes the previous header wording when rewriting managed binds",
withTempHyprConfig(async (configDir) => {
@@ -391,6 +613,72 @@ test(
})
);
+test(
+ "preserves user content while removing stale managed legacy binds",
+ withTempHyprConfig(async (configDir) => {
+ const confPath = path.join(configDir, "hyprland.conf");
+ const legacyBindsPath = path.join(configDir, "openwhispr-binds.conf");
+ fs.mkdirSync(configDir, { recursive: true });
+ fs.writeFileSync(path.join(configDir, "hyprland.lua"), "-- lua config\n");
+ fs.writeFileSync(confPath, "source = ./openwhispr-binds.conf\n");
+ fs.writeFileSync(
+ legacyBindsPath,
+ "# OpenWhispr keybinds (managed automatically)\n" +
+ "exec-once = notify-send com.openwhispr.App\n" +
+ `bind = CTRL SHIFT, Return, exec, ${DBUS_COMMAND}\n`
+ );
+ const HyprlandShortcutManager = loadManager(successfulHyprctl("lua").execFileSync);
+
+ assert.equal(await new HyprlandShortcutManager().registerKeybinding("F8"), true);
+
+ assert.equal(
+ fs.readFileSync(legacyBindsPath, "utf8"),
+ "exec-once = notify-send com.openwhispr.App\n"
+ );
+ assert.equal(fs.readFileSync(confPath, "utf8"), "source = ./openwhispr-binds.conf\n");
+ })
+);
+
+test(
+ "keeps the legacy source target intact until cleanup can be retried",
+ withTempHyprConfig(async (configDir) => {
+ const confPath = path.join(configDir, "hyprland.conf");
+ const legacyBindsPath = path.join(configDir, "openwhispr-binds.conf");
+ const legacyConfig = "# keep this comment\nsource = ./openwhispr-binds.conf\n";
+ const legacyBinds =
+ "# OpenWhispr keybinds (managed automatically)\n" +
+ `bind = CTRL SHIFT, Return, exec, ${DBUS_COMMAND}\n`;
+ fs.mkdirSync(configDir, { recursive: true });
+ fs.writeFileSync(path.join(configDir, "hyprland.lua"), "-- lua config\n");
+ fs.writeFileSync(confPath, legacyConfig);
+ fs.writeFileSync(legacyBindsPath, legacyBinds);
+ const HyprlandShortcutManager = loadManager(successfulHyprctl("lua").execFileSync);
+ const manager = new HyprlandShortcutManager();
+ const writeFileSync = fs.writeFileSync;
+ const failingWrite = test.mock.method(fs, "writeFileSync", (filePath, ...args) => {
+ if (filePath === confPath) {
+ throw Object.assign(new Error("read-only legacy config"), { code: "EACCES" });
+ }
+ return writeFileSync(filePath, ...args);
+ });
+
+ try {
+ assert.equal(await manager.registerKeybinding("F8"), true);
+ assert.equal(manager.persistencePending, true);
+ assert.equal(fs.readFileSync(confPath, "utf8"), legacyConfig);
+ assert.equal(fs.existsSync(legacyBindsPath), true);
+ assert.equal(fs.readFileSync(legacyBindsPath, "utf8"), legacyBinds);
+ } finally {
+ failingWrite.mock.restore();
+ }
+
+ assert.equal(await manager.registerKeybinding("F8"), true);
+ assert.equal(manager.persistencePending, false);
+ assert.equal(fs.readFileSync(confPath, "utf8"), "# keep this comment\n");
+ assert.equal(fs.existsSync(legacyBindsPath), false);
+ })
+);
+
test(
"removes stale managed legacy artifacts after migrating to Lua",
withTempHyprConfig(async (configDir) => {
@@ -417,6 +705,58 @@ test(
})
);
+function readBinds(configDir) {
+ return fs.readFileSync(path.join(configDir, "openwhispr-binds.conf"), "utf8");
+}
+
+test(
+ "keeps per-slot Hyprland binds and callbacks isolated",
+ withTempHyprConfig(async (configDir) => {
+ fs.mkdirSync(configDir, { recursive: true });
+ fs.writeFileSync(path.join(configDir, "hyprland.conf"), "# config\n");
+ const hyprctl = successfulHyprctl("hyprlang");
+ const HyprlandShortcutManager = loadManager(hyprctl.execFileSync);
+
+ const manager = new HyprlandShortcutManager();
+ const cb = {
+ meeting: () => undefined,
+ voiceAgent: () => undefined,
+ translation: () => undefined,
+ };
+
+ await manager.registerKeybinding("Control+Shift+Enter");
+ await manager.registerSlotKeybinding("Alt+F9", "meeting", cb.meeting);
+ await manager.registerSlotKeybinding("Alt+F10", "voiceAgent", cb.voiceAgent);
+ await manager.registerSlotKeybinding("Alt+F11", "translation", cb.translation);
+
+ const binds = readBinds(configDir);
+ assert.match(binds, /\.Toggle\b/);
+ assert.match(binds, /\.ToggleMeeting/);
+ assert.match(binds, /\.ToggleVoiceAgent/);
+ assert.match(binds, /\.ToggleTranslation/);
+
+ assert.equal(await manager.updateKeybinding("Alt+F12"), true);
+ const afterDictationUpdate = readBinds(configDir);
+ assert.match(afterDictationUpdate, /\.ToggleMeeting/);
+ assert.match(afterDictationUpdate, /\.ToggleVoiceAgent/);
+ assert.match(afterDictationUpdate, /\.ToggleTranslation/);
+
+ assert.equal(await manager.unregisterKeybinding("meeting"), true);
+ const after = readBinds(configDir);
+ assert.doesNotMatch(after, /ToggleMeeting/);
+ assert.match(after, /ToggleVoiceAgent/);
+ assert.match(after, /ToggleTranslation/);
+ assert.equal(manager.callbacks.meeting, undefined);
+ assert.equal(manager.callbacks.voiceAgent, cb.voiceAgent);
+
+ const teardown = manager.unregisterKeybinding();
+ assert.deepEqual(manager.bindings, {});
+ assert.equal(await teardown, true);
+ assert.equal(manager.bindings.voiceAgent, undefined);
+ assert.equal(manager.bindings.translation, undefined);
+ })
+);
+
test("punctuation accelerators validate and convert to XKB key names", () => {
const HyprlandShortcutManager = loadManager(() => "ok\n");