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(linux): push-to-talk on Wayland (Hyprland, KDE, GNOME 48+) for dictation hotkey (#1738)
Idris Gadib5c5fb44305b
diff --git a/main.js b/main.jsindex 9dd131e92..e2b5b1657 100644--- a/main.js+++ b/main.js@@ -974,13 +974,34 @@ async function startApp() {applyOpenWhisprOriginHeader(session.defaultSession);- windowManager.setActivationModeCache(environmentManager.getActivationMode());+ await windowManager.setActivationModeCache(environmentManager.getActivationMode());windowManager.setFloatingIconAutoHide(environmentManager.getFloatingIconAutoHide());windowManager.setPanelStartPosition(environmentManager.getPanelStartPosition());+ let activationModeChangeQueue = Promise.resolve();ipcMain.on("activation-mode-changed", (_event, mode) => {- windowManager.setActivationModeCache(mode);- environmentManager.saveActivationMode(mode);+ activationModeChangeQueue = activationModeChangeQueue+ .then(async () => {+ const success = await windowManager.setActivationModeCache(mode);+ const effectiveMode = windowManager.getActivationMode();+ if (success) {+ environmentManager.saveActivationMode(effectiveMode);+ } else {+ for (const browserWindow of BrowserWindow.getAllWindows()) {+ if (!browserWindow.isDestroyed()) {+ browserWindow.webContents.send("setting-updated", {+ key: "activationMode",+ value: effectiveMode,+ });+ }+ }+ }+ windowManager.resetWindowsPushState();+ windowManager.reconcileNativeKeyListeners();+ })+ .catch((err) => {+ debugLogger.error("Failed to change activation mode", { error: err.message }, "hotkey");+ });});ipcMain.on("floating-icon-auto-hide-changed", (_event, enabled) => {@@ -1689,11 +1710,6 @@ async function startApp() {const STARTUP_DELAY_MS = 3000;setTimeout(() => windowManager.reconcileNativeKeyListeners(), STARTUP_DELAY_MS);- ipcMain.on("activation-mode-changed", () => {- windowManager.resetWindowsPushState();- windowManager.reconcileNativeKeyListeners();- });-ipcMain.on("hotkey-changed", () => {windowManager.resetWindowsPushState();windowManager.reconcileNativeKeyListeners();diff --git a/preload.js b/preload.jsindex bf266965d..b8e1e68e6 100644--- a/preload.js+++ b/preload.js@@ -446,7 +446,7 @@ contextBridge.exposeInMainWorld("electronAPI", {cleanupApp: () => ipcRenderer.invoke("cleanup-app"),updateHotkey: (hotkey) => ipcRenderer.invoke("update-hotkey", hotkey),setHotkeyListeningMode: (enabled) => ipcRenderer.invoke("set-hotkey-listening-mode", enabled),- getHotkeyModeInfo: () => ipcRenderer.invoke("get-hotkey-mode-info"),+ getHotkeyModeInfo: (hotkey) => ipcRenderer.invoke("get-hotkey-mode-info", hotkey),getHyprlandConfigStatus: () => ipcRenderer.invoke("get-hyprland-config-status"),startWindowDrag: () => ipcRenderer.invoke("start-window-drag"),stopWindowDrag: () => ipcRenderer.invoke("stop-window-drag"),diff --git a/src/components/OnboardingFlow.tsx b/src/components/OnboardingFlow.tsxindex 1fb366821..99a05240b 100644--- a/src/components/OnboardingFlow.tsx+++ b/src/components/OnboardingFlow.tsx@@ -119,7 +119,10 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {setPermissionAlert({ title: dialog.title, description: dialog.description }));const systemAudio = useSystemAudioPermission();- const { isUsingNativeShortcut, supportsPushToTalk } = useHotkeyModeInfo("onboarding");+ const { supportsPushToTalk, pushToTalkUnavailableReason } = useHotkeyModeInfo(+ "onboarding",+ dictationHotkey+ );const { activationMode, setActivationMode } = settings;// This hook also starts the membership fetch for already-authenticated users;// relying on the login transition alone would leave resumed onboarding stuck@@ -198,12 +201,6 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {setStageReady(false);}, [currentStepId]);- useEffect(() => {- if (isUsingNativeShortcut && !supportsPushToTalk && activationMode === "push") {- setActivationMode("tap");- }- }, [activationMode, isUsingNativeShortcut, setActivationMode, supportsPushToTalk]);-// Track main's actual registration: the platform default may be unregistrable// (GNOME gsettings and X11 reject modifier-only combos like Control+Super), in// which case main silently registered FALLBACK_HOTKEYS instead. Recommend and@@ -716,7 +713,15 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {)}</p></div>- <ActivationModeSelector value={activationMode} onChange={setActivationMode} />+ <ActivationModeSelector+ value={activationMode}+ onChange={setActivationMode}+ pushDisabledReason={+ !supportsPushToTalk+ ? pushToTalkUnavailableReason || t("windows.pttUnavailable")+ : undefined+ }+ /></div>{getPlatform() === "linux" && activationMode === "push" && (<LinuxPttSetupInfo isAvailable={supportsPushToTalk} />diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsxindex 2a24ab161..c39668adc 100644--- a/src/components/SettingsPage.tsx+++ b/src/components/SettingsPage.tsx@@ -1187,8 +1187,13 @@ export default function SettingsPage({[dictationKey, meetingKey, voiceAgentKey, t]);- const { isUsingNativeShortcut, isUsingHyprland, hyprlandConfigStatus, supportsPushToTalk } =- useHotkeyModeInfo("settings");+ const {+ isUsingNativeShortcut,+ isUsingHyprland,+ hyprlandConfigStatus,+ supportsPushToTalk,+ pushToTalkUnavailableReason,+ } = useHotkeyModeInfo("settings", dictationKey);const [effectiveDefaultHotkey, setEffectiveDefaultHotkey] = useState<string | null>(null);const [linuxPttAvailable, setLinuxPttAvailable] = useState(true);@@ -1298,12 +1303,6 @@ export default function SettingsPage({};}, [checkWhisperInstallation, getAppVersion]);- useEffect(() => {- if (isUsingNativeShortcut && !supportsPushToTalk) {- setActivationMode("tap");- }- }, [isUsingNativeShortcut, supportsPushToTalk, setActivationMode]);-useEffect(() => {const loadEffectiveDefaultHotkey = async () => {try {@@ -3487,7 +3486,15 @@ EOF`,<span className="text-xs text-muted-foreground/80">{t("settingsPage.general.hotkey.activationMode")}</span>- <ActivationModeSelector value={activationMode} onChange={setActivationMode} />+ <ActivationModeSelector+ value={activationMode}+ onChange={setActivationMode}+ pushDisabledReason={+ !supportsPushToTalk+ ? pushToTalkUnavailableReason || t("windows.pttUnavailable")+ : undefined+ }+ /></div>{getCachedPlatform() === "linux" && activationMode === "push" && (<LinuxPttSetupInfo isAvailable={linuxPttAvailable} />diff --git a/src/components/ui/ActivationModeSelector.tsx b/src/components/ui/ActivationModeSelector.tsxindex 147fa4207..5ce66b4a7 100644--- a/src/components/ui/ActivationModeSelector.tsx+++ b/src/components/ui/ActivationModeSelector.tsx@@ -6,7 +6,7 @@ type ActivationMode = "tap" | "push";interface ActivationModeSelectorProps {value: ActivationMode;onChange: (mode: ActivationMode) => void;- disabled?: boolean;+ pushDisabledReason?: string;}const OPTIONS = [@@ -17,18 +17,12 @@ const OPTIONS = [export function ActivationModeSelector({value,onChange,- disabled = false,+ pushDisabledReason,}: ActivationModeSelectorProps) {const { t } = useTranslation();return (- <div- className={`- relative flex rounded-md border p-0.5 transition-colors duration-200- bg-surface-1 border-border-subtle- ${disabled ? "opacity-50 cursor-not-allowed" : ""}- `}- >+ <div className="relative flex rounded-md border p-0.5 transition-colors duration-200 bg-surface-1 border-border-subtle">{/* Sliding indicator */}<divclassName={`@@ -39,23 +33,31 @@ export function ActivationModeSelector({`}/>- {OPTIONS.map(({ mode, Icon, labelKey }) => (- <button- key={mode}- type="button"- disabled={disabled}- onClick={() => onChange(mode)}- className={`- relative z-10 flex-1 flex items-center justify-center gap-1 rounded px-2.5 py-1- transition-colors duration-150- ${disabled ? "cursor-not-allowed" : "cursor-pointer"}- ${value === mode ? "text-foreground" : "text-muted-foreground hover:text-foreground"}- `}- >- <Icon className="w-3 h-3" />- <span className="text-xs font-medium">{t(labelKey)}</span>- </button>- ))}+ {OPTIONS.map(({ mode, Icon, labelKey }) => {+ const disabledReason = mode === "push" ? pushDisabledReason : undefined;+ const disabled = Boolean(disabledReason);+ const label = t(labelKey);++ return (+ <button+ key={mode}+ type="button"+ disabled={disabled}+ title={disabledReason}+ aria-label={disabledReason ? `${label}: ${disabledReason}` : undefined}+ onClick={() => onChange(mode)}+ className={`+ relative z-10 flex-1 flex items-center justify-center gap-1 rounded px-2.5 py-1+ transition-colors duration-150+ ${disabled ? "cursor-not-allowed" : "cursor-pointer"}+ ${value === mode ? "text-foreground" : "text-muted-foreground hover:text-foreground"}+ `}+ >+ <Icon className="w-3 h-3" />+ <span className="text-xs font-medium">{label}</span>+ </button>+ );+ })}</div>);}diff --git a/src/helpers/gnomeGlobalShortcutsPortal.js b/src/helpers/gnomeGlobalShortcutsPortal.jsnew file mode 100644index 000000000..1fed40c73--- /dev/null+++ b/src/helpers/gnomeGlobalShortcutsPortal.js@@ -0,0 +1,343 @@+const crypto = require("crypto");+const debugLogger = require("./debugLogger");+const { i18nMain } = require("./i18nMain");++const PORTAL_SERVICE = "org.freedesktop.portal.Desktop";+const PORTAL_PATH = "/org/freedesktop/portal/desktop";+const GLOBAL_SHORTCUTS_INTERFACE = "org.freedesktop.portal.GlobalShortcuts";+const REQUEST_INTERFACE = "org.freedesktop.portal.Request";+const SESSION_INTERFACE = "org.freedesktop.portal.Session";+const REGISTRY_INTERFACE = "org.freedesktop.host.portal.Registry";+const APP_ID = "open-whispr";+const DBUS_CALL_TIMEOUT_MS = 5000;+const PORTAL_REQUEST_TIMEOUT_MS = 120000;++let dbus = null;++function getDBus() {+ if (dbus) return dbus;+ try {+ dbus = require("@homebridge/dbus-native");+ return dbus;+ } catch (err) {+ debugLogger.log("[GnomeGlobalShortcutsPortal] Failed to load dbus-native:", err.message);+ return null;+ }+}++function vardict(entries = []) {+ return entries.map(([key, signature, value]) => [key, [signature, value]]);+}++function readVariant(value) {+ return Array.isArray(value?.[1]) ? value[1][0] : undefined;+}++function readDict(value) {+ return new Map((value || []).map(([key, variant]) => [key, readVariant(variant)]));+}++class GnomeGlobalShortcutsPortal {+ constructor({+ callTimeoutMs = DBUS_CALL_TIMEOUT_MS,+ requestTimeoutMs = PORTAL_REQUEST_TIMEOUT_MS,+ } = {}) {+ this.bus = null;+ this.sessionHandle = null;+ this.callback = null;+ this.available = false;+ this.activationListener = null;+ this.deactivationListener = null;+ this.callTimeoutMs = callTimeoutMs;+ this.requestTimeoutMs = requestTimeoutMs;+ }++ async init() {+ if (this.bus) return this.available;++ const dbusModule = getDBus();+ if (!dbusModule) return false;++ try {+ this.bus = dbusModule.sessionBus();+ this.bus.connection.on("error", (err) => {+ debugLogger.log("[GnomeGlobalShortcutsPortal] D-Bus connection error:", err.message);+ });+ await this._invokeDbus({ member: "GetId" });+ if (!process.env.FLATPAK_ID) {+ await this._invoke({+ destination: PORTAL_SERVICE,+ path: PORTAL_PATH,+ interface: REGISTRY_INTERFACE,+ member: "Register",+ signature: "sa{sv}",+ body: [APP_ID, vardict()],+ });+ }+ const version = await this._invoke({+ destination: PORTAL_SERVICE,+ path: PORTAL_PATH,+ interface: "org.freedesktop.DBus.Properties",+ member: "Get",+ signature: "ss",+ body: [GLOBAL_SHORTCUTS_INTERFACE, "version"],+ });+ this.available = Number(readVariant(version)) >= 1;+ if (!this.available) await this.close();+ return this.available;+ } catch (err) {+ debugLogger.log(+ "[GnomeGlobalShortcutsPortal] Global Shortcuts portal unavailable:",+ err.message+ );+ await this.close();+ return false;+ }+ }++ isAvailable() {+ return this.available;+ }++ async registerKeybinding(preferredTrigger, callback) {+ if (!(await this.init())) return false;++ await this.unregisterKeybinding();+ this.callback = callback;++ try {+ const sessionToken = this._newToken();+ const createRequestToken = this._newToken();+ const session = await this._request(+ "CreateSession",+ "a{sv}",+ [+ vardict([+ ["handle_token", "s", createRequestToken],+ ["session_handle_token", "s", sessionToken],+ ]),+ ],+ createRequestToken+ );+ this.sessionHandle = readDict(session).get("session_handle");+ if (!this.sessionHandle) throw new Error("Portal did not return a session handle");++ await this._listenForShortcutEvents();+ const bindRequestToken = this._newToken();+ const result = await this._request(+ "BindShortcuts",+ "oa(sa{sv})sa{sv}",+ [+ this.sessionHandle,+ [+ [+ "dictation",+ vardict([+ ["description", "s", i18nMain.t("onboarding.activation.holdDescription")],+ ["preferred_trigger", "s", preferredTrigger],+ ]),+ ],+ ],+ "",+ vardict([["handle_token", "s", bindRequestToken]]),+ ],+ bindRequestToken+ );+ const shortcuts = readDict(result).get("shortcuts") || [];+ if (!shortcuts.some(([id]) => id === "dictation")) {+ throw new Error("Portal did not bind the dictation shortcut");+ }++ debugLogger.log("[GnomeGlobalShortcutsPortal] Dictation shortcut registered");+ return true;+ } catch (err) {+ debugLogger.log(+ "[GnomeGlobalShortcutsPortal] Failed to register dictation shortcut:",+ err.message+ );+ await this.unregisterKeybinding();+ return false;+ }+ }++ async unregisterKeybinding() {+ this._removeShortcutListeners();+ this.callback = null;+ if (!this.sessionHandle || !this.bus) return;++ const sessionHandle = this.sessionHandle;+ this.sessionHandle = null;+ try {+ await this._invoke({+ destination: PORTAL_SERVICE,+ path: sessionHandle,+ interface: SESSION_INTERFACE,+ member: "Close",+ });+ } catch (err) {+ debugLogger.log("[GnomeGlobalShortcutsPortal] Failed to close session:", err.message);+ }+ }++ async close() {+ await this.unregisterKeybinding();+ const bus = this.bus;+ this.bus = null;+ this.available = false;+ bus?.connection.end();+ }++ async _listenForShortcutEvents() {+ const bus = this.bus;+ const activationSignal = this.bus.mangle(PORTAL_PATH, GLOBAL_SHORTCUTS_INTERFACE, "Activated");+ const deactivationSignal = this.bus.mangle(+ PORTAL_PATH,+ GLOBAL_SHORTCUTS_INTERFACE,+ "Deactivated"+ );+ this.activationListener = ([sessionHandle, shortcutId]) => {+ if (sessionHandle === this.sessionHandle && shortcutId === "dictation") {+ this.callback?.(undefined, "down");+ }+ };+ this.deactivationListener = ([sessionHandle, shortcutId]) => {+ if (sessionHandle === this.sessionHandle && shortcutId === "dictation") {+ this.callback?.(undefined, "up");+ }+ };+ bus.signals.on(activationSignal, this.activationListener);+ bus.signals.on(deactivationSignal, this.deactivationListener);+ try {+ await Promise.all([+ this._addMatch(this._shortcutMatch("Activated")),+ this._addMatch(this._shortcutMatch("Deactivated")),+ ]);+ } catch (err) {+ this._removeShortcutListeners();+ throw err;+ }+ }++ _removeShortcutListeners() {+ if (!this.bus) return;+ if (this.activationListener) {+ this.bus.signals.removeListener(+ this.bus.mangle(PORTAL_PATH, GLOBAL_SHORTCUTS_INTERFACE, "Activated"),+ this.activationListener+ );+ this.activationListener = null;+ this.bus.removeMatch(this._shortcutMatch("Activated"), () => {});+ }+ if (this.deactivationListener) {+ this.bus.signals.removeListener(+ this.bus.mangle(PORTAL_PATH, GLOBAL_SHORTCUTS_INTERFACE, "Deactivated"),+ this.deactivationListener+ );+ this.deactivationListener = null;+ this.bus.removeMatch(this._shortcutMatch("Deactivated"), () => {});+ }+ }++ async _request(member, signature, body, token) {+ const bus = this.bus;+ const requestPath = this._requestPath(token);+ const signal = bus.mangle(requestPath, REQUEST_INTERFACE, "Response");+ const match = `type='signal',sender='${PORTAL_SERVICE}',path='${requestPath}',interface='${REQUEST_INTERFACE}',member='Response'`;+ await this._addMatch(match);++ return new Promise((resolve, reject) => {+ let settled = false;+ let timeoutId;+ const cleanup = () => {+ clearTimeout(timeoutId);+ bus.signals.removeListener(signal, onResponse);+ try {+ bus.removeMatch(match, () => undefined);+ } catch {}+ };+ const finish = (err, result) => {+ if (settled) return;+ settled = true;+ cleanup();+ if (err) reject(err);+ else resolve(result);+ };+ const onResponse = ([response, results]) => {+ if (response === 0) finish(null, results);+ else finish(new Error(`Portal request was rejected (${response})`));+ };+ bus.signals.once(signal, onResponse);+ timeoutId = setTimeout(+ () => finish(new Error(`Portal request "${member}" timed out`)),+ this.requestTimeoutMs+ );+ timeoutId.unref?.();+ bus.invoke(+ {+ destination: PORTAL_SERVICE,+ path: PORTAL_PATH,+ interface: GLOBAL_SHORTCUTS_INTERFACE,+ member,+ signature,+ body,+ },+ (err) => {+ if (!err) return;+ finish(err);+ }+ );+ });+ }++ _invoke(message) {+ return this._callWithTimeout(message.member, (callback) => this.bus.invoke(message, callback));+ }++ _invokeDbus(message) {+ return this._callWithTimeout(message.member, (callback) =>+ this.bus.invokeDbus(message, callback)+ );+ }++ _addMatch(match) {+ return this._callWithTimeout("AddMatch", (callback) => this.bus.addMatch(match, callback));+ }++ _callWithTimeout(member, invoke) {+ return new Promise((resolve, reject) => {+ let settled = false;+ const finish = (err, result) => {+ if (settled) return;+ settled = true;+ clearTimeout(timeoutId);+ if (err) reject(err);+ else resolve(result);+ };+ const timeoutId = setTimeout(+ () => finish(new Error(`D-Bus call "${member}" timed out`)),+ this.callTimeoutMs+ );+ timeoutId.unref?.();+ try {+ invoke(finish);+ } catch (err) {+ finish(err);+ }+ });+ }++ _newToken() {+ return `openwhispr_${crypto.randomUUID().replace(/-/g, "_")}`;+ }++ _requestPath(token) {+ const sender = this.bus.name.slice(1).replace(/\./g, "_");+ return `/org/freedesktop/portal/desktop/request/${sender}/${token}`;+ }++ _shortcutMatch(member) {+ return `type='signal',sender='${PORTAL_SERVICE}',interface='${GLOBAL_SHORTCUTS_INTERFACE}',member='${member}'`;+ }+}++module.exports = GnomeGlobalShortcutsPortal;diff --git a/src/helpers/gnomeShortcut.js b/src/helpers/gnomeShortcut.jsindex 663097fb3..dc7082133 100644--- a/src/helpers/gnomeShortcut.js+++ b/src/helpers/gnomeShortcut.js@@ -1,5 +1,6 @@const { execFileSync } = require("child_process");const debugLogger = require("./debugLogger");+const GnomeGlobalShortcutsPortal = require("./gnomeGlobalShortcutsPortal");const DBUS_SERVICE_NAME = "com.openwhispr.App";const DBUS_OBJECT_PATH = "/com/openwhispr/App";@@ -26,6 +27,15 @@ const SLOT_CONFIG = {};const KEYBINDING_SCHEMA = "org.gnome.settings-daemon.plugins.media-keys.custom-keybinding";+const PORTAL_MODIFIER_NAMES = new Set([+ "commandorcontrol",+ "control",+ "ctrl",+ "alt",+ "shift",+ "super",+ "meta",+]);// Valid pattern for GNOME shortcut format using X11 keysym names (case-sensitive).// Modifiers are case-insensitive (GTK normalizes them), keysyms are exact.@@ -128,6 +138,7 @@ class GnomeShortcutManager {this.meetingCallback = null;this.voiceAgentCallback = null;this.translationCallback = null;+ this.globalShortcutsPortal = new GnomeGlobalShortcutsPortal();// Track which slots have been registered in gsettingsthis.registeredSlots = new Set();}@@ -253,6 +264,34 @@ class GnomeShortcutManager {}}+ async initGlobalShortcutsPortal() {+ return this.globalShortcutsPortal.init();+ }++ supportsPushToTalk() {+ return this.globalShortcutsPortal.isAvailable();+ }++ async registerPushToTalk(hotkey, callback) {+ const preferredTrigger = GnomeShortcutManager.convertToPortalFormat(hotkey);+ if (!preferredTrigger) return false;++ await this.unregisterKeybinding("dictation");+ const registered = await this.globalShortcutsPortal.registerKeybinding(+ preferredTrigger,+ callback+ );+ if (!registered) {+ const tapShortcut = GnomeShortcutManager.convertToGnomeFormat(hotkey);+ await this.registerKeybinding(tapShortcut, "dictation");+ }+ return registered;+ }++ async unregisterPushToTalk() {+ await this.globalShortcutsPortal.unregisterKeybinding();+ }+static isValidShortcut(shortcut) {if (!shortcut || typeof shortcut !== "string") {return false;@@ -351,46 +390,6 @@ class GnomeShortcutManager {}}- async updateKeybinding(shortcut, slotName = "dictation") {- if (!this.registeredSlots.has(slotName)) {- return this.registerKeybinding(shortcut, slotName);- }-- if (!GnomeShortcutManager.isValidShortcut(shortcut)) {- debugLogger.log(- `[GnomeShortcut] Invalid shortcut format for update: "${shortcut}" (slot "${slotName}")`- );- return false;- }-- const { path: keybindingPath } = getSlotConfig(slotName);-- try {- const existing = this.getExistingKeybindings();- const conflict = this.findConflictingBinding(shortcut, existing, keybindingPath);- if (conflict) {- debugLogger.log(- `[GnomeShortcut] Shortcut conflict on update — "${shortcut}" already used by "${conflict}"`- );- return false;- }-- execFileSync(- "gsettings",- ["set", `${KEYBINDING_SCHEMA}:${keybindingPath}`, "binding", shortcut],- { stdio: "pipe" }- );- debugLogger.log(`[GnomeShortcut] Keybinding updated to "${shortcut}" for slot "${slotName}"`);- return true;- } catch (err) {- debugLogger.log(- `[GnomeShortcut] Failed to update keybinding for slot "${slotName}":`,- err.message- );- return false;- }- }-async unregisterKeybinding(slotName = "dictation") {const { path: keybindingPath } = getSlotConfig(slotName);@@ -543,7 +542,51 @@ class GnomeShortcutManager {return modifiers + gnomeKey;}- close() {+ static convertToPortalFormat(hotkey) {+ if (!hotkey || typeof hotkey !== "string") return "";++ const parts = hotkey+ .split("+")+ .map((part) => part.trim())+ .filter(Boolean);+ if (+ parts.length === 0 ||+ parts.every((part) => PORTAL_MODIFIER_NAMES.has(part.toLowerCase()))+ ) {+ return "";+ }++ const key = parts.pop();+ const keyLower = key.toLowerCase();+ const modifiers = parts+ .map((modifier) => {+ const name = modifier.toLowerCase();+ if (name === "commandorcontrol" || name === "control" || name === "ctrl") return "CTRL";+ if (name === "alt") return "ALT";+ if (name === "shift") return "SHIFT";+ if (name === "super" || name === "meta") return "LOGO";+ return "";+ })+ .filter(Boolean);++ let portalKey;+ if (key === "`" || keyLower === "backquote") {+ portalKey = "grave";+ } else if (key === " ") {+ portalKey = "space";+ } else if (ELECTRON_TO_GNOME_KEY_MAP[keyLower]) {+ portalKey = ELECTRON_TO_GNOME_KEY_MAP[keyLower];+ } else if (/^F\d+$/i.test(key)) {+ portalKey = key.toUpperCase();+ } else {+ portalKey = keyLower;+ }++ return [...modifiers, portalKey].join("+");+ }++ async close() {+ await this.globalShortcutsPortal.close();if (this.bus) {this.bus.connection.end();this.bus = null;diff --git a/src/helpers/hotkeyManager.js b/src/helpers/hotkeyManager.jsindex 0f5d6c4a0..9fb58358f 100644--- a/src/helpers/hotkeyManager.js+++ b/src/helpers/hotkeyManager.js@@ -259,7 +259,12 @@ class HotkeyManager extends EventEmitter {if (this.useKDE && this.kdeManager && slotName !== "cancel") {this.unregisterSlot(slotName);- const result = await this.kdeManager.registerKeybinding(hotkey, slotName, callback);+ const result = await this.kdeManager.registerKeybinding(+ hotkey,+ slotName,+ callback,+ slotName === "dictation" && this.activationMode === "push"+ );if (result !== true) {const reason =KDE_FAILURE_REASONS[result]?.(hotkey) ||@@ -381,6 +386,89 @@ class HotkeyManager extends EventEmitter {return keys;}+ supportsPushToTalk(hotkey = this.currentHotkey) {+ if (this.isUsingNativeShortcut() && isModifierOnlyHotkey(hotkey)) {+ return false;+ }+ if (this.useGnome && this.gnomeManager?.supportsPushToTalk) {+ return this.gnomeManager.supportsPushToTalk();+ }+ return true;+ }++ getPushToTalkUnavailableReason(hotkey = this.currentHotkey) {+ if (this.isUsingNativeShortcut() && isModifierOnlyHotkey(hotkey)) {+ return i18nMain.t("hotkey.errors.osReserved", { hotkey });+ }+ return i18nMain.t("windows.pttUnavailable");+ }++ async setActivationMode(mode) {+ const nextMode = mode === "push" ? "push" : "tap";+ const previousMode = this.activationMode === "push" ? "push" : "tap";+ if (this.activationMode === nextMode) return true;++ const hotkey = this.currentHotkey;+ const callback = this.hotkeyCallback;+ if (nextMode === "push" && !this.supportsPushToTalk(hotkey)) {+ if (hotkey) {+ this.notifyHotkeyFailure(hotkey, {+ error: this.getPushToTalkUnavailableReason(hotkey),+ });+ }+ return false;+ }++ let success = true;+ try {+ if (this.useGnome && this.gnomeManager && hotkey && callback) {+ success = await this.registerGnomeDictationHotkey(hotkey, callback, nextMode);+ } else if (this.useHyprland && this.hyprlandManager && hotkey) {+ success = await this.hyprlandManager.updateKeybinding(hotkey, nextMode === "push");+ if (!success) {+ await this.hyprlandManager.updateKeybinding(hotkey, previousMode === "push");+ }+ }+ } catch (err) {+ debugLogger.warn("[HotkeyManager] Failed to change activation mode:", err.message);+ success = false;+ }++ if (+ !success &&+ previousMode === "push" &&+ nextMode === "tap" &&+ this.useGnome &&+ this.gnomeManager &&+ hotkey &&+ callback+ ) {+ try {+ const restored = await this.registerGnomeDictationHotkey(hotkey, callback, "push");+ if (!restored) {+ debugLogger.warn("[HotkeyManager] Could not restore GNOME push-to-talk binding");+ }+ } catch (err) {+ debugLogger.warn(+ "[HotkeyManager] Error restoring GNOME push-to-talk binding:",+ err.message+ );+ }+ }++ if (!success) {+ if (hotkey) {+ this.notifyHotkeyFailure(hotkey, {+ error: i18nMain.t("hotkey.errors.registrationFailed", { hotkey }),+ });+ }+ return false;+ }++ this.activationMode = nextMode;+ return true;+ }+// Which mouse buttons the macOS listener must swallow for these slots, and// whether OpenWhispr owns Globe — if it does, macOS's own standalone Globe// action has to stand down.@@ -656,8 +744,10 @@ class HotkeyManager extends EventEmitter {const dbusOk = await this.gnomeManager.initDBusService(callback);if (dbusOk) {+ const portalOk = await this.gnomeManager.initGlobalShortcutsPortal();this.useGnome = true;this.hotkeyCallback = callback;+ debugLogger.log("[HotkeyManager] GNOME Global Shortcuts portal:", portalOk);return true;}} catch (err) {@@ -669,6 +759,17 @@ class HotkeyManager extends EventEmitter {return false;}+ async registerGnomeDictationHotkey(hotkey, callback, mode = this.activationMode) {+ if (mode === "push") {+ if (isModifierOnlyHotkey(hotkey)) return false;+ return this.gnomeManager.registerPushToTalk(hotkey, callback);+ }++ await this.gnomeManager.unregisterPushToTalk();+ const gnomeHotkey = GnomeShortcutManager.convertToGnomeFormat(hotkey);+ return this.gnomeManager.registerKeybinding(gnomeHotkey);+ }+async initializeKDEShortcuts(callback) {if (process.platform !== "linux" || !KDEShortcutManager.isKDE()) {return false;@@ -756,18 +857,15 @@ class HotkeyManager extends EventEmitter {try {// DE backends bind one accelerator per slot — use the primary hotkey.const hotkey = parseHotkeyList(await this.getSavedHotkey())[0] || DEFAULT_HOTKEY;- const gnomeHotkey = GnomeShortcutManager.convertToGnomeFormat(hotkey);-- const success = await this.gnomeManager.registerKeybinding(gnomeHotkey);+ const success = await this.registerGnomeDictationHotkey(hotkey, callback);if (success) {this.currentHotkey = hotkey;this.notifyActiveHotkey(hotkey);debugLogger.log(`[HotkeyManager] GNOME hotkey "${hotkey}" registered successfully`);} else {- const ok = await this.tryNativeFallbacks(hotkey, "GNOME", async (fb) => {- const fbGnome = GnomeShortcutManager.convertToGnomeFormat(fb);- return this.gnomeManager.registerKeybinding(fbGnome);- });+ const ok = await this.tryNativeFallbacks(hotkey, "GNOME", (fb) =>+ this.registerGnomeDictationHotkey(fb, callback)+ );if (!ok) {this.useGnome = false;this.loadSavedHotkeyOrDefault(mainWindow, callback);@@ -803,7 +901,10 @@ class HotkeyManager extends EventEmitter {// DE backends bind one accelerator per slot — use the primary hotkey.const hotkey = parseHotkeyList(await this.getSavedHotkey())[0] || DEFAULT_HOTKEY;- const success = await this.hyprlandManager.registerKeybinding(hotkey);+ const success = await this.hyprlandManager.registerKeybinding(+ hotkey,+ this.activationMode === "push"+ );if (success) {this.currentHotkey = hotkey;this.notifyActiveHotkey(hotkey);@@ -812,7 +913,7 @@ class HotkeyManager extends EventEmitter {);} else {const ok = await this.tryNativeFallbacks(hotkey, "Hyprland", (fb) =>- this.hyprlandManager.registerKeybinding(fb)+ this.hyprlandManager.registerKeybinding(fb, this.activationMode === "push"));if (!ok) {this.useHyprland = false;@@ -845,7 +946,12 @@ class HotkeyManager extends EventEmitter {try {// DE backends bind one accelerator per slot — use the primary hotkey.const hotkey = parseHotkeyList(await this.getSavedHotkey())[0] || DEFAULT_HOTKEY;- const result = await this.kdeManager.registerKeybinding(hotkey, "dictation", callback);+ const result = await this.kdeManager.registerKeybinding(+ hotkey,+ "dictation",+ callback,+ this.activationMode === "push"+ );if (result === true) {this.currentHotkey = hotkey;this.notifyActiveHotkey(hotkey);@@ -853,7 +959,7 @@ class HotkeyManager extends EventEmitter {} else if (result === "conflict" || result === "modifier-only") {const ok = await this.tryNativeFallbacks(hotkey, "KDE", (fb) =>this.kdeManager- .registerKeybinding(fb, "dictation", callback)+ .registerKeybinding(fb, "dictation", callback, this.activationMode === "push").then((r) => r === true));if (!ok) {@@ -1167,6 +1273,13 @@ class HotkeyManager extends EventEmitter {// DE backends bind one accelerator per slot; extras stay in storage.const primary = hotkeys[0];+ if (this.activationMode === "push" && !this.supportsPushToTalk(primary)) {+ return {+ success: false,+ message: this.getPushToTalkUnavailableReason(primary),+ };+ }+for (const hotkey of hotkeys) {const conflict = this._findSlotConflict("dictation", hotkey);if (conflict) {@@ -1176,8 +1289,7 @@ class HotkeyManager extends EventEmitter {if (this.useGnome && this.gnomeManager) {debugLogger.log(`[HotkeyManager] Updating GNOME hotkey to "${primary}"`);- const gnomeHotkey = GnomeShortcutManager.convertToGnomeFormat(primary);- const success = await this.gnomeManager.updateKeybinding(gnomeHotkey);+ const success = await this.registerGnomeDictationHotkey(primary, callback);if (!success) {return {success: false,@@ -1200,7 +1312,10 @@ class HotkeyManager extends EventEmitter {if (this.useHyprland && this.hyprlandManager) {debugLogger.log(`[HotkeyManager] Updating Hyprland hotkey to "${primary}"`);- const success = await this.hyprlandManager.updateKeybinding(primary);+ const success = await this.hyprlandManager.updateKeybinding(+ primary,+ this.activationMode === "push"+ );if (!success) {return {success: false,@@ -1225,13 +1340,19 @@ class HotkeyManager extends EventEmitter {debugLogger.log(`[HotkeyManager] Updating KDE hotkey to "${primary}"`);const previousHotkey = this.currentHotkey;await this.kdeManager.unregisterKeybinding("dictation");- const result = await this.kdeManager.registerKeybinding(primary, "dictation", callback);+ const result = await this.kdeManager.registerKeybinding(+ primary,+ "dictation",+ callback,+ this.activationMode === "push"+ );if (result !== true) {if (previousHotkey) {const restored = await this.kdeManager.registerKeybinding(previousHotkey,"dictation",- callback+ callback,+ this.activationMode === "push");if (restored === true) {debugLogger.log(`[HotkeyManager] Restored previous KDE hotkey "${previousHotkey}"`);@@ -1298,7 +1419,9 @@ class HotkeyManager extends EventEmitter {);});}- this.gnomeManager.close();+ void this.gnomeManager.close().catch((err) => {+ debugLogger.warn("[HotkeyManager] Error closing GNOME shortcut manager:", err.message);+ });this.gnomeManager = null;this.useGnome = false;}diff --git a/src/helpers/hyprlandShortcut.js b/src/helpers/hyprlandShortcut.jsindex e5f6ab5b3..eb0ab55b7 100644--- a/src/helpers/hyprlandShortcut.js+++ b/src/helpers/hyprlandShortcut.js@@ -69,8 +69,10 @@ function buildManagedBindsContent(lines = [], format = "conf") {return header + "\n" + (body ? body + "\n" : "");}-function buildLuaBindExpression(luaKeys, dbusCommand) {- return `hl.bind(${JSON.stringify(luaKeys)}, hl.dsp.exec_cmd(${JSON.stringify(dbusCommand)}))`;+function buildLuaBindExpression(luaKeys, dbusCommand, flags = "") {+ return `hl.bind(${JSON.stringify(luaKeys)}, hl.dsp.exec_cmd(${JSON.stringify(+ dbusCommand+ )})${flags ? `, ${flags}` : ""})`;}function runHyprctl(args) {@@ -86,6 +88,14 @@ function runHyprctl(args) {}}+function isModifierOnlyHotkey(hotkey) {+ const parts = hotkey+ .split("+")+ .map((part) => part.trim().toLowerCase())+ .filter(Boolean);+ return parts.length > 0 && parts.every((part) => ELECTRON_TO_HYPRLAND_MOD[part]);+}+function getHyprConfigDir() {if (process.env.HYPRLAND_CONFIG) {return path.dirname(path.resolve(process.env.HYPRLAND_CONFIG));@@ -194,7 +204,7 @@ class HyprlandShortcutManager {}/**- * Initialize a D-Bus service to receive Toggle() calls from Hyprland keybindings.+ * Initialize a D-Bus service to receive hotkey events from Hyprland keybindings.* Reuses the same D-Bus service name/path as the GNOME integration.*/async initDBusService(callback) {@@ -221,12 +231,24 @@ class HyprlandShortcutManager {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: ["", ""],},});@@ -328,7 +350,7 @@ class HyprlandShortcutManager {};}- _writeBindToConfig(config, bindLine) {+ _writeBindToConfig(config, bindLines) {fs.mkdirSync(path.dirname(config.bindsPath), { recursive: true });let content = "";@@ -345,7 +367,8 @@ class HyprlandShortcutManager {return !trimmed.includes(DBUS_SERVICE_NAME);});- const newContent = buildManagedBindsContent([...lines, bindLine], config.format);+ const managedBindLines = Array.isArray(bindLines) ? bindLines : [bindLines];+ const newContent = buildManagedBindsContent([...lines, ...managedBindLines], config.format);fs.writeFileSync(config.bindsPath, newContent, "utf-8");}@@ -455,12 +478,51 @@ class HyprlandShortcutManager {runHyprctl(args);}- _bindRuntime(config, binding, bindValue, dbusCommand) {- const args =- config.format === "lua"- ? ["eval", buildLuaBindExpression(binding, dbusCommand)]- : ["keyword", "bind", bindValue];- runHyprctl(args);+ _bindRuntime(config, converted, isPushToTalk, pressCommand, releaseCommand) {+ const runtimeBinding = config.format === "lua" ? converted.luaKeys : converted.bindKey;++ if (config.format === "lua") {+ runHyprctl([+ "eval",+ buildLuaBindExpression(+ converted.luaKeys,+ pressCommand,+ isPushToTalk ? "{ transparent = true }" : ""+ ),+ ]);+ if (isPushToTalk) {+ try {+ runHyprctl([+ "eval",+ buildLuaBindExpression(+ converted.luaKeys,+ releaseCommand,+ "{ release = true, transparent = true }"+ ),+ ]);+ } catch (err) {+ try {+ this._unbindRuntime(config, runtimeBinding);+ } catch {}+ throw err;+ }+ }+ return runtimeBinding;+ }++ const bindValue = `${converted.bindKey}, exec, ${pressCommand}`;+ runHyprctl(["keyword", isPushToTalk ? "bindt" : "bind", bindValue]);+ if (isPushToTalk) {+ try {+ runHyprctl(["keyword", "bindrt", `${converted.bindKey}, exec, ${releaseCommand}`]);+ } catch (err) {+ try {+ this._unbindRuntime(config, runtimeBinding);+ } catch {}+ throw err;+ }+ }+ return runtimeBinding;}static getHyprlandConfigStatus() {@@ -492,7 +554,7 @@ class HyprlandShortcutManager {* Also writes the bind to a format-specific config file so it survives* `hyprctl reload`.*/- async registerKeybinding(hotkey) {+ async registerKeybinding(hotkey, isPushToTalk = false) {if (!HyprlandShortcutManager.isHyprland()) {debugLogger.log("[HyprlandShortcut] Not running on Hyprland, skipping registration");return false;@@ -503,6 +565,13 @@ class HyprlandShortcutManager {return false;}+ if (isPushToTalk && isModifierOnlyHotkey(hotkey)) {+ debugLogger.log(+ `[HyprlandShortcut] Modifier-only hotkey "${hotkey}" does not support push-to-talk`+ );+ return false;+ }+const converted = HyprlandShortcutManager.convertToHyprlandFormat(hotkey);if (!converted) {debugLogger.log(`[HyprlandShortcut] Could not convert hotkey "${hotkey}" to Hyprland format`);@@ -519,10 +588,8 @@ class HyprlandShortcutManager {if (!unregistered) return false;}- const dbusCommand = `dbus-send --session --type=method_call --dest=${DBUS_SERVICE_NAME} ${DBUS_OBJECT_PATH} ${DBUS_INTERFACE}.Toggle`;-- // Legacy bind payload; Lua builds its expression from the same converted values.- const bindValue = `${converted.bindKey}, exec, ${dbusCommand}`;+ 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`;try {this._unbindRuntime(config, runtimeBinding);@@ -533,17 +600,30 @@ class HyprlandShortcutManager {);}- this._bindRuntime(config, runtimeBinding, bindValue, dbusCommand);+ this._bindRuntime(config, converted, isPushToTalk, pressCommand, releaseCommand);this.currentBinding = runtimeBinding;this.isRegistered = true;try {- const persistedBind =+ const persistedPressBind =config.format === "lua"- ? buildLuaBindExpression(converted.luaKeys, dbusCommand)- : `bind = ${bindValue}`;- this._writeBindToConfig(config, persistedBind);+ ? 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);} catch (err) {@@ -566,9 +646,9 @@ class HyprlandShortcutManager {/*** Update the keybinding to a new hotkey.*/- async updateKeybinding(hotkey) {+ async updateKeybinding(hotkey, isPushToTalk = false) {// Just unregister old and register new- return this.registerKeybinding(hotkey);+ return this.registerKeybinding(hotkey, isPushToTalk);}/**diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex 481caad8d..c4a4b01e9 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -52,7 +52,6 @@ const diarizationHost = (endpoint) => {};const { resolveLocalServerNeeds } = require("./localServerPolicy");const autoStart = require("./autoStart");-const GnomeShortcutManager = require("./gnomeShortcut");const HyprlandShortcutManager = require("./hyprlandShortcut");const AssemblyAiStreaming = require("./assemblyAiStreaming");const { i18nMain, changeLanguage } = require("./i18nMain");@@ -3583,6 +3582,7 @@ class IPCHandlers {// On GNOME, unregister all native keybindings during captureif (hotkeyManager.isUsingGnome() && hotkeyManager.gnomeManager) {+ await hotkeyManager.gnomeManager.unregisterPushToTalk();for (const slot of [...hotkeyManager.gnomeManager.registeredSlots]) {debugLogger.log(`[IPC] Unregistering GNOME keybinding (slot "${slot}") for capture mode`@@ -3635,11 +3635,13 @@ class IPCHandlers {// On GNOME, re-register the keybinding with the effective hotkeyif (hotkeyManager.isUsingGnome() && hotkeyManager.gnomeManager && effectiveHotkey) {- const gnomeHotkey = GnomeShortcutManager.convertToGnomeFormat(effectiveHotkey);debugLogger.log(- `[IPC] Re-registering GNOME keybinding "${gnomeHotkey}" after capture mode`+ `[IPC] Re-registering GNOME keybinding "${effectiveHotkey}" after capture mode`+ );+ await hotkeyManager.registerGnomeDictationHotkey(+ effectiveHotkey,+ this.windowManager.createHotkeyCallback());- await hotkeyManager.gnomeManager.registerKeybinding(gnomeHotkey);}// On Hyprland Wayland, re-register the keybinding with the effective hotkey@@ -3647,7 +3649,10 @@ class IPCHandlers {debugLogger.log(`[IPC] Re-registering Hyprland keybinding "${effectiveHotkey}" after capture mode`);- await hotkeyManager.hyprlandManager.registerKeybinding(effectiveHotkey);+ await hotkeyManager.hyprlandManager.registerKeybinding(+ effectiveHotkey,+ this.windowManager.getActivationMode() === "push"+ );}// On KDE (X11 or Wayland), re-register the keybinding with the effective hotkey@@ -3659,7 +3664,8 @@ class IPCHandlers {const result = await hotkeyManager.kdeManager.registerKeybinding(effectiveHotkey,"dictation",- callback+ callback,+ this.windowManager.getActivationMode() === "push");if (result !== true) {debugLogger.warn(@@ -3686,11 +3692,18 @@ class IPCHandlers {return { success: true };});- ipcMain.handle("get-hotkey-mode-info", async () => {+ ipcMain.handle("get-hotkey-mode-info", async (_event, requestedHotkey) => {+ const hotkeyManager = this.windowManager.hotkeyManager;+ const hotkey =+ typeof requestedHotkey === "string" && requestedHotkey.trim()+ ? requestedHotkey.split(",")[0].trim()+ : hotkeyManager.getCurrentHotkey();const isUsingNativeShortcut = this.windowManager.isUsingNativeShortcutHotkeys();const supportsPushToTalk =process.platform === "linux"- ? this.linuxKeyManager?.isAvailable?.() === true+ ? isUsingNativeShortcut+ ? hotkeyManager.supportsPushToTalk(hotkey)+ : this.linuxKeyManager?.isAvailable?.() === true: !isUsingNativeShortcut;return {@@ -3699,6 +3712,9 @@ class IPCHandlers {isUsingKDE: this.windowManager.isUsingKDEHotkeys(),isUsingNativeShortcut,supportsPushToTalk,+ pushToTalkUnavailableReason: supportsPushToTalk+ ? null+ : hotkeyManager.getPushToTalkUnavailableReason(hotkey),};});diff --git a/src/helpers/kdeShortcut.js b/src/helpers/kdeShortcut.jsindex 190571069..0c5084458 100644--- a/src/helpers/kdeShortcut.js+++ b/src/helpers/kdeShortcut.js@@ -203,7 +203,7 @@ class KDEShortcutManager {const callback =this.callbacks.get(shortcutUnique) || this._findCallbackByFriendlyName(shortcutUnique);if (callback) {- callback();+ callback(undefined, "down");} else {debugLogger.log("[KDEShortcut] No callback found for", {shortcutUnique,@@ -211,6 +211,14 @@ class KDEShortcutManager {});}});+ iface.on("globalShortcutReleased", (componentUnique, shortcutUnique) => {+ debugLogger.log("[KDEShortcut] Shortcut released", { componentUnique, shortcutUnique });+ const slotName = this.callbacks.has(shortcutUnique)+ ? shortcutUnique+ : this._findSlotByFriendlyName(shortcutUnique);+ if (slotName !== "dictation") return;+ this.callbacks.get(slotName)?.(undefined, "up");+ });this.componentProxy = iface;debugLogger.log("[KDEShortcut] Listening for globalShortcutPressed on", componentPath);@@ -222,17 +230,21 @@ class KDEShortcutManager {}_findCallbackByFriendlyName(name) {+ const slotName = this._findSlotByFriendlyName(name);+ return slotName ? this.callbacks.get(slotName) : null;+ }++ _findSlotByFriendlyName(name) {// Map friendly names back to slot namesconst friendlyToSlot = {};for (const slotName of this.registeredSlots) {friendlyToSlot[`OpenWhispr ${slotName}`] = slotName;friendlyToSlot[`OpenWhispr`] = "dictation"; // legacy compat}- const slotName = friendlyToSlot[name];- return slotName ? this.callbacks.get(slotName) : null;+ return friendlyToSlot[name] || null;}- async registerKeybinding(electronHotkey, slotName = "dictation", callback) {+ async registerKeybinding(electronHotkey, slotName = "dictation", callback, isPushToTalk = false) {if (!this.kglobalaccel) return false;const qtKey = KDEShortcutManager.convertToQtKeyCode(electronHotkey);@@ -241,14 +253,19 @@ class KDEShortcutManager {return false;}- // Modifier-only shortcuts (e.g. Control+Super) don't work on X11 —- // XGrabKey requires an actual key code, not just modifiers.- // On Wayland, KWin handles modifier-only natively, so allow them.+ // Modifier-only shortcuts (e.g. Control+Super) don't work on X11.+ // KWin accepts them on Wayland, but emits press and release together after+ // the first modifier is released, so they cannot represent push-to-talk.const QT_MODIFIER_MASK = 0xfe000000;- if (!KDEShortcutManager.isWayland() && (qtKey & ~QT_MODIFIER_MASK) === 0) {- debugLogger.log("[KDEShortcut] Modifier-only shortcut not supported on X11", {+ const isModifierOnly = (qtKey & ~QT_MODIFIER_MASK) === 0;+ const modifierOnlyUnsupported =+ isModifierOnly &&+ (!KDEShortcutManager.isWayland() || (slotName === "dictation" && isPushToTalk));+ if (modifierOnlyUnsupported) {+ debugLogger.log("[KDEShortcut] Modifier-only shortcut not supported in this mode", {slot: slotName,hotkey: electronHotkey,+ isPushToTalk,qtKey: `0x${qtKey.toString(16)}`,});return "modifier-only";diff --git a/src/helpers/windowManager.js b/src/helpers/windowManager.jsindex d7515f187..17bdcba5f 100644--- a/src/helpers/windowManager.js+++ b/src/helpers/windowManager.js@@ -496,9 +496,9 @@ class WindowManager {let lastToggleTime = 0;const DEBOUNCE_MS = 150;- // globalShortcut registrations pass the hotkey that fired; native-shortcut- // backends invoke the callback bare (their slot holds only the primary).- return async (triggeredHotkey) => {+ // globalShortcut registrations pass the hotkey that fired; native shortcuts+ // use down/up phases and resolve their primary hotkey from the active slot.+ return async (triggeredHotkey, phase) => {if (this.hotkeyManager.isInListeningMode()) {return;}@@ -509,6 +509,16 @@ class WindowManager {const activationMode = this.getActivationMode();const currentHotkey = triggeredHotkey || this.hotkeyManager.getCurrentHotkey?.();+ if (process.platform === "linux" && activationMode === "push") {+ if (phase === "down") {+ this.startWindowsPushToTalk(currentHotkey);+ } else if (phase === "up") {+ this.handleWindowsPushKeyUp(currentHotkey);+ }+ return;+ }+ if (phase === "up") return;+if (process.platform === "darwin" &&activationMode === "push" &&@@ -681,16 +691,24 @@ class WindowManager {}const MIN_HOLD_DURATION_MS = 150;+ const MAX_PUSH_DURATION_MS = 300000;const downTime = Date.now();this.showDictationPanel({ reposition: true });this.sendPrepareDictation();+ const safetyTimeoutId = setTimeout(() => {+ if (!this.winPushState || this.winPushState.downTime !== downTime) return;+ debugLogger.warn("Native PTT safety timeout", undefined, "ptt");+ this.handleWindowsPushKeyUp();+ }, MAX_PUSH_DURATION_MS);+this.winPushState = {active: true,key,downTime,isRecording: false,+ safetyTimeoutId,};setTimeout(() => {@@ -715,6 +733,10 @@ class WindowManager {return;}+ if (this.winPushState.safetyTimeoutId) {+ clearTimeout(this.winPushState.safetyTimeoutId);+ }+const wasRecording = this.winPushState.isRecording;this.winPushState = null;@@ -900,8 +922,12 @@ class WindowManager {return this._cachedActivationMode;}- setActivationModeCache(mode) {- this._cachedActivationMode = mode === "push" ? "push" : "tap";+ async setActivationModeCache(mode) {+ const nextMode = mode === "push" ? "push" : "tap";+ const success = await this.hotkeyManager.setActivationMode(nextMode);+ if (!success) return false;+ this._cachedActivationMode = nextMode;+ return true;}/**@@ -914,10 +940,9 @@ class WindowManager {if (this.hotkeyManager.isInListeningMode()) return;const activationMode = this.getActivationMode();const nativeListenerKeys = this.hotkeyManager.getNativeListenerKeys(activationMode);- // GNOME/KDE/Hyprland native shortcuts are press-only. They replace the- // low-level listener in tap mode, but push-to-talk still needs raw dictation- // key-down/key-up events; createHotkeyCallback ignores the native press in- // that mode, so keeping only this slot cannot double-fire.+ // Native desktop shortcuts replace the low-level listener in tap mode. In+ // push mode, keep the dictation listener as a release-event fallback; the+ // push state machine makes duplicate backend and low-level phases harmless.const keys = this.hotkeyManager.isUsingNativeShortcut()? activationMode === "push"? nativeListenerKeys.filter((key) => this.hotkeyManager.slotHasHotkey("dictation", key))diff --git a/src/hooks/useHotkeyModeInfo.ts b/src/hooks/useHotkeyModeInfo.tsindex c53c5b876..560824e19 100644--- a/src/hooks/useHotkeyModeInfo.ts+++ b/src/hooks/useHotkeyModeInfo.ts@@ -10,6 +10,7 @@ export interface HotkeyModeInfo {isUsingNativeShortcut: boolean;isUsingHyprland: boolean;supportsPushToTalk: boolean;+ pushToTalkUnavailableReason: string | null;hyprlandConfigStatus: HyprlandConfigStatus | null;}@@ -17,6 +18,7 @@ const DEFAULT_INFO: HotkeyModeInfo = {isUsingNativeShortcut: false,isUsingHyprland: false,supportsPushToTalk: true,+ pushToTalkUnavailableReason: null,hyprlandConfigStatus: null,};@@ -25,14 +27,14 @@ const DEFAULT_INFO: HotkeyModeInfo = {* (native shortcut, Hyprland) and, on Hyprland, whether its config is* persistable. `scope` tags log output for the calling surface.*/-export function useHotkeyModeInfo(scope: string): HotkeyModeInfo {+export function useHotkeyModeInfo(scope: string, hotkey?: string): HotkeyModeInfo {const [modeInfo, setModeInfo] = useState<HotkeyModeInfo>(DEFAULT_INFO);useEffect(() => {let cancelled = false;const checkHotkeyMode = async () => {try {- const info = await window.electronAPI?.getHotkeyModeInfo?.();+ const info = await window.electronAPI?.getHotkeyModeInfo?.(hotkey);if (!info || cancelled) return;const hyprlandConfigStatus = info.isUsingHyprland? ((await window.electronAPI?.getHyprlandConfigStatus?.()) ?? null)@@ -42,6 +44,7 @@ export function useHotkeyModeInfo(scope: string): HotkeyModeInfo {isUsingNativeShortcut: info.isUsingNativeShortcut,isUsingHyprland: info.isUsingHyprland,supportsPushToTalk: info.supportsPushToTalk,+ pushToTalkUnavailableReason: info.pushToTalkUnavailableReason,hyprlandConfigStatus,});} catch (error) {@@ -52,7 +55,7 @@ export function useHotkeyModeInfo(scope: string): HotkeyModeInfo {return () => {cancelled = true;};- }, [scope]);+ }, [scope, hotkey]);return modeInfo;}diff --git a/src/types/electron.ts b/src/types/electron.tsindex a6f57dec0..6d8f78d43 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -1634,11 +1634,13 @@ declare global {// Hotkey managementupdateHotkey: (key: string) => Promise<{ success: boolean; message: string }>;setHotkeyListeningMode?: (enabled: boolean) => Promise<{ success: boolean }>;- getHotkeyModeInfo?: () => Promise<{+ getHotkeyModeInfo?: (hotkey?: string) => Promise<{isUsingGnome: boolean;isUsingHyprland: boolean;+ isUsingKDE: boolean;isUsingNativeShortcut: boolean;supportsPushToTalk: boolean;+ pushToTalkUnavailableReason: string | null;}>;getHyprlandConfigStatus?: () => Promise<{ canWrite: boolean; path: string } | null>;diff --git a/test/helpers/activationModeSelector.test.js b/test/helpers/activationModeSelector.test.jsnew file mode 100644index 000000000..fa1e028c3--- /dev/null+++ b/test/helpers/activationModeSelector.test.js@@ -0,0 +1,34 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const Module = require("node:module");+const React = require("react");+const { renderToStaticMarkup } = require("react-dom/server");++global.React = React;++const originalLoad = Module._load;+Module._load = function loadWithTranslationStub(request, parent, isMain) {+ if (request === "react-i18next") {+ return { useTranslation: () => ({ t: (key) => key }) };+ }+ return originalLoad.call(this, request, parent, isMain);+};+const { ActivationModeSelector } = require("../../src/components/ui/ActivationModeSelector.tsx");+Module._load = originalLoad;++test("an unsupported Hold option stays explained while Tap remains usable", () => {+ const markup = renderToStaticMarkup(+ React.createElement(ActivationModeSelector, {+ value: "tap",+ onChange: () => undefined,+ pushDisabledReason: "Choose a hotkey with a non-modifier key.",+ })+ );+ const buttons = markup.match(/<button[^>]*>/g);++ assert.equal(buttons.length, 2);+ assert.doesNotMatch(buttons[0], /disabled/);+ assert.match(buttons[1], /disabled/);+ assert.match(buttons[1], /title="Choose a hotkey with a non-modifier key\."/);+ assert.match(buttons[1], /aria-label="common\.hold: Choose a hotkey with a non-modifier key\."/);+});diff --git a/test/helpers/gnomeGlobalShortcutsPortal.test.js b/test/helpers/gnomeGlobalShortcutsPortal.test.jsnew file mode 100644index 000000000..4ffaf1663--- /dev/null+++ b/test/helpers/gnomeGlobalShortcutsPortal.test.js@@ -0,0 +1,165 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const { EventEmitter } = require("node:events");+const Module = require("node:module");++const modulePath = require.resolve("../../src/helpers/gnomeGlobalShortcutsPortal");+const originalLoad = Module._load;++function loadPortal(sessionBus, translate = (key) => key) {+ delete require.cache[modulePath];+ const dbusPath = require.resolve("@homebridge/dbus-native");+ require.cache[dbusPath] = { exports: { sessionBus } };+ Module._load = function loadWithMocks(request, parent, isMain) {+ if (request === "./i18nMain") return { i18nMain: { t: translate } };+ return originalLoad.call(this, request, parent, isMain);+ };+ try {+ return require(modulePath);+ } finally {+ Module._load = originalLoad;+ }+}++function createBus() {+ const calls = { invoke: [], invokeDbus: [] };+ const connection = new EventEmitter();+ connection.end = () => undefined;+ const bus = {+ calls,+ connection,+ name: ":1.42",+ signals: new EventEmitter(),+ invoke(message, callback) {+ calls.invoke.push(message);+ if (message.member === "Get") callback(null, ["u", [1]]);+ else callback(null);+ },+ invokeDbus(message, callback) {+ calls.invokeDbus.push(message);+ callback(null, "bus-id");+ },+ mangle(path, iface, member) {+ return JSON.stringify({ path, interface: iface, member });+ },+ addMatch(_match, callback) {+ callback(null);+ },+ removeMatch(_match, callback) {+ callback?.(null);+ },+ };+ return bus;+}++test("initialization sends GetId through the D-Bus helper with complete headers", async () => {+ const bus = createBus();+ const previousFlatpakId = process.env.FLATPAK_ID;+ process.env.FLATPAK_ID = "com.openwhispr.App";+ const GnomeGlobalShortcutsPortal = loadPortal(() => bus);++ try {+ const portal = new GnomeGlobalShortcutsPortal();+ assert.equal(await portal.init(), true);+ assert.deepEqual(bus.calls.invokeDbus, [{ member: "GetId" }]);+ assert.equal(+ bus.calls.invoke.some(({ member }) => member === "GetId"),+ false+ );+ } finally {+ if (previousFlatpakId === undefined) delete process.env.FLATPAK_ID;+ else process.env.FLATPAK_ID = previousFlatpakId;+ }+});++test("D-Bus method calls reject when the service never replies", async () => {+ const GnomeGlobalShortcutsPortal = loadPortal(() => createBus());+ const portal = new GnomeGlobalShortcutsPortal({ callTimeoutMs: 5 });+ portal.bus = { invoke: () => undefined };++ const deadline = new Promise((_, reject) => {+ setTimeout(() => reject(new Error("test deadline expired")), 100);+ });++ await assert.rejects(+ Promise.race([portal._invoke({ member: "Get" }), deadline]),+ /D-Bus call "Get" timed out/+ );+});++test("portal requests time out and remove their response listener", async () => {+ const GnomeGlobalShortcutsPortal = loadPortal(() => createBus());+ const portal = new GnomeGlobalShortcutsPortal({ requestTimeoutMs: 5 });+ const signals = new EventEmitter();+ const removedMatches = [];+ portal.bus = {+ name: ":1.42",+ signals,+ mangle: (path, iface, member) => JSON.stringify({ path, iface, member }),+ addMatch: (_match, callback) => callback(null),+ removeMatch: (match, callback) => {+ removedMatches.push(match);+ callback?.(null);+ },+ invoke: () => undefined,+ };++ const request = portal._request("BindShortcuts", "", [], "request_token");+ const deadline = new Promise((_, reject) => {+ setTimeout(() => reject(new Error("test deadline expired")), 100);+ });+ await assert.rejects(+ Promise.race([request, deadline]),+ /Portal request "BindShortcuts" timed out/+ );+ assert.equal(signals.eventNames().length, 0);+ assert.equal(removedMatches.length, 1);+});++test("close waits for Session.Close before ending the connection", async () => {+ const GnomeGlobalShortcutsPortal = loadPortal(() => createBus());+ const portal = new GnomeGlobalShortcutsPortal();+ let invokeCallback;+ let connectionEnded = false;+ portal.sessionHandle = "/org/freedesktop/portal/desktop/session/1";+ portal.bus = {+ signals: new EventEmitter(),+ invoke(_message, callback) {+ invokeCallback = callback;+ },+ connection: {+ end() {+ connectionEnded = true;+ },+ },+ };++ const closePromise = portal.close();+ assert.equal(connectionEnded, false);+ invokeCallback(null);+ await closePromise;+ assert.equal(connectionEnded, true);+});++test("portal registration uses the current UI language for its description", async () => {+ const GnomeGlobalShortcutsPortal = loadPortal(+ () => createBus(),+ (key) => (key === "onboarding.activation.holdDescription" ? "Mantener mientras hablas" : key)+ );+ const portal = new GnomeGlobalShortcutsPortal();+ let bindBody;+ portal.init = async () => true;+ portal.unregisterKeybinding = async () => undefined;+ portal._listenForShortcutEvents = () => undefined;+ portal._request = async (member, _signature, body) => {+ if (member === "CreateSession") {+ return [["session_handle", ["o", ["/org/freedesktop/portal/desktop/session/1"]]]];+ }+ bindBody = body;+ return [["shortcuts", ["a(sa{sv})", [[["dictation", []]]]]]];+ };++ assert.equal(await portal.registerKeybinding("ALT+R", () => undefined), true);+ const description = bindBody[1][0][1].find(([key]) => key === "description");+ assert.equal(description[1][1], "Mantener mientras hablas");+});diff --git a/test/helpers/gnomeShortcutFormat.test.js b/test/helpers/gnomeShortcutFormat.test.jsindex 6d08097e0..6c06b49f9 100644--- a/test/helpers/gnomeShortcutFormat.test.js+++ b/test/helpers/gnomeShortcutFormat.test.js@@ -62,3 +62,27 @@ test("raw punctuation strings are rejected by the GNOME validator", () => {assert.equal(GnomeShortcutManager.isValidShortcut("<Control>,"), false);assert.equal(GnomeShortcutManager.isValidShortcut("<Control>plus"), true);});++test("portal shortcuts use the XDG modifier syntax", () => {+ assert.equal(+ GnomeShortcutManager.convertToPortalFormat("Control+Shift+Space"),+ "CTRL+SHIFT+space"+ );+ assert.equal(GnomeShortcutManager.convertToPortalFormat("Super+Alt+F8"), "LOGO+ALT+F8");+ assert.equal(GnomeShortcutManager.convertToPortalFormat("Control+Shift+`"), "CTRL+SHIFT+grave");+ assert.equal(GnomeShortcutManager.convertToPortalFormat("Control+Super"), "");+});++test("failed portal registration restores the working GNOME tap binding", async () => {+ const manager = new GnomeShortcutManager();+ const registrations = [];+ manager.unregisterKeybinding = async () => true;+ manager.registerKeybinding = async (shortcut) => {+ registrations.push(shortcut);+ return true;+ };+ manager.globalShortcutsPortal.registerKeybinding = async () => false;++ assert.equal(await manager.registerPushToTalk("Alt+R", () => undefined), false);+ assert.deepEqual(registrations, ["<Alt>r"]);+});diff --git a/test/helpers/hotkeyActivationMode.test.js b/test/helpers/hotkeyActivationMode.test.jsnew file mode 100644index 000000000..9a6f0aad9--- /dev/null+++ b/test/helpers/hotkeyActivationMode.test.js@@ -0,0 +1,46 @@+const test = require("node:test");+const assert = require("node:assert/strict");++require.cache[require.resolve("electron")] = {+ exports: {+ globalShortcut: {+ register: () => true,+ unregister: () => undefined,+ isRegistered: () => false,+ unregisterAll: () => undefined,+ },+ BrowserWindow: class {+ static getAllWindows() {+ return [];+ }+ },+ },+};++const HotkeyManager = require("../../src/helpers/hotkeyManager");++test("native push-to-talk support is hotkey-aware", () => {+ const manager = new HotkeyManager();+ manager.useKDE = true;++ assert.equal(manager.supportsPushToTalk("Control+Super"), false);+ assert.equal(manager.supportsPushToTalk("F8"), true);+});++test("a failed activation-mode registration preserves Tap and notifies the user", async () => {+ const manager = new HotkeyManager();+ const failures = [];+ manager.activationMode = "tap";+ manager.useGnome = true;+ manager.currentHotkey = "Alt+R";+ manager.hotkeyCallback = () => undefined;+ manager.gnomeManager = {+ registerPushToTalk: async () => false,+ };+ manager.notifyHotkeyFailure = (hotkey, result) => failures.push({ hotkey, result });++ assert.equal(await manager.setActivationMode("push"), false);+ assert.equal(manager.activationMode, "tap");+ assert.equal(failures.length, 1);+ assert.equal(failures[0].hotkey, "Alt+R");+});diff --git a/test/helpers/hyprlandShortcut.test.js b/test/helpers/hyprlandShortcut.test.jsindex e66f7c20c..63ad34a11 100644--- a/test/helpers/hyprlandShortcut.test.js+++ b/test/helpers/hyprlandShortcut.test.js@@ -148,6 +148,64 @@ test(}));+test(+ "rejects modifier-only push-to-talk bindings",+ withTempHyprConfig(async (configDir) => {+ fs.mkdirSync(configDir, { recursive: true });+ fs.writeFileSync(path.join(configDir, "hyprland.conf"), "# legacy config\n");+ const hyprctl = successfulHyprctl("hyprlang");+ const HyprlandShortcutManager = loadManager(hyprctl.execFileSync);++ const manager = new HyprlandShortcutManager();+ assert.equal(await manager.registerKeybinding("Control+Super", true), false);+ assert.equal(+ hyprctl.calls.some(({ args }) => args[0] === "keyword"),+ false+ );+ })+);++test(+ "registers keyed legacy push-to-talk press and release bindings",+ withTempHyprConfig(async (configDir) => {+ fs.mkdirSync(configDir, { recursive: true });+ fs.writeFileSync(path.join(configDir, "hyprland.conf"), "# legacy config\n");+ const hyprctl = successfulHyprctl("hyprlang");+ const HyprlandShortcutManager = loadManager(hyprctl.execFileSync);++ const manager = new HyprlandShortcutManager();+ assert.equal(await manager.registerKeybinding("Alt+R", true), true);++ const bindCalls = hyprctl.calls.filter(({ args }) => args[0] === "keyword");+ assert.deepEqual(+ bindCalls.map(({ args }) => args[1]),+ ["unbind", "bindt", "bindrt"]+ );+ assert.match(bindCalls[1].args[2], /PttDown/);+ assert.match(bindCalls[2].args[2], /PttUp/);+ })+);++test(+ "registers Lua push-to-talk bindings through the active runtime API",+ withTempHyprConfig(async (configDir) => {+ fs.mkdirSync(configDir, { recursive: true });+ fs.writeFileSync(path.join(configDir, "hyprland.lua"), "-- lua config\n");+ const hyprctl = successfulHyprctl("lua");+ const HyprlandShortcutManager = loadManager(hyprctl.execFileSync);++ const manager = new HyprlandShortcutManager();+ assert.equal(await manager.registerKeybinding("F8", true), true);++ const runtimeCalls = hyprctl.calls.filter(({ args }) => args[0] === "eval");+ assert.equal(runtimeCalls.length, 3);+ assert.match(runtimeCalls[1].args[1], /PttDown/);+ assert.match(runtimeCalls[1].args[1], /transparent = true/);+ assert.match(runtimeCalls[2].args[1], /PttUp/);+ assert.match(runtimeCalls[2].args[1], /release = true/);+ })+);+test("reuses each exact Lua key string when changing and unregistering a hotkey",withTempHyprConfig(async (configDir) => {diff --git a/test/helpers/kdeShortcutPushToTalk.test.js b/test/helpers/kdeShortcutPushToTalk.test.jsnew file mode 100644index 000000000..a2ef5e27f--- /dev/null+++ b/test/helpers/kdeShortcutPushToTalk.test.js@@ -0,0 +1,66 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const { EventEmitter } = require("node:events");++const KDEShortcutManager = require("../../src/helpers/kdeShortcut");++test("modifier-only KDE shortcuts are rejected for push-to-talk on Wayland", async () => {+ const previousSessionType = process.env.XDG_SESSION_TYPE;+ process.env.XDG_SESSION_TYPE = "wayland";+ const component = new EventEmitter();+ const manager = new KDEShortcutManager();+ manager.bus = {+ invoke(_message, callback) {+ callback(null, []);+ },+ getService() {+ return {+ getInterface(_path, _interface, callback) {+ callback(null, component);+ },+ };+ },+ };+ manager.kglobalaccel = {+ unRegister(_actionId, callback) {+ callback(null);+ },+ doRegister(_actionId, callback) {+ callback(null);+ },+ setShortcut(_actionId, keys, _flags, callback) {+ callback(null, keys);+ },+ };++ try {+ assert.equal(+ await manager.registerKeybinding("Control+Super", "dictation", () => undefined, true),+ "modifier-only"+ );+ } finally {+ if (previousSessionType === undefined) delete process.env.XDG_SESSION_TYPE;+ else process.env.XDG_SESSION_TYPE = previousSessionType;+ }+});++test("KDE release events use the same friendly-name fallback as press events", async () => {+ const component = new EventEmitter();+ const phases = [];+ const manager = new KDEShortcutManager();+ manager.bus = {+ getService() {+ return {+ getInterface(_path, _interface, callback) {+ callback(null, component);+ },+ };+ },+ };+ manager.registeredSlots.add("dictation");+ manager.callbacks.set("dictation", (_hotkey, phase) => phases.push(phase));++ assert.equal(await manager._listenForComponent(), true);+ component.emit("globalShortcutReleased", "openwhispr", "OpenWhispr dictation");+ assert.deepEqual(phases, ["up"]);+});diff --git a/test/helpers/windowManagerAssistantPanel.test.js b/test/helpers/windowManagerAssistantPanel.test.jsindex a401c107b..7493834af 100644--- a/test/helpers/windowManagerAssistantPanel.test.js+++ b/test/helpers/windowManagerAssistantPanel.test.js@@ -150,7 +150,7 @@ test("compact onboarding stays fixed-size but remains minimizable and closable",});});-test("native Linux push-to-talk keeps only the dictation low-level listener", () => {+test("native Linux push-to-talk keeps only the dictation low-level listener", async () => {const originalPlatform = Object.getOwnPropertyDescriptor(process, "platform");Object.defineProperty(process, "platform", { value: "linux", configurable: true });@@ -158,13 +158,14 @@ test("native Linux push-to-talk keeps only the dictation low-level listener", ()const manager = new WindowManager();let reconciledKeys = null;manager.mainWindow = { isDestroyed: () => false };- manager.setActivationModeCache("push");manager.hotkeyManager = {+ setActivationMode: async () => true,isInListeningMode: () => false,isUsingNativeShortcut: () => true,getNativeListenerKeys: () => ["Control+Space", "Control+Shift+Space"],slotHasHotkey: (slot, key) => slot === "dictation" && key === "Control+Space",};+ await manager.setActivationModeCache("push");manager.linuxKeyManager = {setKeys: (keys) => {reconciledKeys = keys;diff --git a/test/helpers/windowManagerMeetingNotification.test.js b/test/helpers/windowManagerMeetingNotification.test.jsindex 2b9cfb5a1..b7afd4c68 100644--- a/test/helpers/windowManagerMeetingNotification.test.js+++ b/test/helpers/windowManagerMeetingNotification.test.js@@ -135,18 +135,26 @@ function installFakeTimers() {let nextTimerId = 1;const timers = new Map();- global.setTimeout = (callback) => {+ global.setTimeout = (callback, delay = 0) => {const timerId = nextTimerId;nextTimerId += 1;- timers.set(timerId, callback);+ timers.set(timerId, { callback, delay });return timerId;};global.clearTimeout = (timerId) => timers.delete(timerId);return {pendingCount: () => timers.size,+ pendingDelays: () => [...timers.values()].map(({ delay }) => delay),+ runDelay: (delay) => {+ for (const [timerId, timer] of [...timers]) {+ if (timer.delay !== delay) continue;+ timers.delete(timerId);+ timer.callback();+ }+ },runAll: () => {- for (const [timerId, callback] of [...timers]) {+ for (const [timerId, { callback }] of [...timers]) {timers.delete(timerId);callback();}@@ -162,6 +170,47 @@ test.beforeEach(() => {createdWindows.length = 0;});+test("native push-to-talk force-stops after the safety timeout", () => {+ const timers = installFakeTimers();+ const manager = createNormalWindowManager();+ let starts = 0;+ let stops = 0;+ manager.showDictationPanel = () => undefined;+ manager.hideDictationPanel = () => undefined;+ manager.sendPrepareDictation = () => undefined;+ manager.sendCancelDictationPreparation = () => undefined;+ manager.sendStartDictation = () => {+ starts += 1;+ };+ manager.sendStopDictation = () => {+ stops += 1;+ };++ try {+ manager.startWindowsPushToTalk("F8");+ assert.deepEqual(+ timers.pendingDelays().sort((left, right) => left - right),+ [150, 300000]+ );++ timers.runDelay(150);+ assert.equal(starts, 1);+ timers.runDelay(300000);+ assert.equal(stops, 1);+ assert.equal(manager.winPushState, null);+ } finally {+ timers.restore();+ }+});++test("a failed activation-mode change preserves the cached mode", async () => {+ const manager = createNormalWindowManager();+ manager.hotkeyManager.setActivationMode = async () => false;++ assert.equal(await manager.setActivationModeCache("push"), false);+ assert.equal(manager.getActivationMode(), "tap");+});+test("a busy Assistant blocks its voice hotkey before native side effects", () => {const manager = createNormalWindowManager();const rendererChannels = [];