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
feat(hotkeys): support multiple hotkeys per action (#936) (#1017)
Aleksei Sachkoc1695f8c7f20
diff --git a/main.js b/main.jsindex dea8437c4..58c33f73a 100644--- a/main.js+++ b/main.js@@ -914,7 +914,9 @@ async function startApp() {ipcMain.handle("register-meeting-hotkey", async (_event, hotkey) => {if (hotkey) {- const result = await hotkeyManager.registerSlot("meeting", hotkey, meetingHotkeyCallback);+ const result = await hotkeyManager.registerSlot("meeting", hotkey, meetingHotkeyCallback, {+ atomic: true,+ });windowManager.reconcileNativeKeyListeners();if (result.success) {environmentManager.saveMeetingKey(hotkey);@@ -1066,8 +1068,9 @@ async function startApp() {windowManager.controlPanelWindow.webContents.send("globe-key-pressed");}- // Handle dictation if Globe/Fn is the current hotkey- if (isGlobeLikeHotkey(currentHotkey)) {+ // Handle dictation if Globe/Fn is one of the dictation hotkeys+ const dictationUsesGlobe = hotkeyManager.getSlotHotkeys("dictation").some(isGlobeLikeHotkey);+ if (dictationUsesGlobe) {if (mainWindowLive) {// Capture target app PID BEFORE showing the overlayif (textEditMonitor) textEditMonitor.captureTargetPid();@@ -1098,17 +1101,17 @@ async function startApp() {}// Check agent and voice agent slots for Globe/Fn key- const agentHotkey = hotkeyManager.getSlotHotkey("agent");- const voiceAgentHotkey = hotkeyManager.getSlotHotkey("voiceAgent");- const agentUsesGlobe = !!agentHotkey && isGlobeLikeHotkey(agentHotkey);- const voiceAgentUsesGlobe = !!voiceAgentHotkey && isGlobeLikeHotkey(voiceAgentHotkey);+ const agentUsesGlobe = hotkeyManager.getSlotHotkeys("agent").some(isGlobeLikeHotkey);+ const voiceAgentUsesGlobe = hotkeyManager+ .getSlotHotkeys("voiceAgent")+ .some(isGlobeLikeHotkey);if (agentUsesGlobe) {windowManager.toggleAgentOverlay();}if (voiceAgentUsesGlobe) {windowManager.sendToggleVoiceAgent();}- if (!agentUsesGlobe && !voiceAgentUsesGlobe && !isGlobeLikeHotkey(currentHotkey)) {+ if (!agentUsesGlobe && !voiceAgentUsesGlobe && !dictationUsesGlobe) {debugLogger?.debug("[Globe] Ignored — hotkey is not GLOBE", { currentHotkey });}});@@ -1121,7 +1124,7 @@ async function startApp() {windowManager.controlPanelWindow.webContents.send("globe-key-released");}- if (hotkeyManager.getCurrentHotkey && isGlobeLikeHotkey(hotkeyManager.getCurrentHotkey())) {+ if (hotkeyManager.getSlotHotkeys("dictation").some(isGlobeLikeHotkey)) {const activationMode = windowManager.getActivationMode();if (activationMode === "push") {globeKeyDownTime = 0;@@ -1148,28 +1151,29 @@ async function startApp() {let rightModDownTime = 0;let rightModIsRecording = false;let rightModLastStopTime = 0;+ let rightModActiveKey = null;globeKeyManager.on("right-modifier-down", async (modifier) => {- const currentHotkey = hotkeyManager.getCurrentHotkey && hotkeyManager.getCurrentHotkey();-// Check agent and voice agent slots for right-modifier- if (hotkeyManager.getSlotHotkey("agent") === modifier) {+ if (hotkeyManager.slotHasHotkey("agent", modifier)) {windowManager.toggleAgentOverlay();}- if (hotkeyManager.getSlotHotkey("voiceAgent") === modifier) {+ if (hotkeyManager.slotHasHotkey("voiceAgent", modifier)) {windowManager.sendToggleVoiceAgent();}- if (currentHotkey !== modifier) return;+ if (!hotkeyManager.slotHasHotkey("dictation", modifier)) return;if (!isLiveWindow(windowManager.mainWindow)) return;const activationMode = windowManager.getActivationMode();if (textEditMonitor) textEditMonitor.captureTargetPid();if (activationMode === "push") {+ if (rightModActiveKey && rightModActiveKey !== modifier) return;const now = Date.now();if (now - rightModLastStopTime < POST_STOP_COOLDOWN_MS) return;windowManager.showDictationPanel();const pressTime = now;+ rightModActiveKey = modifier;rightModDownTime = pressTime;rightModIsRecording = false;setTimeout(() => {@@ -1184,13 +1188,12 @@ async function startApp() {});globeKeyManager.on("right-modifier-up", async (modifier) => {- const currentHotkey = hotkeyManager.getCurrentHotkey && hotkeyManager.getCurrentHotkey();-- if (currentHotkey === modifier) {+ if (hotkeyManager.slotHasHotkey("dictation", modifier)) {if (!isLiveWindow(windowManager.mainWindow)) return;const activationMode = windowManager.getActivationMode();- if (activationMode === "push") {+ if (activationMode === "push" && (!rightModActiveKey || rightModActiveKey === modifier)) {+ rightModActiveKey = null;rightModDownTime = 0;rightModLastStopTime = Date.now();if (rightModIsRecording) {@@ -1216,14 +1219,11 @@ async function startApp() {const syncSuppressedMouseButtons = () => {const buttons = [];- const currentHotkey = hotkeyManager.getCurrentHotkey && hotkeyManager.getCurrentHotkey();- if (isMouseButtonHotkey(currentHotkey)) buttons.push(currentHotkey);-- for (const slotName of ["agent", "voiceAgent"]) {- const slotHotkey = hotkeyManager.getSlotHotkey(slotName);- if (isMouseButtonHotkey(slotHotkey)) buttons.push(slotHotkey);+ for (const slotName of ["dictation", "agent", "voiceAgent"]) {+ for (const hotkey of hotkeyManager.getSlotHotkeys(slotName)) {+ if (isMouseButtonHotkey(hotkey)) buttons.push(hotkey);+ }}-globeKeyManager.setSuppressedMouseButtons(buttons);};@@ -1231,31 +1231,32 @@ async function startApp() {let mouseButtonDownTime = 0;let mouseButtonIsRecording = false;let mouseButtonLastStopTime = 0;+ let mouseButtonActiveButton = null;globeKeyManager.on("mouse-button-down", async (button) => {if (hotkeyManager.isInListeningMode && hotkeyManager.isInListeningMode()) return;if (!isMouseButtonHotkey(button)) return;- const currentHotkey = hotkeyManager.getCurrentHotkey && hotkeyManager.getCurrentHotkey();-- if (hotkeyManager.getSlotHotkey("agent") === button) {+ if (hotkeyManager.slotHasHotkey("agent", button)) {windowManager.toggleAgentOverlay();}- if (hotkeyManager.getSlotHotkey("voiceAgent") === button) {+ if (hotkeyManager.slotHasHotkey("voiceAgent", button)) {windowManager.sendToggleVoiceAgent();}- if (currentHotkey !== button) return;+ if (!hotkeyManager.slotHasHotkey("dictation", button)) return;if (!isLiveWindow(windowManager.mainWindow)) return;const activationMode = windowManager.getActivationMode();if (textEditMonitor) textEditMonitor.captureTargetPid();if (activationMode === "push") {+ if (mouseButtonActiveButton && mouseButtonActiveButton !== button) return;const now = Date.now();if (now - mouseButtonLastStopTime < POST_STOP_COOLDOWN_MS) return;windowManager.showDictationPanel();const pressTime = now;+ mouseButtonActiveButton = button;mouseButtonDownTime = pressTime;mouseButtonIsRecording = false;setTimeout(() => {@@ -1273,12 +1274,15 @@ async function startApp() {if (hotkeyManager.isInListeningMode && hotkeyManager.isInListeningMode()) return;if (!isMouseButtonHotkey(button)) return;- const currentHotkey = hotkeyManager.getCurrentHotkey && hotkeyManager.getCurrentHotkey();- if (currentHotkey !== button) return;+ if (!hotkeyManager.slotHasHotkey("dictation", button)) return;if (!isLiveWindow(windowManager.mainWindow)) return;const activationMode = windowManager.getActivationMode();- if (activationMode === "push") {+ if (+ activationMode === "push" &&+ (!mouseButtonActiveButton || mouseButtonActiveButton === button)+ ) {+ mouseButtonActiveButton = null;mouseButtonDownTime = 0;mouseButtonLastStopTime = Date.now();if (mouseButtonIsRecording) {@@ -1353,34 +1357,34 @@ async function startApp() {// Dictation supports push-to-talk and needs the overlay window; agent/meeting// drive other windows (matching their globalShortcut callbacks and macOS).const dispatchNativeKeyDown = (key) => {- if (key === hotkeyManager.getCurrentHotkey()) {+ if (hotkeyManager.slotHasHotkey("dictation", key)) {if (!isLiveWindow(windowManager.mainWindow)) return;if (windowManager.getActivationMode() === "push") {- windowManager.startWindowsPushToTalk();+ windowManager.startWindowsPushToTalk(key);} else {windowManager.sendToggleDictation();}return;}- if (key === hotkeyManager.getSlotHotkey("voiceAgent")) {+ if (hotkeyManager.slotHasHotkey("voiceAgent", key)) {windowManager.sendToggleVoiceAgent();- } else if (key === hotkeyManager.getSlotHotkey("agent")) {+ } else if (hotkeyManager.slotHasHotkey("agent", key)) {if (!hotkeyManager.isInListeningMode()) windowManager.toggleAgentOverlay();- } else if (key === hotkeyManager.getSlotHotkey("meeting")) {+ } else if (hotkeyManager.slotHasHotkey("meeting", key)) {if (!hotkeyManager.isInListeningMode()) meetingDetectionEngine?.startManualMeeting();}};// Only dictation drives push-to-talk, so only its key-up matters.const dispatchNativeKeyUp = (key) => {- if (key !== hotkeyManager.getCurrentHotkey()) return;+ if (!hotkeyManager.slotHasHotkey("dictation", key)) return;if (windowManager.winPushState?.active) {- windowManager.handleWindowsPushKeyUp();+ windowManager.handleWindowsPushKeyUp(key);} else if (isLiveWindow(windowManager.mainWindow) &&windowManager.getActivationMode() === "push") {- windowManager.handleWindowsPushKeyUp();+ windowManager.handleWindowsPushKeyUp(key);}};diff --git a/preload.js b/preload.jsindex 11fb30c58..3229a2bc9 100644--- a/preload.js+++ b/preload.js@@ -316,8 +316,7 @@ contextBridge.exposeInMainWorld("electronAPI", {// Cleanup functioncleanupApp: () => ipcRenderer.invoke("cleanup-app"),updateHotkey: (hotkey) => ipcRenderer.invoke("update-hotkey", hotkey),- setHotkeyListeningMode: (enabled, newHotkey) =>- ipcRenderer.invoke("set-hotkey-listening-mode", enabled, newHotkey),+ setHotkeyListeningMode: (enabled) => ipcRenderer.invoke("set-hotkey-listening-mode", enabled),getHotkeyModeInfo: () => ipcRenderer.invoke("get-hotkey-mode-info"),getHyprlandConfigStatus: () => ipcRenderer.invoke("get-hyprland-config-status"),startWindowDrag: () => ipcRenderer.invoke("start-window-drag"),diff --git a/src/App.jsx b/src/App.jsxindex 378b01f89..4b31bfc2b 100644--- a/src/App.jsx+++ b/src/App.jsx@@ -5,7 +5,7 @@ import { X } from "lucide-react";import { useToast } from "./components/ui/useToast";import { LoadingDots } from "./components/ui/LoadingDots";import { useHotkey } from "./hooks/useHotkey";-import { formatHotkeyLabel } from "./utils/hotkeys";+import { formatHotkeyListLabel } from "./utils/hotkeys";import { useWindowDrag } from "./hooks/useWindowDrag";import { useAudioRecording } from "./hooks/useAudioRecording";import { useSettingsStore } from "./stores/settingsStore";@@ -294,7 +294,7 @@ export default function App() {case "hover":return {className: `${baseClasses} bg-black/50 cursor-pointer`,- tooltip: formatHotkeyLabel(hotkey),+ tooltip: formatHotkeyListLabel(hotkey),};case "recording":return {diff --git a/src/components/HistoryView.tsx b/src/components/HistoryView.tsxindex 72efff565..31dfbf273 100644--- a/src/components/HistoryView.tsx+++ b/src/components/HistoryView.tsx@@ -1,10 +1,10 @@-import { useMemo } from "react";+import { Fragment, useMemo } from "react";import { useTranslation } from "react-i18next";import { Button } from "./ui/button";import { Loader2, Sparkles, Cloud, X, Mic, Trash2, Archive } from "lucide-react";import TranscriptionItem from "./ui/TranscriptionItem";import type { TranscriptionItem as TranscriptionItemType } from "../types/electron";-import { formatHotkeyLabel } from "../utils/hotkeys";+import { formatHotkeyLabel, parseHotkeyList } from "../utils/hotkeys";import { formatDateGroup } from "../utils/dateFormatting";import { cn } from "./lib/utils";import { useUpcomingEvents } from "../hooks/useUpcomingEvents";@@ -283,9 +283,14 @@ export default function HistoryView({</h3><div className="flex items-center gap-2 text-xs text-foreground/50 dark:text-foreground/25"><span>{t("controlPanel.history.press")}</span>- <kbd className="inline-flex items-center h-5 px-1.5 rounded-sm bg-surface-1 dark:bg-white/6 border border-border/50 text-xs font-mono font-medium text-foreground/60 dark:text-foreground/40">- {formatHotkeyLabel(hotkey)}- </kbd>+ {parseHotkeyList(hotkey).map((hk, index) => (+ <Fragment key={hk}>+ {index > 0 && <span className="text-foreground/30">/</span>}+ <kbd className="inline-flex items-center h-5 px-1.5 rounded-sm bg-surface-1 dark:bg-white/6 border border-border/50 text-xs font-mono font-medium text-foreground/60 dark:text-foreground/40">+ {formatHotkeyLabel(hk)}+ </kbd>+ </Fragment>+ ))}<span>{t("controlPanel.history.toStart")}</span></div></div>diff --git a/src/components/OnboardingFlow.tsx b/src/components/OnboardingFlow.tsxindex 649afa483..da299e058 100644--- a/src/components/OnboardingFlow.tsx+++ b/src/components/OnboardingFlow.tsx@@ -33,7 +33,14 @@ import LanguageSelector from "./ui/LanguageSelector";import AuthenticationStep from "./AuthenticationStep";import EmailVerificationStep from "./EmailVerificationStep";import { setAgentName as saveAgentName } from "../utils/agentName";-import { formatHotkeyLabel, getDefaultHotkey, isGlobeLikeHotkey } from "../utils/hotkeys";+import {+ formatHotkeyLabel,+ formatHotkeyListLabel,+ getDefaultHotkey,+ isGlobeLikeHotkey,+ parseHotkeyList,+ serializeHotkeyList,+} from "../utils/hotkeys";import { useAuth } from "../hooks/useAuth";import { HotkeyInput } from "./ui/HotkeyInput";import { useHotkeyRegistration } from "../hooks/useHotkeyRegistration";@@ -122,7 +129,11 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {const cortiClientId = useSettingsStore((s) => s.cortiClientId);const cortiClientSecret = useSettingsStore((s) => s.cortiClientSecret);- const [hotkey, setHotkey] = useState(dictationKey || getDefaultHotkey());+ // Onboarding edits only the primary dictation hotkey; extra bindings are+ // preserved via withExtraDictationHotkeys.+ const [hotkey, setHotkey] = useState(+ () => parseHotkeyList(dictationKey)[0] || getDefaultHotkey()+ );const [agentName, setAgentName] = useState("OpenWhispr");const [skipAuth, setSkipAuth] = useState(false);const [pendingVerificationEmail, setPendingVerificationEmail] = useState<string | null>(null);@@ -130,7 +141,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {const { isUsingNativeShortcut, isUsingHyprland, hyprlandConfigStatus, supportsPushToTalk } =useHotkeyModeInfo("onboarding");const readableHotkey = formatHotkeyLabel(hotkey);- const readableVoiceAgentKey = formatHotkeyLabel(voiceAgentKey);+ const readableVoiceAgentKey = formatHotkeyListLabel(voiceAgentKey);const { alertDialog, confirmDialog, showAlertDialog, hideAlertDialog, hideConfirmDialog } =useDialogs();const [connectivityDialog, setConnectivityDialog] = useState<{@@ -141,9 +152,15 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {const autoRegisterInFlightRef = useRef(false);const hotkeyStepInitializedRef = useRef(false);+ // Replace the primary dictation hotkey while keeping additional bindings intact.+ const withExtraDictationHotkeys = useCallback(+ (primary: string) => serializeHotkeyList([primary, ...parseHotkeyList(dictationKey).slice(1)]),+ [dictationKey]+ );+const { registerHotkey, isRegistering: isHotkeyRegistering } = useHotkeyRegistration({onSuccess: (registeredHotkey) => {- setHotkey(registeredHotkey);+ setHotkey(parseHotkeyList(registeredHotkey)[0] || registeredHotkey);setDictationKey(registeredHotkey);},showSuccessToast: false,@@ -157,8 +174,12 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {const validateVoiceAgentHotkey = useCallback((newHotkey: string) =>- validateHotkeyForSlot(newHotkey, { "settingsPage.general.hotkey.title": hotkey }, t),- [hotkey, t]+ validateHotkeyForSlot(+ newHotkey,+ { "settingsPage.general.hotkey.title": withExtraDictationHotkeys(hotkey) },+ t+ ),+ [hotkey, withExtraDictationHotkeys, t]);const permissionsHook = usePermissions(showAlertDialog);@@ -281,7 +302,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {// Check if backend already registered a hotkey (e.g., KDE D-Bus fallback)const backendKey = localStorage.getItem("dictationKey");if (backendKey && backendKey.trim() !== "") {- setHotkey(backendKey);+ setHotkey(parseHotkeyList(backendKey)[0] || backendKey);setDictationKey(backendKey);return;}@@ -319,7 +340,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {}try {- const result = await window.electronAPI.updateHotkey(hotkey);+ const result = await window.electronAPI.updateHotkey(withExtraDictationHotkeys(hotkey));if (result && !result.success) {showAlertDialog({title: t("onboarding.hotkey.couldNotRegisterTitle"),@@ -336,14 +357,14 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {});return false;}- }, [hotkey, showAlertDialog, t]);+ }, [hotkey, withExtraDictationHotkeys, showAlertDialog, t]);const saveSettings = useCallback(async () => {const hotkeyRegistered = await ensureHotkeyRegistered();if (!hotkeyRegistered) {return false;}- setDictationKey(hotkey);+ setDictationKey(withExtraDictationHotkeys(hotkey));saveAgentName(agentName);const skippedAuth = skipAuth;@@ -372,6 +393,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {return true;}, [hotkey,+ withExtraDictationHotkeys,agentName,setDictationKey,ensureHotkeyRegistered,@@ -745,7 +767,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {<HotkeyInputvalue={hotkey}onChange={async (newHotkey) => {- const success = await registerHotkey(newHotkey);+ const success = await registerHotkey(withExtraDictationHotkeys(newHotkey));if (success) {setHotkey(newHotkey);}@@ -814,9 +836,15 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {</span></div><HotkeyInput- value={voiceAgentKey}- onChange={setVoiceAgentKey}- onClear={() => setVoiceAgentKey("")}+ value={parseHotkeyList(voiceAgentKey)[0] ?? ""}+ onChange={(newHotkey) =>+ setVoiceAgentKey(+ serializeHotkeyList([newHotkey, ...parseHotkeyList(voiceAgentKey).slice(1)])+ )+ }+ onClear={() =>+ setVoiceAgentKey(serializeHotkeyList(parseHotkeyList(voiceAgentKey).slice(1)))+ }variant="hero"validate={validateVoiceAgentHotkey}/>diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsxindex 00c0697b6..52741693c 100644--- a/src/components/SettingsPage.tsx+++ b/src/components/SettingsPage.tsx@@ -65,7 +65,7 @@ import { useUpdater } from "../hooks/useUpdater";import PromptStudio from "./ui/PromptStudio";import { ProviderTabs } from "./ui/ProviderTabs";-import { HotkeyInput } from "./ui/HotkeyInput";+import { HotkeyListInput } from "./ui/HotkeyListInput";import { useHotkeyRegistration } from "../hooks/useHotkeyRegistration";import { useHotkeyModeInfo } from "../hooks/useHotkeyModeInfo";import { useLocalStorage } from "../hooks/useLocalStorage";@@ -957,6 +957,28 @@ export default function SettingsPage({registerFn: meetingRegisterFn,});+ // Agent hotkey setters resolve to false when main-process registration fails;+ // surface it and return the result so HotkeyListInput rolls the row back.+ const [isAgentHotkeyCommitting, setIsAgentHotkeyCommitting] = useState(false);+ const commitAgentHotkey = useCallback(+ async (setter: (key: string) => Promise<boolean>, key: string) => {+ setIsAgentHotkeyCommitting(true);+ try {+ const ok = await setter(key);+ if (!ok) {+ showAlertDialog({+ title: t("hooks.hotkeyRegistration.titles.notRegistered"),+ description: t("hooks.hotkeyRegistration.errors.failedToRegister"),+ });+ }+ return ok;+ } finally {+ setIsAgentHotkeyCommitting(false);+ }+ },+ [showAlertDialog, t]+ );+const validateDictationHotkey = useCallback((hotkey: string) =>validateHotkeyForSlot(@@ -3222,27 +3244,29 @@ EOF`,/><SettingsPanel><SettingsPanelRow>- <HotkeyInput+ <HotkeyListInputvalue={dictationKey}- onChange={async (newHotkey) => {- await registerHotkey(newHotkey);- }}- disabled={isHotkeyRegistering}+ onChange={(list) => registerHotkey(list)}validate={validateDictationHotkey}+ disabled={isHotkeyRegistering}+ maxHotkeys={isUsingNativeShortcut ? 1 : undefined}+ required+ footerEnd={+ effectiveDefaultHotkey &&+ dictationKey &&+ dictationKey !== effectiveDefaultHotkey ? (+ <button+ onClick={() => registerHotkey(effectiveDefaultHotkey)}+ disabled={isHotkeyRegistering}+ className="text-xs text-muted-foreground/70 hover:text-foreground transition-colors disabled:opacity-50"+ >+ {t("settingsPage.general.hotkey.resetToDefault", {+ hotkey: formatHotkeyLabel(effectiveDefaultHotkey),+ })}+ </button>+ ) : null+ }/>- {effectiveDefaultHotkey &&- dictationKey &&- dictationKey !== effectiveDefaultHotkey && (- <button- onClick={() => registerHotkey(effectiveDefaultHotkey)}- disabled={isHotkeyRegistering}- className="mt-2 text-xs text-muted-foreground/70 hover:text-foreground transition-colors disabled:opacity-50"- >- {t("settingsPage.general.hotkey.resetToDefault", {- hotkey: formatHotkeyLabel(effectiveDefaultHotkey),- })}- </button>- )}</SettingsPanelRow>{(!isUsingNativeShortcut || getCachedPlatform() === "linux") && (@@ -3269,11 +3293,13 @@ EOF`,/><SettingsPanel><SettingsPanelRow>- <HotkeyInput+ <HotkeyListInputvalue={voiceAgentKey}- onChange={setVoiceAgentKey}- onClear={() => setVoiceAgentKey("")}+ onChange={(list) => commitAgentHotkey(setVoiceAgentKey, list)}+ onClear={() => commitAgentHotkey(setVoiceAgentKey, "")}validate={validateVoiceAgentHotkey}+ disabled={isAgentHotkeyCommitting}+ maxHotkeys={isUsingNativeShortcut ? 1 : undefined}/></SettingsPanelRow></SettingsPanel>@@ -3287,17 +3313,16 @@ EOF`,/><SettingsPanel><SettingsPanelRow>- <HotkeyInput+ <HotkeyListInputvalue={meetingKey}- onChange={async (newHotkey) => {- await registerMeetingHotkey(newHotkey);- }}+ onChange={(list) => registerMeetingHotkey(list)}onClear={async () => {await window.electronAPI?.registerMeetingHotkey?.("");setMeetingKey("");}}- disabled={isMeetingHotkeyRegistering}validate={validateMeetingHotkey}+ disabled={isMeetingHotkeyRegistering}+ maxHotkeys={isUsingNativeShortcut ? 1 : undefined}/></SettingsPanelRow><SettingsPanelRow className="flex items-center justify-between gap-3 border-t border-border/40 dark:border-white/5">@@ -3340,11 +3365,13 @@ EOF`,/><SettingsPanel><SettingsPanelRow>- <HotkeyInput+ <HotkeyListInputvalue={chatAgentKey}- onChange={setChatAgentKey}- onClear={() => setChatAgentKey("")}+ onChange={(list) => commitAgentHotkey(setChatAgentKey, list)}+ onClear={() => commitAgentHotkey(setChatAgentKey, "")}validate={validateChatAgentHotkey}+ disabled={isAgentHotkeyCommitting}+ maxHotkeys={isUsingNativeShortcut ? 1 : undefined}/></SettingsPanelRow></SettingsPanel>diff --git a/src/components/onboarding/MeetingSetupStep.tsx b/src/components/onboarding/MeetingSetupStep.tsxindex 542e30335..8c349fb63 100644--- a/src/components/onboarding/MeetingSetupStep.tsx+++ b/src/components/onboarding/MeetingSetupStep.tsx@@ -4,6 +4,7 @@ import { MeetingNotificationCard } from "../MeetingNotificationCard";import { HotkeyInput } from "../ui/HotkeyInput";import { useHotkeyRegistration } from "../../hooks/useHotkeyRegistration";import { validateHotkeyForSlot } from "../../utils/hotkeyValidation";+import { parseHotkeyList, serializeHotkeyList } from "../../utils/hotkeys";interface MeetingSetupStepProps {meetingKey: string;@@ -74,9 +75,12 @@ export default function MeetingSetupStep({</p></div><HotkeyInput- value={meetingKey}+ value={parseHotkeyList(meetingKey)[0] ?? ""}onChange={async (newHotkey) => {- await registerMeetingHotkey(newHotkey);+ // Edits the primary meeting hotkey; extra bindings are preserved.+ await registerMeetingHotkey(+ serializeHotkeyList([newHotkey, ...parseHotkeyList(meetingKey).slice(1)])+ );}}disabled={isRegistering}validate={validateMeetingHotkey}diff --git a/src/components/ui/HotkeyInput.tsx b/src/components/ui/HotkeyInput.tsxindex 2525a2ee1..de0793f80 100644--- a/src/components/ui/HotkeyInput.tsx+++ b/src/components/ui/HotkeyInput.tsx@@ -198,7 +198,6 @@ export function HotkeyInput({const [validationWarning, setValidationWarning] = useState<string | null>(null);const [isFnHeld, setIsFnHeld] = useState(false);const containerRef = useRef<HTMLDivElement>(null);- const lastCapturedHotkeyRef = useRef<string | null>(null);const keyDownTimeRef = useRef<number>(0);const warningTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);const fnHeldRef = useRef(false);@@ -286,7 +285,6 @@ export function HotkeyInput({}setValidationWarning(null);- lastCapturedHotkeyRef.current = hotkey;onChange(hotkey);setIsCapturing(false);setActiveModifiers(new Set());@@ -427,8 +425,7 @@ export function HotkeyInput({setActiveModifiers(new Set());setValidationWarning(null);clearFnHeld();- window.electronAPI?.setHotkeyListeningMode?.(false, lastCapturedHotkeyRef.current);- lastCapturedHotkeyRef.current = null;+ window.electronAPI?.setHotkeyListeningMode?.(false);onBlur?.();}, [onBlur, clearFnHeld]);@@ -440,7 +437,7 @@ export function HotkeyInput({useEffect(() => {return () => {- window.electronAPI?.setHotkeyListeningMode?.(false, null);+ window.electronAPI?.setHotkeyListeningMode?.(false);if (warningTimeoutRef.current) clearTimeout(warningTimeoutRef.current);};}, []);@@ -475,22 +472,25 @@ export function HotkeyInput({const isGlobe = isGlobeLikeHotkey(value);const hotkeyParts = value?.includes("+") ? displayValue.split("+") : [];- // mousedown is prevented so clicking never focuses the container and starts capture+ // mousedown is prevented so clicking never focuses the container and starts+ // capture; focus/key events are stopped so keyboard use doesn't either.const clearButton =onClear && value && !isCapturing && !disabled ? (<buttontype="button"- tabIndex={-1}aria-label={t("hotkeyInput.remove")}onMouseDown={(e) => {e.preventDefault();e.stopPropagation();}}+ onFocus={(e) => e.stopPropagation()}+ onKeyDown={(e) => e.stopPropagation()}+ onKeyUp={(e) => e.stopPropagation()}onClick={(e) => {e.stopPropagation();onClear();}}- className="opacity-0 group-hover:opacity-100 transition-opacity duration-150 text-muted-foreground/50 hover:text-destructive cursor-pointer"+ className="rounded opacity-0 group-hover:opacity-100 focus-visible:opacity-100 outline-none focus-visible:ring-2 focus-visible:ring-ring/30 transition-opacity duration-150 text-muted-foreground/50 hover:text-destructive cursor-pointer"><Trash2 className="w-3.5 h-3.5" /></button>diff --git a/src/components/ui/HotkeyListInput.tsx b/src/components/ui/HotkeyListInput.tsxnew file mode 100644index 000000000..80358c887--- /dev/null+++ b/src/components/ui/HotkeyListInput.tsx@@ -0,0 +1,155 @@+import { useEffect, useState, type ReactNode } from "react";+import { useTranslation } from "react-i18next";+import { Plus } from "lucide-react";+import { Button } from "./button";+import { HotkeyInput } from "./HotkeyInput";+import { parseHotkeyList, serializeHotkeyList } from "../../utils/hotkeys";+import { normalizeHotkey } from "../../utils/hotkeyValidator";+import { getPlatform } from "../../utils/platform";++export interface HotkeyListInputProps {+ /** Comma-separated list of hotkeys (a single hotkey is just a one-item list). */+ value: string;+ /**+ * Called with the new comma-separated list whenever it has at least one entry.+ * If it resolves to `false`, the optimistic UI change is rolled back.+ */+ onChange: (list: string) => unknown;+ /** Called when the list becomes empty (removing the last entry). Omit to make the slot required. */+ onClear?: () => unknown;+ disabled?: boolean;+ /** When true, the last remaining hotkey cannot be removed and the list is never emptied. */+ required?: boolean;+ /** Cap on list size, e.g. 1 on backends that only apply the primary hotkey. */+ maxHotkeys?: number;+ /** Per-hotkey validation (e.g. cross-slot conflicts). Receives a single hotkey. */+ validate?: (hotkey: string) => string | null | undefined;+ /** Optional content shown on the right of the action row (e.g. a "Reset" link). */+ footerEnd?: ReactNode;+}++/**+ * A slot's hotkeys as a stack of editable {@link HotkeyInput} rows plus an+ * "Add another hotkey" button (issue #936). The visible list is optimistic+ * local state so add/remove/edit apply instantly; external `value` changes are+ * adopted, and an `onChange`/`onClear` that resolves to `false` rolls back.+ */+export function HotkeyListInput({+ value,+ onChange,+ onClear,+ disabled = false,+ required = false,+ maxHotkeys = Infinity,+ validate,+ footerEnd,+}: HotkeyListInputProps) {+ const { t } = useTranslation();+ const [items, setItems] = useState<string[]>(() => parseHotkeyList(value));+ const [adding, setAdding] = useState(false);+ const platform = getPlatform();++ // Adopt external changes to `value` (other windows, async revert on failure)+ // without clobbering an in-flight optimistic edit whose round-trip settles to+ // the same list.+ useEffect(() => {+ setItems((current) => {+ const incoming = parseHotkeyList(value);+ return serializeHotkeyList(incoming) === serializeHotkeyList(current) ? current : incoming;+ });+ }, [value]);++ const isSameHotkey = (a: string, b: string) =>+ normalizeHotkey(a, platform) === normalizeHotkey(b, platform);++ // Block binding the same hotkey twice within this slot (normalized, so alias+ // spellings collide too), then defer to the caller's cross-slot validation.+ const makeValidate = (excludeIndex: number) => (hotkey: string) => {+ if (items.some((existing, i) => i !== excludeIndex && isSameHotkey(existing, hotkey))) {+ return t("hotkeyInput.duplicate");+ }+ return validate?.(hotkey);+ };++ // Roll back only if the optimistic value is still current — an external+ // adoption that happened while the round-trip was in flight wins.+ const commit = async (next: string[]) => {+ const previous = items;+ setItems(next);+ const result = await onChange(serializeHotkeyList(next));+ if (result === false) setItems((current) => (current === next ? previous : current));+ };++ const replaceAt = (index: number, next: string) => {+ void commit(items.map((h, i) => (i === index ? next : h)));+ };++ const removeAt = async (index: number) => {+ const remaining = items.filter((_, i) => i !== index);+ if (remaining.length > 0) {+ void commit(remaining);+ return;+ }+ const previous = items;+ setItems(remaining);+ const result = await onClear?.();+ if (result === false) setItems((current) => (current === remaining ? previous : current));+ };++ const addHotkey = (hotkey: string) => {+ setAdding(false);+ if (!hotkey || items.some((existing) => isSameHotkey(existing, hotkey))) return;+ void commit([...items, hotkey]);+ };++ const canRemove = !required || items.length > 1;+ const showAdd = !adding && items.length > 0 && items.length < maxHotkeys;++ return (+ <div className="flex flex-col gap-2">+ {items.map((hotkey, index) => (+ <HotkeyInput+ key={`${hotkey}-${index}`}+ value={hotkey}+ onChange={(next) => replaceAt(index, next)}+ onClear={canRemove ? () => void removeAt(index) : undefined}+ disabled={disabled}+ validate={makeValidate(index)}+ />+ ))}++ {(items.length === 0 || adding) && (+ <HotkeyInput+ value=""+ autoFocus={adding}+ onChange={addHotkey}+ onBlur={() => setAdding(false)}+ disabled={disabled}+ validate={makeValidate(-1)}+ />+ )}++ {(showAdd || footerEnd) && !adding && (+ <div className="flex items-center justify-between gap-3 mt-0.5">+ {showAdd ? (+ <Button+ type="button"+ variant="outline-flat"+ size="sm"+ onClick={() => setAdding(true)}+ disabled={disabled}+ >+ <Plus className="w-3.5 h-3.5" />+ {t("hotkeyInput.addAnother")}+ </Button>+ ) : (+ <span />+ )}+ {footerEnd}+ </div>+ )}+ </div>+ );+}++export default HotkeyListInput;diff --git a/src/helpers/hotkeyList.js b/src/helpers/hotkeyList.jsnew file mode 100644index 000000000..31c624e21--- /dev/null+++ b/src/helpers/hotkeyList.js@@ -0,0 +1,52 @@+// Parsing/serialization for hotkey lists (#936), stored as comma-separated+// strings — backward compatible with legacy single-value entries. The comma+// KEY is itself a valid hotkey (e.g. "Control+,"): no accelerator legitimately+// ends with "+", so a split segment ending in "+" gets its comma restored.+//+// Keep in sync with the renderer twin in src/utils/hotkeys.ts.++const HOTKEY_LIST_SEPARATOR = ",";++/**+ * Normalize a stored hotkey value (string, comma-separated string, or array)+ * into a clean array: trimmed, de-duplicated, empties removed, order preserved.+ *+ * @param {string|string[]|null|undefined} value+ * @returns {string[]}+ */+function parseHotkeyList(value) {+ if (value == null) return [];++ const raw = Array.isArray(value)+ ? value.flatMap((item) => String(item).split(HOTKEY_LIST_SEPARATOR))+ : String(value).split(HOTKEY_LIST_SEPARATOR);++ const seen = new Set();+ const result = [];+ for (let i = 0; i < raw.length; i++) {+ let hotkey = raw[i].trim();+ // A non-final segment ending in "+" lost its comma key to the split.+ if (hotkey.endsWith("+") && i < raw.length - 1) {+ hotkey += HOTKEY_LIST_SEPARATOR;+ }+ if (!hotkey || seen.has(hotkey)) continue;+ seen.add(hotkey);+ result.push(hotkey);+ }+ return result;+}++/**+ * Serialize a hotkey value into the canonical comma-separated storage string.+ *+ * @param {string|string[]|null|undefined} value+ * @returns {string}+ */+function serializeHotkeyList(value) {+ return parseHotkeyList(value).join(HOTKEY_LIST_SEPARATOR);+}++module.exports = {+ parseHotkeyList,+ serializeHotkeyList,+};diff --git a/src/helpers/hotkeyManager.js b/src/helpers/hotkeyManager.jsindex ced388f47..249065464 100644--- a/src/helpers/hotkeyManager.js+++ b/src/helpers/hotkeyManager.js@@ -5,6 +5,7 @@ const GnomeShortcutManager = require("./gnomeShortcut");const HyprlandShortcutManager = require("./hyprlandShortcut");const KDEShortcutManager = require("./kdeShortcut");const { i18nMain } = require("./i18nMain");+const { parseHotkeyList } = require("./hotkeyList");// Delay to ensure localStorage is accessible after window loadconst HOTKEY_REGISTRATION_DELAY_MS = 1000;@@ -82,9 +83,11 @@ const SUGGESTED_HOTKEYS = {class HotkeyManager extends EventEmitter {constructor() {super();+ // Each slot holds a list of hotkeys (#936). `accelerators` mirrors `hotkeys`+ // index-for-index (null for native-listener entries).this.slots = new Map();const defaultDictation = process.platform === "darwin" ? "GLOBE" : "Control+Super";- this.slots.set("dictation", { hotkey: defaultDictation, callback: null, accelerator: null });+ this.slots.set("dictation", { hotkeys: [defaultDictation], callback: null, accelerators: [] });this.isInitialized = false;this.isListeningMode = false;this.gnomeManager = null;@@ -95,14 +98,26 @@ class HotkeyManager extends EventEmitter {this.useKDE = false;}- // Backward-compatible property accessors+ // Ensure a slot exists and return it (slots always use the list shape).+ _ensureSlot(slotName) {+ let slot = this.slots.get(slotName);+ if (!slot) {+ slot = { hotkeys: [], callback: null, accelerators: [] };+ this.slots.set(slotName, slot);+ }+ if (!Array.isArray(slot.hotkeys)) slot.hotkeys = [];+ if (!Array.isArray(slot.accelerators)) slot.accelerators = [];+ return slot;+ }++ // Primary (first) dictation hotkey; setting it replaces the whole list.get currentHotkey() {- return this.slots.get("dictation")?.hotkey ?? null;+ return this.slots.get("dictation")?.hotkeys?.[0] ?? null;}set currentHotkey(value) {- const slot = this.slots.get("dictation") || { hotkey: null, callback: null, accelerator: null };- slot.hotkey = value;+ const slot = this._ensureSlot("dictation");+ slot.hotkeys = value ? [value] : [];this.slots.set("dictation", slot);}@@ -111,7 +126,7 @@ class HotkeyManager extends EventEmitter {}set hotkeyCallback(value) {- const slot = this.slots.get("dictation") || { hotkey: null, callback: null, accelerator: null };+ const slot = this._ensureSlot("dictation");slot.callback = value;this.slots.set("dictation", slot);}@@ -167,8 +182,28 @@ class HotkeyManager extends EventEmitter {return suggestions.filter((s) => s !== failedHotkey).slice(0, 3);}- async registerSlot(slotName, hotkey, callback) {- this.unregisterSlot(slotName);+ async registerSlot(slotName, hotkeyInput, callback, options) {+ const hotkeys = parseHotkeyList(hotkeyInput);+ if (hotkeys.length === 0) {+ return {+ success: false,+ error: i18nMain.t("hotkey.errors.registrationFailed", {+ hotkey: String(hotkeyInput ?? ""),+ }),+ };+ }+ // GNOME/KDE/Hyprland bind one accelerator per slot, so they use the primary+ // (first) hotkey; the globalShortcut path below registers the whole list.+ const hotkey = hotkeys[0];+ if (+ hotkeys.length > 1 &&+ ((this.useGnome && GNOME_NATIVE_SLOTS.has(slotName)) ||+ (this.useKDE && slotName !== "cancel"))+ ) {+ debugLogger.log(+ `[HotkeyManager] Slot "${slotName}" has ${hotkeys.length} hotkeys but this Linux desktop backend only applies the primary ("${hotkey}")`+ );+ }// On GNOME (X11 or Wayland), route named slots through native gsettingsif (this.useGnome && this.gnomeManager && GNOME_NATIVE_SLOTS.has(slotName)) {@@ -183,6 +218,8 @@ class HotkeyManager extends EventEmitter {};}+ this.unregisterSlot(slotName);+if (slotName === "agent") {this.gnomeManager.setAgentCallback(callback);} else if (slotName === "meeting") {@@ -202,10 +239,10 @@ class HotkeyManager extends EventEmitter {};}- const slot = this.slots.get(slotName) || { hotkey: null, callback: null, accelerator: null };- slot.hotkey = hotkey;+ const slot = this._ensureSlot(slotName);+ slot.hotkeys = [hotkey];slot.callback = callback;- slot.accelerator = null;+ slot.accelerators = [];this.slots.set(slotName, slot);debugLogger.log(@@ -218,6 +255,8 @@ class HotkeyManager extends EventEmitter {// Temporary slots like "cancel" stay on globalShortcut to avoid stale// KGlobalAccel registrations after crash (Escape would stop working system-wide).if (this.useKDE && this.kdeManager && slotName !== "cancel") {+ this.unregisterSlot(slotName);+if (slotName === "agent") {this.kdeManager.setAgentCallback(callback);}@@ -234,19 +273,19 @@ class HotkeyManager extends EventEmitter {return { success: false, error: reason };}- const slot = this.slots.get(slotName) || { hotkey: null, callback: null, accelerator: null };- slot.hotkey = hotkey;+ const slot = this._ensureSlot(slotName);+ slot.hotkeys = [hotkey];slot.callback = callback;- slot.accelerator = null;+ slot.accelerators = [];this.slots.set(slotName, slot);debugLogger.log(`[HotkeyManager] KDE slot "${slotName}" set to "${hotkey}"`);return { success: true, hotkey };}- const result = this.setupShortcuts(hotkey, callback, slotName);+ const result = this.setupShortcuts(hotkeys, callback, slotName, options);if (result.success) {- const slot = this.slots.get(slotName) || {};+ const slot = this._ensureSlot(slotName);slot.callback = callback;this.slots.set(slotName, slot);}@@ -255,7 +294,7 @@ class HotkeyManager extends EventEmitter {unregisterSlot(slotName) {const slot = this.slots.get(slotName);- if (!slot || !slot.hotkey) return;+ if (!slot || !(slot.hotkeys && slot.hotkeys.length)) return;// On KDE (X11 or Wayland), persistent slots are managed via KGlobalAccelif (this.useKDE && this.kdeManager && slotName !== "cancel") {@@ -265,8 +304,8 @@ class HotkeyManager extends EventEmitter {err.message);});- slot.hotkey = null;- slot.accelerator = null;+ slot.hotkeys = [];+ slot.accelerators = [];return;}@@ -278,31 +317,54 @@ class HotkeyManager extends EventEmitter {err.message);});- slot.hotkey = null;- slot.accelerator = null;+ slot.hotkeys = [];+ slot.accelerators = [];return;}- const hk = slot.hotkey;- if (- !isGlobeLikeHotkey(hk) &&- !isMouseButtonHotkey(hk) &&- !isRightSideModifier(hk) &&- !isModifierOnlyHotkey(hk)- ) {- const accel = normalizeToAccelerator(hk);- try {- globalShortcut.unregister(accel);- } catch {- // already unregistered+ for (const hk of slot.hotkeys || []) {+ if (+ !isGlobeLikeHotkey(hk) &&+ !isMouseButtonHotkey(hk) &&+ !isRightSideModifier(hk) &&+ !isModifierOnlyHotkey(hk)+ ) {+ const accel = normalizeToAccelerator(hk);+ try {+ globalShortcut.unregister(accel);+ } catch {+ // already unregistered+ }}}- slot.hotkey = null;- slot.accelerator = null;+ slot.hotkeys = [];+ slot.accelerators = [];}+ // Primary (first) hotkey for a slot — back-compat for callers that expect a+ // single value (display, GNOME/KDE native paths).getSlotHotkey(slotName) {- return this.slots.get(slotName)?.hotkey ?? null;+ return this.slots.get(slotName)?.hotkeys?.[0] ?? null;+ }++ // Full list of hotkeys bound to a slot.+ getSlotHotkeys(slotName) {+ return [...(this.slots.get(slotName)?.hotkeys ?? [])];+ }++ // True if `key` is one of the hotkeys bound to `slotName`.+ slotHasHotkey(slotName, key) {+ if (!key) return false;+ return (this.slots.get(slotName)?.hotkeys ?? []).includes(key);+ }++ // Name of the slot that owns `key`, or null. First match wins.+ findSlotByHotkey(key) {+ if (!key) return null;+ for (const [slotName, slot] of this.slots) {+ if ((slot.hotkeys ?? []).includes(key)) return slotName;+ }+ return null;}/**@@ -311,165 +373,195 @@ class HotkeyManager extends EventEmitter {* register through globalShortcut, and in push-to-talk mode dictation also needs* raw key-down/key-up events. Only the dictation slot supports push-to-talk;* every other slot is tap-to-toggle. Globe/mouse hotkeys are macOS-only.+ * Each slot may bind several hotkeys, so we evaluate every one.*/getNativeListenerKeys(activationMode) {const keys = [];for (const [slotName, slot] of this.slots) {- const hotkey = slot.hotkey;- if (!hotkey || isGlobeLikeHotkey(hotkey) || isMouseButtonHotkey(hotkey)) continue;- const pushToTalk = slotName === "dictation" && activationMode === "push";- if (pushToTalk || isModifierOnlyHotkey(hotkey) || isRightSideModifier(hotkey)) {- keys.push(hotkey);+ for (const hotkey of slot.hotkeys ?? []) {+ if (!hotkey || isGlobeLikeHotkey(hotkey) || isMouseButtonHotkey(hotkey)) continue;+ const pushToTalk = slotName === "dictation" && activationMode === "push";+ if (pushToTalk || isModifierOnlyHotkey(hotkey) || isRightSideModifier(hotkey)) {+ keys.push(hotkey);+ }}}return keys;}- setupShortcuts(hotkey = "Control+Super", callback, slotName = "dictation") {- if (!callback) {- throw new Error(i18nMain.t("hotkey.errors.callbackRequired"));- }-- const slot = this.slots.get(slotName) || { hotkey: null, callback: null, accelerator: null };- this.slots.set(slotName, slot);-- debugLogger.log(`[HotkeyManager] Setting up hotkey: "${hotkey}" for slot "${slotName}"`);- debugLogger.log(`[HotkeyManager] Platform: ${process.platform}, Arch: ${process.arch}`);- debugLogger.log(`[HotkeyManager] Current hotkey for slot: "${slot.hotkey}"`);-- const checkAccelerator = normalizeToAccelerator(hotkey);- if (- hotkey === slot.hotkey &&- !isGlobeLikeHotkey(hotkey) &&- !isMouseButtonHotkey(hotkey) &&- !isRightSideModifier(hotkey) &&- !isModifierOnlyHotkey(hotkey) &&- globalShortcut.isRegistered(checkAccelerator)- ) {- debugLogger.log(- `[HotkeyManager] Hotkey "${hotkey}" is already registered for slot "${slotName}", no change needed`- );- return { success: true, hotkey };- }-- const previousHotkey = slot.hotkey;-- // Unregister the previous hotkey for this slot (skip native-listener-only hotkeys)- if (- previousHotkey &&- !isGlobeLikeHotkey(previousHotkey) &&- !isMouseButtonHotkey(previousHotkey) &&- !isRightSideModifier(previousHotkey) &&- !isModifierOnlyHotkey(previousHotkey)- ) {- const prevAccelerator = normalizeToAccelerator(previousHotkey);- try {- debugLogger.log(`[HotkeyManager] Unregistering previous hotkey: "${prevAccelerator}"`);- globalShortcut.unregister(prevAccelerator);- } catch (error) {- debugLogger.warn(- `[HotkeyManager] Skipping previous hotkey unregister for non-accelerator "${prevAccelerator}": ${error.message}`- );- }- }-+ // Register one hotkey without mutating any slot. `accelerator` is null for+ // hotkeys handled by native listeners.+ _registerSingleHotkey(hotkey, callback) {try {- const conflict = this._findSlotConflict(slotName, hotkey);- if (conflict) return conflict;-if (isMouseButtonHotkey(hotkey)) {if (process.platform !== "darwin") {- return {- success: false,- error: i18nMain.t("hotkey.errors.mouseButtonOnlyMac"),- };+ return { success: false, hotkey, error: i18nMain.t("hotkey.errors.mouseButtonOnlyMac") };}- slot.hotkey = hotkey;- slot.accelerator = null;debugLogger.log(`[HotkeyManager] Mouse button "${hotkey}" set - using macOS native listener`);- return { success: true, hotkey };+ return { success: true, hotkey, accelerator: null };}if (isGlobeLikeHotkey(hotkey)) {if (process.platform !== "darwin") {debugLogger.log("[HotkeyManager] GLOBE key rejected - not on macOS");- return {- success: false,- error: i18nMain.t("hotkey.errors.globeOnlyMac"),- };+ return { success: false, hotkey, error: i18nMain.t("hotkey.errors.globeOnlyMac") };}- slot.hotkey = hotkey;- slot.accelerator = null;debugLogger.log(`[HotkeyManager] GLOBE/Fn key "${hotkey}" set successfully`);- return { success: true, hotkey };+ return { success: true, hotkey, accelerator: null };}if (isRightSideModifier(hotkey)) {- slot.hotkey = hotkey;- slot.accelerator = null;debugLogger.log(`[HotkeyManager] Right-side modifier "${hotkey}" set - using native listener`);- return { success: true, hotkey };+ return { success: true, hotkey, accelerator: null };}if (isModifierOnlyHotkey(hotkey) && process.platform === "win32") {- slot.hotkey = hotkey;- slot.accelerator = null;debugLogger.log(`[HotkeyManager] Modifier-only "${hotkey}" set - using Windows native listener`);- return { success: true, hotkey };+ return { success: true, hotkey, accelerator: null };}const accelerator = normalizeToAccelerator(hotkey);-- const alreadyRegistered = globalShortcut.isRegistered(accelerator);- debugLogger.log(- `[HotkeyManager] Is "${accelerator}" already registered? ${alreadyRegistered}`- );-if (process.platform === "linux") {globalShortcut.unregister(accelerator);}- const success = globalShortcut.register(accelerator, callback);+ // Pass the triggering hotkey so shared callbacks act on the one that fired.+ const success = globalShortcut.register(accelerator, () => callback(hotkey));debugLogger.log(`[HotkeyManager] Registration result for "${hotkey}": ${success}`);-if (success) {- slot.hotkey = hotkey;- slot.accelerator = accelerator;- debugLogger.log(`[HotkeyManager] Hotkey "${hotkey}" registered successfully`);- return { success: true, hotkey };- } else {- const failureInfo = this.getFailureReason(accelerator);- debugLogger.error("Failed to register hotkey", { error: hotkey, ...failureInfo }, "hotkey");- debugLogger.log(`[HotkeyManager] Registration failed:`, failureInfo);+ return { success: true, hotkey, accelerator };+ }++ const failureInfo = this.getFailureReason(accelerator);+ debugLogger.error("Failed to register hotkey", { error: hotkey, ...failureInfo }, "hotkey");+ return {+ success: false,+ hotkey,+ error: failureInfo.message,+ reason: failureInfo.reason,+ suggestions: failureInfo.suggestions,+ };+ } catch (error) {+ debugLogger.error("Error setting up shortcut", { error: error.message }, "hotkey");+ return { success: false, hotkey, error: error.message };+ }+ }- this._restorePreviousHotkey(previousHotkey, callback);+ /**+ * Register a slot's hotkey list (string, comma-separated string, or array).+ * Default is best-effort: succeeds if at least one hotkey registers, with+ * individual failures in `result.failures`. `atomic: true` rolls the whole+ * slot back to its previous bindings on any failure.+ */+ setupShortcuts(+ hotkeyInput = "Control+Super",+ callback,+ slotName = "dictation",+ { atomic = false } = {}+ ) {+ if (!callback) {+ throw new Error(i18nMain.t("hotkey.errors.callbackRequired"));+ }- let errorMessage = failureInfo.message;- if (failureInfo.suggestions.length > 0) {- errorMessage += ` ${i18nMain.t("hotkey.errors.trySuggestions", {- suggestions: failureInfo.suggestions.join(", "),- })}`;- }+ const slot = this._ensureSlot(slotName);+ const desired = parseHotkeyList(hotkeyInput);- return {- success: false,- error: errorMessage,- reason: failureInfo.reason,- suggestions: failureInfo.suggestions,- };+ debugLogger.log(+ `[HotkeyManager] Setting up hotkeys: "${desired.join(", ")}" for slot "${slotName}"`+ );+ debugLogger.log(`[HotkeyManager] Platform: ${process.platform}, Arch: ${process.arch}`);+ debugLogger.log(+ `[HotkeyManager] Current hotkeys for slot: "${(slot.hotkeys || []).join(", ")}"`+ );++ if (desired.length === 0) {+ return {+ success: false,+ error: i18nMain.t("hotkey.errors.registrationFailed", { hotkey: "" }),+ };+ }++ // Reject if any desired hotkey conflicts with another slot before tearing+ // down this slot's current registration.+ for (const hotkey of desired) {+ const conflict = this._findSlotConflict(slotName, hotkey);+ if (conflict) return conflict;+ }++ const previousHotkeys = [...(slot.hotkeys || [])];+ const previousAccelerators = [...(slot.accelerators || [])];++ // Unregister this slot's previous globalShortcut accelerators.+ for (const prevAccel of previousAccelerators) {+ if (!prevAccel) continue;+ try {+ debugLogger.log(`[HotkeyManager] Unregistering previous accelerator: "${prevAccel}"`);+ globalShortcut.unregister(prevAccel);+ } catch (error) {+ debugLogger.warn(+ `[HotkeyManager] Skipping previous unregister for "${prevAccel}": ${error.message}`+ );}- } catch (error) {- debugLogger.error("Error setting up shortcuts", { error: error.message }, "hotkey");- debugLogger.log(`[HotkeyManager] Exception during registration:`, error.message);- this._restorePreviousHotkey(previousHotkey, callback);- return { success: false, error: error.message };}++ const registeredHotkeys = [];+ const registeredAccelerators = [];+ const failures = [];+ for (const hotkey of desired) {+ const res = this._registerSingleHotkey(hotkey, callback);+ if (res.success) {+ registeredHotkeys.push(res.hotkey);+ registeredAccelerators.push(res.accelerator ?? null);+ } else {+ failures.push(res);+ }+ }++ if (registeredHotkeys.length === 0 || (atomic && failures.length > 0)) {+ // Roll back: unregister anything we just registered, then restore the+ // previous bindings so the slot keeps working.+ registeredAccelerators.forEach((accel) => {+ if (!accel) return;+ try {+ globalShortcut.unregister(accel);+ } catch {+ // already unregistered+ }+ });+ this._restorePreviousHotkeys(previousHotkeys, previousAccelerators, callback);+ slot.hotkeys = previousHotkeys;+ slot.accelerators = previousAccelerators;++ const failureInfo = failures[0] || {};+ let errorMessage =+ failureInfo.error || i18nMain.t("hotkey.errors.registrationFailed", { hotkey: desired[0] });+ const suggestions = failureInfo.suggestions || [];+ if (suggestions.length > 0) {+ errorMessage += ` ${i18nMain.t("hotkey.errors.trySuggestions", {+ suggestions: suggestions.join(", "),+ })}`;+ }+ return { success: false, error: errorMessage, reason: failureInfo.reason, suggestions };+ }++ slot.hotkeys = registeredHotkeys;+ slot.accelerators = registeredAccelerators;+ slot.callback = callback;+ debugLogger.log(+ `[HotkeyManager] Slot "${slotName}" registered: "${registeredHotkeys.join(", ")}"`+ );++ const result = { success: true, hotkey: registeredHotkeys[0], hotkeys: registeredHotkeys };+ if (failures.length > 0) {+ result.failures = failures.map((f) => ({ hotkey: f.hotkey, error: f.error }));+ }+ return result;}_findSlotConflict(slotName, hotkey) {@@ -483,8 +575,10 @@ class HotkeyManager extends EventEmitter {for (const [otherSlotName, otherSlot] of this.slots) {if (otherSlotName === slotName) continue;+ const otherHotkeys = otherSlot.hotkeys || [];+ const otherAccelerators = otherSlot.accelerators || [];const match =- otherSlot.hotkey === hotkey || (accelerator && otherSlot.accelerator === accelerator);+ otherHotkeys.includes(hotkey) || (accelerator && otherAccelerators.includes(accelerator));if (match) {debugLogger.warn(`[HotkeyManager] Hotkey "${hotkey}" conflicts with slot "${otherSlotName}"`@@ -503,31 +597,27 @@ class HotkeyManager extends EventEmitter {return null;}- _restorePreviousHotkey(previousHotkey, callback) {- if (- !previousHotkey ||- isGlobeLikeHotkey(previousHotkey) ||- isMouseButtonHotkey(previousHotkey) ||- isRightSideModifier(previousHotkey) ||- isModifierOnlyHotkey(previousHotkey)- ) {- return;- }- const prevAccel = normalizeToAccelerator(previousHotkey);- try {- const restored = globalShortcut.register(prevAccel, callback);- if (restored) {- debugLogger.log(- `[HotkeyManager] Restored previous hotkey "${previousHotkey}" after failed registration`+ _restorePreviousHotkeys(previousHotkeys, previousAccelerators, callback) {+ (previousHotkeys || []).forEach((previousHotkey, i) => {+ // Native-listener entries (null accelerator) are re-armed by+ // reconcileNativeKeyListeners instead.+ const prevAccel = previousAccelerators?.[i];+ if (!prevAccel) return;+ try {+ const restored = globalShortcut.register(prevAccel, () => callback(previousHotkey));+ if (restored) {+ debugLogger.log(+ `[HotkeyManager] Restored previous hotkey "${previousHotkey}" after failed registration`+ );+ } else {+ debugLogger.warn(`[HotkeyManager] Could not restore previous hotkey "${previousHotkey}"`);+ }+ } catch (err) {+ debugLogger.warn(+ `[HotkeyManager] Exception restoring previous hotkey "${previousHotkey}": ${err.message}`);- } else {- debugLogger.warn(`[HotkeyManager] Could not restore previous hotkey "${previousHotkey}"`);}- } catch (err) {- debugLogger.warn(- `[HotkeyManager] Exception restoring previous hotkey "${previousHotkey}": ${err.message}`- );- }+ });}async initializeGnomeShortcuts(callback) {@@ -637,7 +727,8 @@ class HotkeyManager extends EventEmitter {if (gnomeOk) {const registerGnomeHotkey = async () => {try {- const hotkey = await this.getSavedHotkey();+ // 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);@@ -682,7 +773,8 @@ class HotkeyManager extends EventEmitter {if (hyprlandOk) {const registerHyprlandHotkey = async () => {try {- const hotkey = await this.getSavedHotkey();+ // 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);if (success) {@@ -724,7 +816,8 @@ class HotkeyManager extends EventEmitter {if (kdeOk) {const registerKDEHotkey = async () => {try {- const hotkey = await this.getSavedHotkey();+ // 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);if (result === true) {this.currentHotkey = hotkey;@@ -778,6 +871,7 @@ class HotkeyManager extends EventEmitter {if (envHotkey) {const result = this.setupShortcuts(envHotkey, callback);if (result.success) {+ this._notifyStartupRegistration(envHotkey, result);debugLogger.log(`[HotkeyManager] Hotkey "${envHotkey}" registered from env`);} else {debugLogger.log(`[HotkeyManager] Env hotkey "${envHotkey}" failed, waiting for page`);@@ -823,7 +917,7 @@ class HotkeyManager extends EventEmitter {if (savedHotkey && savedHotkey.trim() !== "") {const result = this.setupShortcuts(savedHotkey, callback);if (result.success) {- this.notifyActiveHotkey(savedHotkey);+ this._notifyStartupRegistration(savedHotkey, result);debugLogger.log(`[HotkeyManager] Restored saved hotkey: "${savedHotkey}"`);return;}@@ -1002,6 +1096,14 @@ class HotkeyManager extends EventEmitter {}}+ // Tell the renderer which hotkeys actually registered and which failed.+ _notifyStartupRegistration(requestedHotkey, result) {+ this.notifyActiveHotkey(result.hotkeys ? result.hotkeys.join(",") : requestedHotkey);+ for (const failure of result.failures || []) {+ this.notifyHotkeyFailure(failure.hotkey, failure);+ }+ }+notifyHotkeyFallback(originalHotkey, fallbackHotkey) {if (this.mainWindow && !this.mainWindow.isDestroyed()) {this.mainWindow.webContents.send("hotkey-fallback-used", {@@ -1021,43 +1123,43 @@ class HotkeyManager extends EventEmitter {}}- async updateHotkey(hotkey, callback) {+ async updateHotkey(hotkeyInput, callback) {if (!callback) {throw new Error("Callback function is required for hotkey update");}try {- const conflict = this._findSlotConflict("dictation", hotkey);- if (conflict) {- return { success: false, message: conflict.error, reason: conflict.reason };+ const hotkeys = parseHotkeyList(hotkeyInput);+ if (hotkeys.length === 0) {+ return {+ success: false,+ message: i18nMain.t("hotkey.errors.registrationFailed", { hotkey: "" }),+ };}-- if (isMouseButtonHotkey(hotkey)) {- const result = this.setupShortcuts(hotkey, callback);- if (result.success) {- const saved = await this.saveHotkeyToRenderer(hotkey);- if (!saved) {- debugLogger.warn(- "[HotkeyManager] Mouse button hotkey set but failed to persist to localStorage"- );- }- return { success: true, message: `Hotkey updated to: ${hotkey}` };+ const hotkeyStr = hotkeys.join(",");+ // DE backends bind one accelerator per slot; extras stay in storage.+ const primary = hotkeys[0];++ for (const hotkey of hotkeys) {+ const conflict = this._findSlotConflict("dictation", hotkey);+ if (conflict) {+ return { success: false, message: conflict.error, reason: conflict.reason };}- return { success: false, message: result.error };}if (this.useGnome && this.gnomeManager) {- debugLogger.log(`[HotkeyManager] Updating GNOME hotkey to "${hotkey}"`);- const gnomeHotkey = GnomeShortcutManager.convertToGnomeFormat(hotkey);+ debugLogger.log(`[HotkeyManager] Updating GNOME hotkey to "${primary}"`);+ const gnomeHotkey = GnomeShortcutManager.convertToGnomeFormat(primary);const success = await this.gnomeManager.updateKeybinding(gnomeHotkey);if (!success) {return {success: false,- message: `Failed to update GNOME hotkey to "${hotkey}". Check the format is valid.`,+ message: i18nMain.t("hotkey.errors.updateFailedCheckFormat", { hotkey: primary }),};}- this.currentHotkey = hotkey;- const saved = await this.saveHotkeyToRenderer(hotkey);+ this.currentHotkey = primary;+ this.notifyActiveHotkey(primary);+ const saved = await this.saveHotkeyToRenderer(hotkeyStr);if (!saved) {debugLogger.warn("[HotkeyManager] GNOME hotkey registered but failed to persist to localStorage"@@ -1065,21 +1167,22 @@ class HotkeyManager extends EventEmitter {}return {success: true,- message: `Hotkey updated to: ${hotkey} (via GNOME native shortcut)`,+ message: `Hotkey updated to: ${primary} (via GNOME native shortcut)`,};}if (this.useHyprland && this.hyprlandManager) {- debugLogger.log(`[HotkeyManager] Updating Hyprland hotkey to "${hotkey}"`);- const success = await this.hyprlandManager.updateKeybinding(hotkey);+ debugLogger.log(`[HotkeyManager] Updating Hyprland hotkey to "${primary}"`);+ const success = await this.hyprlandManager.updateKeybinding(primary);if (!success) {return {success: false,- message: `Failed to update Hyprland hotkey to "${hotkey}". Check the format is valid.`,+ message: i18nMain.t("hotkey.errors.updateFailedCheckFormat", { hotkey: primary }),};}- this.currentHotkey = hotkey;- const saved = await this.saveHotkeyToRenderer(hotkey);+ this.currentHotkey = primary;+ this.notifyActiveHotkey(primary);+ const saved = await this.saveHotkeyToRenderer(hotkeyStr);if (!saved) {debugLogger.warn("[HotkeyManager] Hyprland hotkey registered but failed to persist to localStorage"@@ -1087,15 +1190,15 @@ class HotkeyManager extends EventEmitter {}return {success: true,- message: `Hotkey updated to: ${hotkey} (via Hyprland native shortcut)`,+ message: `Hotkey updated to: ${primary} (via Hyprland native shortcut)`,};}if (this.useKDE && this.kdeManager) {- debugLogger.log(`[HotkeyManager] Updating KDE hotkey to "${hotkey}"`);+ debugLogger.log(`[HotkeyManager] Updating KDE hotkey to "${primary}"`);const previousHotkey = this.currentHotkey;await this.kdeManager.unregisterKeybinding("dictation");- const result = await this.kdeManager.registerKeybinding(hotkey, "dictation", callback);+ const result = await this.kdeManager.registerKeybinding(primary, "dictation", callback);if (result !== true) {if (previousHotkey) {const restored = await this.kdeManager.registerKeybinding(@@ -1108,12 +1211,13 @@ class HotkeyManager extends EventEmitter {}}const reason =- KDE_FAILURE_REASONS[result]?.(hotkey) ||- i18nMain.t("hotkey.errors.registrationFailed", { hotkey });+ KDE_FAILURE_REASONS[result]?.(primary) ||+ i18nMain.t("hotkey.errors.registrationFailed", { hotkey: primary });return { success: false, message: reason };}- this.currentHotkey = hotkey;- const saved = await this.saveHotkeyToRenderer(hotkey);+ this.currentHotkey = primary;+ this.notifyActiveHotkey(primary);+ const saved = await this.saveHotkeyToRenderer(hotkeyStr);if (!saved) {debugLogger.warn("[HotkeyManager] KDE hotkey registered but failed to persist to localStorage"@@ -1121,19 +1225,20 @@ class HotkeyManager extends EventEmitter {}return {success: true,- message: `Hotkey updated to: ${hotkey} (via KDE D-Bus shortcut)`,+ message: `Hotkey updated to: ${primary} (via KDE D-Bus shortcut)`,};}- const result = this.setupShortcuts(hotkey, callback);+ const result = this.setupShortcuts(hotkeys, callback, "dictation", { atomic: true });if (result.success) {- const saved = await this.saveHotkeyToRenderer(hotkey);+ this.notifyActiveHotkey(hotkeyStr);+ const saved = await this.saveHotkeyToRenderer(hotkeyStr);if (!saved) {debugLogger.warn("[HotkeyManager] Hotkey registered but failed to persist to localStorage");}- return { success: true, message: `Hotkey updated to: ${hotkey}` };+ return { success: true, message: `Hotkey updated to: ${hotkeyStr}` };} else {return {success: false,@@ -1195,8 +1300,8 @@ class HotkeyManager extends EventEmitter {for (const slotName of this.slots.keys()) {const slot = this.slots.get(slotName);if (slot) {- slot.hotkey = null;- slot.accelerator = null;+ slot.hotkeys = [];+ slot.accelerators = [];}}globalShortcut.unregisterAll();diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex 519b3a638..8db80f35c 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -2292,15 +2292,17 @@ class IPCHandlers {return await this.windowManager.updateHotkey(hotkey);});- ipcMain.handle("set-hotkey-listening-mode", async (event, enabled, newHotkey = null) => {+ ipcMain.handle("set-hotkey-listening-mode", async (event, enabled) => {if (this._hotkeyCaptureMode === enabled) return { success: true, skipped: true };this._hotkeyCaptureMode = enabled;this.windowManager.setHotkeyListeningMode(enabled);ipcMain.emit("hotkey-listening-mode-changed", null, enabled);const hotkeyManager = this.windowManager.hotkeyManager;- // When exiting capture mode with a new hotkey, use that to avoid reading stale state- const effectiveHotkey = !enabled && newHotkey ? newHotkey : hotkeyManager.getCurrentHotkey();+ // Restore from slot state only. A freshly captured hotkey is registered by+ // its own update IPC (invoked before this one); re-binding it here would+ // overwrite the primary on DE backends or leak untracked registrations.+ const effectiveHotkey = hotkeyManager.getCurrentHotkey();const {isGlobeLikeHotkey,@@ -2320,15 +2322,16 @@ class IPCHandlers {// Dictation is always active; meeting and agent may or may not be set.const allSlots = hotkeyManager.slots;for (const [slot, info] of allSlots) {- if (!info?.hotkey) continue;-- if (!usesNativeListener(info.hotkey)) {+ // Native-listener entries (null accelerator) are handled by stopping+ // the key listeners below.+ for (const accel of info?.accelerators || []) {+ if (!accel) continue;debugLogger.log(- `[IPC] Unregistering globalShortcut "${info.hotkey}" (slot "${slot}") for capture mode`+ `[IPC] Unregistering globalShortcut "${accel}" (slot "${slot}") for capture mode`);const { globalShortcut } = require("electron");try {- globalShortcut.unregister(info.hotkey);+ globalShortcut.unregister(accel);} catch {}}}@@ -2371,21 +2374,24 @@ class IPCHandlers {hotkeyManager.isUsingKDE() ||hotkeyManager.isUsingGnome() ||hotkeyManager.isUsingHyprland();- if (effectiveHotkey && !usesNativeListener(effectiveHotkey) && !usesNativePath) {+ if (!usesNativePath) {const { globalShortcut } = require("electron");- const accelerator = effectiveHotkey.startsWith("Fn+")- ? effectiveHotkey.slice(3)- : effectiveHotkey;- if (!globalShortcut.isRegistered(accelerator)) {- debugLogger.log(- `[IPC] Re-registering globalShortcut "${accelerator}" after capture mode`- );- const callback = this.windowManager.createHotkeyCallback();- const registered = globalShortcut.register(accelerator, callback);- if (!registered) {- debugLogger.warn(- `[IPC] Failed to re-register globalShortcut "${accelerator}" after capture mode`+ // Re-register every globalShortcut-backed dictation hotkey (the slot+ // may hold several).+ for (const hk of hotkeyManager.getSlotHotkeys("dictation")) {+ if (!hk || usesNativeListener(hk)) continue;+ const accelerator = hk.startsWith("Fn+") ? hk.slice(3) : hk;+ if (!globalShortcut.isRegistered(accelerator)) {+ debugLogger.log(+ `[IPC] Re-registering globalShortcut "${accelerator}" after capture mode`);+ const callback = this.windowManager.createHotkeyCallback();+ const registered = globalShortcut.register(accelerator, () => callback(hk));+ if (!registered) {+ debugLogger.warn(+ `[IPC] Failed to re-register globalShortcut "${accelerator}" after capture mode`+ );+ }}}}@@ -2400,10 +2406,7 @@ class IPCHandlers {debugLogger.log(`[IPC] Re-registering GNOME keybinding "${gnomeHotkey}" after capture mode`);- const success = await hotkeyManager.gnomeManager.registerKeybinding(gnomeHotkey);- if (success) {- hotkeyManager.currentHotkey = effectiveHotkey;- }+ await hotkeyManager.gnomeManager.registerKeybinding(gnomeHotkey);}// On Hyprland Wayland, re-register the keybinding with the effective hotkey@@ -2411,10 +2414,7 @@ class IPCHandlers {debugLogger.log(`[IPC] Re-registering Hyprland keybinding "${effectiveHotkey}" after capture mode`);- const success = await hotkeyManager.hyprlandManager.registerKeybinding(effectiveHotkey);- if (success) {- hotkeyManager.currentHotkey = effectiveHotkey;- }+ await hotkeyManager.hyprlandManager.registerKeybinding(effectiveHotkey);}// On KDE (X11 or Wayland), re-register the keybinding with the effective hotkey@@ -2428,9 +2428,7 @@ class IPCHandlers {"dictation",callback);- if (result === true) {- hotkeyManager.currentHotkey = effectiveHotkey;- } else {+ if (result !== true) {debugLogger.warn(`[IPC] Failed to re-register KDE keybinding "${effectiveHotkey}" after capture mode`,{ result }@@ -2440,12 +2438,13 @@ class IPCHandlers {// Re-register non-dictation slots (meeting, agent) that were unregistered on capture enterfor (const [slot, info] of hotkeyManager.slots) {- if (slot === "dictation" || slot === "cancel" || !info?.hotkey || !info?.callback)+ const hotkeys = info?.hotkeys || [];+ if (slot === "dictation" || slot === "cancel" || hotkeys.length === 0 || !info?.callback)continue;debugLogger.log(- `[IPC] Re-registering slot "${slot}" ("${info.hotkey}") after capture mode`+ `[IPC] Re-registering slot "${slot}" ("${hotkeys.join(", ")}") after capture mode`);- await hotkeyManager.registerSlot(slot, info.hotkey, info.callback).catch((err) => {+ await hotkeyManager.registerSlot(slot, hotkeys, info.callback).catch((err) => {debugLogger.warn(`[IPC] Failed to re-register slot "${slot}":`, err.message);});}@@ -3076,7 +3075,8 @@ class IPCHandlers {});ipcMain.handle("get-active-dictation-key", async () => {- return this.windowManager?.hotkeyManager?.currentHotkey ?? null;+ const hotkeys = this.windowManager?.hotkeyManager?.getSlotHotkeys?.("dictation") ?? [];+ return hotkeys.length > 0 ? hotkeys.join(",") : null;});ipcMain.handle("get-effective-default-hotkey", async () => {@@ -7640,7 +7640,9 @@ class IPCHandlers {return { success: true, message: "Agent hotkey cleared" };}- const result = await hotkeyManager.registerSlot("agent", hotkey, agentCallback);+ const result = await hotkeyManager.registerSlot("agent", hotkey, agentCallback, {+ atomic: true,+ });this.windowManager.reconcileNativeKeyListeners();if (result.success) {this.environmentManager.saveAgentKey?.(hotkey);@@ -7667,7 +7669,9 @@ class IPCHandlers {return { success: true, message: "Voice agent hotkey cleared" };}- const result = await hotkeyManager.registerSlot("voiceAgent", hotkey, voiceAgentCallback);+ const result = await hotkeyManager.registerSlot("voiceAgent", hotkey, voiceAgentCallback, {+ atomic: true,+ });this.windowManager.reconcileNativeKeyListeners();if (result.success) {this.environmentManager.saveVoiceAgentKey?.(hotkey);diff --git a/src/helpers/windowManager.js b/src/helpers/windowManager.jsindex 0bc1c1f8b..7f01ce897 100644--- a/src/helpers/windowManager.js+++ b/src/helpers/windowManager.js@@ -218,13 +218,15 @@ class WindowManager {let lastToggleTime = 0;const DEBOUNCE_MS = 150;- return async () => {+ // globalShortcut registrations pass the hotkey that fired; native-shortcut+ // backends invoke the callback bare (their slot holds only the primary).+ return async (triggeredHotkey) => {if (this.hotkeyManager.isInListeningMode()) {return;}const activationMode = this.getActivationMode();- const currentHotkey = this.hotkeyManager.getCurrentHotkey?.();+ const currentHotkey = triggeredHotkey || this.hotkeyManager.getCurrentHotkey?.();if (process.platform === "darwin" &&@@ -389,7 +391,7 @@ class WindowManager {return required;}- startWindowsPushToTalk() {+ startWindowsPushToTalk(key) {if (this.winPushState?.active) {return;}@@ -401,6 +403,7 @@ class WindowManager {this.winPushState = {active: true,+ key,downTime,isRecording: false,};@@ -417,10 +420,15 @@ class WindowManager {}, MIN_HOLD_DURATION_MS);}- handleWindowsPushKeyUp() {+ // With several dictation hotkeys bound, only the key that started the push+ // may stop it; called without a key to force-stop (resetWindowsPushState).+ handleWindowsPushKeyUp(key) {if (!this.winPushState?.active) {return;}+ if (key && this.winPushState.key && key !== this.winPushState.key) {+ return;+ }const wasRecording = this.winPushState.isRecording;this.winPushState = null;diff --git a/src/hooks/useHotkey.js b/src/hooks/useHotkey.jsindex 281fe6935..9f9fb6e54 100644--- a/src/hooks/useHotkey.js+++ b/src/hooks/useHotkey.js@@ -2,7 +2,10 @@ import { useSettingsStore } from "../stores/settingsStore";import { getDefaultHotkey } from "../utils/hotkeys";export const useHotkey = () => {- const hotkey = useSettingsStore((s) => s.dictationKey) || getDefaultHotkey();+ // Prefer the hotkeys the main process actually registered over the stored+ // preference (they diverge on partial registration and DE-native backends).+ const hotkey =+ useSettingsStore((s) => s.activeDictationKey || s.dictationKey) || getDefaultHotkey();const setHotkey = useSettingsStore((s) => s.setDictationKey);return {diff --git a/src/hooks/useHotkeyRegistration.ts b/src/hooks/useHotkeyRegistration.tsindex 342b2f5ee..be8c0862c 100644--- a/src/hooks/useHotkeyRegistration.ts+++ b/src/hooks/useHotkeyRegistration.ts@@ -1,6 +1,6 @@import { useState, useCallback, useRef } from "react";import { useTranslation } from "react-i18next";-import { formatHotkeyLabel } from "../utils/hotkeys";+import { formatHotkeyListLabel } from "../utils/hotkeys";import { validateHotkey } from "../utils/hotkeyValidator";import { getPlatform } from "../utils/platform";@@ -161,7 +161,7 @@ export function useHotkeyRegistration(// Success!if (showSuccessToast && showAlert) {- const displayLabel = formatHotkeyLabel(hotkey);+ const displayLabel = formatHotkeyListLabel(hotkey);showAlert({title: t("hooks.hotkeyRegistration.titles.saved"),description: t("hooks.hotkeyRegistration.messages.nowUsing", { hotkey: displayLabel }),diff --git a/src/hooks/useSettings.ts b/src/hooks/useSettings.tsindex cca14772e..5fac381de 100644--- a/src/hooks/useSettings.ts+++ b/src/hooks/useSettings.ts@@ -43,6 +43,9 @@ export interface CleanupSettings {export interface HotkeySettings {dictationKey: string;+ /** Hotkeys actually registered by the main process (may be a subset of+ * dictationKey, e.g. primary-only on GNOME/KDE/Hyprland). Display-only. */+ activeDictationKey: string | null;meetingKey: string;voiceAgentKey: string;meetingHotkeyLayoutMode: "side-panel" | "full-width";diff --git a/src/locales/de/translation.json b/src/locales/de/translation.jsonindex 82d5234da..2e802bce9 100644--- a/src/locales/de/translation.json+++ b/src/locales/de/translation.json@@ -91,6 +91,7 @@"alreadyRegistered": "\"{{hotkey}}\" ist bereits von einer anderen Anwendung registriert.","osReserved": "\"{{hotkey}}\" ist möglicherweise von Ihrer Desktop-Umgebung reserviert.","registrationFailed": "\"{{hotkey}}\" konnte nicht registriert werden. Möglicherweise wird es von einer anderen Anwendung verwendet.",+ "updateFailedCheckFormat": "Hotkey konnte nicht auf \"{{hotkey}}\" aktualisiert werden. Prüfen Sie, ob das Format gültig ist.","trySuggestions": "Versuchen Sie: {{suggestions}}","slotConflict": "Diese Tastenkombination wird bereits für {{slot}} verwendet."}@@ -927,7 +928,9 @@"recording": "Aufnahme","tryShortcut": "Versuchen Sie Ctrl+Shift+K","tryShortcutMac": "Versuchen Sie ⌘⇧K",- "remove": "Hotkey entfernen"+ "remove": "Hotkey entfernen",+ "addAnother": "Weiteren Hotkey hinzufügen",+ "duplicate": "Bereits hinzugefügt"},"languageSelector": {"noLanguagesFound": "Keine Sprachen gefunden",diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex ae7bf36cb..a88caa28a 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -91,6 +91,7 @@"alreadyRegistered": "\"{{hotkey}}\" is already registered by another application.","osReserved": "\"{{hotkey}}\" may be reserved by your desktop environment.","registrationFailed": "Could not register \"{{hotkey}}\". It may be in use by another application.",+ "updateFailedCheckFormat": "Failed to update hotkey to \"{{hotkey}}\". Check the format is valid.","trySuggestions": "Try: {{suggestions}}","slotConflict": "This hotkey is already used for {{slot}}."}@@ -1015,7 +1016,9 @@"recording": "Recording","tryShortcut": "Try Ctrl+Shift+K","tryShortcutMac": "Try ⌘⇧K",- "remove": "Remove hotkey"+ "remove": "Remove hotkey",+ "addAnother": "Add another hotkey",+ "duplicate": "Already added"},"languageSelector": {"noLanguagesFound": "No languages found",diff --git a/src/locales/es/translation.json b/src/locales/es/translation.jsonindex 086b2dcca..c748578f5 100644--- a/src/locales/es/translation.json+++ b/src/locales/es/translation.json@@ -91,6 +91,7 @@"alreadyRegistered": "\"{{hotkey}}\" ya está registrada por otra aplicación.","osReserved": "\"{{hotkey}}\" puede estar reservada por tu entorno de escritorio.","registrationFailed": "No se pudo registrar \"{{hotkey}}\". Puede estar en uso por otra aplicación.",+ "updateFailedCheckFormat": "No se pudo actualizar el atajo a \"{{hotkey}}\". Comprueba que el formato sea válido.","trySuggestions": "Prueba: {{suggestions}}","slotConflict": "Este atajo ya está asignado a {{slot}}."}@@ -975,7 +976,9 @@"recording": "Grabando","tryShortcut": "Prueba Ctrl+Shift+K","tryShortcutMac": "Prueba ⌘⇧K",- "remove": "Eliminar atajo"+ "remove": "Eliminar atajo",+ "addAnother": "Añadir otro atajo",+ "duplicate": "Ya añadido"},"languageSelector": {"noLanguagesFound": "No se encontraron idiomas",diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.jsonindex 3edc6c0b6..b13063373 100644--- a/src/locales/fr/translation.json+++ b/src/locales/fr/translation.json@@ -91,6 +91,7 @@"alreadyRegistered": "\"{{hotkey}}\" est déjà enregistré par une autre application.","osReserved": "\"{{hotkey}}\" peut être réservé par votre environnement de bureau.","registrationFailed": "Impossible d'enregistrer \"{{hotkey}}\". Il est peut-être utilisé par une autre application.",+ "updateFailedCheckFormat": "Impossible de mettre à jour le raccourci vers \"{{hotkey}}\". Vérifiez que le format est valide.","trySuggestions": "Essayez : {{suggestions}}","slotConflict": "Ce raccourci est déjà utilisé pour {{slot}}."}@@ -975,7 +976,9 @@"recording": "Enregistrement","tryShortcut": "Essayez Ctrl+Shift+K","tryShortcutMac": "Essayez ⌘⇧K",- "remove": "Supprimer le raccourci"+ "remove": "Supprimer le raccourci",+ "addAnother": "Ajouter un autre raccourci",+ "duplicate": "Déjà ajouté"},"languageSelector": {"noLanguagesFound": "Aucune langue trouvée",diff --git a/src/locales/it/translation.json b/src/locales/it/translation.jsonindex 72bc9f442..aec16145d 100644--- a/src/locales/it/translation.json+++ b/src/locales/it/translation.json@@ -91,6 +91,7 @@"alreadyRegistered": "\"{{hotkey}}\" è già registrata da un'altra applicazione.","osReserved": "\"{{hotkey}}\" potrebbe essere riservata dal sistema operativo.","registrationFailed": "Impossibile registrare \"{{hotkey}}\". Potrebbe essere in uso da un'altra applicazione.",+ "updateFailedCheckFormat": "Impossibile aggiornare la scorciatoia a \"{{hotkey}}\". Verifica che il formato sia valido.","trySuggestions": "Prova: {{suggestions}}","slotConflict": "Questa scorciatoia è già utilizzata per {{slot}}."}@@ -927,7 +928,9 @@"recording": "Registrazione","tryShortcut": "Prova Ctrl+Shift+K","tryShortcutMac": "Prova ⌘⇧K",- "remove": "Rimuovi scorciatoia"+ "remove": "Rimuovi scorciatoia",+ "addAnother": "Aggiungi un'altra scorciatoia",+ "duplicate": "Già aggiunto"},"languageSelector": {"noLanguagesFound": "Nessuna lingua trovata",diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.jsonindex 469b515a8..f8ba262b7 100644--- a/src/locales/ja/translation.json+++ b/src/locales/ja/translation.json@@ -91,6 +91,7 @@"alreadyRegistered": "\"{{hotkey}}\" は別のアプリケーションで既に登録されています。","osReserved": "\"{{hotkey}}\" はデスクトップ環境で予約されている可能性があります。","registrationFailed": "\"{{hotkey}}\" を登録できませんでした。別のアプリケーションで使用されている可能性があります。",+ "updateFailedCheckFormat": "「{{hotkey}}」へのホットキーの更新に失敗しました。形式が正しいか確認してください。","trySuggestions": "お試しください: {{suggestions}}","slotConflict": "このホットキーは既に{{slot}}で使用されています。"}@@ -927,7 +928,9 @@"recording": "記録中","tryShortcut": "Ctrl+Shift+K をお試しください","tryShortcutMac": "⌘⇧K をお試しください",- "remove": "ホットキーを削除"+ "remove": "ホットキーを削除",+ "addAnother": "ホットキーをもう1つ追加",+ "duplicate": "すでに追加されています"},"languageSelector": {"noLanguagesFound": "言語が見つかりません",diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.jsonindex e5d4472f3..eb121d367 100644--- a/src/locales/pt/translation.json+++ b/src/locales/pt/translation.json@@ -91,6 +91,7 @@"alreadyRegistered": "\"{{hotkey}}\" já está registrada por outro aplicativo.","osReserved": "\"{{hotkey}}\" pode estar reservada pelo seu ambiente de desktop.","registrationFailed": "Não foi possível registrar \"{{hotkey}}\". Pode estar em uso por outro aplicativo.",+ "updateFailedCheckFormat": "Não foi possível atualizar o atalho para \"{{hotkey}}\". Verifique se o formato é válido.","trySuggestions": "Tente: {{suggestions}}","slotConflict": "Este atalho já está sendo usado para {{slot}}."}@@ -906,7 +907,9 @@"recording": "Gravando","tryShortcut": "Tente Ctrl+Shift+K","tryShortcutMac": "Tente ⌘⇧K",- "remove": "Remover atalho"+ "remove": "Remover atalho",+ "addAnother": "Adicionar outro atalho",+ "duplicate": "Já adicionado"},"languageSelector": {"noLanguagesFound": "Nenhum idioma encontrado",diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.jsonindex dffc9e565..ef3931e39 100644--- a/src/locales/ru/translation.json+++ b/src/locales/ru/translation.json@@ -91,6 +91,7 @@"alreadyRegistered": "«{{hotkey}}» уже зарегистрирована другим приложением.","osReserved": "«{{hotkey}}» может быть зарезервирована вашей операционной системой.","registrationFailed": "Не удалось зарегистрировать «{{hotkey}}». Возможно, она используется другим приложением.",+ "updateFailedCheckFormat": "Не удалось обновить горячую клавишу на «{{hotkey}}». Проверьте правильность формата.","trySuggestions": "Попробуйте: {{suggestions}}","slotConflict": "Эта горячая клавиша уже используется для {{slot}}."}@@ -927,7 +928,9 @@"recording": "Запись","tryShortcut": "Попробуйте Ctrl+Shift+K","tryShortcutMac": "Попробуйте ⌘⇧K",- "remove": "Удалить горячую клавишу"+ "remove": "Удалить горячую клавишу",+ "addAnother": "Добавить ещё одну горячую клавишу",+ "duplicate": "Уже добавлена"},"languageSelector": {"noLanguagesFound": "Языки не найдены",diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.jsonindex c0279ba55..4b017e085 100644--- a/src/locales/zh-CN/translation.json+++ b/src/locales/zh-CN/translation.json@@ -91,6 +91,7 @@"alreadyRegistered": "\"{{hotkey}}\" 已被其他应用注册。","osReserved": "\"{{hotkey}}\" 可能被系统保留。","registrationFailed": "无法注册 \"{{hotkey}}\",该快捷键可能已被其他应用占用。",+ "updateFailedCheckFormat": "无法将快捷键更新为 \"{{hotkey}}\",请检查格式是否有效。","trySuggestions": "建议尝试:{{suggestions}}","slotConflict": "此快捷键已用于{{slot}}。"}@@ -927,7 +928,9 @@"recording": "录制中","tryShortcut": "试试 Ctrl+Shift+K","tryShortcutMac": "试试 ⌘⇧K",- "remove": "移除快捷键"+ "remove": "移除快捷键",+ "addAnother": "添加其他快捷键",+ "duplicate": "已添加"},"languageSelector": {"noLanguagesFound": "未找到匹配的语言",diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.jsonindex a4762c3f3..7469d9abf 100644--- a/src/locales/zh-TW/translation.json+++ b/src/locales/zh-TW/translation.json@@ -91,6 +91,7 @@"alreadyRegistered": "\"{{hotkey}}\" 已被其他應用程式註冊。","osReserved": "\"{{hotkey}}\" 可能被你的作業系統保留。","registrationFailed": "無法註冊「{{hotkey}}」。可能已被其他應用程式使用。",+ "updateFailedCheckFormat": "無法將快速鍵更新為「{{hotkey}}」。請檢查格式是否有效。","trySuggestions": "試試看:{{suggestions}}","slotConflict": "此快捷鍵已用於{{slot}}。"}@@ -927,7 +928,9 @@"recording": "記錄中","tryShortcut": "試試 Ctrl+Shift+K","tryShortcutMac": "試試 ⌘⇧K",- "remove": "移除快捷鍵"+ "remove": "移除快捷鍵",+ "addAnother": "新增其他快捷鍵",+ "duplicate": "已新增"},"languageSelector": {"noLanguagesFound": "找不到語言",diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.tsindex 8a5ff4f7e..ee98290de 100644--- a/src/stores/settingsStore.ts+++ b/src/stores/settingsStore.ts@@ -614,7 +614,7 @@ export interface SettingsStatesetDictationKey: (key: string) => void;setMeetingKey: (key: string) => void;- setVoiceAgentKey: (key: string) => void;+ setVoiceAgentKey: (key: string) => Promise<boolean>;setMeetingHotkeyLayoutMode: (mode: "side-panel" | "full-width") => void;setOnboardingUseCases: (useCases: string[]) => void;setOnboardingUseCaseNote: (note: string) => void;@@ -660,7 +660,7 @@ export interface SettingsStatesetChatAgentModel: (value: string) => void;setChatAgentProvider: (value: string) => void;- setChatAgentKey: (key: string) => void;+ setChatAgentKey: (key: string) => Promise<boolean>;setChatAgentCloudMode: (value: string) => void;setChatAgentMode: (mode: InferenceMode) => void;setChatAgentCloudBaseUrl: (value: string) => void;@@ -695,6 +695,7 @@ function createBooleanSetter(key: string) {// Setter for hotkeys that must be registered with the main process before// being persisted. Rolls back to the previous key if registration fails.+// Resolves to false on failure so optimistic UIs (HotkeyListInput) can revert.function createRegisteredHotkeySetter(key: "chatAgentKey" | "voiceAgentKey",label: string,@@ -702,10 +703,10 @@ function createRegisteredHotkeySetter(((hotkey: string) => Promise<{ success: boolean; message: string }>) | undefined,fallbackSave?: (hotkey: string) => void) {- return (hotkey: string) => {+ return async (hotkey: string): Promise<boolean> => {if (!isBrowser) {useSettingsStore.setState({ [key]: hotkey });- return;+ return true;}const registerFn = getRegisterFn();@@ -713,34 +714,31 @@ function createRegisteredHotkeySetter(localStorage.setItem(key, hotkey);useSettingsStore.setState({ [key]: hotkey });fallbackSave?.(hotkey);- return;+ return true;}const previousKey = useSettingsStore.getState()[key];- void registerFn(hotkey)- .then((result) => {- if (!result?.success) {- localStorage.setItem(key, previousKey);- useSettingsStore.setState({ [key]: previousKey });- logger.warn(- `Failed to update ${label}`,- { hotkey, message: result?.message },- "settings"- );- return;- }+ try {+ const result = await registerFn(hotkey);+ if (!result?.success) {+ localStorage.setItem(key, previousKey);+ useSettingsStore.setState({ [key]: previousKey });+ logger.warn(`Failed to update ${label}`, { hotkey, message: result?.message }, "settings");+ return false;+ }- localStorage.setItem(key, hotkey);- useSettingsStore.setState({ [key]: hotkey });- })- .catch((error) => {- logger.warn(- `Failed to update ${label}`,- { hotkey, error: error instanceof Error ? error.message : String(error) },- "settings"- );- });+ localStorage.setItem(key, hotkey);+ useSettingsStore.setState({ [key]: hotkey });+ return true;+ } catch (error) {+ logger.warn(+ `Failed to update ${label}`,+ { hotkey, error: error instanceof Error ? error.message : String(error) },+ "settings"+ );+ return false;+ }};}@@ -929,6 +927,7 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({vertexApiKey: "",dictationKey: readString("dictationKey", ""),+ activeDictationKey: null,meetingKey: readString("meetingKey", ""),voiceAgentKey: readString("voiceAgentKey", ""),onboardingUseCases: readStringArray("onboardingUseCases", []),@@ -2059,12 +2058,13 @@ export async function initializeSettings(): Promise<void> {);}- // Show the active hotkey in UI (zustand only, not localStorage).+ // Track what is actually registered, separately from the editable+ // dictationKey preference so partial registrations never get persisted.// May return constructor default during early startup; corrected by dictation-key-active event later.try {const activeKey = await window.electronAPI?.getActiveDictationKey?.();if (activeKey) {- useSettingsStore.setState({ dictationKey: activeKey });+ useSettingsStore.setState({ activeDictationKey: activeKey });}} catch (err) {logger.warn(@@ -2317,9 +2317,9 @@ export async function initializeSettings(): Promise<void> {}});- // Active hotkey updates from backend — zustand only, not localStorage.+ // Active hotkey updates from backend — display state, never persisted.window.electronAPI?.onDictationKeyActive?.((key: string) => {- useSettingsStore.setState({ dictationKey: key });+ useSettingsStore.setState({ activeDictationKey: key });});// Sync settings pushed from main process (e.g., hotkey changed in control panel)diff --git a/src/types/electron.ts b/src/types/electron.tsindex ec18d4914..009c8a80e 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -966,10 +966,7 @@ declare global {// Hotkey managementupdateHotkey: (key: string) => Promise<{ success: boolean; message: string }>;- setHotkeyListeningMode?: (- enabled: boolean,- newHotkey?: string | null- ) => Promise<{ success: boolean }>;+ setHotkeyListeningMode?: (enabled: boolean) => Promise<{ success: boolean }>;getHotkeyModeInfo?: () => Promise<{isUsingGnome: boolean;isUsingHyprland: boolean;diff --git a/src/utils/hotkeyValidation.ts b/src/utils/hotkeyValidation.tsindex 2d4c477e1..503ba7d51 100644--- a/src/utils/hotkeyValidation.ts+++ b/src/utils/hotkeyValidation.ts@@ -1,5 +1,6 @@import type { TFunction } from "i18next";import { getValidationMessage, normalizeHotkey } from "./hotkeyValidator";+import { parseHotkeyList } from "./hotkeys";import { getPlatform } from "./platform";export function validateHotkeyForSlot(@@ -13,8 +14,13 @@ export function validateHotkeyForSlot(const normalized = normalizeHotkey(hotkey, platform);- for (const [labelKey, otherHotkey] of Object.entries(excludeSlots)) {- if (otherHotkey && normalizeHotkey(otherHotkey, platform) === normalized) {+ // A slot's value may be a comma-separated hotkey list (#936) — conflict if+ // the candidate matches any entry.+ for (const [labelKey, otherValue] of Object.entries(excludeSlots)) {+ const conflicts = parseHotkeyList(otherValue).some(+ (other) => normalizeHotkey(other, platform) === normalized+ );+ if (conflicts) {return t("hotkey.errors.slotConflict", { slot: t(labelKey) });}}diff --git a/src/utils/hotkeyValidator.ts b/src/utils/hotkeyValidator.tsindex 8daf31d65..956850dc1 100644--- a/src/utils/hotkeyValidator.ts+++ b/src/utils/hotkeyValidator.ts@@ -1,4 +1,9 @@-import { formatHotkeyLabelForPlatform, isGlobeLikeHotkey, isMouseButtonHotkey } from "./hotkeys";+import {+ formatHotkeyLabelForPlatform,+ isGlobeLikeHotkey,+ isMouseButtonHotkey,+ parseHotkeyList,+} from "./hotkeys";export type Platform = "darwin" | "win32" | "linux";@@ -519,6 +524,25 @@ export function validateHotkey(return { valid: false, error: "Please enter a valid shortcut." };}+ // A slot may hold several hotkeys as a comma-separated list (#936) — validate+ // each entry independently and return the first failure. parseHotkeyList keeps+ // comma-key hotkeys like "Control+," intact, so a single such hotkey falls+ // through to the regular single-hotkey validation below.+ if (hotkey.includes(",")) {+ const items = parseHotkeyList(hotkey);+ if (items.length === 0) {+ return { valid: false, error: "Please enter a valid shortcut." };+ }+ if (items.length > 1) {+ for (const item of items) {+ const result = validateHotkey(item, platform, existingHotkeys);+ if (!result.valid) return result;+ }+ return { valid: true };+ }+ hotkey = items[0];+ }+if (isGlobeLikeHotkey(hotkey)) {if (platform !== "darwin") {return {diff --git a/src/utils/hotkeys.ts b/src/utils/hotkeys.tsindex d309ee190..d4eee3d89 100644--- a/src/utils/hotkeys.ts+++ b/src/utils/hotkeys.ts@@ -9,6 +9,36 @@ export function isGlobeLikeHotkey(hotkey: string): boolean {return hotkey === "GLOBE" || hotkey === "Fn";}+/**+ * Parse a comma-separated hotkey list (a legacy single value is a one-item+ * list): trimmed, de-duplicated, empties removed, order preserved. The comma+ * KEY is itself a valid hotkey (e.g. "Control+,"): no accelerator legitimately+ * ends with "+", so a split segment ending in "+" gets its comma restored.+ *+ * Keep in sync with the main-process twin in src/helpers/hotkeyList.js.+ */+export function parseHotkeyList(value?: string | null): string[] {+ if (!value) return [];+ const raw = value.split(",");+ const seen = new Set<string>();+ const result: string[] = [];+ for (let i = 0; i < raw.length; i++) {+ let hotkey = raw[i].trim();+ if (hotkey.endsWith("+") && i < raw.length - 1) {+ hotkey += ",";+ }+ if (!hotkey || seen.has(hotkey)) continue;+ seen.add(hotkey);+ result.push(hotkey);+ }+ return result;+}++/** Serialize a hotkey list back to the canonical comma-separated string. */+export function serializeHotkeyList(list: string[]): string {+ return parseHotkeyList(list.join(",")).join(",");+}+export function isMouseButtonHotkey(hotkey: string): boolean {return /^MouseButton[45]$/i.test(hotkey || "");}@@ -59,6 +89,16 @@ export function formatHotkeyLabel(hotkey?: string | null): string {return formatHotkeyLabelForPlatform(resolvedHotkey, platform);}+/**+ * Label for a comma-separated hotkey list: entries formatted individually and+ * joined with " / "; empty lists fall back like formatHotkeyLabel.+ */+export function formatHotkeyListLabel(value?: string | null): string {+ const list = parseHotkeyList(value);+ if (list.length === 0) return formatHotkeyLabel(value);+ return list.map((hotkey) => formatHotkeyLabel(hotkey)).join(" / ");+}+export function formatHotkeyLabelForPlatform(hotkey: string, platform: Platform): string {if (!hotkey || hotkey.trim() === "") {return "";diff --git a/test/helpers/hotkeyList.test.js b/test/helpers/hotkeyList.test.jsnew file mode 100644index 000000000..e776cd84f--- /dev/null+++ b/test/helpers/hotkeyList.test.js@@ -0,0 +1,64 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const { parseHotkeyList, serializeHotkeyList } = require("../../src/helpers/hotkeyList.js");++test("parses a legacy single hotkey into a one-element list", () => {+ assert.deepEqual(parseHotkeyList("Control+Shift+R"), ["Control+Shift+R"]);+ assert.deepEqual(parseHotkeyList("GLOBE"), ["GLOBE"]);+});++test("parses a comma-separated list", () => {+ assert.deepEqual(parseHotkeyList("GLOBE,Control+Shift+R"), ["GLOBE", "Control+Shift+R"]);+});++test("trims whitespace around each hotkey", () => {+ assert.deepEqual(parseHotkeyList(" GLOBE , Control+Shift+R "), ["GLOBE", "Control+Shift+R"]);+});++test("drops empty entries and de-duplicates, preserving order", () => {+ assert.deepEqual(parseHotkeyList("F8,,F8,F9,"), ["F8", "F9"]);+});++test("handles empty / nullish input", () => {+ assert.deepEqual(parseHotkeyList(""), []);+ assert.deepEqual(parseHotkeyList(null), []);+ assert.deepEqual(parseHotkeyList(undefined), []);+});++test("accepts an array and normalizes it (including nested comma strings)", () => {+ assert.deepEqual(parseHotkeyList(["GLOBE", "Control+Shift+R"]), ["GLOBE", "Control+Shift+R"]);+ assert.deepEqual(parseHotkeyList(["GLOBE,Control+Alt", " F8 "]), ["GLOBE", "Control+Alt", "F8"]);+});++test("serializes a list back to a canonical comma-separated string", () => {+ assert.equal(serializeHotkeyList(["GLOBE", "Control+Shift+R"]), "GLOBE,Control+Shift+R");+ assert.equal(serializeHotkeyList("F8, F9 ,F8"), "F8,F9");+ assert.equal(serializeHotkeyList([]), "");+ assert.equal(serializeHotkeyList(null), "");+});++test("round-trips parse -> serialize -> parse", () => {+ const input = " GLOBE , Control+Shift+R , MouseButton4 ";+ const once = serializeHotkeyList(input);+ assert.equal(once, "GLOBE,Control+Shift+R,MouseButton4");+ assert.deepEqual(parseHotkeyList(once), ["GLOBE", "Control+Shift+R", "MouseButton4"]);+});++test("keeps a legacy comma-key hotkey intact (the comma is the key, not a separator)", () => {+ assert.deepEqual(parseHotkeyList("Control+,"), ["Control+,"]);+ assert.deepEqual(parseHotkeyList("Command+Shift+,"), ["Command+Shift+,"]);+});++test("parses comma-key hotkeys inside a list", () => {+ assert.deepEqual(parseHotkeyList("GLOBE,Control+,"), ["GLOBE", "Control+,"]);+ assert.deepEqual(parseHotkeyList("Control+,,F8"), ["Control+,", "F8"]);+ assert.deepEqual(parseHotkeyList(["Control+,", "F8"]), ["Control+,", "F8"]);+});++test("round-trips lists containing comma-key hotkeys", () => {+ const list = ["Control+,", "F8", "GLOBE"];+ const serialized = serializeHotkeyList(list);+ assert.equal(serialized, "Control+,,F8,GLOBE");+ assert.deepEqual(parseHotkeyList(serialized), list);+});diff --git a/test/helpers/hotkeySlotRollback.test.js b/test/helpers/hotkeySlotRollback.test.jsnew file mode 100644index 000000000..e13ee5814--- /dev/null+++ b/test/helpers/hotkeySlotRollback.test.js@@ -0,0 +1,70 @@+const test = require("node:test");+const assert = require("node:assert/strict");++// Stub electron's globalShortcut before hotkeyManager loads so slot+// registration can run outside Electron. Accelerators containing "BAD"+// simulate an OS-level conflict.+const registered = new Map();+require.cache[require.resolve("electron")] = {+ exports: {+ globalShortcut: {+ register(accelerator, callback) {+ if (accelerator.includes("BAD") || 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 noop = () => {};++test.beforeEach(() => registered.clear());++test("atomic registerSlot failure keeps the slot's previous working hotkeys", async () => {+ const mgr = new HotkeyManager();++ const first = await mgr.registerSlot("agent", "F7", noop, { atomic: true });+ assert.equal(first.success, true);+ assert.deepEqual(mgr.getSlotHotkeys("agent"), ["F7"]);+ assert.equal(registered.has("F7"), true);++ const second = await mgr.registerSlot("agent", "F7,Control+BAD", noop, { atomic: true });+ assert.equal(second.success, false);+ assert.deepEqual(mgr.getSlotHotkeys("agent"), ["F7"]);+ assert.equal(registered.has("F7"), true, "previous hotkey must stay registered after rollback");+});++test("non-atomic registerSlot keeps the working subset and reports failures", async () => {+ const mgr = new HotkeyManager();++ const result = await mgr.registerSlot("agent", "F7,Control+BAD", noop);+ assert.equal(result.success, true);+ assert.deepEqual(result.hotkeys, ["F7"]);+ assert.equal(result.failures.length, 1);+ assert.equal(result.failures[0].hotkey, "Control+BAD");+});++test("re-registering a slot replaces its previous accelerators", async () => {+ const mgr = new HotkeyManager();++ await mgr.registerSlot("agent", "F7", noop, { atomic: true });+ const result = await mgr.registerSlot("agent", "F6,F5", noop, { atomic: true });+ assert.equal(result.success, true);+ assert.deepEqual(mgr.getSlotHotkeys("agent"), ["F6", "F5"]);+ assert.equal(registered.has("F7"), false, "old accelerator must be unregistered");+ assert.equal(registered.has("F6"), true);+ assert.equal(registered.has("F5"), true);+});diff --git a/test/helpers/nativeListenerKeys.test.js b/test/helpers/nativeListenerKeys.test.jsindex f8523b502..c8fc274f6 100644--- a/test/helpers/nativeListenerKeys.test.js+++ b/test/helpers/nativeListenerKeys.test.js@@ -4,12 +4,14 @@ const assert = require("node:assert/strict");const HotkeyManager = require("../../src/helpers/hotkeyManager.js");// Build a manager with an explicit set of slot hotkeys, independent of the-// platform default so the assertions are deterministic everywhere.+// platform default so the assertions are deterministic everywhere. A slot value+// may be a single hotkey string or an array (multi-hotkey, issue #936).const makeManager = (slots) => {const mgr = new HotkeyManager();mgr.slots.clear();- for (const [name, hotkey] of Object.entries(slots)) {- mgr.slots.set(name, { hotkey, callback: null, accelerator: null });+ for (const [name, value] of Object.entries(slots)) {+ const hotkeys = Array.isArray(value) ? value : value ? [value] : [];+ mgr.slots.set(name, { hotkeys, callback: null, accelerators: [] });}return mgr;};@@ -50,3 +52,43 @@ test("right-side modifiers use the native listener; globe/empty slots do not", (});assert.deepEqual(mgr.getNativeListenerKeys("tap"), ["RightControl"]);});++test("a multi-hotkey slot watches each native hotkey but leaves regular keys to globalShortcut", () => {+ // dictation bound to both GLOBE (native, macOS) and Control+Shift+R (regular).+ const mgr = makeManager({ dictation: ["GLOBE", "Control+Shift+R", "RightControl"] });+ assert.deepEqual(mgr.getNativeListenerKeys("tap"), ["RightControl"]);+});++test("push mode watches every dictation hotkey, including regular keys", () => {+ const mgr = makeManager({ dictation: ["F8", "Control+Shift+R"] });+ assert.deepEqual(mgr.getNativeListenerKeys("push").sort(), ["Control+Shift+R", "F8"]);+});++test("membership and lookup helpers work across multi-hotkey slots", () => {+ const mgr = makeManager({+ dictation: ["GLOBE", "Control+Shift+R"],+ agent: "Control+Alt",+ });+ assert.equal(mgr.slotHasHotkey("dictation", "Control+Shift+R"), true);+ assert.equal(mgr.slotHasHotkey("dictation", "F12"), false);+ assert.equal(mgr.findSlotByHotkey("Control+Shift+R"), "dictation");+ assert.equal(mgr.findSlotByHotkey("Control+Alt"), "agent");+ assert.equal(mgr.findSlotByHotkey("Nope"), null);+ assert.deepEqual(mgr.getSlotHotkeys("dictation"), ["GLOBE", "Control+Shift+R"]);+ assert.equal(mgr.getSlotHotkey("dictation"), "GLOBE");+});++test("_findSlotConflict detects a hotkey already bound to another slot's list", () => {+ const mgr = makeManager({+ dictation: ["GLOBE", "Control+Shift+R"],+ agent: "Control+Alt",+ });+ // Re-using a dictation hotkey for the agent slot should conflict.+ const conflict = mgr._findSlotConflict("agent", "Control+Shift+R");+ assert.equal(conflict?.reason, "slot_conflict");+ assert.equal(conflict?.conflictSlot, "dictation");+ // A fresh hotkey does not conflict.+ assert.equal(mgr._findSlotConflict("agent", "F7"), null);+ // Re-checking a slot against its own hotkey is not a conflict.+ assert.equal(mgr._findSlotConflict("dictation", "GLOBE"), null);+});