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(keybinds): record any combination, including Ctrl+Win and mouse buttons
Ruben Lütkece46671de95e
diff --git a/jarvis/ui/web/frontend/src/hooks/hotkeyCombo.test.ts b/jarvis/ui/web/frontend/src/hooks/hotkeyCombo.test.tsindex 12d75a0a73..2162ee5ce3 100644--- a/jarvis/ui/web/frontend/src/hooks/hotkeyCombo.test.ts+++ b/jarvis/ui/web/frontend/src/hooks/hotkeyCombo.test.ts@@ -5,6 +5,7 @@ import {codeToModifierToken,composeCombo,comboTokens,+ normalizedComboTokens,validateCombo,} from "./useHotkey";@@ -91,7 +92,16 @@ describe("codeToModifierToken", () => {expect(codeToModifierToken("ShiftRight")).toBe("shift");expect(codeToModifierToken("AltLeft")).toBe("alt");expect(codeToModifierToken("AltRight")).toBe("right_alt");- expect(codeToModifierToken("MetaLeft")).toBe("win");+ expect(codeToModifierToken("MetaLeft", "pc")).toBe("win");+ });++ it("names the Meta key the way the host's keyboard does", () => {+ // The same physical key, two vocabularies the backends genuinely tell+ // apart. Emitting "win" on a Mac produced a combo the Mac backend cannot+ // match, and made "cmd" — the token it DOES want — unreachable from the UI.+ expect(codeToModifierToken("MetaLeft", "mac")).toBe("cmd");+ expect(codeToModifierToken("MetaRight", "mac")).toBe("cmd");+ expect(codeToModifierToken("MetaRight", "pc")).toBe("win");});it("returns null for non-modifier codes", () => {@@ -155,8 +165,37 @@ describe("chordToCombo", () => {expect(chordToCombo(ev("KeyA", { shiftKey: true }), ["a"])).toBe("shift+a");});- it("returns null while only modifiers are held (no real key yet)", () => {- expect(chordToCombo(ev("ControlLeft", { ctrlKey: true }), [])).toBeNull();+ it("records a modifier-only chord instead of dropping it", () => {+ // This used to return null the moment no non-modifier key was held, which+ // is why holding Ctrl+Win recorded literally NOTHING: the field stayed+ // blank and the gesture expired on the idle timer with no feedback at all.+ // The combo is legal (the backends register it happily), so the recorder+ // has to be able to produce it.+ expect(+ chordToCombo(ev("MetaLeft", { ctrlKey: true, metaKey: true }), [], "pc"),+ ).toBe("ctrl+win");+ expect(chordToCombo(ev("ControlLeft", { ctrlKey: true }), [])).toBe("ctrl");+ expect(+ chordToCombo(ev("MetaLeft", { ctrlKey: true, metaKey: true }), [], "mac"),+ ).toBe("ctrl+cmd");+ });++ it("returns null only when nothing at all is held", () => {+ expect(chordToCombo(ev("Escape"), [])).toBeNull();+ });++ it("keeps the Meta key in a chord with a real key", () => {+ expect(chordToCombo(ev("KeyJ", { metaKey: true }), ["j"], "pc")).toBe("win+j");+ expect(chordToCombo(ev("KeyJ", { metaKey: true }), ["j"], "mac")).toBe("cmd+j");+ });++ it("builds a mouse-button chord (the token names the backends register)", () => {+ // A mouse press carries the modifier flags but no `code`; the held-set is+ // the same one the keys use, so Ctrl + side button is one ordinary chord.+ expect(chordToCombo(ev("", { ctrlKey: true }), ["mouse_x1"])).toBe(+ "ctrl+mouse_x1",+ );+ expect(chordToCombo(ev(""), ["mouse_middle"])).toBe("mouse_middle");});it("de-duplicates repeated tokens from key-repeat", () => {@@ -164,68 +203,94 @@ describe("chordToCombo", () => {});});+describe("normalizedComboTokens", () => {+ it("folds the spellings the Windows backend cannot tell apart", () => {+ // ctrl+left_alt+j and ctrl+right_alt+j are ONE registration. Comparing the+ // raw tokens accepted both and the second then died at register time,+ // leaving a bound-looking row that does nothing.+ expect([...normalizedComboTokens("ctrl+left_alt+j")].sort()).toEqual(+ [...normalizedComboTokens("ctrl+right_alt+j")].sort(),+ );+ expect([...normalizedComboTokens("ctrl+super+space")].sort()).toEqual(+ [...normalizedComboTokens("ctrl+win+space")].sort(),+ );+ });+});+describe("validateCombo", () => {it("flags the empty combo", () => {expect(validateCombo("").status).toBe("empty");expect(validateCombo(" ").status).toBe("empty");});- it("rejects a modifier-only combo with a reason", () => {- expect(validateCombo("ctrl+shift")).toEqual({- status: "error",- reason: "only_modifiers",- });+ it("accepts a modifier-only combo and cautions that it fires on any superset", () => {+ // Inverted on purpose (maintainer directive 2026-07-28: any combination is+ // selectable). The refusal it replaces made Ctrl+Win unbindable while+ // claiming it "cannot be a trigger" — untrue: the backends register it and+ // it fires. What IS true is the prefix behaviour, so that is now said out+ // loud instead of used as a wall. A silent acceptance would be the real+ // regression, so the caution is asserted, not just the status.+ const v = validateCombo("ctrl+win");+ expect(v.status).toBe("ok");+ expect(v.cautions).toContain("modifier_only");+ expect(validateCombo("ctrl+shift").cautions).toContain("modifier_only");});- it("rejects a solo typing key (letters, digits, space, enter)", () => {+ it("accepts a solo typing key (letters, digits, space, enter) with a caution", () => {for (const combo of ["j", "5", "space", "enter", "tab", "numpad_5"]) {- expect(validateCombo(combo)).toEqual({- status: "error",- reason: "solo_typing_key",- });+ const v = validateCombo(combo);+ expect(v.status).toBe("ok");+ expect(v.cautions).toContain("solo_typing_key");}});- it("accepts solo function keys (mirrors the backend rule)", () => {- expect(validateCombo("f5").status).toBe("ok");- expect(validateCombo("f13").status).toBe("ok");+ it("accepts solo function keys with no caution at all (mirrors the backend rule)", () => {+ expect(validateCombo("f5")).toEqual({ status: "ok", cautions: [] });+ expect(validateCombo("f13")).toEqual({ status: "ok", cautions: [] });});it("accepts solo navigation keys but warns they fire while navigating", () => {- expect(validateCombo("up")).toEqual({ status: "warning", reason: "solo_nav" });- expect(validateCombo("home")).toEqual({ status: "warning", reason: "solo_nav" });- expect(validateCombo("ctrl+up").status).toBe("ok");+ expect(validateCombo("up").cautions).toEqual(["solo_nav"]);+ expect(validateCombo("home").cautions).toEqual(["solo_nav"]);+ expect(validateCombo("ctrl+up")).toEqual({ status: "ok", cautions: [] });});- it("rejects Windows-key combos (reserved by the OS)", () => {- expect(validateCombo("win+j")).toEqual({- status: "error",- reason: "windows_reserved",- });+ it("accepts Windows-key combos — the backend polls, the shell cannot claim them first", () => {+ // Inverted: the old refusal's own justification (the shell owns Win+ // shortcuts) does not hold for this app, whose Windows backend reads the+ // key state instead of registering a hotkey with the shell.+ expect(validateCombo("win+j")).toEqual({ status: "ok", cautions: [] });+ // A Win chord the desktop ALSO acts on is cautioned, not refused.+ expect(validateCombo("win+d", {}, "pc").cautions).toContain("os_shortcut");});- 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("accepts F12 in any combo but says the debugger takes it too", () => {+ expect(validateCombo("f12").cautions).toEqual(["os_shortcut"]);+ expect(validateCombo("ctrl+shift+f12").cautions).toEqual(["os_shortcut"]);+ // Its neighbours stay caution-free.+ expect(validateCombo("f11").cautions).toEqual([]);+ expect(validateCombo("ctrl+shift+f13").cautions).toEqual([]);});- 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" });- // A richer combo that merely contains them stays allowed.- expect(validateCombo("ctrl+shift+c").status).toBe("ok");+ it("accepts the OS-critical shortcuts Alt+F4 and Ctrl+C with a caution", () => {+ expect(validateCombo("alt+f4").cautions).toEqual(["os_shortcut"]);+ expect(validateCombo("ctrl+c").cautions).toEqual(["os_shortcut"]);+ // A richer combo that merely contains them stays silent.+ expect(validateCombo("ctrl+shift+c").cautions).toEqual([]);+ });++ it("cautions a Command chord macOS keeps for itself", () => {+ expect(validateCombo("cmd+q").cautions).toContain("os_shortcut");+ expect(validateCombo("cmd+shift+q").cautions).toEqual([]);+ });++ it("accepts mouse buttons and says the click is not swallowed", () => {+ const v = validateCombo("mouse_x1");+ expect(v.status).toBe("ok");+ expect(v.cautions).toEqual(["mouse_button"]);+ // A bare mouse button is NOT a "fires while you type" case.+ expect(v.cautions).not.toContain("solo_typing_key");+ expect(validateCombo("ctrl+mouse_middle").cautions).toEqual(["mouse_button"]);});it("rejects an overlap (subset/superset) with another action's combo", () => {@@ -234,14 +299,24 @@ describe("validateCombo", () => {status: "error",reason: "collision",conflict: { action: "hangup", combo: "f1+f2" },+ cautions: [],});expect(validateCombo("f3+f4+f5", others)).toEqual({status: "error",reason: "collision",conflict: { action: "call", combo: "f3+f4" },+ cautions: [],});});+ it("catches an overlap that only appears after normalization", () => {+ // The two spellings are ONE registration on Windows; comparing raw tokens+ // let the user save both and silently killed the second.+ expect(+ validateCombo("ctrl+left_alt+j", { call: "ctrl+right_alt+j" }).reason,+ ).toBe("collision");+ });+it("allows sharing a modifier with another action (no chord overlap)", () => {expect(validateCombo("ctrl+shift+h", { call: "ctrl+right_alt+j" }).status,diff --git a/jarvis/ui/web/frontend/src/hooks/useHotkey.ts b/jarvis/ui/web/frontend/src/hooks/useHotkey.tsindex fcecf38d42..81363a07be 100644--- a/jarvis/ui/web/frontend/src/hooks/useHotkey.ts+++ b/jarvis/ui/web/frontend/src/hooks/useHotkey.ts@@ -1,5 +1,11 @@import { useCallback, useEffect, useState } from "react";+import {+ MOUSE_BUTTON_TOKENS,+ detectKeyboardPlatform,+ type KeyboardPlatform,+} from "@/views/settings/keyboardLayout";+/** A KeyboardEvent-shaped object — accepts both a DOM and a React event. */export interface KeyEventLike {code: string;@@ -77,15 +83,35 @@ export function codeToKeyToken(code: string): string | null {return null; // unsupported key (punctuation, media keys, etc.)}+/**+ * The token for the Meta/Command/Windows key ON THIS HOST.+ *+ * The same physical key, two names the backends genuinely tell apart: the+ * Quartz backend decodes ``kCGEventFlagMaskCommand`` as ``cmd``, the Windows+ * and X11 backends match ``win``/``window``. Emitting ``win`` on a Mac (what+ * this file used to do unconditionally) produced a combo whose modifier the+ * Mac user's keyboard cannot express, and made ``cmd`` unreachable from the UI+ * altogether.+ */+function metaToken(platform: KeyboardPlatform): string {+ return platform === "mac" ? "cmd" : "win";+}+/*** Modifier tokens for an event, in canonical order (ctrl, alt/right_alt, shift,- * win).+ * meta).** NOTE: Windows reports AltGr (the right Alt key) as Ctrl+Alt. We therefore* trust event.code: AltRight → right_alt, and only emit "ctrl" from an actual* ControlLeft/ControlRight press, not from the synthetic Ctrl that AltGr adds.+ *+ * ``platform`` is injectable so the pure functions stay deterministic in tests;+ * it defaults to the host the app is running on.*/-function modifierTokens(e: KeyEventLike): string[] {+export function modifierTokens(+ e: KeyEventLike,+ platform: KeyboardPlatform = detectKeyboardPlatform(),+): string[] {const mods: string[] = [];const altGr =e.getModifierState?.("AltGraph") === true || e.code === "AltRight";@@ -98,7 +124,7 @@ function modifierTokens(e: KeyEventLike): string[] {mods.push("alt");}if (e.shiftKey) mods.push("shift");- if (e.metaKey) mods.push("win");+ if (e.metaKey) mods.push(metaToken(platform));return mods;}@@ -109,10 +135,13 @@ function modifierTokens(e: KeyEventLike): string[] {* Returns null if the event carries no non-modifier key yet (the user is still* only holding modifiers) — the caller keeps capturing until a real key lands.*/-export function eventToCombo(e: KeyEventLike): string | null {+export function eventToCombo(+ e: KeyEventLike,+ platform: KeyboardPlatform = detectKeyboardPlatform(),+): string | null {const key = codeToKeyToken(e.code);if (key === null) return null;- return [...modifierTokens(e), key].join("+");+ return [...modifierTokens(e, platform), key].join("+");}/**@@ -124,39 +153,76 @@ export function eventToCombo(e: KeyEventLike): string | null {* "f3+f4"). Modifiers come first in canonical order, then the non-modifier keys* sorted for stability so "f4+f3" and "f3+f4" normalise to the same string* (matching the backend's order-preserving combo + string-based collision- * check). Returns null while only modifiers are held (no real key yet).+ * check).+ *+ * A MODIFIER-ONLY chord is a real result, not null. It used to return null the+ * moment the held key set was empty, which meant the recorder could never+ * PRODUCE "ctrl+win": holding those two keys recorded literally nothing, the+ * field stayed blank and the gesture expired on the idle timer with no+ * feedback. Nothing downstream needed a change — ``composeCombo`` already+ * round-trips a modifier-only selection for the click-to-assign path, and the+ * backends register such a combo happily. Returns null only when NOTHING at all+ * is held.*/export function chordToCombo(e: KeyEventLike,heldTokens: Iterable<string>,+ platform: KeyboardPlatform = detectKeyboardPlatform(),): string | null {const keys = [...new Set(heldTokens)].sort();- if (keys.length === 0) return null;- return [...modifierTokens(e), ...keys].join("+");+ const mods = modifierTokens(e, platform);+ if (keys.length === 0 && mods.length === 0) return null;+ return [...mods, ...keys].join("+");}/*** Canonical modifier order — modifiers always render/serialize before the- * non-modifier keys, matching ``modifierTokens`` (ctrl, alt-family, shift, win).- * ``right_alt`` and ``alt`` never co-occur in practice, so their relative order- * is moot; keeping both keeps the lookup a plain membership test.+ * non-modifier keys, matching ``modifierTokens`` (ctrl, alt-family, shift,+ * meta-family). ``right_alt`` and ``alt`` never co-occur in practice, so their+ * relative order is moot; keeping both keeps the lookup a plain membership+ * test.+ *+ * The list is the full alias vocabulary the backend's ``_MODIFIER_TOKENS``+ * knows, not just the tokens this UI emits: a jarvis.toml written by hand (or+ * on another OS) may spell the same key ``super``/``meta``/``command``, and a+ * spelling missing here would be classified as a KEY — rendering it as a+ * keycap, sorting it among the letters and mis-firing the "a real key is+ * present" rules.*/export const MODIFIER_TOKENS = ["ctrl",+ "control",+ "right_ctrl",+ "right_control","right_alt",+ "left_alt",+ "altgr","alt","shift","win",+ "window",+ "super",+ "meta",+ "cmd",+ "command",] as const;+/** Whether a token is a modifier rather than a "real" key. */+export function isModifierToken(token: string): boolean {+ return (MODIFIER_TOKENS as readonly string[]).includes(token);+}+/*** Map a physical modifier ``event.code`` to its jarvis token- * ("ControlLeft" → "ctrl", "AltRight" → "right_alt", "MetaLeft" → "win").- * Returns null for any non-modifier code. Complements ``codeToKeyToken`` (which- * returns null for modifiers); together they classify every key on the visual- * keyboard.+ * ("ControlLeft" → "ctrl", "AltRight" → "right_alt", "MetaLeft" → "win", or+ * "cmd" on a Mac). Returns null for any non-modifier code. Complements+ * ``codeToKeyToken`` (which returns null for modifiers); together they classify+ * every key on the visual keyboard.*/-export function codeToModifierToken(code: string): string | null {+export function codeToModifierToken(+ code: string,+ platform: KeyboardPlatform = detectKeyboardPlatform(),+): string | null {switch (code) {case "ControlLeft":case "ControlRight":@@ -170,7 +236,7 @@ export function codeToModifierToken(code: string): string | null {return "right_alt";case "MetaLeft":case "MetaRight":- return "win";+ return metaToken(platform);default:return null;}@@ -185,13 +251,14 @@ export function codeToModifierToken(code: string): string | null {** A modifier-only selection round-trips ("ctrl+shift") instead of collapsing* to "" — dropping it made a clicked modifier invisible (the key never lit up)- * and silently lost on the next click. ``validateCombo`` is what blocks- * SAVING a modifier-only combo; composing it is a legitimate interim state.+ * and silently lost on the next click. It is also a perfectly saveable combo+ * in its own right (Ctrl+Win): ``validateCombo`` cautions that it fires on any+ * superset, and does not block it.*/export function composeCombo(tokens: Iterable<string>): string {const set = new Set(tokens);const mods = MODIFIER_TOKENS.filter((m) => set.has(m));- const keys = [...set].filter((t) => !MODIFIER_TOKENS.includes(t as never)).sort();+ const keys = [...set].filter((t) => !isModifierToken(t)).sort();return [...mods, ...keys].join("+");}@@ -233,96 +300,189 @@ const _SOLO_SAFE_TOKENS = new Set([]);/**- * 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.+ * Keys the OS is documented to keep for itself — mirrors+ * ``_RESERVED_SOLO_KEYS`` in ``jarvis/trigger/hotkey.py``. F12 is claimed by the+ * debugger. It is a CAUTION, not a refusal: the shortcut still fires, the+ * debugger just gets the key too.*/const _RESERVED_TOKENS = new Set(["f12"]);-/** Live validation result for a combo being built in the keybind recorder. */-export type ComboValidation =- | { status: "empty" }- | { status: "ok" }- | { status: "warning"; reason: "solo_nav" }- | {- status: "error";- reason:- | "only_modifiers"- | "solo_typing_key"- | "windows_reserved"- | "f12_reserved"- | "alt_f4"- | "ctrl_c";- }- | {- status: "error";- reason: "collision";- conflict: { action: string; combo: string };- };+/**+ * The shell shortcuts each OS assigns to its Meta key, mirroring+ * ``_WINDOWS_CRITICAL_KEYS`` / ``_MACOS_CRITICAL_KEYS`` in+ * ``jarvis/trigger/hotkey.py``. Binding one is allowed — the desktop simply+ * keeps doing its thing on top of the shortcut, which the user deserves to be+ * told before they discover it.+ */+const _WINDOWS_CRITICAL_KEYS = new Set([+ "d", "e", "l", "r", "x", "i", "s", "v", "a", "p",+ "tab", "left", "right", "up", "down",+]);++const _MACOS_CRITICAL_KEYS = new Set([+ "c", "v", "x", "z", "q", "w", "a", "s", "space", "tab",+]);++const _CTRL_FAMILY = new Set(["ctrl", "control", "right_ctrl", "right_control"]);+const _ALT_FAMILY = new Set(["alt", "right_alt", "left_alt", "altgr"]);+const _META_FAMILY = new Set(["win", "window", "super", "meta"]);+const _CMD_FAMILY = new Set(["cmd", "command", "meta", "super"]);++/**+ * Token folds the Windows backend applies before it registers a combo+ * (``_KEY_MAP`` in ``jarvis/trigger/backends/global_hotkeys.py``). Two combos+ * that fold onto the same set are ONE registration no matter how differently+ * they are spelled — ``ctrl+left_alt+j`` and ``ctrl+right_alt+j`` were accepted+ * as two shortcuts and the second one then died at register time, leaving a+ * bound-looking row that does nothing.+ */+const _NORMALIZE_FOLD: Record<string, string> = {+ ctrl: "control",+ right_ctrl: "right_control",+ right_alt: "alt",+ left_alt: "alt",+ altgr: "alt",+ win: "window",+ super: "window",+ meta: "window",+ cmd: "command",+};++/** The key set a combo ACTUALLY registers as — mirrors the backend's+ * ``normalized_combo_tokens``. */+export function normalizedComboTokens(combo: string): Set<string> {+ return new Set(+ [...comboTokens(combo)].map((t) => _NORMALIZE_FOLD[t] ?? t),+ );+}++/**+ * A non-blocking note about a combo that is perfectly legal but behaves in a+ * way the user should know about before they save it. Mirrors the+ * ``cautions`` channel of the backend's ``HotkeyVerdict``.+ */+export type ComboCaution =+ | "modifier_only"+ | "solo_typing_key"+ | "solo_nav"+ | "os_shortcut"+ | "mouse_button";++/**+ * Live validation result for a combo being built in the keybind recorder.+ *+ * ``status: "error"`` is now reserved for the ONE thing that genuinely cannot+ * be saved — an overlap with another action, which the backend route rejects+ * with a 400. Everything this validator used to refuse (a modifiers-only+ * chord, the Windows key, a bare typing key, an OS shortcut) is accepted and+ * reported through ``cautions``: the user owns their keyboard, and the+ * refusals were both unhelpful and, for the Windows key, factually wrong — the+ * Windows backend polls ``GetAsyncKeyState`` rather than registering with the+ * shell, so it always saw those combos.+ */+export interface ComboValidation {+ status: "empty" | "ok" | "error";+ /** Set only when ``status === "error"``. */+ reason?: "collision";+ /** The other action a collision is with. */+ conflict?: { action: string; combo: string };+ /** Non-blocking notes; may be present on any status. */+ cautions: ComboCaution[];+}/*** Validate a combo AS THE USER BUILDS IT — the frontend mirror of the backend- * ``validate_hotkey`` rules plus the route's overlap check, so every rule is+ * ``validate_hotkey`` verdict plus the route's overlap check, so every rule is* surfaced live (inline, localized) instead of as a post-Save error toast.* The backend remains the authority on save; this never replaces it.** ``others`` maps the OTHER actions' names to their current combos; a key-set* subset/superset relation with any of them is a collision (the polling* backend fires a combo as soon as its keys are down, so f1 alongside f1+f2- * would trigger both actions on one press).+ * would trigger both actions on one press). The comparison runs on the+ * NORMALIZED sets, so two spellings of one registration also collide.*/export function validateCombo(combo: string,others: Record<string, string> = {},+ platform: KeyboardPlatform = detectKeyboardPlatform(),): ComboValidation {const tokens = comboTokens(combo);- if (tokens.size === 0) return { status: "empty" };+ if (tokens.size === 0) return { status: "empty", cautions: [] };- const mods = [...tokens].filter((t) => MODIFIER_TOKENS.includes(t as never));- const keys = [...tokens].filter((t) => !MODIFIER_TOKENS.includes(t as never));+ const mods = [...tokens].filter((t) => isModifierToken(t));+ const keys = [...tokens].filter((t) => !isModifierToken(t));+ const mouse = keys.filter((k) =>+ (MOUSE_BUTTON_TOKENS as readonly string[]).includes(k),+ );+ const cautions: ComboCaution[] = [];++ // Same order and the same conditions as the backend's validate_hotkey.+ if (keys.length === 0) {+ cautions.push("modifier_only");+ } else if (+ mods.length === 0 &&+ keys.length === 1 &&+ mouse.length === 0 &&+ !_SOLO_SAFE_TOKENS.has(keys[0])+ ) {+ cautions.push("solo_typing_key");+ }- 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" };+ const onlyFrom = (family: Set<string>) =>+ mods.length > 0 && mods.every((m) => family.has(m));+ const altHeld = mods.some((m) => _ALT_FAMILY.has(m));+ if (keys.some((k) => _RESERVED_TOKENS.has(k))) cautions.push("os_shortcut");+ if (altHeld && keys.includes("f4")) cautions.push("os_shortcut");+ if (onlyFrom(_CTRL_FAMILY) && keys.length === 1 && keys[0] === "c") {+ cautions.push("os_shortcut");}- if ((mods.includes("alt") || mods.includes("right_alt")) && keys.includes("f4")) {- return { status: "error", reason: "alt_f4" };+ if (+ onlyFrom(_META_FAMILY) &&+ keys.length === 1 &&+ (platform === "mac"+ ? _MACOS_CRITICAL_KEYS.has(keys[0])+ : _WINDOWS_CRITICAL_KEYS.has(keys[0]))+ ) {+ cautions.push("os_shortcut");}- if (mods.length > 0 && mods.every((m) => m === "ctrl") && keys.length === 1 && keys[0] === "c") {- return { status: "error", reason: "ctrl_c" };+ if (onlyFrom(_CMD_FAMILY) && keys.length === 1 && _MACOS_CRITICAL_KEYS.has(keys[0])) {+ cautions.push("os_shortcut");}- if (mods.length === 0 && keys.length === 1 && !_SOLO_SAFE_TOKENS.has(keys[0])) {- return { status: "error", reason: "solo_typing_key" };+ if (mouse.length > 0) cautions.push("mouse_button");+ if (mods.length === 0 && keys.length === 1 && _NAV_SOLO_TOKENS.has(keys[0])) {+ cautions.push("solo_nav");}+ const unique = [...new Set(cautions)];+ const normalized = normalizedComboTokens(combo);const isSubset = (a: Set<string>, b: Set<string>) =>[...a].every((t) => b.has(t));for (const [action, other] of Object.entries(others)) {- const otherTokens = comboTokens(other);+ const otherTokens = normalizedComboTokens(other);if (otherTokens.size === 0) continue;- if (isSubset(tokens, otherTokens) || isSubset(otherTokens, tokens)) {+ if (isSubset(normalized, otherTokens) || isSubset(otherTokens, normalized)) {return {status: "error",reason: "collision",conflict: { action, combo: other.trim().toLowerCase() },+ cautions: unique,};}}- if (mods.length === 0 && keys.length === 1 && _NAV_SOLO_TOKENS.has(keys[0])) {- return { status: "warning", reason: "solo_nav" };- }- return { status: "ok" };+ return { status: "ok", cautions: unique };}// Mirrors KEYBIND_ACTIONS in jarvis/core/config_writer.py — keep in sync.// "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";+// to start, again to stop), "paste_last" re-inserts the last transcription.+export type KeybindAction =+ | "call"+ | "hangup"+ | "dictate"+ | "dictate_toggle"+ | "paste_last";/*** Response of GET /api/settings/keybinds.@@ -337,6 +497,16 @@ export interface KeybindsConfig {defaults: Partial<Record<KeybindAction, string>>;suggestions: string[];restart_required: boolean;+ /**+ * Whether THIS host can bind a mouse button, mirroring the backend's+ * ``mouse_hotkeys_available()`` capability probe (Windows always; macOS needs+ * pyobjc Quartz; Linux/X11 needs the opt-in pynput extra; Wayland cannot at+ * all). Optional because the route does not serve it yet — while it is+ * absent the picker offers the buttons, and a host that cannot use them+ * degrades through the backend's own honest message on save. The moment the+ * field appears, the picker hides the buttons and shows ``reason`` instead.+ */+ mouse_buttons?: { supported: boolean; reason?: string };}/** Result of a successful PUT /api/settings/keybinds. */diff --git a/jarvis/ui/web/frontend/src/views/KeybindsPanel.test.tsx b/jarvis/ui/web/frontend/src/views/KeybindsPanel.test.tsxindex 63bd06ff2f..aea1fd9a31 100644--- a/jarvis/ui/web/frontend/src/views/KeybindsPanel.test.tsx+++ b/jarvis/ui/web/frontend/src/views/KeybindsPanel.test.tsx@@ -1,6 +1,10 @@import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";import { afterEach, describe, expect, it, vi } from "vitest";import { KeybindsPanel } from "./SettingsView";+// Resolved through the real i18n layer, not hardcoded: the locale strings are+// owned by another surface, so the assertion pins the KEY the component uses+// rather than a copy of the English wording.+import { translate } from "@/i18n";// All four keybind actions, as the backend reports them (KEYBIND_ACTIONS in// jarvis/core/config_writer.py). Settings renders three of them — hands-free@@ -53,14 +57,19 @@ describe("KeybindsPanel", () => {expect(screen.queryByText(/push-to-talk/i)).toBeNull();});- it("renders the dictation row and leaves hands-free to the voice section", async () => {+ it("never duplicates a dictation row that belongs 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"));+ await waitFor(() => expect(comboText("call")).toBe("F3+F4"));// 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.+ // section's Shortcuts tab — never duplicated here. Push-to-talk is moving+ // the same way (Settings keeps Call and Hangup); while it is still rendered+ // here it must at least name the right Alt key the way its keycap reads,+ // not "Right-Alt".expect(screen.queryByTestId("combo-field-dictate_toggle")).toBeNull();+ if (screen.queryByTestId("combo-field-dictate")) {+ expect(comboText("dictate")).toBe("Ctrl+AltGr+J");+ }});it("captures a two-key chord (F7 + F8) pressed simultaneously", async () => {@@ -215,7 +224,7 @@ describe("KeybindsPanel", () => {expect((saveButtons[0] as HTMLButtonElement).disabled).toBe(true);});- it("keeps a clicked modifier visible and blocks saving until a real key lands", async () => {+ it("saves a modifier-only combo (Ctrl+Win) and cautions instead of blocking", async () => {stubFetch();render(<KeybindsPanel />);@@ -227,17 +236,75 @@ describe("KeybindsPanel", () => {fireEvent.click(screen.getByTestId("key-F3"));fireEvent.click(screen.getByTestId("key-F4"));fireEvent.click(screen.getByTestId("key-ControlLeft"));+ fireEvent.click(screen.getByTestId("key-MetaLeft"));- // The clicked modifier stays visibly selected (the old composeCombo- // collapsed a modifier-only state to "" and silently dropped it).+ // The clicked modifiers stay visibly selected (the old composeCombo+ // collapsed a modifier-only state to "" and silently dropped it) …expect(screen.getByTestId("key-ControlLeft").getAttribute("aria-pressed"),).toBe("true");expect(- screen.getByTestId("keybind-validation-call").textContent,- ).toMatch(/real key/i);+ screen.getByTestId("key-MetaLeft").getAttribute("aria-pressed"),+ ).toBe("true");+ // … and the combo is a real, saveable one. Inverted from the old "blocks+ // saving until a real key lands": the user owns their keyboard, so the+ // prefix behaviour is a sentence, not a wall.+ expect(comboText("call")).toBe("Ctrl+Win");+ expect(screen.getByTestId("keybind-validation-call")).toBeTruthy();const saveButtons = screen.getAllByRole("button", { name: /save/i });- expect((saveButtons[0] as HTMLButtonElement).disabled).toBe(true);+ expect((saveButtons[0] as HTMLButtonElement).disabled).toBe(false);+ });++ it("records Ctrl+Win from a physical chord (the gesture used to vanish)", async () => {+ stubFetch();+ render(<KeybindsPanel />);++ await waitFor(() => expect(comboText("call")).toBe("F3+F4"));+ fireEvent.click(screen.getByTestId("combo-field-call"));++ // Holding two modifiers used to record literally nothing — chordToCombo+ // returned null with no key in the held set, so the field stayed blank and+ // the gesture expired silently.+ fireEvent.keyDown(window, { code: "ControlLeft", key: "Control", ctrlKey: true });+ fireEvent.keyDown(window, {+ code: "MetaLeft",+ key: "Meta",+ ctrlKey: true,+ metaKey: true,+ });+ fireEvent.keyUp(window, { code: "MetaLeft", key: "Meta", ctrlKey: true });+ fireEvent.keyUp(window, { code: "ControlLeft", key: "Control" });++ await waitFor(() => expect(comboText("call")).toBe("Ctrl+Win"));+ });++ it("records a mouse side button without the press dismissing the recorder", async () => {+ stubFetch();+ render(<KeybindsPanel />);++ await waitFor(() => expect(comboText("call")).toBe("F3+F4"));+ fireEvent.click(screen.getByTestId("combo-field-call"));++ // Button 3 is X1 ("Back"). A captured press must not reach the page as an+ // ordinary click, or it would navigate the app away mid-recording.+ const down = fireEvent.mouseDown(window, { button: 3 });+ expect(down).toBe(false); // preventDefault() was called+ fireEvent.mouseUp(window, { button: 3 });++ await waitFor(() => expect(comboText("call")).toBe("MouseBack"));+ });++ it("leaves the primary mouse button alone so the picker stays clickable", async () => {+ stubFetch();+ render(<KeybindsPanel />);++ await waitFor(() => expect(comboText("call")).toBe("F3+F4"));+ fireEvent.click(screen.getByTestId("combo-field-call"));++ // Left-clicking anything while armed must behave normally — the Save+ // button and the on-screen keys are operated with it.+ expect(fireEvent.mouseDown(window, { button: 0 })).toBe(true);+ expect(comboText("call")).toBe("F3+F4");});it("applies rapid-fire key toggles cumulatively (functional state update)", async () => {@@ -261,7 +328,7 @@ describe("KeybindsPanel", () => {expect(comboText("call")).toBe("Q");});- it("marks the Windows key as reserved (not clickable) on the keyboard", async () => {+ it("offers the Windows key for click-to-assign (it is not reserved)", async () => {stubFetch();render(<KeybindsPanel />);@@ -270,8 +337,50 @@ describe("KeybindsPanel", () => {);fireEvent.click(recordButtons[0]);+ // Inverted: the cap used to be drawn dead with a "reserved by the system"+ // tooltip. Clicking it is the path that MATTERS for this key — pressing it+ // physically makes Windows open Start and pull focus out of the app+ // mid-recording, so the on-screen key has to work.const winKey = screen.getByTestId("key-MetaLeft") as HTMLButtonElement;- expect(winKey.disabled).toBe(true);+ expect(winKey.disabled).toBe(false);+ fireEvent.click(winKey);+ expect(winKey.getAttribute("aria-pressed")).toBe("true");+ });++ it("offers the bindable mouse buttons on the picker", async () => {+ stubFetch();+ render(<KeybindsPanel />);++ const recordButtons = await waitFor(() =>+ screen.getAllByRole("button", { name: /record/i }),+ );+ fireEvent.click(recordButtons[0]); // Call row (f3+f4)++ fireEvent.click(screen.getByTestId("key-F3"));+ fireEvent.click(screen.getByTestId("key-F4"));+ fireEvent.click(screen.getByTestId("key-MouseButton1")); // middle button++ expect(comboText("call")).toBe("MiddleClick");+ });++ it("says what to do while the recorder is empty and armed", async () => {+ stubFetch();+ render(<KeybindsPanel />);++ await waitFor(() => expect(comboText("call")).toBe("F3+F4"));+ fireEvent.click(screen.getByTestId("combo-field-call"));+ // Strip the current combo so the field is in the bare recording state that+ // "looked ugly": it used to say only that a mode was on, which reads as a+ // broken field. It now names the gesture, and the line under it spells out+ // how the gesture ends.+ fireEvent.click(screen.getByTestId("key-F3"));+ fireEvent.click(screen.getByTestId("key-F4"));++ expect(screen.getByTestId("combo-field-call").textContent).toContain(+ translate("settings_view.keybinds.record_prompt"),+ );+ expect(screen.getByText(translate("settings_view.keybinds.record_prompt_hint")))+ .toBeTruthy();});it("closes the recorder after a successful save (no stale-snapshot Esc)", async () => {diff --git a/jarvis/ui/web/frontend/src/views/settings/KeybindRow.tsx b/jarvis/ui/web/frontend/src/views/settings/KeybindRow.tsxindex 1b3c1dd812..3e9fbfbe53 100644--- a/jarvis/ui/web/frontend/src/views/settings/KeybindRow.tsx+++ b/jarvis/ui/web/frontend/src/views/settings/KeybindRow.tsx@@ -8,13 +8,18 @@ import {composeCombo,comboTokens,validateCombo,+ type ComboCaution,type ComboValidation,type KeybindAction,type KeybindsConfig,type KeybindSaveResult,} from "@/hooks/useHotkey";import { KeyboardMap } from "@/views/settings/KeyboardMap";-import { detectKeyboardPlatform } from "@/views/settings/keyboardLayout";+import {+ detectKeyboardPlatform,+ mouseButtonCode,+ mouseButtonToToken,+} from "@/views/settings/keyboardLayout";import { useEventStore } from "@/store/events";import { useT } from "@/i18n";@@ -36,8 +41,21 @@ export function formatCombo(combo: string): string {right_alt: _KB_PLATFORM === "mac" ? "⌥" : "AltGr",altgr: _KB_PLATFORM === "mac" ? "⌥" : "AltGr",shift: "Shift",- win: "Win",+ // Same physical key, two vocabularies: it is Command on a Mac keyboard and+ // the Windows key on a PC one. Rendering "Win" on a Mac named a cap that+ // machine does not have, and a Command combo fell through to a raw "CMD".+ win: _KB_PLATFORM === "mac" ? "⌘" : "Win",+ window: _KB_PLATFORM === "mac" ? "⌘" : "Win",+ super: _KB_PLATFORM === "mac" ? "⌘" : "Win",+ meta: _KB_PLATFORM === "mac" ? "⌘" : "Win",+ cmd: "⌘",+ command: "⌘",space: "Space",+ // Mouse buttons, named the way the hardware and the browser do (X1/X2 are+ // Back/Forward in every application that uses them).+ mouse_middle: "Middle Click",+ mouse_x1: "Mouse Back",+ mouse_x2: "Mouse Fwd",// Navigation / editing cluster + numpad operators (the backend key names).up: "↑",down: "↓",@@ -80,6 +98,24 @@ export const ACTION_LABEL_KEY: Record<KeybindAction, string> = {hangup: "settings_view.keybinds.hangup_label",dictate: "settings_view.keybinds.dictate_label",dictate_toggle: "settings_view.keybinds.dictate_toggle_label",+ paste_last: "settings_view.keybinds.paste_last_label",+};++/**+ * The localized sentence for each non-blocking caution.+ *+ * ``mouse_button`` deliberately shares the OS-shortcut sentence: a bound mouse+ * button is not swallowed either — whatever you are pointing at still gets its+ * click — which is exactly what that sentence promises. It stays a separate+ * reason so a dedicated string can be pointed at it later without touching the+ * rule that produces it.+ */+const CAUTION_KEY: Record<ComboCaution, string> = {+ modifier_only: "settings_view.keybinds.caution_modifier_only",+ os_shortcut: "settings_view.keybinds.caution_os_shortcut",+ mouse_button: "settings_view.keybinds.caution_os_shortcut",+ solo_typing_key: "settings_view.keybinds.validation.solo_typing_key",+ solo_nav: "settings_view.keybinds.validation.solo_nav",};/** The combo rendered as keycap chips ("Ctrl + F5" → [Ctrl] + [F5]). */@@ -99,13 +135,20 @@ export function ComboChips({ combo }: { combo: string }) {);}-/** The localized live-validation message for the combo being built, or null. */+/**+ * The localized live message for the combo being built, or null.+ *+ * A collision is the one BLOCKING message (the backend route rejects it with a+ * 400). Everything else is a caution: the combo is saveable, the sentence only+ * says what else will happen when it fires. Several cautions can apply at once+ * — they are joined into ONE line, because a second line makes the on-screen+ * keyboard below jump on every click.+ */export function validationText(v: ComboValidation,t: (key: string) => string,): string | null {- if (v.status !== "error" && v.status !== "warning") return null;- if (v.reason === "collision") {+ if (v.status === "error" && v.reason === "collision" && v.conflict) {// 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.@@ -114,7 +157,12 @@ export function validationText(.replace("{action}", labelKey ? t(labelKey) : v.conflict.action).replace("{combo}", formatCombo(v.conflict.combo));}- return t(`settings_view.keybinds.validation.${v.reason}`);+ const cautions = v.cautions ?? [];+ if (cautions.length === 0) return null;+ // De-duplicated by SENTENCE, not by reason: two reasons deliberately share+ // one string, and printing it twice reads like a stutter.+ const sentences = [...new Set(cautions.map((c) => t(CAUTION_KEY[c])))];+ return sentences.join(" ");}export interface KeybindRowProps {@@ -324,12 +372,79 @@ export function KeybindRow({}}+ // A MouseEvent carries the same modifier flags a KeyboardEvent does, but no+ // `code` — the modifier reader only consults `code` to tell AltGr from a+ // plain Alt, which a mouse press cannot be.+ function asKeyEventLike(e: MouseEvent) {+ return {+ code: "",+ ctrlKey: e.ctrlKey,+ altKey: e.altKey,+ shiftKey: e.shiftKey,+ metaKey: e.metaKey,+ getModifierState: (k: string) => e.getModifierState(k),+ };+ }++ // Mouse buttons join the SAME held-set the keys use, so Ctrl + side button+ // records as one chord and the commit-on-full-release rule needs no special+ // case. The primary and secondary buttons are never captured: the recorder's+ // own controls (Save, the on-screen keys) have to stay clickable while it+ // is armed, and the OS "swap buttons" setting makes those two unreliable to+ // bind anyway.+ function onMouseDown(e: MouseEvent) {+ const tok = mouseButtonToToken(e.button);+ if (tok === null) return;+ e.preventDefault();+ e.stopPropagation();+ const code = mouseButtonCode(e.button);+ pressed.add(code);+ setPressedCodes(new Set(pressed));+ held.add(tok);+ const next = chordToCombo(asKeyEventLike(e), held);+ if (next) {+ pending = next;+ setCombo(next);+ setSaved(false);+ }+ if (idle) clearTimeout(idle);+ idle = setTimeout(commit, 900);+ }++ function onMouseUp(e: MouseEvent) {+ const tok = mouseButtonToToken(e.button);+ if (tok === null) return;+ e.preventDefault();+ e.stopPropagation();+ pressed.delete(mouseButtonCode(e.button));+ setPressedCodes(new Set(pressed));+ if (pressed.size === 0 && pending) {+ if (idle) clearTimeout(idle);+ commit();+ }+ }++ // The side buttons are Back/Forward and the middle button starts autoscroll;+ // suppressing the follow-up event keeps a recording gesture from navigating+ // the app out from under itself.+ function onAuxClick(e: MouseEvent) {+ if (mouseButtonToToken(e.button) === null) return;+ e.preventDefault();+ e.stopPropagation();+ }+window.addEventListener("keydown", onKeyDown, true);window.addEventListener("keyup", onKeyUp, true);+ window.addEventListener("mousedown", onMouseDown, true);+ window.addEventListener("mouseup", onMouseUp, true);+ window.addEventListener("auxclick", onAuxClick, true);return () => {if (idle) clearTimeout(idle);window.removeEventListener("keydown", onKeyDown, true);window.removeEventListener("keyup", onKeyUp, true);+ window.removeEventListener("mousedown", onMouseDown, true);+ window.removeEventListener("mouseup", onMouseUp, true);+ window.removeEventListener("auxclick", onAuxClick, true);};}, [capturing]);@@ -416,9 +531,11 @@ export function KeybindRow({{combo ? (<ComboChips combo={combo} />) : (- <span className="text-muted-foreground">+ <span className={capturing ? "text-foreground" : "text-muted-foreground"}>{capturing- ? t("settings_view.keybinds.recording")+ ? // Say what to DO, not that a mode is on: the bare "recording"+ // state read as a broken field ("it just went empty").+ t("settings_view.keybinds.record_prompt"): loading? "—": t("settings_view.keybinds.unbound")}@@ -427,9 +544,9 @@ export function KeybindRow({</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.+ // ONE stable status line: the blocking message when there is one, otherwise+ // the cautions, otherwise the recording hint. Two separately appearing lines+ // made the keyboard below jump vertically on every combo click.const statusLine = (capturing || validationMsg) && (<pdata-testid={validationMsg ? `keybind-validation-${action}` : undefined}@@ -441,7 +558,7 @@ export function KeybindRow({: "text-muted-foreground"}`}>- {validationMsg ?? t("settings_view.keybinds.recording_hint")}+ {validationMsg ?? t("settings_view.keybinds.record_prompt_hint")}</p>);@@ -452,6 +569,9 @@ export function KeybindRow({boundTokens={boundTokens}platform={_KB_PLATFORM}onToggleToken={onToggleToken}+ // Absent until the route serves the probe — see KeybindsConfig.+ mouseSupported={config?.mouse_buttons?.supported ?? true}+ mouseReason={config?.mouse_buttons?.reason}/>);diff --git a/jarvis/ui/web/frontend/src/views/settings/KeyboardMap.tsx b/jarvis/ui/web/frontend/src/views/settings/KeyboardMap.tsxindex 030b287c85..a220baf4c0 100644--- a/jarvis/ui/web/frontend/src/views/settings/KeyboardMap.tsx+++ b/jarvis/ui/web/frontend/src/views/settings/KeyboardMap.tsx@@ -3,6 +3,7 @@ import { codeToKeyToken, codeToModifierToken } from "@/hooks/useHotkey";import { useT } from "@/i18n";import {ARROW_ROWS,+ MOUSE_CAPS,NAV_ROWS,mainRows,type KeyCap,@@ -11,9 +12,10 @@ import {} from "./keyboardLayout";/** The bindable jarvis token for a cap, or null when it cannot be bound. */-function capToken(cap: KeyCap): string | null {+function capToken(cap: KeyCap, platform: KeyboardPlatform): string | null {if (cap.dead) return null;- return codeToModifierToken(cap.code) ?? codeToKeyToken(cap.code);+ if (cap.token) return cap.token;+ return codeToModifierToken(cap.code, platform) ?? codeToKeyToken(cap.code);}interface KeyboardMapProps {@@ -26,28 +28,39 @@ interface KeyboardMapProps {platform: KeyboardPlatform;/** Toggle a bindable key in/out of the combo (click-to-assign). */onToggleToken: (token: string) => void;+ /**+ * Whether this host can bind a mouse button. False hides the cluster rather+ * than offering a control that cannot work (Wayland, a Mac without pyobjc);+ * ``mouseReason`` is the backend's English sentence saying why.+ */+ mouseSupported?: boolean;+ mouseReason?: string;}function Key({cap,+ platform,pressedCodes,selectedTokens,boundTokens,onToggleToken,}: {cap: KeyCap;+ platform: KeyboardPlatform;pressedCodes: Set<string>;selectedTokens: Set<string>;boundTokens: Record<string, string>;onToggleToken: (token: string) => void;}) {- const t = useT();- const token = capToken(cap);- // The Windows key is reserved by the OS (the backend rejects every win+…- // combo), so offering it as clickable only manufactures a doomed save —- // render it like a dead key and say why in the tooltip.- const reserved = token === "win";- const bindable = token !== null && !reserved;+ const token = capToken(cap, platform);+ // Every key the backend can register is clickable — including the Meta key.+ // It used to be drawn dead with a "reserved by the system" tooltip, on the+ // premise that the OS claims it. That was wrong for this app: the Windows+ // backend polls the key state instead of registering with the shell, so it+ // sees Win combos like any other. Click-to-assign matters MOST for this key,+ // because pressing it physically makes Windows open Start and pull focus out+ // of the app mid-recording.+ const bindable = token !== null;const pressed = pressedCodes.has(cap.code);const selected = bindable && selectedTokens.has(token);const boundLabel = bindable ? boundTokens[token] : undefined;@@ -72,13 +85,7 @@ function Key({data-testid={`key-${cap.code}`}aria-label={cap.code}aria-pressed={selected}- title={- reserved- ? `${cap.label} — ${t("settings_view.keybinds.keyboard.reserved")}`- : boundLabel- ? `${cap.label} — ${boundLabel}`- : cap.label- }+ title={boundLabel ? `${cap.label} — ${boundLabel}` : cap.label}disabled={!bindable}onClick={bindable ? () => onToggleToken(token) : undefined}style={{ flexGrow: cap.width ?? 1, flexBasis: 0 }}@@ -94,12 +101,12 @@ function Key({);}-function Row({- row,- ...rest-}: {- row: KeyRow;-} & Omit<KeyboardMapProps, "platform">) {+type KeyProps = Pick<+ KeyboardMapProps,+ "pressedCodes" | "selectedTokens" | "boundTokens" | "platform" | "onToggleToken"+>;++function Row({ row, ...rest }: { row: KeyRow } & KeyProps) {return (<div className="flex gap-1">{row.map((cap) => (@@ -122,9 +129,17 @@ export function KeyboardMap({boundTokens,platform,onToggleToken,+ mouseSupported = true,+ mouseReason,}: KeyboardMapProps) {const t = useT();- const keyProps = { pressedCodes, selectedTokens, boundTokens, onToggleToken };+ const keyProps: KeyProps = {+ pressedCodes,+ selectedTokens,+ boundTokens,+ platform,+ onToggleToken,+ };const rows = useMemo(() => mainRows(platform), [platform]);return (@@ -165,6 +180,29 @@ export function KeyboardMap({</div>))}</div>++ {/* Mouse buttons. Click-to-assign is the reliable path here: a side+ button is Back/Forward in most apps and the middle button starts+ autoscroll, so the physical press may be consumed before the+ recorder sees it. */}+ {mouseSupported ? (+ <div className="flex gap-1">+ {MOUSE_CAPS.map((cap) => (+ <div key={cap.code} className="w-[3.25rem]">+ <Key cap={cap} {...keyProps} />+ </div>+ ))}+ </div>+ ) : (+ mouseReason && (+ <p+ data-testid="mouse-unavailable"+ className="max-w-[10rem] text-[10px] leading-snug text-muted-foreground"+ >+ {mouseReason}+ </p>+ )+ )}</div></div>diff --git a/jarvis/ui/web/frontend/src/views/settings/keyboardLayout.ts b/jarvis/ui/web/frontend/src/views/settings/keyboardLayout.tsindex a6e66bea71..ab8d032559 100644--- a/jarvis/ui/web/frontend/src/views/settings/keyboardLayout.ts+++ b/jarvis/ui/web/frontend/src/views/settings/keyboardLayout.ts@@ -1,5 +1,13 @@/**- * Physical keyboard layout data for the visual keybind picker (KeyboardMap).+ * Physical INPUT vocabulary for the visual keybind picker (KeyboardMap): the+ * keyboard layout, the bindable mouse buttons, and the host keyboard family.+ *+ * Dependency direction (deliberate, do not invert): this module imports+ * NOTHING. ``@/hooks/useHotkey`` imports FROM here for the platform probe and+ * the mouse vocabulary. Reversing it would put a module-scope call to a hook+ * module in the import graph of every component that renders a keybind row —+ * and that module is mocked wholesale in several view tests, so the call would+ * resolve to ``undefined`` at import time.** The layout is a compact TKL ("tenkeyless") arrangement — the form factor that* still carries everything a voice keybind can use: the function row, the main@@ -28,6 +36,12 @@ export interface KeyCap {width?: number;/** Drawn for context but not bindable (punctuation / CapsLock). */dead?: boolean;+ /**+ * Explicit bindable token, for caps whose ``code`` is not a keyboard code —+ * the mouse buttons, whose "code" is synthesized by the recorder. When set it+ * wins over the ``codeToModifierToken``/``codeToKeyToken`` lookup.+ */+ token?: string;}export type KeyRow = KeyCap[];@@ -178,3 +192,66 @@ export function detectKeyboardPlatform(): KeyboardPlatform {const probe = `${navigator.platform ?? ""} ${navigator.userAgent ?? ""}`;return /Mac|iPhone|iPad|iPod/i.test(probe) ? "mac" : "pc";}++// ---------------------------------------------------------------------------+// Mouse buttons+// ---------------------------------------------------------------------------++/**+ * The mouse buttons a shortcut may contain — the exact tokens the hotkey+ * backends register (``MOUSE_BUTTON_TOKENS`` in+ * ``jarvis/trigger/backends/global_hotkeys.py``, consumed by all three OS+ * backends). Keep the spelling identical: a token the backend does not know+ * makes the whole combo unregisterable.+ *+ * The LEFT and RIGHT buttons are deliberately absent, on every platform. The+ * OS "swap mouse buttons" setting is applied below the level the backends read+ * at, so a shortcut recorded as "left" fires on the physical right button for a+ * left-handed user — and binding the primary click globally makes the machine+ * unusable anyway. Middle / X1 / X2 are unaffected by the swap.+ */+export const MOUSE_BUTTON_TOKENS = [+ "mouse_middle",+ "mouse_x1",+ "mouse_x2",+] as const;++/**+ * DOM ``MouseEvent.button`` → jarvis token. 1 = middle, 3 = X1 (Back),+ * 4 = X2 (Forward). Returns null for the primary (0) and secondary (2)+ * buttons, which stay ordinary clicks so the recorder's own controls — Save,+ * the on-screen keys — remain operable while it is capturing.+ */+export function mouseButtonToToken(button: number): string | null {+ switch (button) {+ case 1:+ return "mouse_middle";+ case 3:+ return "mouse_x1";+ case 4:+ return "mouse_x2";+ default:+ return null;+ }+}++/**+ * The synthetic "code" a mouse button gets in the recorder's held-set, so the+ * press highlight, the full-release commit and the on-screen cap all key off+ * one identifier the way a real ``event.code`` does.+ */+export function mouseButtonCode(button: number): string {+ return `MouseButton${button}`;+}++/**+ * The bindable mouse buttons as caps for the picker. Click-to-assign matters+ * here for the same reason it does for the Windows key: a side button may be+ * consumed as Back/Forward navigation before the recorder sees it, and the+ * middle button can start autoscroll.+ */+export const MOUSE_CAPS: KeyCap[] = [+ { code: mouseButtonCode(1), label: "Middle", token: "mouse_middle" },+ { code: mouseButtonCode(3), label: "Back", token: "mouse_x1" },+ { code: mouseButtonCode(4), label: "Forward", token: "mouse_x2" },+];