Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(voice): give dictation two shortcut rows on a shared keybind row
Ruben Lütked0acffffc2e1
diff --git a/docs/os-parity.md b/docs/os-parity.mdindex f07848b8ee..4ada451ce3 100644--- a/docs/os-parity.md+++ b/docs/os-parity.md@@ -70,6 +70,7 @@ experiences today.| P-21 | Low | Coding-CLI panes | OpenCode panes ship single-login for the same class of reason: the only variable that moves its credentials and session database is `XDG_DATA_HOME`, which is a SHARED variable rather than a dedicated override — redirecting it per pane would also redirect any other XDG-aware tool the agent spawns inside that pane | `jarvis/workspace/agents.py` (the `opencode` entry) | All OSes: one OpenCode login. Verified on Windows that `XDG_DATA_HOME` does move `auth.json` and the session database; the blast radius on macOS and Linux has not been measured, which is why it is not wired up || P-22 | Low | Coding-CLI panes | Kimi Code uses the bundled Git Bash as its shell environment on Windows, so without Git for Windows installed the binary answers `--version` correctly and the agent then cannot run a single shell command | Kimi vendor docs; `jarvis/workspace/agents.py` (the `kimi` entry) | Windows without Git for Windows: the pane opens, the CLI reports a healthy version, and shell commands fail inside it. macOS/Linux unaffected. `KIMI_SHELL_PATH` points at a non-standard `bash.exe`. An install check that only runs `--version` cannot see this || P-23 | Info | Coding-CLI panes | Kimi Code's alternate screen cannot be disabled (an open upstream request notes it is the outlier versus Claude Code, Codex and the Gemini CLI), so it may conflict with the pane's own scrollback the way a Claude Code pane once did | Upstream issue; `jarvis/agentic_ide/screen.py` | All OSes equally — not an OS gap, recorded here because it is the same class of pane defect and is expected to need the same kind of fix |+| P-26 | Low | Keybind recorder | A Mac user cannot RECORD a Command (⌘) shortcut, even though the backend validator accepts `cmd+…` on darwin. Two frontend layers close the door: `modifierTokens` maps `metaKey` to the `win` token (there is one token for "the Meta key", and it is named after the Windows key), and `KeyboardMap` then renders that cap disabled with a "Reserved by the system" tooltip — correct on a PC, wrong on a Mac, where ⌘ is the natural modifier for exactly this kind of shortcut. Deliberately deferred, not overlooked: separating the two Meta keys means a new token that the hotkey backends (`global_hotkeys._KEY_MAP`, `pynput._GENERIC_MODIFIER_ALIASES`) must also learn, and the shipped defaults (`ctrl+right_alt+j` push-to-talk, `ctrl+right_alt+space` hands-free) need no ⌘ on any OS | `jarvis/ui/web/frontend/src/hooks/useHotkey.ts::modifierTokens`, `src/views/settings/KeyboardMap.tsx` (`reserved = token === "win"`), `jarvis/trigger/hotkey.py::validate_hotkey` | macOS: every shipped default works, and Ctrl/Option/Shift combos record and save normally — only ⌘-based combos are unreachable from the UI (a `cmd+…` combo already present in `jarvis.toml` keeps working). Windows/Linux: correct as-is, the Windows/Super key genuinely is OS-reserved |## Maintenancediff --git a/jarvis/ui/web/frontend/src/hooks/hotkeyCombo.test.ts b/jarvis/ui/web/frontend/src/hooks/hotkeyCombo.test.tsindex 569ab6379b..12d75a0a73 100644--- a/jarvis/ui/web/frontend/src/hooks/hotkeyCombo.test.ts+++ b/jarvis/ui/web/frontend/src/hooks/hotkeyCombo.test.ts@@ -204,6 +204,23 @@ describe("validateCombo", () => {});});+ it("rejects F12 in any combo (permanently reserved by the debugger)", () => {+ // The backend's _RESERVED_SOLO_KEYS rejects f12 no matter what modifiers+ // surround it. Without the mirror rule the recorder let the user build the+ // combo and only the Save round-trip said no.+ expect(validateCombo("f12")).toEqual({+ status: "error",+ reason: "f12_reserved",+ });+ expect(validateCombo("ctrl+shift+f12")).toEqual({+ status: "error",+ reason: "f12_reserved",+ });+ // Its neighbours stay perfectly bindable.+ expect(validateCombo("f11").status).toBe("ok");+ expect(validateCombo("ctrl+shift+f13").status).toBe("ok");+ });+it("rejects the OS-critical shortcuts Alt+F4 and Ctrl+C", () => {expect(validateCombo("alt+f4")).toEqual({ status: "error", reason: "alt_f4" });expect(validateCombo("ctrl+c")).toEqual({ status: "error", reason: "ctrl_c" });diff --git a/jarvis/ui/web/frontend/src/hooks/useHotkey.ts b/jarvis/ui/web/frontend/src/hooks/useHotkey.tsindex 847ca87614..ba6b1c3924 100644--- a/jarvis/ui/web/frontend/src/hooks/useHotkey.ts+++ b/jarvis/ui/web/frontend/src/hooks/useHotkey.ts@@ -223,6 +223,14 @@ const _SOLO_SAFE_TOKENS = new Set([..._NAV_SOLO_TOKENS,]);+/**+ * Keys the OS keeps for itself no matter what the combo looks like — mirrors+ * ``_RESERVED_SOLO_KEYS`` in ``jarvis/trigger/hotkey.py``. F12 is permanently+ * claimed by the debugger. Without this rule the recorder happily let the user+ * build an F12 combo and only the Save round-trip said no.+ */+const _RESERVED_TOKENS = new Set(["f12"]);+/** Live validation result for a combo being built in the keybind recorder. */export type ComboValidation =| { status: "empty" }@@ -234,6 +242,7 @@ export type ComboValidation =| "only_modifiers"| "solo_typing_key"| "windows_reserved"+ | "f12_reserved"| "alt_f4"| "ctrl_c";}@@ -266,6 +275,11 @@ export function validateCombo(if (keys.length === 0) return { status: "error", reason: "only_modifiers" };if (mods.includes("win")) return { status: "error", reason: "windows_reserved" };+ // Reserved regardless of the modifiers around it — same order as the backend+ // (windows-key rule first, then the reserved key, then the OS shortcuts).+ if (keys.some((k) => _RESERVED_TOKENS.has(k))) {+ return { status: "error", reason: "f12_reserved" };+ }if ((mods.includes("alt") || mods.includes("right_alt")) && keys.includes("f4")) {return { status: "error", reason: "alt_f4" };}@@ -297,12 +311,21 @@ export function validateCombo(}// Mirrors KEYBIND_ACTIONS in jarvis/core/config_writer.py — keep in sync.-export type KeybindAction = "call" | "hangup" | "dictate";+// "dictate" is push-to-talk (hold), "dictate_toggle" is hands-free (press once+// to start, again to stop).+export type KeybindAction = "call" | "hangup" | "dictate" | "dictate_toggle";-/** Response of GET /api/settings/keybinds. */+/**+ * Response of GET /api/settings/keybinds.+ *+ * `Partial` on purpose: the frontend and the backend are updated separately, so+ * a build that already knows a new action can talk to a backend that does not+ * report it yet. Every read must therefore default (`?? ""`) instead of+ * assuming a string — an undefined combo used to crash the whole panel.+ */export interface KeybindsConfig {- keybinds: Record<KeybindAction, string>;- defaults: Record<KeybindAction, string>;+ keybinds: Partial<Record<KeybindAction, string>>;+ defaults: Partial<Record<KeybindAction, string>>;suggestions: string[];restart_required: boolean;}diff --git a/jarvis/ui/web/frontend/src/hooks/useKeybinds.test.ts b/jarvis/ui/web/frontend/src/hooks/useKeybinds.test.tsindex 17a263f366..4d2d9e090c 100644--- a/jarvis/ui/web/frontend/src/hooks/useKeybinds.test.ts+++ b/jarvis/ui/web/frontend/src/hooks/useKeybinds.test.ts@@ -2,10 +2,17 @@ import { renderHook, waitFor, act } from "@testing-library/react";import { afterEach, describe, expect, it, vi } from "vitest";import { useKeybinds } from "./useHotkey";+const KEYBINDS = {+ call: "f3+f4",+ hangup: "f1+f2",+ dictate: "ctrl+right_alt+j",+ dictate_toggle: "ctrl+right_alt+space",+};+const FULL = {- keybinds: { call: "f3+f4", hangup: "f1+f2" },- defaults: { call: "f3+f4", hangup: "f1+f2" },- suggestions: [],+ keybinds: KEYBINDS,+ defaults: { ...KEYBINDS },+ suggestions: ["ctrl+shift+space", "ctrl+shift+d"],restart_required: true,};@@ -20,6 +27,32 @@ describe("useKeybinds", () => {const { result } = renderHook(() => useKeybinds());await waitFor(() => expect(result.current.config).not.toBeNull());expect(result.current.config?.keybinds.call).toBe("f3+f4");+ // The two dictation actions travel over the same route as call/hangup —+ // one config, four actions, no second endpoint.+ expect(result.current.config?.keybinds.dictate).toBe("ctrl+right_alt+j");+ expect(result.current.config?.keybinds.dictate_toggle).toBe(+ "ctrl+right_alt+space",+ );+ expect(result.current.config?.suggestions).toContain("ctrl+shift+space");+ });++ it("PUTs the hands-free action under its own id", async () => {+ const fetchMock = vi+ .fn()+ .mockResolvedValue({ ok: true, json: async () => FULL });+ vi.stubGlobal("fetch", fetchMock);++ const { result } = renderHook(() => useKeybinds());+ await waitFor(() => expect(result.current.config).not.toBeNull());+ await act(async () => {+ await result.current.saveKeybind("dictate_toggle", "ctrl+shift+d");+ });++ const putCall = fetchMock.mock.calls.find((c) => c[1]?.method === "PUT");+ expect(JSON.parse(putCall?.[1].body)).toMatchObject({+ action: "dictate_toggle",+ hotkey: "ctrl+shift+d",+ });});it("PUTs the chosen action + combo on save", async () => {diff --git a/jarvis/ui/web/frontend/src/views/KeybindsPanel.test.tsx b/jarvis/ui/web/frontend/src/views/KeybindsPanel.test.tsxindex 5dc5cdf489..63bd06ff2f 100644--- a/jarvis/ui/web/frontend/src/views/KeybindsPanel.test.tsx+++ b/jarvis/ui/web/frontend/src/views/KeybindsPanel.test.tsx@@ -2,9 +2,23 @@ import { act, fireEvent, render, screen, waitFor } from "@testing-library/react"import { afterEach, describe, expect, it, vi } from "vitest";import { KeybindsPanel } from "./SettingsView";+// All four keybind actions, as the backend reports them (KEYBIND_ACTIONS in+// jarvis/core/config_writer.py). Settings renders three of them — hands-free+// dictation lives in the voice section's Shortcuts tab — but the panel must+// stay correct when the config carries an action it does not render.const FULL = {- keybinds: { call: "f3+f4", hangup: "f1+f2" },- defaults: { call: "f3+f4", hangup: "f1+f2" },+ keybinds: {+ call: "f3+f4",+ hangup: "f1+f2",+ dictate: "ctrl+right_alt+j",+ dictate_toggle: "ctrl+right_alt+space",+ },+ defaults: {+ call: "f3+f4",+ hangup: "f1+f2",+ dictate: "ctrl+right_alt+j",+ dictate_toggle: "ctrl+right_alt+space",+ },suggestions: [],restart_required: true,};@@ -20,7 +34,7 @@ function stubFetch() {/** The combo field's visible text with whitespace collapsed ("F3+F4") —* works for both the plain string and the kbd-chip rendering. */-function comboText(action: "call" | "hangup"): string {+function comboText(action: "call" | "hangup" | "dictate"): string {return (screen.getByTestId(`combo-field-${action}`)@@ -39,6 +53,16 @@ describe("KeybindsPanel", () => {expect(screen.queryByText(/push-to-talk/i)).toBeNull();});+ it("renders the dictation row and leaves hands-free to the voice section", async () => {+ stubFetch();+ render(<KeybindsPanel />);+ // The right Alt key is named the way its keycap reads, not "Right-Alt".+ await waitFor(() => expect(comboText("dictate")).toBe("Ctrl+AltGr+J"));+ // Hands-free dictation is a real action, but its row lives in the voice+ // section's Shortcuts tab next to push-to-talk — not duplicated here.+ expect(screen.queryByTestId("combo-field-dictate_toggle")).toBeNull();+ });+it("captures a two-key chord (F7 + F8) pressed simultaneously", async () => {stubFetch();render(<KeybindsPanel />);diff --git a/jarvis/ui/web/frontend/src/views/SettingsView.keybinds.test.tsx b/jarvis/ui/web/frontend/src/views/SettingsView.keybinds.test.tsxindex 0c6d092fdf..1a470678cb 100644--- a/jarvis/ui/web/frontend/src/views/SettingsView.keybinds.test.tsx+++ b/jarvis/ui/web/frontend/src/views/SettingsView.keybinds.test.tsx@@ -16,9 +16,17 @@ vi.mock("@/i18n", async (importOriginal) => {});const { saveKeybind, state } = vi.hoisted(() => {+ // All four backend actions (KEYBIND_ACTIONS) — Settings renders three of+ // them; hands-free dictation lives in the voice section's Shortcuts tab.+ const keybinds = {+ call: "f3+f4",+ hangup: "f1+f2",+ dictate: "ctrl+right_alt+j",+ dictate_toggle: "ctrl+right_alt+space",+ };const defaultConfig = {- keybinds: { call: "f3+f4", hangup: "f1+f2" },- defaults: { call: "f3+f4", hangup: "f1+f2" },+ keybinds,+ defaults: { ...keybinds },suggestions: [] as string[],restart_required: false,};@@ -60,7 +68,10 @@ describe("KeybindsPanel — Clear button", () => {render(<KeybindsPanel />);expect(screen.queryByTestId("clear-keybind-call")).not.toBeNull();expect(screen.queryByTestId("clear-keybind-hangup")).not.toBeNull();+ expect(screen.queryByTestId("clear-keybind-dictate")).not.toBeNull();expect(screen.queryByTestId("clear-keybind-ptt")).toBeNull();+ // Hands-free dictation is bound in the voice section, not here.+ expect(screen.queryByTestId("clear-keybind-dictate_toggle")).toBeNull();});it("clicking Clear saves an empty hotkey for that action", async () => {diff --git a/jarvis/ui/web/frontend/src/views/SettingsView.tsx b/jarvis/ui/web/frontend/src/views/SettingsView.tsxindex 6262e2df6e..e68aee8a7e 100644--- a/jarvis/ui/web/frontend/src/views/SettingsView.tsx+++ b/jarvis/ui/web/frontend/src/views/SettingsView.tsx@@ -1,4 +1,4 @@-import { Fragment, useEffect, useMemo, useRef, useState } from "react";+import { useEffect, useRef, useState } from "react";import {Settings,Mic,@@ -7,7 +7,6 @@ import {Languages,ChevronDown,Check,- X,} from "lucide-react";import { ViewHeader } from "@/views/ChatsView";import { Switch } from "@/components/ui/switch";@@ -26,20 +25,8 @@ import {useLocalSpeechInstall,type WakeWordSaveResult,} from "@/hooks/useWakeWord";-import {- useKeybinds,- chordToCombo,- codeToKeyToken,- composeCombo,- comboTokens,- validateCombo,- type ComboValidation,- type KeybindAction,- type KeybindsConfig,- type KeybindSaveResult,-} from "@/hooks/useHotkey";-import { KeyboardMap } from "@/views/settings/KeyboardMap";-import { detectKeyboardPlatform } from "@/views/settings/keyboardLayout";+import { useKeybinds, type KeybindAction } from "@/hooks/useHotkey";+import { KeybindRow } from "@/views/settings/KeybindRow";import { deriveAssistantName } from "@/lib/deriveAssistantName";import { WAKE_ENGINES, WAKE_ENGINE_I18N_KEY } from "@/constants/wakeEngines";import { useEventStore } from "@/store/events";@@ -729,48 +716,6 @@ function WakeWordPanel() {);}-/** Pretty-print a combo string ("ctrl+right_alt+j" → "Ctrl + Right-Alt + J"). */-function formatCombo(combo: string): string {- const labels: Record<string, string> = {- ctrl: "Ctrl",- control: "Ctrl",- right_ctrl: "Right-Ctrl",- alt: "Alt",- left_alt: "Left-Alt",- right_alt: "Right-Alt",- altgr: "AltGr",- shift: "Shift",- win: "Win",- space: "Space",- // Navigation / editing cluster + numpad operators (the backend key names).- up: "↑",- down: "↓",- left: "←",- right: "→",- insert: "Insert",- delete: "Delete",- home: "Home",- end: "End",- page_up: "PageUp",- page_down: "PageDown",- enter: "Enter",- tab: "Tab",- backspace: "Backspace",- add_key: "Num +",- subtract_key: "Num −",- multiply_key: "Num *",- divide_key: "Num /",- decimal_key: "Num .",- };- // Numpad digits render as "Num 3" rather than "NUMPAD_3".- const numpad = (p: string) =>- /^numpad_[0-9]$/.test(p) ? "Num " + p.slice(7) : null;- return combo- .split("+")- .map((p) => labels[p] ?? numpad(p) ?? p.toUpperCase())- .join(" + ");-}-const _KEYBIND_ROWS: { action: KeybindAction; labelKey: string }[] = [{ action: "call", labelKey: "settings_view.keybinds.call_label" },{ action: "hangup", labelKey: "settings_view.keybinds.hangup_label" },@@ -778,11 +723,15 @@ const _KEYBIND_ROWS: { action: KeybindAction; labelKey: string }[] = [];/**- * Editable Call and Hangup keybinds, one row each. The user clicks Record and- * presses a combination (captured via eventToCombo), or resets to default,- * then saves. The backend validator is the authority — an unsafe combo or a- * collision with the other action is rejected with a reason shown as a toast.- * A successful save surfaces a restart-required hint.+ * Editable Call, Hangup and Dictation keybinds, one row each. The user clicks+ * Record and presses a combination, or resets to default, then saves. The+ * backend validator is the authority — an unsafe combo or a collision with+ * another action is rejected with a reason shown as a toast. A successful save+ * surfaces a restart-required hint.+ *+ * Hands-free dictation (`dictate_toggle`) is deliberately NOT a row here: the+ * two dictation shortcuts belong together, and the voice section's Shortcuts+ * tab is where they live side by side. The row component is shared.*/export function KeybindsPanel() {const t = useT();@@ -817,382 +766,3 @@ export function KeybindsPanel() {</div>);}--// The keyboard family (Mac vs PC modifier labels) is fixed for the session.-const _KB_PLATFORM = detectKeyboardPlatform();--// Each action's i18n label key — used to mark a key "already used by <action>".-const _ACTION_LABEL_KEY: Record<KeybindAction, string> = {- call: "settings_view.keybinds.call_label",- hangup: "settings_view.keybinds.hangup_label",- dictate: "settings_view.keybinds.dictate_label",-};--/** The combo rendered as keycap chips ("Ctrl + F5" → [Ctrl] + [F5]). */-function ComboChips({ combo }: { combo: string }) {- const parts = formatCombo(combo).split(" + ");- return (- <>- {parts.map((p, i) => (- <Fragment key={`${p}-${i}`}>- {i > 0 && <span className="text-muted-foreground/50">+</span>}- <kbd className="rounded border border-border bg-muted/70 px-1.5 py-0.5 font-mono text-[11px] leading-none text-foreground shadow-[inset_0_-1px_0_rgba(0,0,0,0.35)]">- {p}- </kbd>- </Fragment>- ))}- </>- );-}--/** The localized live-validation message for the combo being built, or null. */-function validationText(- v: ComboValidation,- t: (key: string) => string,-): string | null {- if (v.status !== "error" && v.status !== "warning") return null;- if (v.reason === "collision") {- return t("settings_view.keybinds.validation.collision")- .replace("{action}", v.conflict.action)- .replace("{combo}", formatCombo(v.conflict.combo));- }- return t(`settings_view.keybinds.validation.${v.reason}`);-}--function KeybindRow({- action,- label,- config,- loading,- onSave,-}: {- action: KeybindAction;- label: string;- config: KeybindsConfig | null;- loading: boolean;- onSave: (a: KeybindAction, h: string) => Promise<KeybindSaveResult>;-}) {- const t = useT();- const pushToast = useEventStore((s) => s.pushToast);- const current = config?.keybinds[action] ?? "";- const def = config?.defaults[action];-- const [combo, setCombo] = useState("");- const [capturing, setCapturing] = useState(false);- const [saving, setSaving] = useState(false);- const [saved, setSaved] = useState(false);- // Physical codes currently held — mirrored from the recorder so the on-screen- // keyboard lights up live as the user presses keys.- const [pressedCodes, setPressedCodes] = useState<Set<string>>(new Set());-- useEffect(() => {- if (config) setCombo(config.keybinds[action]);- }, [config, action]);-- // Tokens already bound to the OTHER actions → marked "used" on the keyboard so- // the user can pick a free key (their keys "can't be free", as reported).- const boundTokens = useMemo(() => {- const out: Record<string, string> = {};- if (!config) return out;- for (const [act, c] of Object.entries(config.keybinds)) {- if (act === action) continue;- const lbl = t(_ACTION_LABEL_KEY[act as KeybindAction]);- for (const tok of comboTokens(c)) out[tok] = lbl;- }- return out;- }, [config, action, t]);-- // The OTHER actions' combos keyed by their translated label, so a collision- // message names the action exactly the way the UI labels it.- const otherCombos = useMemo(() => {- const out: Record<string, string> = {};- if (!config) return out;- for (const [act, c] of Object.entries(config.keybinds)) {- if (act !== action) out[t(_ACTION_LABEL_KEY[act as KeybindAction])] = c;- }- return out;- }, [config, action, t]);-- // Live validation — every backend rule surfaces HERE, while the user builds- // the combo, instead of as a cryptic post-Save error toast (the reported- // "I picked Arrow Up and got a weird error message" experience).- const validation = useMemo(- () => validateCombo(combo, otherCombos),- [combo, otherCombos],- );- const invalid = validation.status === "error";- const validationMsg = validationText(validation, t);-- // Click-to-assign: toggle a key in/out of the combo without a physical press.- // Functional update — toggles dispatched before the next render must each- // build on the previous one, not on a stale closure combo (last-click-wins).- function onToggleToken(token: string) {- setCombo((prev) => {- const tokens = comboTokens(prev);- if (tokens.has(token)) tokens.delete(token);- else tokens.add(token);- return composeCombo(tokens);- });- setSaved(false);- }-- // While capturing, listen on `window` (capture phase) instead of on a single- // button. Three reasons:- // 1. Focus: clicking the "Record" button puts focus on THAT button, so a- // key listener living only on the display field never fired — the combo- // was silently dropped. A window listener catches the chord no matter- // which control has focus.- // 2. Chord: a held set accumulates every non-modifier key, so several keys- // pressed together (WASD, F7+F8, I+Y) — which the global-hotkeys backend- // registers natively (the Call default is f3+f4) — all land in the combo- // instead of only the first one.- // 3. Commit on FULL release, not on the first keyup. We track every- // physically-held key (incl. modifiers, by `event.code`) and only commit- // once the user has let go of everything. Committing on the first keyup- // ended the recording the instant any one key lifted, so a human pressing- // a chord (whose key releases are never perfectly simultaneous, and whose- // presses roll in one after another) only ever got the first key — the- // reported "press several, only one is recorded" bug. Now the rule is the- // natural one: "hold your keys, then let go".- // preventDefault on both edges also stops the keystrokes from leaking into- // the rest of the app while recording (the "everything lags" symptom).- // What Escape restores: the SAVED value (the server truth), falling back to- // the combo as of recording start when nothing is saved yet. Kept in a ref so- // the capture effect (deps: [capturing]) always reads the live value — a- // mid-recording save refetches the config, and restoring a stale snapshot- // would silently diverge the field from what the server actually has.- const currentRef = useRef(current);- currentRef.current = current;- const comboBeforeCapture = useRef(combo);-- useEffect(() => {- if (!capturing) return;- comboBeforeCapture.current = combo; // fallback when nothing is saved yet- setPressedCodes(new Set()); // fresh highlight state for this gesture- const held = new Set<string>(); // non-modifier key tokens seen this gesture- const pressed = new Set<string>(); // physical event.codes currently down- let pending: string | null = null; // fullest chord captured so far- let idle: ReturnType<typeof setTimeout> | undefined; // fallback-commit timer-- function commit() {- if (pending) {- setCombo(pending);- setSaved(false);- setCapturing(false);- }- }-- function onKeyDown(e: KeyboardEvent) {- e.preventDefault();- e.stopPropagation();- if (e.key === "Escape") {- if (idle) clearTimeout(idle); // cancel a pending fallback commit- // Undo the live preview: back to the saved value (server truth).- setCombo(currentRef.current || comboBeforeCapture.current);- setCapturing(false);- return;- }- pressed.add(e.code);- setPressedCodes(new Set(pressed)); // live keyboard highlight- const tok = codeToKeyToken(e.code);- if (tok) held.add(tok);- const next = chordToCombo(e, held);- if (next) {- pending = next;- setCombo(next); // live preview as the chord grows- setSaved(false);- }- // Fallback: some keys — function keys especially, and any key whose- // release lands while the window is losing focus — do NOT reliably- // deliver a keyup. Without this the "commit on full release" path below- // would hang forever ("F5+F6 never records"). Re-arm an idle timer on- // every keydown; once the user stops pressing for ~900 ms, commit the- // chord we have even if a keyup never came.- if (idle) clearTimeout(idle);- idle = setTimeout(commit, 900);- }-- function onKeyUp(e: KeyboardEvent) {- e.preventDefault();- e.stopPropagation();- pressed.delete(e.code);- setPressedCodes(new Set(pressed)); // live keyboard highlight- // Fast path: commit the instant EVERY key is released. `pending` holds- // the fullest chord seen during the gesture, so the release order never- // matters and early-lifted keys are not lost.- if (pressed.size === 0 && pending) {- if (idle) clearTimeout(idle);- commit();- }- }-- window.addEventListener("keydown", onKeyDown, true);- window.addEventListener("keyup", onKeyUp, true);- return () => {- if (idle) clearTimeout(idle);- window.removeEventListener("keydown", onKeyDown, true);- window.removeEventListener("keyup", onKeyUp, true);- };- }, [capturing]);-- // Clear the live highlight on the falling edge of capturing, so reopening the- // picker never flashes the previous chord's keys before the first new press.- useEffect(() => {- if (!capturing) setPressedCodes(new Set());- }, [capturing]);-- async function onSaveClick() {- const trimmed = combo.trim().toLowerCase();- if (!trimmed) return;- setSaving(true);- setSaved(false);- try {- const res = await onSave(action, trimmed);- setSaved(res.restart_required);- // The save concludes the recording session. Leaving the recorder open- // kept a stale pre-recording snapshot around that a later Esc would- // "restore" — silently diverging the field from the saved value.- setCapturing(false);- pushToast("success", t("settings_view.keybinds.saved"));- } catch (e) {- // Backend rejected the combo (unsafe / collision) — show its reason.- pushToast("error", (e as Error).message);- } finally {- setSaving(false);- }- }-- // Immediate, one-click unbind — no staging step, mirroring the "Reset to- // default" link's immediacy. Bypasses onSaveClick's trimmed-empty guard,- // which exists to stop an in-progress recording from saving nothing.- async function onClearClick() {- setSaving(true);- try {- const res = await onSave(action, "");- setCombo("");- setCapturing(false);- setSaved(res.restart_required);- pushToast("success", t("settings_view.keybinds.cleared"));- } catch (e) {- pushToast("error", (e as Error).message);- } finally {- setSaving(false);- }- }-- const dirty = !!config && combo.trim().toLowerCase() !== current;- const showReset = !!def && combo.trim().toLowerCase() !== def;-- return (- <div className="rounded-md border border-border/60 bg-background/40 p-3">- <div className="flex items-center justify-between gap-2">- <span className="text-xs font-semibold text-foreground">{label}</span>- {showReset && (- <button- type="button"- className="text-[11px] text-muted-foreground underline hover:text-foreground"- onClick={() => {- if (def) {- setCombo(def);- setSaved(false);- }- }}- >- {t("settings_view.keybinds.reset")}- </button>- )}- </div>- <div className="mt-2 flex items-center gap-2">- <button- type="button"- data-testid={`combo-field-${action}`}- onClick={() => setCapturing((c) => !c)}- disabled={loading}- className={`flex min-h-[34px] flex-1 flex-wrap items-center gap-1 rounded-md border px-3 py-1.5 text-left text-sm transition-colors focus:outline-none focus:ring-1 focus:ring-primary disabled:opacity-50 ${- capturing- ? "border-primary bg-primary/10"- : "border-input bg-background"- }`}- >- {capturing && (- <span className="relative mr-1 flex h-2 w-2 shrink-0">- <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-primary opacity-75" />- <span className="relative inline-flex h-2 w-2 rounded-full bg-primary" />- </span>- )}- {combo ? (- <ComboChips combo={combo} />- ) : (- <span className="text-muted-foreground">- {capturing- ? t("settings_view.keybinds.recording")- : loading- ? "—"- : t("settings_view.keybinds.unbound")}- </span>- )}- </button>- <Button- size="sm"- variant="outline"- onClick={() => setCapturing((c) => !c)}- disabled={loading}- >- {capturing- ? t("settings_view.keybinds.stop")- : t("settings_view.keybinds.record")}- </Button>- <Button- size="sm"- onClick={onSaveClick}- disabled={saving || loading || !dirty || invalid}- >- {saving ? t("settings_view.saving") : t("settings_view.keybinds.save")}- </Button>- <Button- type="button"- size="sm"- variant="ghost"- data-testid={`clear-keybind-${action}`}- aria-label={t("settings_view.keybinds.clear")}- title={t("settings_view.keybinds.clear")}- onClick={onClearClick}- disabled={saving || loading || !current}- >- <X className="h-3.5 w-3.5" />- </Button>- </div>- {/* ONE stable status line: the validation message when there is one,- the recording hint otherwise. Two separately appearing lines made the- keyboard below jump vertically on every combo click. */}- {(capturing || validationMsg) && (- <p- data-testid={validationMsg ? `keybind-validation-${action}` : undefined}- className={`mt-2 text-[11px] ${- validationMsg- ? validation.status === "error"- ? "text-destructive"- : "text-amber-400"- : "text-muted-foreground"- }`}- >- {validationMsg ?? t("settings_view.keybinds.recording_hint")}- </p>- )}- {capturing && (- <KeyboardMap- pressedCodes={pressedCodes}- selectedTokens={comboTokens(combo)}- boundTokens={boundTokens}- platform={_KB_PLATFORM}- onToggleToken={onToggleToken}- />- )}- {saved && (- <p className="mt-2 text-[11px] text-muted-foreground">- {t("settings_view.keybinds.restart_required")}- </p>- )}- </div>- );-}diff --git a/jarvis/ui/web/frontend/src/views/settings/KeybindRow.tsx b/jarvis/ui/web/frontend/src/views/settings/KeybindRow.tsxnew file mode 100644index 0000000000..fac99eff95--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/settings/KeybindRow.tsx@@ -0,0 +1,630 @@+import { Fragment, useEffect, useMemo, useRef, useState } from "react";+import { Pencil, Plus, X } from "lucide-react";++import { Button } from "@/components/ui/button";+import {+ chordToCombo,+ codeToKeyToken,+ composeCombo,+ comboTokens,+ validateCombo,+ type ComboValidation,+ type KeybindAction,+ type KeybindsConfig,+ type KeybindSaveResult,+} from "@/hooks/useHotkey";+import { KeyboardMap } from "@/views/settings/KeyboardMap";+import { detectKeyboardPlatform } from "@/views/settings/keyboardLayout";+import { useEventStore } from "@/store/events";+import { useT } from "@/i18n";++// The keyboard family (Mac vs PC modifier labels) is fixed for the session.+const _KB_PLATFORM = detectKeyboardPlatform();++/** Pretty-print a combo string ("ctrl+right_alt+j" → "Ctrl + AltGr + J"). */+export function formatCombo(combo: string): string {+ const labels: Record<string, string> = {+ ctrl: "Ctrl",+ control: "Ctrl",+ right_ctrl: "Right-Ctrl",+ alt: "Alt",+ left_alt: "Left-Alt",+ // The right Alt key is labelled the way the keycap actually reads — "AltGr"+ // on a PC layout, the Option glyph on a Mac — so the chip in the row and the+ // cap on the on-screen keyboard name the SAME physical key. "Right-Alt"+ // named a key that no keyboard prints.+ right_alt: _KB_PLATFORM === "mac" ? "⌥" : "AltGr",+ altgr: _KB_PLATFORM === "mac" ? "⌥" : "AltGr",+ shift: "Shift",+ win: "Win",+ space: "Space",+ // Navigation / editing cluster + numpad operators (the backend key names).+ up: "↑",+ down: "↓",+ left: "←",+ right: "→",+ insert: "Insert",+ delete: "Delete",+ home: "Home",+ end: "End",+ page_up: "PageUp",+ page_down: "PageDown",+ enter: "Enter",+ tab: "Tab",+ backspace: "Backspace",+ add_key: "Num +",+ subtract_key: "Num −",+ multiply_key: "Num *",+ divide_key: "Num /",+ decimal_key: "Num .",+ };+ // Numpad digits render as "Num 3" rather than "NUMPAD_3".+ const numpad = (p: string) =>+ /^numpad_[0-9]$/.test(p) ? "Num " + p.slice(7) : null;+ return combo+ .split("+")+ .map((p) => labels[p] ?? numpad(p) ?? p.toUpperCase())+ .join(" + ");+}++/**+ * Each action's i18n label key — used to mark a key "already used by <action>"+ * and to name the other side of a collision the way the UI labels it.+ * Mirrors KEYBIND_ACTIONS in jarvis/core/config_writer.py.+ */+export const ACTION_LABEL_KEY: Record<KeybindAction, string> = {+ call: "settings_view.keybinds.call_label",+ hangup: "settings_view.keybinds.hangup_label",+ dictate: "settings_view.keybinds.dictate_label",+ dictate_toggle: "settings_view.keybinds.dictate_toggle_label",+};++/** The combo rendered as keycap chips ("Ctrl + F5" → [Ctrl] + [F5]). */+export function ComboChips({ combo }: { combo: string }) {+ const parts = formatCombo(combo).split(" + ");+ return (+ <>+ {parts.map((p, i) => (+ <Fragment key={`${p}-${i}`}>+ {i > 0 && <span className="text-muted-foreground/50">+</span>}+ <kbd className="rounded border border-border bg-muted/70 px-1.5 py-0.5 font-mono text-[11px] leading-none text-foreground shadow-[inset_0_-1px_0_rgba(0,0,0,0.35)]">+ {p}+ </kbd>+ </Fragment>+ ))}+ </>+ );+}++/** The localized live-validation message for the combo being built, or null. */+export function validationText(+ v: ComboValidation,+ t: (key: string) => string,+): string | null {+ if (v.status !== "error" && v.status !== "warning") return null;+ if (v.reason === "collision") {+ // The conflict carries the ACTION ID (unique); the message names it the way+ // the UI labels that row. An id the frontend does not know yet (a newer+ // backend) falls back to the raw id instead of rendering an empty name.+ const labelKey = ACTION_LABEL_KEY[v.conflict.action as KeybindAction];+ return t("settings_view.keybinds.validation.collision")+ .replace("{action}", labelKey ? t(labelKey) : v.conflict.action)+ .replace("{combo}", formatCombo(v.conflict.combo));+ }+ return t(`settings_view.keybinds.validation.${v.reason}`);+}++export interface KeybindRowProps {+ action: KeybindAction;+ label: string;+ config: KeybindsConfig | null;+ loading: boolean;+ onSave: (a: KeybindAction, h: string) => Promise<KeybindSaveResult>;+ /** One explanatory line under the label (voice variant only). */+ hint?: string;+ /**+ * "settings" — the compact row inside Settings → Voice Keybinds (unchanged).+ * "voice" — the wider row of the Shortcuts tab: label + hint on the left, the+ * combo chips plus a pencil (record) and a plus (pick on the keyboard) on the+ * right.+ */+ variant?: "settings" | "voice";+ /** Curated combos offered as one-click chips (voice variant only). */+ suggestions?: string[];+ /**+ * Called after a combo was accepted by the backend. Lets the owner apply a+ * side effect that belongs to the same user intent (the Push-to-Talk row+ * pins the dictation mode to "hold"). Failures are the owner's to report.+ */+ onSaved?: (combo: string) => void | Promise<void>;+}++/**+ * One editable keybind: shows the current combo, records a new one (physical+ * chord or click-to-assign on the on-screen keyboard), validates it live and+ * saves it. The backend validator stays the authority — a rejected combo+ * surfaces its reason as a toast.+ */+export function KeybindRow({+ action,+ label,+ config,+ loading,+ onSave,+ hint,+ variant = "settings",+ suggestions,+ onSaved,+}: KeybindRowProps) {+ const t = useT();+ const pushToast = useEventStore((s) => s.pushToast);+ // `?? ""` is load-bearing: a backend that does not know this action yet+ // returns no entry at all, and an undefined combo would crash comboTokens.+ const current = config?.keybinds[action] ?? "";+ const def = config?.defaults[action];++ const [combo, setCombo] = useState("");+ const [capturing, setCapturing] = useState(false);+ const [saving, setSaving] = useState(false);+ const [saved, setSaved] = useState(false);+ // Physical codes currently held — mirrored from the recorder so the on-screen+ // keyboard lights up live as the user presses keys.+ const [pressedCodes, setPressedCodes] = useState<Set<string>>(new Set());++ useEffect(() => {+ if (config) setCombo(config.keybinds[action] ?? "");+ }, [config, action]);++ // Tokens already bound to the OTHER actions → marked "used" on the keyboard so+ // the user can pick a free key (their keys "can't be free", as reported).+ const boundTokens = useMemo(() => {+ const out: Record<string, string> = {};+ if (!config) return out;+ for (const [act, c] of Object.entries(config.keybinds)) {+ if (act === action) continue;+ const labelKey = ACTION_LABEL_KEY[act as KeybindAction];+ const lbl = labelKey ? t(labelKey) : act;+ for (const tok of comboTokens(c ?? "")) out[tok] = lbl;+ }+ return out;+ }, [config, action, t]);++ // The OTHER actions' combos keyed by their ACTION ID. Keying by the translated+ // label collapsed two rows that happen to share a label into one entry, so one+ // of them stopped being checked for collisions; validationText translates the+ // id back for the message.+ const otherCombos = useMemo(() => {+ const out: Record<string, string> = {};+ if (!config) return out;+ for (const [act, c] of Object.entries(config.keybinds)) {+ if (act !== action) out[act] = c ?? "";+ }+ return out;+ }, [config, action]);++ // Live validation — every backend rule surfaces HERE, while the user builds+ // the combo, instead of as a cryptic post-Save error toast (the reported+ // "I picked Arrow Up and got a weird error message" experience).+ const validation = useMemo(+ () => validateCombo(combo, otherCombos),+ [combo, otherCombos],+ );+ const invalid = validation.status === "error";+ const validationMsg = validationText(validation, t);++ // Click-to-assign: toggle a key in/out of the combo without a physical press.+ // Functional update — toggles dispatched before the next render must each+ // build on the previous one, not on a stale closure combo (last-click-wins).+ function onToggleToken(token: string) {+ setCombo((prev) => {+ const tokens = comboTokens(prev);+ if (tokens.has(token)) tokens.delete(token);+ else tokens.add(token);+ return composeCombo(tokens);+ });+ setSaved(false);+ }++ // While capturing, listen on `window` (capture phase) instead of on a single+ // button. Three reasons:+ // 1. Focus: clicking the "Record" button puts focus on THAT button, so a+ // key listener living only on the display field never fired — the combo+ // was silently dropped. A window listener catches the chord no matter+ // which control has focus.+ // 2. Chord: a held set accumulates every non-modifier key, so several keys+ // pressed together (WASD, F7+F8, I+Y) — which the global-hotkeys backend+ // registers natively (the Call default is f3+f4) — all land in the combo+ // instead of only the first one.+ // 3. Commit on FULL release, not on the first keyup. We track every+ // physically-held key (incl. modifiers, by `event.code`) and only commit+ // once the user has let go of everything. Committing on the first keyup+ // ended the recording the instant any one key lifted, so a human pressing+ // a chord (whose key releases are never perfectly simultaneous, and whose+ // presses roll in one after another) only ever got the first key — the+ // reported "press several, only one is recorded" bug. Now the rule is the+ // natural one: "hold your keys, then let go".+ // preventDefault on both edges also stops the keystrokes from leaking into+ // the rest of the app while recording (the "everything lags" symptom).+ // What Escape restores: the SAVED value (the server truth), falling back to+ // the combo as of recording start when nothing is saved yet. Kept in a ref so+ // the capture effect (deps: [capturing]) always reads the live value — a+ // mid-recording save refetches the config, and restoring a stale snapshot+ // would silently diverge the field from what the server actually has.+ const currentRef = useRef(current);+ currentRef.current = current;+ const comboBeforeCapture = useRef(combo);++ useEffect(() => {+ if (!capturing) return;+ comboBeforeCapture.current = combo; // fallback when nothing is saved yet+ setPressedCodes(new Set()); // fresh highlight state for this gesture+ const held = new Set<string>(); // non-modifier key tokens seen this gesture+ const pressed = new Set<string>(); // physical event.codes currently down+ let pending: string | null = null; // fullest chord captured so far+ let idle: ReturnType<typeof setTimeout> | undefined; // fallback-commit timer++ function commit() {+ if (pending) {+ setCombo(pending);+ setSaved(false);+ setCapturing(false);+ }+ }++ function onKeyDown(e: KeyboardEvent) {+ e.preventDefault();+ e.stopPropagation();+ if (e.key === "Escape") {+ if (idle) clearTimeout(idle); // cancel a pending fallback commit+ // Undo the live preview: back to the saved value (server truth).+ setCombo(currentRef.current || comboBeforeCapture.current);+ setCapturing(false);+ return;+ }+ pressed.add(e.code);+ setPressedCodes(new Set(pressed)); // live keyboard highlight+ const tok = codeToKeyToken(e.code);+ if (tok) held.add(tok);+ const next = chordToCombo(e, held);+ if (next) {+ pending = next;+ setCombo(next); // live preview as the chord grows+ setSaved(false);+ }+ // Fallback: some keys — function keys especially, and any key whose+ // release lands while the window is losing focus — do NOT reliably+ // deliver a keyup. Without this the "commit on full release" path below+ // would hang forever ("F5+F6 never records"). Re-arm an idle timer on+ // every keydown; once the user stops pressing for ~900 ms, commit the+ // chord we have even if a keyup never came.+ if (idle) clearTimeout(idle);+ idle = setTimeout(commit, 900);+ }++ function onKeyUp(e: KeyboardEvent) {+ e.preventDefault();+ e.stopPropagation();+ pressed.delete(e.code);+ setPressedCodes(new Set(pressed)); // live keyboard highlight+ // Fast path: commit the instant EVERY key is released. `pending` holds+ // the fullest chord seen during the gesture, so the release order never+ // matters and early-lifted keys are not lost.+ if (pressed.size === 0 && pending) {+ if (idle) clearTimeout(idle);+ commit();+ }+ }++ window.addEventListener("keydown", onKeyDown, true);+ window.addEventListener("keyup", onKeyUp, true);+ return () => {+ if (idle) clearTimeout(idle);+ window.removeEventListener("keydown", onKeyDown, true);+ window.removeEventListener("keyup", onKeyUp, true);+ };+ }, [capturing]);++ // Clear the live highlight on the falling edge of capturing, so reopening the+ // picker never flashes the previous chord's keys before the first new press.+ useEffect(() => {+ if (!capturing) setPressedCodes(new Set());+ }, [capturing]);++ async function onSaveClick() {+ const trimmed = combo.trim().toLowerCase();+ if (!trimmed) return;+ setSaving(true);+ setSaved(false);+ try {+ const res = await onSave(action, trimmed);+ setSaved(res.restart_required);+ // The save concludes the recording session. Leaving the recorder open+ // kept a stale pre-recording snapshot around that a later Esc would+ // "restore" — silently diverging the field from the saved value.+ setCapturing(false);+ pushToast("success", t("settings_view.keybinds.saved"));+ await onSaved?.(trimmed);+ } catch (e) {+ // Backend rejected the combo (unsafe / collision) — show its reason.+ pushToast("error", (e as Error).message);+ } finally {+ setSaving(false);+ }+ }++ // Immediate, one-click unbind — no staging step, mirroring the "Reset to+ // default" link's immediacy. Bypasses onSaveClick's trimmed-empty guard,+ // which exists to stop an in-progress recording from saving nothing.+ async function onClearClick() {+ setSaving(true);+ try {+ const res = await onSave(action, "");+ setCombo("");+ setCapturing(false);+ setSaved(res.restart_required);+ pushToast("success", t("settings_view.keybinds.cleared"));+ } catch (e) {+ pushToast("error", (e as Error).message);+ } finally {+ setSaving(false);+ }+ }++ const dirty = !!config && combo.trim().toLowerCase() !== current;+ const showReset = !!def && combo.trim().toLowerCase() !== def;++ // Curated combos that are still free — a chip proposing a combo another+ // action already owns would only manufacture a rejected save.+ const freeSuggestions = useMemo(() => {+ if (!suggestions?.length) return [];+ const taken = new Set(+ Object.values(otherCombos)+ .map((c) => c.trim().toLowerCase())+ .filter(Boolean),+ );+ return suggestions+ .map((s) => s.trim().toLowerCase())+ .filter((s) => s && !taken.has(s) && s !== combo.trim().toLowerCase())+ .slice(0, 4);+ }, [suggestions, otherCombos, combo]);++ const comboField = (+ <button+ type="button"+ data-testid={`combo-field-${action}`}+ onClick={() => setCapturing((c) => !c)}+ disabled={loading}+ className={`flex min-h-[34px] flex-wrap items-center gap-1 rounded-md border px-3 py-1.5 text-left text-sm transition-colors focus:outline-none focus:ring-1 focus:ring-primary disabled:opacity-50 ${+ variant === "voice" ? "" : "flex-1"+ } ${capturing ? "border-primary bg-primary/10" : "border-input bg-background"}`}+ >+ {capturing && (+ <span className="relative mr-1 flex h-2 w-2 shrink-0">+ <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-primary opacity-75" />+ <span className="relative inline-flex h-2 w-2 rounded-full bg-primary" />+ </span>+ )}+ {combo ? (+ <ComboChips combo={combo} />+ ) : (+ <span className="text-muted-foreground">+ {capturing+ ? t("settings_view.keybinds.recording")+ : loading+ ? "—"+ : t("settings_view.keybinds.unbound")}+ </span>+ )}+ </button>+ );++ // ONE stable status line: the validation message when there is one, the+ // recording hint otherwise. Two separately appearing lines made the keyboard+ // below jump vertically on every combo click.+ const statusLine = (capturing || validationMsg) && (+ <p+ data-testid={validationMsg ? `keybind-validation-${action}` : undefined}+ className={`mt-2 text-[11px] ${+ validationMsg+ ? validation.status === "error"+ ? "text-destructive"+ : "text-amber-400"+ : "text-muted-foreground"+ }`}+ >+ {validationMsg ?? t("settings_view.keybinds.recording_hint")}+ </p>+ );++ const keyboard = capturing && (+ <KeyboardMap+ pressedCodes={pressedCodes}+ selectedTokens={comboTokens(combo)}+ boundTokens={boundTokens}+ platform={_KB_PLATFORM}+ onToggleToken={onToggleToken}+ />+ );++ const restartHint = saved && (+ <p className="mt-2 text-[11px] text-muted-foreground">+ {t("settings_view.keybinds.restart_required")}+ </p>+ );++ if (variant === "voice") {+ return (+ <div className="rounded-lg border border-border bg-card/60 p-4">+ <div className="flex flex-wrap items-start justify-between gap-3">+ <div className="min-w-0 flex-1">+ <p className="text-sm font-semibold text-foreground">{label}</p>+ {hint && (+ <p className="mt-0.5 text-xs text-muted-foreground">{hint}</p>+ )}+ </div>+ <div className="flex shrink-0 items-center gap-2">+ {comboField}+ <Button+ type="button"+ size="sm"+ variant="outline"+ data-testid={`record-keybind-${action}`}+ aria-label={+ capturing+ ? t("settings_view.keybinds.stop")+ : t("settings_view.keybinds.record")+ }+ title={+ capturing+ ? t("settings_view.keybinds.stop")+ : t("settings_view.keybinds.record")+ }+ onClick={() => setCapturing((c) => !c)}+ disabled={loading}+ >+ <Pencil className="h-3.5 w-3.5" />+ </Button>+ <Button+ type="button"+ size="sm"+ variant="outline"+ data-testid={`add-keybind-${action}`}+ aria-label={t("settings_view.keybinds.keyboard.hint")}+ title={t("settings_view.keybinds.keyboard.hint")}+ onClick={() => setCapturing(true)}+ disabled={loading}+ >+ <Plus className="h-3.5 w-3.5" />+ </Button>+ <Button+ type="button"+ size="sm"+ variant="ghost"+ data-testid={`clear-keybind-${action}`}+ aria-label={t("settings_view.keybinds.clear")}+ title={t("settings_view.keybinds.clear")}+ onClick={onClearClick}+ disabled={saving || loading || !current}+ >+ <X className="h-3.5 w-3.5" />+ </Button>+ </div>+ </div>++ {freeSuggestions.length > 0 && (+ <div className="mt-3 flex flex-wrap items-center gap-2">+ <span className="text-[11px] text-muted-foreground">+ {t("voice.shortcuts.suggestions_title")}+ </span>+ {freeSuggestions.map((s) => (+ <button+ key={s}+ type="button"+ data-testid={`suggestion-${action}-${s}`}+ onClick={() => {+ setCombo(s);+ setSaved(false);+ }}+ className="rounded-full border border-border bg-background px-2 py-0.5 font-mono text-[11px] text-muted-foreground transition-colors hover:border-primary/60 hover:text-foreground"+ >+ {formatCombo(s)}+ </button>+ ))}+ </div>+ )}++ {statusLine}++ {/* The commit controls only appear once there is something to commit —+ a resting row is just the shortcut, not a form. */}+ {(dirty || showReset) && (+ <div className="mt-3 flex flex-wrap items-center gap-2">+ <Button+ size="sm"+ onClick={onSaveClick}+ disabled={saving || loading || !dirty || invalid}+ >+ {saving+ ? t("settings_view.saving")+ : t("settings_view.keybinds.save")}+ </Button>+ {showReset && (+ <button+ type="button"+ className="text-[11px] text-muted-foreground underline hover:text-foreground"+ onClick={() => {+ if (def) {+ setCombo(def);+ setSaved(false);+ }+ }}+ >+ {t("settings_view.keybinds.reset")}+ </button>+ )}+ </div>+ )}++ {keyboard}+ {restartHint}+ </div>+ );+ }++ return (+ <div className="rounded-md border border-border/60 bg-background/40 p-3">+ <div className="flex items-center justify-between gap-2">+ <span className="text-xs font-semibold text-foreground">{label}</span>+ {showReset && (+ <button+ type="button"+ className="text-[11px] text-muted-foreground underline hover:text-foreground"+ onClick={() => {+ if (def) {+ setCombo(def);+ setSaved(false);+ }+ }}+ >+ {t("settings_view.keybinds.reset")}+ </button>+ )}+ </div>+ <div className="mt-2 flex items-center gap-2">+ {comboField}+ <Button+ size="sm"+ variant="outline"+ onClick={() => setCapturing((c) => !c)}+ disabled={loading}+ >+ {capturing+ ? t("settings_view.keybinds.stop")+ : t("settings_view.keybinds.record")}+ </Button>+ <Button+ size="sm"+ onClick={onSaveClick}+ disabled={saving || loading || !dirty || invalid}+ >+ {saving ? t("settings_view.saving") : t("settings_view.keybinds.save")}+ </Button>+ <Button+ type="button"+ size="sm"+ variant="ghost"+ data-testid={`clear-keybind-${action}`}+ aria-label={t("settings_view.keybinds.clear")}+ title={t("settings_view.keybinds.clear")}+ onClick={onClearClick}+ disabled={saving || loading || !current}+ >+ <X className="h-3.5 w-3.5" />+ </Button>+ </div>+ {statusLine}+ {keyboard}+ {restartHint}+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/views/voice/ShortcutsTab.test.tsx b/jarvis/ui/web/frontend/src/views/voice/ShortcutsTab.test.tsxnew file mode 100644index 0000000000..84f0356cd0--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/voice/ShortcutsTab.test.tsx@@ -0,0 +1,190 @@+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";++// ViewHeader lives in ChatsView, which drags in the whole chat surface. The tab+// only needs the header's shape — and a testid so "renders no header when+// embedded" is assertable.+vi.mock("@/views/ChatsView", () => ({+ ViewHeader: ({ title }: { title: string }) => (+ <header data-testid="view-header">{title}</header>+ ),+}));++import { ShortcutsTab } from "@/views/voice/ShortcutsTab";++const KEYBINDS = {+ call: "f3+f4",+ hangup: "f1+f2",+ dictate: "ctrl+right_alt+j",+ dictate_toggle: "ctrl+right_alt+space",+};++const CONFIG = {+ keybinds: KEYBINDS,+ defaults: { ...KEYBINDS },+ suggestions: ["ctrl+shift+space", "ctrl+shift+d"],+ restart_required: false,+};++/** Route-aware fetch stub; returns the recorded calls for assertions. */+function stubFetch() {+ const calls: { url: string; method: string; body: unknown }[] = [];+ const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {+ const method = init?.method ?? "GET";+ calls.push({+ url,+ method,+ body: init?.body ? JSON.parse(init.body as string) : null,+ });+ if (url === "/api/settings/keybinds" && method === "PUT") {+ return {+ ok: true,+ json: async () => ({+ ok: true,+ action: "dictate",+ hotkey: "ctrl+shift+space",+ persisted: true,+ restart_required: false,+ }),+ };+ }+ if (url === "/api/dictation/settings") {+ return { ok: true, json: async () => ({ ok: true }) };+ }+ return { ok: true, json: async () => CONFIG };+ });+ vi.stubGlobal("fetch", fetchMock);+ return calls;+}++/** The row's combo field text with whitespace collapsed ("Ctrl+AltGr+J"). */+function comboText(action: string): string {+ return (+ screen.getByTestId(`combo-field-${action}`).textContent?.replace(/\s+/g, "") ??+ ""+ );+}++afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+});++describe("ShortcutsTab", () => {+ it("shows both dictation shortcuts with their current combos", async () => {+ stubFetch();+ render(<ShortcutsTab />);++ // Push-to-talk is the `dictate` action, hands-free the new+ // `dictate_toggle` — two rows, one per way of starting dictation.+ await waitFor(() => expect(comboText("dictate")).toBe("Ctrl+AltGr+J"));+ expect(comboText("dictate_toggle")).toBe("Ctrl+AltGr+Space");+ expect(screen.getByText("Push to talk")).toBeTruthy();+ expect(screen.getByText("Hands-free")).toBeTruthy();+ // Call and Hangup are NOT editable here — this tab is about dictation.+ expect(screen.queryByTestId("combo-field-call")).toBeNull();+ });++ it("renders its own header standalone and stands it down when embedded", async () => {+ stubFetch();+ const { rerender } = render(<ShortcutsTab />);+ await waitFor(() => expect(screen.getByTestId("view-header")).toBeTruthy());++ rerender(<ShortcutsTab hideHeader />);+ expect(screen.queryByTestId("view-header")).toBeNull();+ });++ it("saving push-to-talk also pins the dictation mode to hold", async () => {+ const calls = stubFetch();+ render(<ShortcutsTab />);+ await waitFor(() => expect(comboText("dictate")).toBe("Ctrl+AltGr+J"));++ // A suggested combo is one click away; Save appears once the row is dirty.+ fireEvent.click(screen.getByTestId("suggestion-dictate-ctrl+shift+space"));+ await waitFor(() => expect(comboText("dictate")).toBe("Ctrl+Shift+Space"));+ fireEvent.click(screen.getAllByRole("button", { name: /^save$/i })[0]);++ await waitFor(() =>+ expect(+ calls.some(+ (c) =>+ c.url === "/api/settings/keybinds" &&+ c.method === "PUT" &&+ (c.body as { action: string }).action === "dictate",+ ),+ ).toBe(true),+ );+ // "Push to talk" must MEAN hold — a user left on [dictation].mode="toggle"+ // would otherwise hold the keys and get toggle behaviour.+ await waitFor(() =>+ expect(+ calls.some(+ (c) =>+ c.url === "/api/dictation/settings" &&+ c.method === "PUT" &&+ (c.body as { mode: string }).mode === "hold",+ ),+ ).toBe(true),+ );+ });++ it("does not pin the mode when the hands-free row is saved", async () => {+ const calls = stubFetch();+ render(<ShortcutsTab />);+ await waitFor(() => expect(comboText("dictate_toggle")).toBe("Ctrl+AltGr+Space"));++ fireEvent.click(+ screen.getByTestId("suggestion-dictate_toggle-ctrl+shift+d"),+ );+ await waitFor(() => expect(comboText("dictate_toggle")).toBe("Ctrl+Shift+D"));+ fireEvent.click(screen.getAllByRole("button", { name: /^save$/i })[0]);++ await waitFor(() =>+ expect(calls.some((c) => c.method === "PUT")).toBe(true),+ );+ expect(calls.some((c) => c.url === "/api/dictation/settings")).toBe(false);+ });++ it("opens the on-screen keyboard and flags keys other actions already own", async () => {+ stubFetch();+ render(<ShortcutsTab />);+ await waitFor(() => expect(comboText("dictate")).toBe("Ctrl+AltGr+J"));++ fireEvent.click(screen.getByTestId("record-keybind-dictate"));++ // Call (f3+f4) and Hangup (f1+f2) are bound elsewhere; the map must say so+ // here too, or the user picks a key that cannot be saved.+ const f3 = await waitFor(() => screen.getByTestId("key-F3"));+ expect(f3.getAttribute("title")).toMatch(/call/i);+ expect(screen.getByTestId("key-F1").getAttribute("title")).toMatch(/hangup/i);+ // The hands-free row's own keys are flagged for the push-to-talk row too.+ expect(screen.getByTestId("key-Space").getAttribute("title")).toMatch(+ /hands-free/i,+ );+ });++ it("blocks an overlapping combo before it can be saved", async () => {+ stubFetch();+ render(<ShortcutsTab />);+ await waitFor(() => expect(comboText("dictate")).toBe("Ctrl+AltGr+J"));++ // Build hangup's exact combo on the push-to-talk row: F1+F2.+ fireEvent.click(screen.getByTestId("record-keybind-dictate"));+ fireEvent.click(screen.getByTestId("key-ControlLeft"));+ fireEvent.click(screen.getByTestId("key-AltRight"));+ fireEvent.click(screen.getByTestId("key-KeyJ"));+ fireEvent.click(screen.getByTestId("key-F1"));+ fireEvent.click(screen.getByTestId("key-F2"));++ const line = await waitFor(() =>+ screen.getByTestId("keybind-validation-dictate"),+ );+ // The collision names the other action the way the UI labels it, not by+ // its raw id.+ expect(line.textContent).toMatch(/hangup/i);+ const save = screen.getAllByRole("button", {+ name: /^save$/i,+ })[0] as HTMLButtonElement;+ expect(save.disabled).toBe(true);+ });+});diff --git a/jarvis/ui/web/frontend/src/views/voice/ShortcutsTab.tsx b/jarvis/ui/web/frontend/src/views/voice/ShortcutsTab.tsxindex a829b9b07f..8213558eac 100644--- a/jarvis/ui/web/frontend/src/views/voice/ShortcutsTab.tsx+++ b/jarvis/ui/web/frontend/src/views/voice/ShortcutsTab.tsx@@ -1,6 +1,9 @@import { Keyboard } from "lucide-react";import { ViewHeader } from "@/views/ChatsView";+import { KeybindRow } from "@/views/settings/KeybindRow";+import { useKeybinds, type KeybindAction } from "@/hooks/useHotkey";+import { useEventStore } from "@/store/events";import { useT } from "@/i18n";export interface ShortcutsTabProps {@@ -14,16 +17,57 @@ export interface ShortcutsTabProps {hideHeader?: boolean;}+const ROWS: {+ action: KeybindAction;+ labelKey: string;+ hintKey: string;+}[] = [+ {+ action: "dictate",+ labelKey: "voice.shortcuts.ptt_label",+ hintKey: "voice.shortcuts.ptt_hint",+ },+ {+ action: "dictate_toggle",+ labelKey: "voice.shortcuts.toggle_label",+ hintKey: "voice.shortcuts.toggle_hint",+ },+];+/*** "Shortcuts" tab of the merged voice section — the keys that start dictation.*- * Placeholder shell: the shell, its section id and its i18n keys ship first so- * the rest of the section can be built against a stable surface. The two- * keybind rows (push-to-talk + hands-free) and the on-screen keyboard land here- * next.+ * Two rows over the SAME row component Settings uses, so the recorder, the live+ * validation, the collision check and the on-screen keyboard behave identically+ * in both places:+ *+ * * Push to talk → the `dictate` action (hold the keys, speak, let go)+ * * Hands-free → the `dictate_toggle` action (press once, press again)+ *+ * Saving the push-to-talk combo also pins `[dictation].mode` to "hold". A user+ * who has switched the mode to "toggle" would otherwise hold the push-to-talk+ * keys and get toggle behaviour — the label would be lying. The hands-free row+ * needs no such pin: its action is release-independent by construction.*/export function ShortcutsTab({ hideHeader = false }: ShortcutsTabProps = {}) {const t = useT();+ const pushToast = useEventStore((s) => s.pushToast);+ const { config, loading, error, saveKeybind } = useKeybinds();++ async function pinHoldMode() {+ try {+ const res = await fetch("/api/dictation/settings", {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ mode: "hold", persist: true }),+ });+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ } catch (e) {+ // The keybind itself is already saved — report the missing side effect+ // instead of failing the whole save (or, worse, staying silent).+ pushToast("warning", (e as Error).message);+ }+ }return (<div className="flex h-full flex-col">@@ -38,7 +82,30 @@ export function ShortcutsTab({ hideHeader = false }: ShortcutsTabProps = {}) {className="flex-1 overflow-y-auto scrollbar-jarvis p-6"data-testid="voice-shortcuts-tab">- <div className="mx-auto flex max-w-3xl flex-col gap-4" />+ <div className="mx-auto flex max-w-3xl flex-col gap-4">+ {/* Embedded, the band above carries the section brand rather than+ this tab's purpose — so the purpose is stated here instead. */}+ {hideHeader && (+ <p className="text-xs text-muted-foreground">+ {t("voice.shortcuts.description")}+ </p>+ )}+ {error && <p className="text-xs text-destructive">{error}</p>}+ {ROWS.map((row) => (+ <KeybindRow+ key={row.action}+ action={row.action}+ variant="voice"+ label={t(row.labelKey)}+ hint={t(row.hintKey)}+ config={config}+ loading={loading}+ onSave={saveKeybind}+ suggestions={config?.suggestions}+ onSaved={row.action === "dictate" ? pinHoldMode : undefined}+ />+ ))}+ </div></div></div>);