Skip to content

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.

feat(trigger): allow any key combination and mouse buttons as a shortcut

Ruben Lütke8468b3c784e4
diff --git a/docs/os-parity.md b/docs/os-parity.md
index 4ada451ce3..8efe2a9372 100644
--- a/docs/os-parity.md
+++ b/docs/os-parity.md
@@ -71,6 +71,7 @@ experiences today.
| 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 |
+| P-27 | Low | Mouse-button shortcuts | A shortcut may now be a MOUSE BUTTON (middle, and the two side buttons — `mouse_middle` / `mouse_x1` / `mouse_x2`). All three OSes are implemented in the same change and share one token vocabulary, but the delivery is not uniform: Windows needs nothing extra (the backend polls `GetAsyncKeyState`, which reports mouse buttons); macOS needs pyobjc `Quartz` plus the Accessibility + Input Monitoring grants the hotkey tap already requires; Linux/X11 needs `pynput`, which is the opt-in `[desktop-linux]` extra for the reason recorded in P-24 (`evdev` is source-only). Wayland cannot do it at all — no global button grab exists, the same design reason keyboard shortcuts degrade there. The left and right buttons are deliberately not bindable on any OS: their meaning follows the system "swap mouse buttons" setting, so a shortcut recorded as "left" would fire on the physical right button for a left-handed user | `jarvis/trigger/hotkey.py::mouse_hotkeys_available`, `backends/global_hotkeys.py::_MOUSE_TOKEN_TO_VK`, `backends/pynput.py::_start_mouse_listener`, `backends/quartz.py::_MOUSE_BUTTON_TO_TOKEN` | Every host answers the capability question BEFORE offering the control: `mouse_hotkeys_available()` returns an English sentence naming what is missing and what still works, and a backend that cannot start its mouse hook logs the same thing and keeps the KEYBOARD shortcuts alive rather than failing the whole binding. macOS/Linux desktop with the extras: full parity with Windows. Wayland and headless: key combinations only |
## Maintenance
diff --git a/jarvis/trigger/backends/global_hotkeys.py b/jarvis/trigger/backends/global_hotkeys.py
index fe005f336b..64bf711390 100644
--- a/jarvis/trigger/backends/global_hotkeys.py
+++ b/jarvis/trigger/backends/global_hotkeys.py
@@ -30,6 +30,31 @@ import threading
log = logging.getLogger(__name__)
+# ---------------------------------------------------------------------------
+# Mouse buttons as shortcut keys (maintainer directive 2026-07-28).
+#
+# These three tokens are the shared vocabulary for EVERY backend — the Windows
+# poller, the macOS event tap and the Linux pynput listener all translate them
+# to their own primitive. They live here because this module already owns the
+# canonical combo vocabulary (``_KEY_MAP`` / ``_normalize_combo``); one
+# definition, three consumers, no hand-mirrored copy to drift (AP-4).
+#
+# Left and right button are deliberately NOT offered. Their meaning follows the
+# system "swap mouse buttons" setting, so a shortcut recorded as "left" would
+# fire on the physical right button for a left-handed user — and binding the
+# primary click globally makes the machine unusable in the first place.
+# ---------------------------------------------------------------------------
+MOUSE_BUTTON_TOKENS = frozenset({"mouse_middle", "mouse_x1", "mouse_x2"})
+
+# Friendlier spellings a hand-written jarvis.toml may use. X1/X2 are what the
+# hardware calls the two side buttons; Back/Forward is what they do in a
+# browser.
+_MOUSE_ALIASES = {
+ "mouse_back": "mouse_x1",
+ "mouse_forward": "mouse_x2",
+ "middle_mouse": "mouse_middle",
+}
+
# Map jarvis.toml combo syntax -> global-hotkeys syntax. global-hotkeys only
# knows the generic "alt"/"control" — no left/right distinction except for
# "right_control" — so we fold right_alt/left_alt onto "alt".
@@ -41,15 +66,38 @@ _KEY_MAP = {
"altgr": "alt",
"win": "window",
# Same physical key, other names: X11 and most Linux desktops call it
- # Super, some configs spell it Meta. ``validate_hotkey`` refuses new
- # bindings that use them, but a jarvis.toml written before that rule
- # existed may still carry one — folding them here means such a config
- # normalizes to a real token instead of arming a combo that never fires.
+ # Super, some configs spell it Meta. Folding them here means a config that
+ # spells the key either way normalizes to the one token every backend
+ # matches, instead of arming a combo that never fires.
"super": "window",
"meta": "window",
"shift": "shift",
+ **_MOUSE_ALIASES,
+}
+
+# The Windows virtual-key codes for the three buttons, as the numeric tokens
+# ``global_hotkeys`` accepts (its ``_to_virtualkey`` parses a hex string when the
+# name is not one of its own, and its matcher's only primitive is
+# ``GetAsyncKeyState``, which reports mouse buttons). Applied at the library
+# boundary only — everything above it keeps the readable token, so a log line
+# and a jarvis.toml stay legible on every OS.
+_MOUSE_TOKEN_TO_VK = {
+ "mouse_middle": "0x04", # VK_MBUTTON
+ "mouse_x1": "0x05", # VK_XBUTTON1 (Back)
+ "mouse_x2": "0x06", # VK_XBUTTON2 (Forward)
}
+
+def _canonical_token(token: str) -> str:
+ """Fold an alias spelling onto its canonical token (``mouse_back`` -> x1)."""
+ return _MOUSE_ALIASES.get(token, token)
+
+
+def _to_library_combo(normalized: str) -> str:
+ """Swap the friendly mouse tokens for the numeric VK the library wants."""
+ parts = [p.strip() for p in normalized.split("+") if p.strip()]
+ return " + ".join(_MOUSE_TOKEN_TO_VK.get(p, p) for p in parts)
+
# --------------------------------------------------------------------------
# Module-level single-checker guard.
#
@@ -133,6 +181,12 @@ class GlobalHotkeysBackend:
self._gh = None
return
+ # The rows arrive with the shared vocabulary (``mouse_x2``); the library
+ # speaks virtual-key numbers for the mouse. Translate ONCE here, and use
+ # the translated strings for registration AND removal — the two must be
+ # byte-identical or ``remove_hotkeys`` leaves a stale registration that
+ # bricks the next re-entry.
+ bindings = [[_to_library_combo(row[0]), *row[1:]] for row in bindings]
combo_strings = [row[0] for row in bindings]
# Idempotent (re-)registration. A previous lifecycle in this process
@@ -231,9 +285,12 @@ class GlobalHotkeysBackend:
__all__ = [
+ "MOUSE_BUTTON_TOKENS",
"GlobalHotkeysBackend",
"_KEY_MAP",
+ "_canonical_token",
"_normalize_combo",
+ "_to_library_combo",
"_start_checker_once",
"_stop_checker_once",
"_reset_checker_state_for_tests",
diff --git a/jarvis/trigger/backends/pynput.py b/jarvis/trigger/backends/pynput.py
index cfe51f8f95..e0a183b15a 100644
--- a/jarvis/trigger/backends/pynput.py
+++ b/jarvis/trigger/backends/pynput.py
@@ -39,6 +39,8 @@ import logging
import sys
import threading
+from jarvis.trigger.backends.global_hotkeys import MOUSE_BUTTON_TOKENS
+
log = logging.getLogger(__name__)
@@ -99,6 +101,20 @@ _GENERIC_MODIFIER_ALIASES: dict[str, frozenset[str]] = {
"meta": frozenset({"cmd", "cmd_l", "cmd_r"}),
}
+# ``pynput.mouse.Button`` member name -> the shared mouse token. The X11 backend
+# numbers the extra buttons (the two side buttons land on 8 and 9); other
+# backends name them x1/x2. Matching by NAME keeps this table honest on a
+# platform whose pynput build simply has no such member — the button then never
+# appears in the held set and the shortcut stays quiet instead of firing on the
+# wrong button.
+_MOUSE_NAME_TO_TOKEN = {
+ "middle": "mouse_middle",
+ "button8": "mouse_x1",
+ "button9": "mouse_x2",
+ "x1": "mouse_x1",
+ "x2": "mouse_x2",
+}
+
# --------------------------------------------------------------------------
# Module-level single-listener guard (mirrors the Windows refcount intent):
# two live HotkeyTriggers must share ONE listener thread, else every press
@@ -147,6 +163,10 @@ class PynputBackend:
# pynput ``keyboard.Listener`` once started; ``None`` until / on degrade.
# Typed ``object | None`` to avoid a hard module-scope pynput type import.
self._listener: object | None = None
+ # The mouse listener, started only when a bound combo actually contains
+ # a mouse button — an idle desktop must not pay for a second OS hook.
+ self._mouse_listener: object | None = None
+ self._needs_mouse = False
self._started = False
self._got_event = False
self._incremented = False
@@ -175,6 +195,9 @@ class PynputBackend:
}
)
self._combos = combos
+ self._needs_mouse = any(
+ combo["tokens"] & MOUSE_BUTTON_TOKENS for combo in combos
+ )
def _token_for(self, key) -> str | None:
"""Map a pynput key event to our canonical token, or ``None``."""
@@ -203,6 +226,63 @@ class PynputBackend:
self._held.discard(token)
self._reconcile()
+ def _on_click(self, _x, _y, button, pressed) -> None: # noqa: ANN001 — pynput callback
+ """Feed a mouse button into the same held-set the keyboard uses."""
+ token = _MOUSE_NAME_TO_TOKEN.get(str(getattr(button, "name", "")).lower())
+ if token is None:
+ return
+ if pressed:
+ self._held.add(token)
+ self._reconcile()
+ return
+ self._reconcile() # check release edges BEFORE dropping the token
+ self._held.discard(token)
+ self._reconcile()
+
+ def _start_mouse_listener(self) -> None:
+ """Start the mouse hook — only when a combo needs it. Degrades honestly.
+
+ A failure here must not take the KEYBOARD shortcuts down with it: the
+ message names what stopped working and what still does, so a user never
+ has to guess why one shortcut of two went quiet (AP-23).
+ """
+ if not self._needs_mouse or self._mouse_listener is not None:
+ return
+ try:
+ from pynput import mouse # type: ignore[import-untyped] # lazy (HN-7)
+
+ listener = mouse.Listener(on_click=self._on_click)
+ listener.start()
+ except Exception as exc: # noqa: BLE001 — degrade, never crash the pipeline
+ log.warning(
+ "Mouse-button shortcuts are unavailable on this system (%s) — "
+ "shortcuts that use a key combination still work, and voice "
+ "still works via the wake word.",
+ exc,
+ )
+ self._mouse_listener = None
+ return
+ self._mouse_listener = listener
+
+ def _stop_mouse_listener(self) -> None:
+ """Tear the mouse hook down. Idempotent, never raises."""
+ listener = self._mouse_listener
+ self._mouse_listener = None
+ if listener is None:
+ return
+ for step_name, step in (
+ ("stop", lambda: listener.stop()), # type: ignore[attr-defined]
+ ("join", lambda: listener.join(timeout=2.0)), # type: ignore[attr-defined]
+ ):
+ try:
+ step()
+ except Exception: # noqa: BLE001 — teardown must never propagate
+ log.debug(
+ "pynput mouse listener %s failed (non-fatal)",
+ step_name,
+ exc_info=True,
+ )
+
def _reconcile(self) -> None:
"""Fire press/release handlers on chord down/up transitions."""
if not self._permission_check():
@@ -311,6 +391,7 @@ class PynputBackend:
self._listener = None
return
self._listener = listener
+ self._start_mouse_listener()
with _LISTENER_LOCK:
global _LISTENER_REFCOUNT
@@ -319,7 +400,8 @@ class PynputBackend:
self._started = True
def stop(self) -> None:
- """Stop the pynput listener. Idempotent."""
+ """Stop the pynput listeners. Idempotent."""
+ self._stop_mouse_listener()
listener = self._listener
if listener is not None:
try:
@@ -356,6 +438,7 @@ class PynputBackend:
def unregister(self) -> None:
"""Drop the armed bindings. The listener is torn down in ``stop``."""
self._combos = []
+ self._needs_mouse = False
def received_any_event(self) -> bool:
"""True once any bound chord has fired (AD-8 macOS permission hint)."""
@@ -364,6 +447,7 @@ class PynputBackend:
__all__ = [
"PynputBackend",
+ "_MOUSE_NAME_TO_TOKEN",
"_combo_is_down",
"_parse_combo_tokens",
"_reset_listener_state_for_tests",
diff --git a/jarvis/trigger/backends/quartz.py b/jarvis/trigger/backends/quartz.py
index 11749a7ba0..4b03c580d6 100644
--- a/jarvis/trigger/backends/quartz.py
+++ b/jarvis/trigger/backends/quartz.py
@@ -23,6 +23,9 @@ Known trade-offs (documented, honest):
as most native hotkey utilities.
* ``right_control`` matches either Control key (the flags word does not carry
a portable left/right distinction).
+* Mouse buttons (middle and the two side buttons) join the same tap, and only
+ when a bound combo actually contains one — the tap never asks for the
+ primary click.
The combo vocabulary, edge semantics (press fires on the chord-down
transition, release only for push-to-talk rows), the permission fail-closed
@@ -35,6 +38,7 @@ from __future__ import annotations
import logging
import threading
+from jarvis.trigger.backends.global_hotkeys import MOUSE_BUTTON_TOKENS
from jarvis.trigger.backends.pynput import (
_macos_hotkey_permissions_granted,
_parse_combo_tokens,
@@ -69,6 +73,17 @@ _FLAG_MASK_TO_TOKEN: tuple[tuple[int, str], ...] = (
(1 << 20, "cmd"), # kCGEventFlagMaskCommand
)
+# ``kCGMouseEventButtonNumber`` -> the shared mouse token. Quartz numbers the
+# buttons in hardware order: 0 left, 1 right, 2 middle, 3 and 4 the side pair.
+# Left and right are deliberately absent (see ``MOUSE_BUTTON_TOKENS``), which is
+# also why the tap only ever asks for the ``OtherMouse`` events — the primary
+# click never even reaches this backend.
+_MOUSE_BUTTON_TO_TOKEN: dict[int, str] = {
+ 2: "mouse_middle",
+ 3: "mouse_x1",
+ 4: "mouse_x2",
+}
+
class QuartzHotkeyBackend:
"""Quartz event-tap hotkey backend for macOS (AD-8).
@@ -89,6 +104,10 @@ class QuartzHotkeyBackend:
self._runloop: object | None = None
self._thread: threading.Thread | None = None
self._teardown_failed = False
+ # Widen the tap to mouse events only when a bound combo needs one: a
+ # narrower mask is fewer events crossing the tap for every click the
+ # user makes all day.
+ self._needs_mouse = False
# ------------------------------------------------------------------
# Registration + chord matching (mirrors PynputBackend semantics)
@@ -115,6 +134,9 @@ class QuartzHotkeyBackend:
}
)
self._combos = combos
+ self._needs_mouse = any(
+ combo["tokens"] & MOUSE_BUTTON_TOKENS for combo in combos
+ )
def _reconcile(self) -> None:
"""Fire press/release handlers on chord down/up transitions."""
@@ -159,6 +181,21 @@ class QuartzHotkeyBackend:
self._held.discard(token)
self._reconcile()
+ def _handle_mouse_down(self, button_number: int) -> None:
+ token = _MOUSE_BUTTON_TO_TOKEN.get(button_number)
+ if token is None:
+ return
+ self._held.add(token)
+ self._reconcile()
+
+ def _handle_mouse_up(self, button_number: int) -> None:
+ token = _MOUSE_BUTTON_TO_TOKEN.get(button_number)
+ if token is None:
+ return
+ self._reconcile() # check release edges BEFORE dropping the token
+ self._held.discard(token)
+ self._reconcile()
+
def _handle_flags(self, flags: int) -> None:
"""Sync the modifier subset of the held-set from the flags word."""
for mask, token in _FLAG_MASK_TO_TOKEN:
@@ -217,6 +254,25 @@ class QuartzHotkeyBackend:
)
return
+ # Resolved once, tolerantly: a pyobjc build without the mouse constants
+ # must degrade to "keyboard shortcuts only", never make every event
+ # raise inside the tap callback.
+ mouse_down_type = getattr(Quartz, "kCGEventOtherMouseDown", None)
+ mouse_up_type = getattr(Quartz, "kCGEventOtherMouseUp", None)
+ button_field = getattr(Quartz, "kCGMouseEventButtonNumber", None)
+ mouse_ready = (
+ mouse_down_type is not None
+ and mouse_up_type is not None
+ and button_field is not None
+ )
+ if self._needs_mouse and not mouse_ready:
+ log.warning(
+ "Mouse-button shortcuts are unavailable on this system (the "
+ "installed Quartz build exposes no mouse event constants) — "
+ "shortcuts that use a key combination still work, and voice "
+ "still works via the wake word."
+ )
+
def _callback(_proxy, event_type, event, _refcon):
try:
if event_type == Quartz.kCGEventKeyDown:
@@ -231,6 +287,14 @@ class QuartzHotkeyBackend:
self._handle_key_up(int(keycode))
elif event_type == Quartz.kCGEventFlagsChanged:
self._handle_flags(int(Quartz.CGEventGetFlags(event)))
+ elif mouse_ready and event_type == mouse_down_type:
+ self._handle_mouse_down(
+ int(Quartz.CGEventGetIntegerValueField(event, button_field))
+ )
+ elif mouse_ready and event_type == mouse_up_type:
+ self._handle_mouse_up(
+ int(Quartz.CGEventGetIntegerValueField(event, button_field))
+ )
elif event_type in (
Quartz.kCGEventTapDisabledByTimeout,
Quartz.kCGEventTapDisabledByUserInput,
@@ -248,6 +312,9 @@ class QuartzHotkeyBackend:
| Quartz.CGEventMaskBit(Quartz.kCGEventKeyUp)
| Quartz.CGEventMaskBit(Quartz.kCGEventFlagsChanged)
)
+ if self._needs_mouse and mouse_ready:
+ mask |= Quartz.CGEventMaskBit(mouse_down_type)
+ mask |= Quartz.CGEventMaskBit(mouse_up_type)
tap = Quartz.CGEventTapCreate(
Quartz.kCGSessionEventTap,
Quartz.kCGHeadInsertEventTap,
@@ -381,6 +448,7 @@ class QuartzHotkeyBackend:
def unregister(self) -> None:
"""Drop the armed bindings. The tap is torn down in ``stop``."""
self._combos = []
+ self._needs_mouse = False
def received_any_event(self) -> bool:
"""True once any bound chord has fired (AD-8 macOS permission hint)."""
diff --git a/jarvis/trigger/hotkey.py b/jarvis/trigger/hotkey.py
index f988416a64..3ab94e4516 100644
--- a/jarvis/trigger/hotkey.py
+++ b/jarvis/trigger/hotkey.py
@@ -47,7 +47,9 @@ from __future__ import annotations
import asyncio
import logging
-from collections.abc import AsyncIterator
+from collections.abc import AsyncIterator, Iterator
+from dataclasses import dataclass
+from typing import Any
# Relocated Windows machinery (AD-7). Imported here so callers that historically
# did ``from jarvis.trigger.hotkey import _normalize_combo`` keep working, and so
@@ -58,6 +60,8 @@ from jarvis.trigger.backends import HotkeyBackend, make_hotkey_backend
from jarvis.trigger.backends import global_hotkeys as _gh_backend
from jarvis.trigger.backends.global_hotkeys import (
_KEY_MAP, # noqa: F401 — re-exported for backwards compatibility
+ MOUSE_BUTTON_TOKENS,
+ _canonical_token,
_normalize_combo,
_reset_checker_state_for_tests,
)
@@ -116,109 +120,186 @@ _SOLO_SAFE_KEYS = frozenset({f"f{i}" for i in range(1, 25)}) | frozenset(
_RESERVED_SOLO_KEYS = frozenset({"f12"})
# Command-modified chords macOS assigns to universal system actions. Binding one
-# as a trigger means the user loses that action (Cmd+Q quits the focused app,
-# Cmd+W closes its window, Cmd+Space is Spotlight) — the exact class of mistake
-# the Windows list below already prevented. These were all ACCEPTED before
-# ``cmd`` became a recognised modifier.
+# means the focused app keeps doing that action too (Cmd+Q quits it, Cmd+W closes
+# its window, Cmd+Space opens Spotlight) — worth a caution, never a refusal.
_MACOS_CRITICAL_KEYS = frozenset({"c", "v", "x", "z", "q", "w", "a", "s", "space", "tab"})
+# The Windows-shell equivalent of the list above. It did not exist while
+# Win-key combos were refused outright; now that they are allowed, a user who
+# binds Win+D deserves the same warning a Mac user gets for Cmd+W — the shell
+# keeps showing the desktop on top of triggering the shortcut.
+_WINDOWS_CRITICAL_KEYS = frozenset(
+ {"d", "e", "l", "r", "x", "i", "s", "v", "a", "p", "tab", "left", "right", "up", "down"}
+)
+
+
+@dataclass(frozen=True)
+class HotkeyVerdict:
+ """The result of :func:`validate_hotkey`: a verdict plus soft cautions.
+
+ Why this shape and not a three-element tuple: every existing caller does
+ ``ok, reason = validate_hotkey(...)``. Appending a third element to the
+ tuple would turn each of them into a ``ValueError: too many values to
+ unpack`` at runtime — a silent-in-review, loud-in-production break across
+ the settings route, the setup wizard and four test modules. A small object
+ that ITERATES as the historical two-tuple keeps every one of those call
+ sites byte-identical, while ``verdict.cautions`` is there for the UI that
+ wants it. It is opt-in by construction: a caller who never asks for a
+ caution cannot accidentally receive one in place of the reason.
+
+ ``ok`` is False only for input that means nothing at all (an empty combo).
+ Everything the validator used to refuse — a modifiers-only chord, a bare
+ typing key, an OS-critical shortcut — is now ACCEPTED with a caution,
+ because the user, not the validator, owns the keyboard.
+ """
+
+ ok: bool
+ reason: str = ""
+ cautions: tuple[str, ...] = ()
+
+ @property
+ def caution(self) -> str:
+ """Every caution as one user-facing sentence block (``""`` when none)."""
+ return " ".join(self.cautions)
+
+ def __bool__(self) -> bool:
+ return self.ok
+
+ def __iter__(self) -> Iterator[Any]:
+ # The historical ``(ok, reason)`` contract — see the class docstring.
+ yield self.ok
+ yield self.reason
+
+ def __len__(self) -> int:
+ return 2
+
+ def __getitem__(self, index: int) -> Any:
+ return (self.ok, self.reason)[index]
+
-def validate_hotkey(combo: str, *, platform: str | None = None) -> tuple[bool, str]:
+def validate_hotkey(combo: str, *, platform: str | None = None) -> HotkeyVerdict:
"""Validate a user-supplied hotkey string (call / hangup / dictate).
- Returns ``(ok, reason)``. ``reason`` is an English, user-facing sentence
- when ``ok`` is False (the UI surfaces it). The rules encode the CLAUDE.md
- hotkey guidance so a bad combo can never reach the hotkey backend (where an
- invalid registration would silently disable that shortcut):
-
- * non-empty and parseable (``mod+mod+key`` syntax),
- * at least one non-modifier key (a combo of only Ctrl/Alt/Shift is dead),
- * a modifier OR a second key — a single bare key (``j``) as a global
- hotkey fires on every keystroke while typing,
- * no Windows-key combos (reserved by the OS),
- * not an OS-critical shortcut — Alt+F4 closes windows, Ctrl+C is
- copy/interrupt, and on the macOS side Cmd+Q/W/C/V/Space and friends,
- * not a permanently reserved key (F12 belongs to the debugger).
-
- ``platform`` (``"win32"`` / ``"darwin"`` / ``"linux"``) is only used to warn
- about a Command-based chord on a host that has no Command key; it defaults
- to the live platform and exists so tests are deterministic. The combo
- vocabulary itself stays platform-neutral: a config file may legitimately
- travel between a Mac and a PC.
+ Returns a :class:`HotkeyVerdict` that still unpacks as the historical
+ ``(ok, reason)`` pair. The policy (maintainer directive 2026-07-28): **any
+ key combination is selectable**, mouse buttons included. The validator
+ refuses only what is genuinely meaningless — an empty combo — and reports
+ everything else as a NON-BLOCKING caution the UI can show next to the
+ saved shortcut:
+
+ * a modifiers-only chord (``ctrl+win``) also fires when any further key
+ joins it, so it triggers on Ctrl+Win+Left, Ctrl+Win+D and friends;
+ * a bare typing key fires while you type ordinary text;
+ * an OS-critical combo (Alt+F4, Ctrl+C, the macOS Command shortcuts,
+ F12) is still delivered to the focused app, which keeps doing its
+ thing on top of the shortcut;
+ * a Command chord on a machine that has no Command key cannot fire
+ there — honest, and harmless for a config that travels to a Mac;
+ * a mouse button does not swallow the click.
+
+ The two refusals that used to live here — "a combo of only Ctrl/Alt/Shift
+ cannot be a trigger" and "Windows / Super key combos are reserved by the
+ OS" — are gone because both were untrue for this codebase: the Windows
+ backend polls ``GetAsyncKeyState`` (it never calls ``RegisterHotKey``, so
+ the shell cannot claim the chord first), and Win/Super/Command are
+ first-class tokens in all three backends. What they cost the user was
+ real; what they protected against is a caution, not a wall.
+
+ ``platform`` (``"win32"`` / ``"darwin"`` / ``"linux"``) picks the
+ platform-specific cautions; it defaults to the live platform and exists so
+ tests are deterministic. The combo vocabulary itself stays
+ platform-neutral: a config file may legitimately travel between a Mac and
+ a PC.
"""
if not combo or not combo.strip():
- return False, "Hotkey is empty."
- parts = [p.strip().lower() for p in combo.split("+") if p.strip()]
+ return HotkeyVerdict(False, "Hotkey is empty.")
+ parts = [_canonical_token(p.strip().lower()) for p in combo.split("+") if p.strip()]
if not parts:
- return False, "Hotkey is empty."
+ return HotkeyVerdict(False, "Hotkey is empty.")
modifiers = [p for p in parts if p in _MODIFIER_TOKENS]
non_modifiers = [p for p in parts if p not in _MODIFIER_TOKENS]
+ mouse_buttons = [p for p in parts if p in MOUSE_BUTTON_TOKENS]
+ cautions: list[str] = []
if not non_modifiers:
- return False, "Add a real key — a combo of only Ctrl/Alt/Shift cannot be a trigger."
- if (
- not modifiers
- and len(parts) < 2
- and parts[0] not in _SOLO_SAFE_KEYS
- ):
- return False, (
- "This key fires while typing normal text — add Ctrl/Alt/Shift or a "
- "second key. (Function keys and navigation keys like F5 or Arrow Up "
- "can be used on their own.)"
+ cautions.append(
+ "This shortcut is modifier keys only, so it also fires the moment "
+ "any other key joins them — Ctrl+Win would trigger on Ctrl+Win+Left "
+ "(switch virtual desktop), Ctrl+Win+D and every other Ctrl+Win "
+ "shortcut too."
)
- # ``super`` / ``meta`` are the same physical key as ``win`` under different
- # names (X11 and most Linux desktops call it Super, pynput reports it as
- # ``cmd``). Before they were listed here, ``ctrl+super+space`` passed
- # validation and then registered a binding that could never fire: neither
- # ``global_hotkeys._KEY_MAP`` nor ``pynput._MODIFIER_TO_KEY_ATTR`` knew the
- # token, so the combo was armed and silently dead. Rejecting it is the
- # honest answer — the OS owns that key on all three platforms.
- if any(p in ("win", "window", "super", "meta") for p in modifiers):
- return False, (
- "Windows / Super key combos are reserved by the OS — pick "
- "Ctrl/Alt/Shift."
+ elif not modifiers and len(parts) < 2 and parts[0] not in _SOLO_SAFE_KEYS and not mouse_buttons:
+ cautions.append(
+ "This key also fires while you type normal text — every press of it "
+ "triggers the shortcut. Add Ctrl/Alt/Shift or a second key if that "
+ "is not what you want."
)
reserved = sorted(set(non_modifiers) & _RESERVED_SOLO_KEYS)
if reserved:
- return False, (
- f"{reserved[0].upper()} is permanently reserved by the operating "
- "system (the debugger claims it) — choose another key."
+ cautions.append(
+ f"{reserved[0].upper()} is claimed by the system debugger — some "
+ "applications will take it before the shortcut sees it."
)
_CTRL = ("ctrl", "control", "right_ctrl", "right_control")
_ALT = ("alt", "right_alt", "left_alt", "altgr")
- # ``meta``/``super`` are listed for completeness only — the Windows/Super
- # rule above already rejected any combo containing them, so they can never
- # reach this branch. macOS Command is spelled ``cmd``/``command``.
_CMD = ("cmd", "command", "meta", "super")
+ _WIN = ("win", "window", "super", "meta")
alt_held = any(p in _ALT for p in modifiers)
# "X-only" means X-family modifiers and nothing else — so the exact OS
- # shortcut is blocked while a richer combo that merely contains it (e.g.
- # Ctrl+Shift+C) stays allowed.
+ # shortcut is cautioned while a richer combo that merely contains it (e.g.
+ # Ctrl+Shift+C) stays silent.
ctrl_only = bool(modifiers) and all(p in _CTRL for p in modifiers)
cmd_only = bool(modifiers) and all(p in _CMD for p in modifiers)
+ win_only = bool(modifiers) and all(p in _WIN for p in modifiers)
if alt_held and "f4" in non_modifiers:
- return False, "Alt+F4 closes the active window — choose another combo."
+ cautions.append(_os_shortcut_caution("Alt+F4", "closes the active window"))
if ctrl_only and non_modifiers == ["c"]:
- return False, "Ctrl+C is the copy / interrupt shortcut — choose another combo."
+ cautions.append(_os_shortcut_caution("Ctrl+C", "copies, and interrupts a terminal"))
+ if win_only and len(non_modifiers) == 1 and non_modifiers[0] in _WINDOWS_CRITICAL_KEYS:
+ cautions.append(
+ _os_shortcut_caution(
+ f"Win+{non_modifiers[0].upper()}",
+ "is a system shortcut on Windows (show the desktop, lock the "
+ "screen, the emoji picker and friends)",
+ )
+ )
if cmd_only and len(non_modifiers) == 1 and non_modifiers[0] in _MACOS_CRITICAL_KEYS:
- return False, (
- f"Command+{non_modifiers[0].upper()} is a system shortcut on macOS "
- "(copy, quit, close, Spotlight and friends) — add Shift/Alt or "
- "choose another key."
+ cautions.append(
+ _os_shortcut_caution(
+ f"Command+{non_modifiers[0].upper()}",
+ "is a system shortcut on macOS (copy, quit, close, Spotlight "
+ "and friends)",
+ )
)
if any(p in ("cmd", "command") for p in modifiers):
host = platform if platform is not None else _detect_platform()
if host not in (None, "darwin"):
- return False, (
- "There is no Command key on this computer — use Ctrl, Alt or "
- "Shift instead. (Command shortcuts work on macOS.)"
+ cautions.append(
+ "There is no Command key on this computer, so this shortcut "
+ "cannot fire here. (It works on macOS — a shortcut set on a "
+ "Mac keeps working when the config travels back.)"
)
- return True, ""
+ if mouse_buttons:
+ cautions.append(
+ "A mouse button does not swallow the click: the button keeps doing "
+ "its normal job in whatever you are pointing at while it also "
+ "triggers this shortcut."
+ )
+
+ return HotkeyVerdict(True, "", tuple(cautions))
+
+
+def _os_shortcut_caution(pretty: str, does_what: str) -> str:
+ """One caution sentence for a combo the focused app also acts on."""
+ return (
+ f"{pretty} {does_what} — the app you are working in still receives it, "
+ "so you get both at once."
+ )
def _detect_platform() -> str | None:
@@ -235,6 +316,114 @@ def _detect_platform() -> str | None:
return None
+def normalized_combo_tokens(combo: str) -> frozenset[str]:
+ """The key set a combo ACTUALLY registers as, after normalization.
+
+ ``ctrl+right_alt+j`` and ``ctrl+left_alt+j`` are different strings and the
+ identical registration: the Windows backend folds every Alt variant onto
+ the generic ``alt`` (it cannot tell the sides apart), and win/super/meta
+ all fold onto ``window``. Any comparison of two shortcuts has to happen on
+ THIS set — comparing the raw tokens accepts two combos the OS sees as one.
+ """
+ return frozenset(
+ p.strip() for p in _normalize_combo(combo).split("+") if p.strip()
+ )
+
+
+def combos_collide(a: str, b: str) -> bool:
+ """Whether two shortcuts cannot coexist — normalized, not raw.
+
+ The bug this closes: the settings route compared RAW token sets, so
+ ``ctrl+left_alt+j`` and ``ctrl+right_alt+j`` passed the overlap check as
+ two different shortcuts and then normalized to the SAME registration. The
+ second one lost the race inside ``register`` and died with a log line
+ nobody sees, leaving the user with two bound-looking rows, one of them
+ silently dead.
+
+ Two relations collide, both evaluated on the normalized key sets:
+
+ * identical sets — the same registration under two spellings;
+ * subset / superset — the polling backends match a chord as soon as its
+ keys are down, so ``f1`` and ``f1+f2`` fire each other.
+
+ An unbound (empty) combo never collides: an empty set is a subset of
+ everything, and every save would be refused the moment one action is
+ cleared.
+ """
+ tokens_a = normalized_combo_tokens(a)
+ tokens_b = normalized_combo_tokens(b)
+ if not tokens_a or not tokens_b:
+ return False
+ return tokens_a <= tokens_b or tokens_b <= tokens_a
+
+
+def mouse_hotkeys_available(platform: str | None = None) -> tuple[bool, str]:
+ """Can this host bind a MOUSE BUTTON as a shortcut? ``(ok, reason)``.
+
+ A capability probe, never a platform name test (AP-21/AP-23). ``reason``
+ is an English sentence for the user when the answer is no, naming what is
+ missing and what still works — the UI shows it instead of offering a
+ control that would do nothing:
+
+ * Windows — always: the backend polls ``GetAsyncKeyState``, which reports
+ mouse buttons alongside keys.
+ * macOS — needs pyobjc's ``Quartz`` (the event tap already exists; it just
+ listens for mouse events too now) plus the Accessibility / Input
+ Monitoring grants the backend already checks at ``start``.
+ * Linux/X11 — needs ``pynput`` (the opt-in ``[desktop-linux]`` extra).
+ Wayland has no global button grabs at all, the same reason keyboard
+ shortcuts degrade there.
+
+ Kept import-light and lazy so it never runs on the boot path (AP-26).
+ """
+ host = platform if platform is not None else _detect_platform()
+ if host == "win32":
+ return True, ""
+ if host == "darwin":
+ if _module_present("Quartz"):
+ return True, ""
+ return False, (
+ "Mouse-button shortcuts need the pyobjc Quartz package, which is "
+ "not installed — install the [full] profile. Key combinations "
+ "still work."
+ )
+ if host == "linux":
+ try:
+ from jarvis.platform.probes import is_wayland
+
+ wayland = is_wayland()
+ except Exception: # noqa: BLE001 — a probe failure must never hard-fail
+ wayland = False
+ if wayland:
+ return False, (
+ "Wayland does not let an application watch the mouse buttons "
+ "globally, so a mouse-button shortcut cannot work here. Use a "
+ "key combination, or bind a compositor shortcut to the Jarvis "
+ "CLI."
+ )
+ if _module_present("pynput"):
+ return True, ""
+ return False, (
+ "Mouse-button shortcuts need the pynput package, which is not "
+ "installed — install the [desktop-linux] extra. Key combinations "
+ "still work."
+ )
+ return False, (
+ "This system has no way to watch the mouse buttons globally — use a "
+ "key combination instead."
+ )
+
+
+def _module_present(name: str) -> bool:
+ """Is ``name`` importable, without importing it (cheap, AP-26)."""
+ try:
+ import importlib.util
+
+ return importlib.util.find_spec(name) is not None
+ except Exception: # noqa: BLE001 — a broken meta-path must not raise here
+ return False
+
+
class HotkeyTrigger:
"""Manages several named hotkey bindings at once.
@@ -468,7 +657,12 @@ class HotkeyTrigger:
__all__ = [
+ "MOUSE_BUTTON_TOKENS",
"HotkeyTrigger",
+ "HotkeyVerdict",
+ "combos_collide",
+ "mouse_hotkeys_available",
+ "normalized_combo_tokens",
"validate_hotkey",
"_normalize_combo",
"_reset_checker_state_for_tests",
diff --git a/tests/unit/dictation/test_dictate_keybind.py b/tests/unit/dictation/test_dictate_keybind.py
index 6cd5218558..ada53deb8d 100644
--- a/tests/unit/dictation/test_dictate_keybind.py
+++ b/tests/unit/dictation/test_dictate_keybind.py
@@ -58,22 +58,28 @@ def test_the_shipped_dictation_combos_validate_everywhere(platform: str) -> None
@pytest.mark.parametrize("combo", ["cmd+c", "cmd+v", "cmd+q", "cmd+w", "cmd+space"])
-def test_macos_system_shortcuts_are_refused(combo: str) -> None:
- ok, reason = validate_hotkey(combo, platform="darwin")
- assert ok is False
- assert "macOS" in reason
+def test_macos_system_shortcuts_are_cautioned_not_refused(combo: str) -> None:
+ """INVERTED 2026-07-28: any combination is selectable. Losing Cmd+Q to a
+ shortcut is the user's call to make — but they get told first."""
+ verdict = validate_hotkey(combo, platform="darwin")
+ assert verdict.ok is True
+ assert "macOS" in verdict.caution
+ assert "still receives it" in verdict.caution
@pytest.mark.parametrize("combo", ["cmd+d", "cmd+shift+d", "cmd+alt+space"])
def test_usable_command_chords_are_accepted_on_macos(combo: str) -> None:
- ok, reason = validate_hotkey(combo, platform="darwin")
- assert ok is True, reason
+ verdict = validate_hotkey(combo, platform="darwin")
+ assert verdict.ok is True, verdict.reason
+ assert verdict.cautions == ()
-def test_command_chord_is_refused_where_there_is_no_command_key() -> None:
- ok, reason = validate_hotkey("cmd+d", platform="win32")
- assert ok is False
- assert "Command key" in reason
+def test_command_chord_is_cautioned_where_there_is_no_command_key() -> None:
+ """A config that travels from a Mac keeps its Cmd shortcut instead of being
+ rewritten; the PC it lands on says honestly that the key does not exist."""
+ verdict = validate_hotkey("cmd+d", platform="win32")
+ assert verdict.ok is True
+ assert "no Command key" in verdict.caution
# --------------------------------------------------------------------------
@@ -81,29 +87,46 @@ def test_command_chord_is_refused_where_there_is_no_command_key() -> None:
# --------------------------------------------------------------------------
-def test_f12_is_refused_as_reserved() -> None:
- ok, reason = validate_hotkey("f12", platform="win32")
- assert ok is False
- assert "reserved" in reason.lower()
+def test_f12_carries_a_caution_instead_of_a_refusal() -> None:
+ verdict = validate_hotkey("f12", platform="win32")
+ assert verdict.ok is True
+ assert "debugger" in verdict.caution
@pytest.mark.parametrize(
- ("combo", "expected"),
+ ("combo", "expected_ok", "expect_caution"),
[
- ("ctrl+alt+d", True),
- ("f5", True),
- ("f3+f4", True),
- ("win+d", False),
- ("alt+f4", False),
- ("ctrl+c", False),
- ("j", False),
- ("ctrl", False),
- ("", False),
+ ("ctrl+alt+d", True, False),
+ ("f5", True, False),
+ ("f3+f4", True, False),
+ # INVERTED 2026-07-28 — these five used to be refusals. The maintainer
+ # asked for ANY key combination, explicitly including Ctrl+Win; the
+ # honest cost of each is now a caution the UI shows, not a wall.
+ ("win+d", True, True),
+ ("ctrl+win", True, True),
+ ("alt+f4", True, True),
+ ("ctrl+c", True, True),
+ ("j", True, True),
+ ("ctrl", True, True),
+ # The one thing that still means nothing at all.
+ ("", False, False),
],
)
-def test_existing_rules_are_unchanged(combo: str, expected: bool) -> None:
- ok, _reason = validate_hotkey(combo, platform="win32")
- assert ok is expected
+def test_only_an_empty_combo_is_refused(
+ combo: str, expected_ok: bool, expect_caution: bool
+) -> None:
+ verdict = validate_hotkey(combo, platform="win32")
+ assert verdict.ok is expected_ok
+ assert bool(verdict.cautions) is expect_caution, verdict.caution
+
+
+def test_win_d_is_accepted_but_names_what_it_costs() -> None:
+ """``win+d`` shows the desktop on Windows. Jarvis still SEES the press (the
+ backend polls key state rather than registering a system hot key), so the
+ honest statement is 'you get both', not 'you cannot have this'."""
+ verdict = validate_hotkey("win+d", platform="win32")
+ assert verdict.ok is True
+ assert verdict.caution
# --------------------------------------------------------------------------
diff --git a/tests/unit/trigger/test_hotkey.py b/tests/unit/trigger/test_hotkey.py
index a161c87991..e350569fcd 100644
--- a/tests/unit/trigger/test_hotkey.py
+++ b/tests/unit/trigger/test_hotkey.py
@@ -111,55 +111,124 @@ def test_validate_hotkey_accepts_safe_combos(combo):
assert ok, f"{combo!r} should be valid, got: {reason}"
+@_pytest.mark.parametrize("combo", ["", " ", "+", " + "])
+def test_validate_hotkey_rejects_only_the_meaningless(combo):
+ """The ONLY hard refusal left (maintainer directive 2026-07-28): a combo
+ with no keys in it. Everything else the user asks for, the user gets."""
+ from jarvis.trigger.hotkey import validate_hotkey
+
+ ok, reason = validate_hotkey(combo)
+ assert not ok, f"{combo!r} should be rejected"
+ assert reason, "a rejection must carry a user-facing reason"
+
+
@_pytest.mark.parametrize(
- "combo",
+ ("combo", "caution_marker"),
[
- "", # empty
- " ", # blank
- "ctrl+alt+shift", # modifiers only — no real key
- "j", # single bare letter — fires on every keystroke
- "5", # single bare digit — fires while typing numbers
- "space", # typing key solo — fires on every space
- "enter", # typing key solo
- "tab", # typing key solo
- "backspace", # typing key solo
- "numpad_5", # numpad digit solo — fires while typing numbers
- "win+j", # Windows key reserved
- "alt+f4", # closes windows
- "ctrl+c", # copy / interrupt
+ # Was: "a combo of only Ctrl/Alt/Shift cannot be a trigger."
+ ("ctrl+alt+shift", "modifier keys only"),
+ ("ctrl+win", "modifier keys only"),
+ # Was: "This key fires while typing normal text."
+ ("j", "while you type"),
+ ("5", "while you type"),
+ ("space", "while you type"),
+ ("enter", "while you type"),
+ ("tab", "while you type"),
+ ("backspace", "while you type"),
+ ("numpad_5", "while you type"),
+ # Was: OS-critical refusals.
+ ("alt+f4", "Alt+F4"),
+ ("ctrl+c", "Ctrl+C"),
+ ("f12", "debugger"),
],
)
-def test_validate_hotkey_rejects_unsafe_combos(combo):
+def test_formerly_refused_combos_are_accepted_with_a_caution(combo, caution_marker):
+ """The refusals became a NON-BLOCKING warning channel: the combo saves, and
+ the UI can tell the user what it will cost them. A caution that is empty is
+ the real regression here — that would be silent acceptance."""
from jarvis.trigger.hotkey import validate_hotkey
- ok, reason = validate_hotkey(combo)
- assert not ok, f"{combo!r} should be rejected"
- assert reason, "a rejection must carry a user-facing reason"
+ verdict = validate_hotkey(combo, platform="win32")
+ assert verdict.ok is True, f"{combo!r} must be selectable now"
+ assert caution_marker in verdict.caution, verdict.caution
+
+
+def test_the_verdict_still_unpacks_as_the_historical_pair():
+ """Every existing caller does ``ok, reason = validate_hotkey(...)``. A third
+ tuple element would have turned all of them into a ValueError."""
+ from jarvis.trigger.hotkey import validate_hotkey
+
+ ok, reason = validate_hotkey("ctrl+win", platform="win32")
+ assert ok is True
+ assert reason == ""
+ ok, reason = validate_hotkey("")
+ assert ok is False
+ assert reason
+
+
+def test_a_clean_combo_carries_no_caution():
+ """Cautions must stay rare, or the UI trains the user to ignore them."""
+ from jarvis.trigger.hotkey import validate_hotkey
+
+ verdict = validate_hotkey("ctrl+right_alt+j", platform="win32")
+ assert verdict.ok is True
+ assert verdict.cautions == ()
+ assert verdict.caution == ""
def test_validate_hotkey_allows_ctrl_c_when_part_of_larger_combo():
"""Ctrl+C alone is the interrupt; Ctrl+Shift+C is a different, safe combo."""
from jarvis.trigger.hotkey import validate_hotkey
- ok, _ = validate_hotkey("ctrl+shift+c")
- assert ok
+ verdict = validate_hotkey("ctrl+shift+c")
+ assert verdict.ok
+ assert verdict.cautions == ()
@_pytest.mark.parametrize(
- "combo",
- ["super+d", "meta+d", "ctrl+super+space", "ctrl+meta+j", "shift+super+k"],
+ ("combo", "registers_as"),
+ [
+ ("super+d", {"window", "d"}),
+ ("meta+d", {"window", "d"}),
+ ("ctrl+super+space", {"control", "window", "space"}),
+ ("ctrl+meta+j", {"control", "window", "j"}),
+ ("shift+super+k", {"shift", "window", "k"}),
+ ],
)
@_pytest.mark.parametrize("platform", ["win32", "darwin", "linux"])
-def test_validate_hotkey_rejects_the_super_and_meta_aliases(combo, platform):
- """The hole this closes: ``super``/``meta`` are the SAME physical key as
- ``win``, but they were checked by neither the Windows rule nor the Command
- rule. A combo using them passed validation and then registered a binding no
- backend could ever match — armed, and permanently dead."""
- from jarvis.trigger.hotkey import validate_hotkey
+def test_the_super_and_meta_aliases_normalize_to_a_key_that_fires(
+ combo, registers_as, platform
+):
+ """INVERTED from ``..._rejects_the_super_and_meta_aliases``.
+
+ The bug that test recorded was real and must stay closed: ``super``/``meta``
+ are the SAME physical key as ``win``, and a combo using them was once armed
+ against a token no backend knew — armed, and permanently dead. Refusing them
+ was the wrong cure (the maintainer wants Ctrl+Win), so the guarantee moves
+ from "rejected" to "accepted AND actually reaches the key every backend
+ watches": the alias folds onto ``window``, which the Windows poller reads as
+ VK_LWIN/VK_RWIN, the Quartz tap decodes from the Command flag, and pynput
+ matches through its ``cmd`` aliases. Accepting them WITHOUT this assertion
+ would re-open the original bug."""
+ from jarvis.trigger.backends.pynput import _GENERIC_MODIFIER_ALIASES, _parse_combo_tokens
+ from jarvis.trigger.hotkey import normalized_combo_tokens, validate_hotkey
+
+ verdict = validate_hotkey(combo, platform=platform)
+ assert verdict.ok is True, f"{combo!r} must be selectable on {platform}"
+
+ # It normalizes onto the one token the backends share...
+ assert normalized_combo_tokens(combo) == registers_as
+ # ...and that token resolves to a real physical key in the pynput matcher
+ # rather than a literal string nothing can ever match.
+ tokens = _parse_combo_tokens(_normalize_for_test(combo))
+ assert "cmd" in tokens
+ assert _GENERIC_MODIFIER_ALIASES["cmd"] == frozenset({"cmd", "cmd_l", "cmd_r"})
+
+
+def _normalize_for_test(combo: str) -> str:
+ from jarvis.trigger.hotkey import _normalize_combo
- ok, reason = validate_hotkey(combo, platform=platform)
- assert not ok, f"{combo!r} should be rejected on {platform}"
- assert "Super" in reason or "Windows" in reason
+ return _normalize_combo(combo)
def test_legacy_super_combos_still_normalize_to_a_real_key():
diff --git a/tests/unit/trigger/test_hotkey_policy.py b/tests/unit/trigger/test_hotkey_policy.py
new file mode 100644
index 0000000000..ceef0b59fc
--- /dev/null
+++ b/tests/unit/trigger/test_hotkey_policy.py
@@ -0,0 +1,288 @@
+"""Shortcut policy: any key combination, mouse buttons, honest collisions.
+
+Three separate guarantees live here, all landed together on 2026-07-28:
+
+1. **Any combination is selectable.** ``validate_hotkey`` hard-refuses only a
+ combo with no keys in it; everything it used to refuse is reported through
+ a non-blocking caution channel instead (``HotkeyVerdict.cautions``).
+2. **Mouse buttons are real shortcut keys** on every OS that can watch them,
+ with one shared vocabulary and an honest message where a backend cannot.
+3. **Collisions are compared NORMALIZED.** ``ctrl+left_alt+j`` and
+ ``ctrl+right_alt+j`` are one registration on Windows; the raw-token check
+ they used to face accepted both and left the second silently dead.
+"""
+
+from __future__ import annotations
+
+import sys
+import types
+
+import pytest
+
+from jarvis.trigger.hotkey import (
+ MOUSE_BUTTON_TOKENS,
+ HotkeyVerdict,
+ combos_collide,
+ mouse_hotkeys_available,
+ normalized_combo_tokens,
+ validate_hotkey,
+)
+
+# ----------------------------------------------------------------------
+# 1. The caution channel
+# ----------------------------------------------------------------------
+
+
+def test_ctrl_win_is_accepted_and_says_it_is_a_prefix_trigger() -> None:
+ """The headline case. Ctrl+Win used to die at the modifier-only gate before
+ the Windows gate was even reached. It now saves — with the one thing the
+ user cannot know by looking at it: a modifiers-only chord fires on every
+ superset, so Ctrl+Win+Left (switch virtual desktop) triggers it too."""
+ verdict = validate_hotkey("ctrl+win", platform="win32")
+
+ assert verdict.ok is True
+ assert verdict.reason == ""
+ assert "Ctrl+Win+Left" in verdict.caution
+
+
+def test_a_verdict_is_truthy_exactly_when_it_is_ok() -> None:
+ assert bool(validate_hotkey("ctrl+alt+j")) is True
+ assert bool(validate_hotkey("")) is False
+
+
+def test_cautions_accumulate_rather_than_shadow_each_other() -> None:
+ """Two independent problems must both reach the user."""
+ verdict = validate_hotkey("cmd+q", platform="win32")
+
+ assert verdict.ok is True
+ assert len(verdict.cautions) == 2
+ assert "macOS" in verdict.caution
+ assert "no Command key" in verdict.caution
+
+
+def test_verdict_indexes_like_the_old_tuple() -> None:
+ verdict = HotkeyVerdict(False, "Hotkey is empty.")
+ assert verdict[0] is False
+ assert verdict[1] == "Hotkey is empty."
+ assert len(verdict) == 2
+
+
+# ----------------------------------------------------------------------
+# 2. Mouse buttons
+# ----------------------------------------------------------------------
+
+
[email protected]("token", sorted(MOUSE_BUTTON_TOKENS))
+def test_a_solo_mouse_button_is_a_valid_shortcut(token: str) -> None:
+ verdict = validate_hotkey(token, platform="win32")
+
+ assert verdict.ok is True
+ # It must NOT inherit the "fires while you type" caution — a mouse button
+ # is not a typing key.
+ assert "while you type" not in verdict.caution
+ assert "does not swallow the click" in verdict.caution
+
+
+def test_a_mouse_button_combines_with_modifiers() -> None:
+ verdict = validate_hotkey("ctrl+mouse_x2", platform="win32")
+
+ assert verdict.ok is True
+ assert "does not swallow the click" in verdict.caution
+
+
+def test_mouse_aliases_fold_onto_one_canonical_token() -> None:
+ """``mouse_back`` and ``mouse_x1`` are the same physical button; two
+ spellings must never become two registrations."""
+ assert normalized_combo_tokens("mouse_back") == {"mouse_x1"}
+ assert normalized_combo_tokens("mouse_forward") == {"mouse_x2"}
+ assert normalized_combo_tokens("middle_mouse") == {"mouse_middle"}
+ assert combos_collide("mouse_back", "mouse_x1") is True
+
+
+def test_the_primary_buttons_are_deliberately_not_bindable() -> None:
+ """Left/right follow the system "swap mouse buttons" setting, so a shortcut
+ recorded as 'left' would fire on the physical right button for a left-handed
+ user — and binding the primary click globally makes the machine unusable."""
+ assert "mouse_left" not in MOUSE_BUTTON_TOKENS
+ assert "mouse_right" not in MOUSE_BUTTON_TOKENS
+
+
+def test_every_mouse_token_is_known_to_all_three_backends() -> None:
+ """AP-4 parity: one vocabulary, three translations. A token that reaches
+ only one backend is a shortcut that works on one OS and silently does
+ nothing on the other two."""
+ from jarvis.trigger.backends.global_hotkeys import _MOUSE_TOKEN_TO_VK
+ from jarvis.trigger.backends.pynput import _MOUSE_NAME_TO_TOKEN
+ from jarvis.trigger.backends.quartz import _MOUSE_BUTTON_TO_TOKEN
+
+ assert set(_MOUSE_TOKEN_TO_VK) == set(MOUSE_BUTTON_TOKENS)
+ assert set(_MOUSE_NAME_TO_TOKEN.values()) == set(MOUSE_BUTTON_TOKENS)
+ assert set(_MOUSE_BUTTON_TO_TOKEN.values()) == set(MOUSE_BUTTON_TOKENS)
+
+
+def test_windows_registers_a_mouse_button_as_its_virtual_key() -> None:
+ """The library matches on ``GetAsyncKeyState``, which reports mouse buttons
+ — but only for a numeric VK token. The friendly token stays readable
+ everywhere above the library boundary."""
+ from jarvis.trigger.backends.global_hotkeys import _normalize_combo, _to_library_combo
+
+ normalized = _normalize_combo("ctrl+mouse_x2")
+ assert normalized == "control + mouse_x2"
+ assert _to_library_combo(normalized) == "control + 0x06"
+
+
+def test_windows_backend_registers_and_removes_the_same_mouse_string() -> None:
+ """Registration and removal must be byte-identical, or a stale registration
+ survives teardown and bricks the next re-arm (the F1+F2-went-dead class)."""
+ from jarvis.trigger.backends.global_hotkeys import GlobalHotkeysBackend
+ from tests.fakes.fake_global_hotkeys import FakeGlobalHotkeys
+
+ fake = FakeGlobalHotkeys()
+ saved = sys.modules.get("global_hotkeys")
+ sys.modules["global_hotkeys"] = fake
+ try:
+ backend = GlobalHotkeysBackend()
+ backend.register([["control + mouse_x1", None, lambda: None]])
+ assert "control+0x05" in fake.registered
+ backend.unregister()
+ assert not fake.registered
+ finally:
+ if saved is not None:
+ sys.modules["global_hotkeys"] = saved
+ else:
+ sys.modules.pop("global_hotkeys", None)
+
+
+def test_linux_side_button_drives_one_edge_pair() -> None:
+ """X11 numbers the side buttons 8 and 9; a chord of modifier + side button
+ must fire exactly one down edge and one up edge."""
+ from jarvis.trigger.backends.pynput import PynputBackend
+
+ edges: list[str] = []
+ backend = PynputBackend()
+ backend.register(
+ [["control + mouse_x2", lambda: edges.append("down"), lambda: edges.append("up")]]
+ )
+ assert backend._needs_mouse is True
+
+ backend._on_press_key(types.SimpleNamespace(char=None, name="ctrl_l"))
+ backend._on_click(0, 0, types.SimpleNamespace(name="button9"), True)
+ backend._on_click(0, 0, types.SimpleNamespace(name="button9"), False)
+ backend._on_press_key(types.SimpleNamespace(char=None, name="ctrl_l"))
+
+ assert edges == ["down", "up"]
+
+
+def test_linux_ignores_an_unmapped_mouse_button() -> None:
+ """A button no token names must be inert, never fire the nearest chord."""
+ from jarvis.trigger.backends.pynput import PynputBackend
+
+ edges: list[str] = []
+ backend = PynputBackend()
+ backend.register([["mouse_middle", None, lambda: edges.append("fired")]])
+
+ backend._on_click(0, 0, types.SimpleNamespace(name="scroll_up"), True)
+
+ assert edges == []
+
+
+def test_linux_keyboard_only_bindings_start_no_mouse_hook() -> None:
+ """An idle desktop must not pay for a hook nothing asked for."""
+ from jarvis.trigger.backends.pynput import PynputBackend
+
+ backend = PynputBackend()
+ backend.register([["control + alt + j", None, lambda: None]])
+
+ assert backend._needs_mouse is False
+
+
+def test_macos_side_button_drives_one_edge_pair() -> None:
+ from jarvis.trigger.backends.quartz import QuartzHotkeyBackend
+
+ edges: list[str] = []
+ backend = QuartzHotkeyBackend()
+ backend._permission_check = lambda: True
+ backend.register(
+ [["alt + mouse_x1", lambda: edges.append("down"), lambda: edges.append("up")]]
+ )
+ assert backend._needs_mouse is True
+
+ backend._handle_flags(1 << 19) # Option/Alt down
+ backend._handle_mouse_down(3) # side button 1
+ backend._handle_mouse_up(3)
+ backend._handle_flags(0)
+
+ assert edges == ["down", "up"]
+
+
+def test_macos_ignores_the_primary_buttons() -> None:
+ """Button 0/1 are left/right — the tap never asks for them, and even if one
+ arrived it must not touch a chord."""
+ from jarvis.trigger.backends.quartz import QuartzHotkeyBackend
+
+ edges: list[str] = []
+ backend = QuartzHotkeyBackend()
+ backend._permission_check = lambda: True
+ backend.register([["mouse_middle", None, lambda: edges.append("fired")]])
+
+ backend._handle_mouse_down(0)
+ backend._handle_mouse_down(1)
+
+ assert edges == []
+
+
+def test_mouse_support_is_reported_per_host_with_an_honest_reason() -> None:
+ ok, reason = mouse_hotkeys_available(platform="win32")
+ assert ok is True
+ assert reason == ""
+
+ ok, reason = mouse_hotkeys_available(platform="haiku")
+ assert ok is False
+ assert reason
+ assert "key combination" in reason
+
+
+def test_wayland_reports_no_mouse_shortcuts_instead_of_pretending(monkeypatch) -> None:
+ import jarvis.platform.probes as probes
+
+ monkeypatch.setattr(probes, "is_wayland", lambda: True)
+ ok, reason = mouse_hotkeys_available(platform="linux")
+
+ assert ok is False
+ assert "Wayland" in reason
+
+
+# ----------------------------------------------------------------------
+# 3. Collision detection on the NORMALIZED combo
+# ----------------------------------------------------------------------
+
+
+def test_left_and_right_alt_collide_because_windows_cannot_tell_them_apart() -> None:
+ """THE bug: both were accepted as different shortcuts, both were shown as
+ bound, and the second one was dead the moment it was registered."""
+ assert combos_collide("ctrl+left_alt+j", "ctrl+right_alt+j") is True
+ assert normalized_combo_tokens("ctrl+left_alt+j") == normalized_combo_tokens(
+ "ctrl+right_alt+j"
+ )
+
+
+def test_super_and_win_spellings_collide() -> None:
+ assert combos_collide("ctrl+super+space", "ctrl+win+space") is True
+
+
+def test_a_subset_still_collides() -> None:
+ """The polling backends match a chord as soon as its keys are down."""
+ assert combos_collide("f1", "f1+f2") is True
+ assert combos_collide("f1+f2", "f1") is True
+
+
+def test_unrelated_combos_do_not_collide() -> None:
+ assert combos_collide("ctrl+alt+j", "ctrl+alt+k") is False
+ assert combos_collide("f3+f4", "f1+f2") is False
+
+
+def test_an_unbound_action_never_collides() -> None:
+ """An empty key set is a subset of everything — without this guard, every
+ save would be refused the moment one shortcut is cleared."""
+ assert combos_collide("", "ctrl+alt+j") is False
+ assert combos_collide("ctrl+alt+j", " ") is False