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(hotkeys): backends answer whether a chord is physically down
rubenluetke10-beepceb7fb5fea7b
diff --git a/jarvis/trigger/backends/__init__.py b/jarvis/trigger/backends/__init__.pyindex b26bff98e5..016472248f 100644--- a/jarvis/trigger/backends/__init__.py+++ b/jarvis/trigger/backends/__init__.py@@ -72,6 +72,20 @@ class HotkeyBackend(Protocol):"""True once at least one bound chord has actually fired (AD-8)."""...+ def chord_is_down(self, combo: str) -> bool | None:+ """Is every key of the normalized ``combo`` down RIGHT NOW?++ Three answers, and the third is load-bearing: ``True`` / ``False`` when+ the backend can see the keyboard (Windows reads ``GetAsyncKeyState``;+ the event-tap and listener backends consult their held-set), ``None``+ when it cannot tell — not started, no package, an unnameable token. A+ consumer that gets ``None`` keeps working from the press/release edges+ alone; it must never treat ``None`` as "up". This is what lets a+ hold-to-record lane notice a key-up edge that was lost in transit+ (BUG-191) without inventing a release on a host that has no idea.+ """+ ...+def make_hotkey_backend() -> HotkeyBackend:"""Select the hotkey backend for this host (AD-8).diff --git a/jarvis/trigger/backends/global_hotkeys.py b/jarvis/trigger/backends/global_hotkeys.pyindex 8de143abbc..e802361158 100644--- a/jarvis/trigger/backends/global_hotkeys.py+++ b/jarvis/trigger/backends/global_hotkeys.py@@ -493,6 +493,87 @@ class GlobalHotkeysBackend:"""return self._gh is not None and self._started+ def chord_is_down(self, combo: str) -> bool | None:+ """Is every key of ``combo`` physically down RIGHT NOW? ``None`` = unknown.++ Ground truth, not bookkeeping: the same ``GetAsyncKeyState`` the poller+ itself reads, asked directly. It exists because the press/release EDGES+ can be lost between the poller thread and the consumer (a checker+ restart mid-hold re-creates the binding's press state, a callback that+ raises kills the thread, a registry re-arm starts from "not pressed"),+ and a hold-to-record lane that only ever hears edges keeps recording+ until its duration cap when the up edge goes missing (BUG-191). Asking+ the keyboard is the one answer that cannot go stale.++ ``combo`` is the normalized form the trigger registers (``control ++ window``). ``window`` means either Win key, like the poller. Off Windows,+ without the package, or for a token the library cannot name, the answer+ is ``None`` so the caller degrades to "edges only" rather than guessing.+ """+ if self._gh is None:+ return None+ tokens = [p.strip() for p in _to_library_combo(combo).split("+") if p.strip()]+ if not tokens:+ return None+ for token in tokens:+ if token == "window": # noqa: S105 — a key name, not a secret+ down = _async_key_is_down(_VK_LWIN) or _async_key_is_down(_VK_RWIN)+ if down is None:+ return None+ if not down:+ return False+ continue+ vk = _virtual_key_for(token)+ if vk is None:+ return None+ down = _async_key_is_down(vk)+ if down is None:+ return None+ if not down:+ return False+ return True+++# Virtual-key codes for the two Win keys (``VK_LWIN`` / ``VK_RWIN``), spelled+# out so the probe below needs no ``win32con`` import to name them.+_VK_LWIN = 0x5B+_VK_RWIN = 0x5C+++def _virtual_key_for(token: str) -> int | None:+ """The Windows virtual-key code for a library token, or ``None``.++ Delegates to the library's own table so the probe and the poller agree on+ every spelling; a numeric token (the mouse buttons arrive as ``0x04``) is+ parsed the same way the library parses it.+ """+ try:+ from global_hotkeys.hotkey_checker import _to_virtualkey # type: ignore[import-untyped]+ except Exception: # noqa: BLE001 — no package, no answer+ return None+ try:+ vk = _to_virtualkey(token)+ except Exception: # noqa: BLE001 — an unnameable token is "unknown", never a crash+ return None+ return int(vk) if vk is not None else None+++def _async_key_is_down(vk: int) -> bool | None:+ """``GetAsyncKeyState(vk) < 0`` — the key is down at this instant.++ ``None`` when the Win32 binding is not importable (any host that is not+ Windows), which the caller treats as "cannot tell".+ """+ try:+ import win32api # type: ignore[import-untyped] # lazy (HN-7)+ except Exception: # noqa: BLE001 — not Windows / pywin32 missing+ return None+ try:+ return int(win32api.GetAsyncKeyState(int(vk))) < 0+ except Exception: # noqa: BLE001 — a failed probe is "unknown", never a crash+ log.debug("GetAsyncKeyState(%r) failed", vk, exc_info=True)+ return None+__all__ = ["MOUSE_BUTTON_TOKENS",diff --git a/jarvis/trigger/backends/noop.py b/jarvis/trigger/backends/noop.pyindex a700615d30..d3007d0ed4 100644--- a/jarvis/trigger/backends/noop.py+++ b/jarvis/trigger/backends/noop.py@@ -128,5 +128,9 @@ class NoopBackend:def received_any_event(self) -> bool:return False+ def chord_is_down(self, combo: str) -> bool | None:+ """No listener, no keyboard state to report — honestly unknown."""+ return None+__all__ = ["NoopBackend", "_reset_noop_log_flag_for_tests", "explain_unavailable"]diff --git a/jarvis/trigger/backends/pynput.py b/jarvis/trigger/backends/pynput.pyindex e7ff5d915a..ca33eba2df 100644--- a/jarvis/trigger/backends/pynput.py+++ b/jarvis/trigger/backends/pynput.py@@ -201,6 +201,22 @@ class PynputBackend:combo["tokens"] & MOUSE_BUTTON_TOKENS for combo in combos)+ def chord_is_down(self, combo: str) -> bool | None:+ """Is every token of ``combo`` in the held-set right now? ``None`` = unknown.++ pynput has no "ask the keyboard" primitive, so this is the listener's+ own bookkeeping — the same edge-fed set the matcher reads. It is honest+ about that: while the listener is not running there is no set to+ consult and the answer is ``None``, so a consumer degrades to+ "edges only" instead of trusting a stale view.+ """+ if not self._started or self._listener is None:+ return None+ tokens = frozenset(_parse_combo_tokens(combo))+ if not tokens:+ return None+ return _combo_is_down(tokens, self._held)+def _token_for(self, key) -> str | None:"""Map a pynput key event to our canonical token, or ``None``."""# ``KeyCode`` for character keys exposes ``.char``; ``Key`` enum membersdiff --git a/jarvis/trigger/backends/quartz.py b/jarvis/trigger/backends/quartz.pyindex 8937bbf065..ce728b02ca 100644--- a/jarvis/trigger/backends/quartz.py+++ b/jarvis/trigger/backends/quartz.py@@ -186,6 +186,24 @@ class QuartzHotkeyBackend:combo["tokens"] & MOUSE_BUTTON_TOKENS for combo in combos)+ def chord_is_down(self, combo: str) -> bool | None:+ """Is every token of ``combo`` in the held-set right now? ``None`` = unknown.++ The tap re-syncs the modifier half of ``_held`` from every event's+ flags word (``_handle_flags``), so for a modifier chord this tracks the+ keyboard closely; plain keys are edge-fed like pynput. While the tap is+ not running there is nothing to consult, and the answer is ``None`` so a+ consumer degrades to "edges only" instead of trusting a stale view.+ """+ if not self._started or self._tap is None:+ return None+ tokens = frozenset(+ "ctrl" if t == "ctrl_r" else t for t in _parse_combo_tokens(combo)+ )+ if not tokens:+ return None+ return tokens.issubset(self._held)+def _permitted(self) -> bool:"""The grant verdict, re-probed at most every ``_PERMISSION_TTL_S``.diff --git a/jarvis/trigger/hotkey.py b/jarvis/trigger/hotkey.pyindex 4264bc2854..0c7343d3e8 100644--- a/jarvis/trigger/hotkey.py+++ b/jarvis/trigger/hotkey.py@@ -517,16 +517,58 @@ class HotkeyTrigger:def _make_handler(self, event_name: str):def _on_press() -> None:- if event_name in SELF_INPUT_SUPPRESSED_EVENTS and synthetic_input_recent():- log.debug(- "Hotkey %r ignored: Jarvis is synthesizing input right now.",- event_name,- )- return- if self._loop and not self._loop.is_closed():- self._loop.call_soon_threadsafe(self._push_nowait, event_name)+ # Runs on the BACKEND's thread — the Windows poller calls it with+ # no try/except around it (``HotkeyChecker.run``), so anything that+ # escapes here kills that thread and, with it, every global+ # shortcut in the process until a restart. Nothing may escape.+ try:+ if event_name in SELF_INPUT_SUPPRESSED_EVENTS and synthetic_input_recent():+ log.debug(+ "Hotkey %r ignored: Jarvis is synthesizing input right now.",+ event_name,+ )+ return+ loop = self._loop+ if loop is None or loop.is_closed():+ return+ loop.call_soon_threadsafe(self._push_nowait, event_name)+ except RuntimeError:+ # The loop closed between the check and the call — shutdown.+ log.debug("Hotkey %r dropped: the event loop is closing.", event_name)+ except Exception: # noqa: BLE001 — a dead poller is worse than any lost edge+ log.exception("Hotkey %r handler failed (edge dropped).", event_name)return _on_press+ def chord_is_down(self, event_name: str) -> bool | None:+ """Is the chord bound to ``event_name`` physically down right now?++ Asks the backend for every combo the binding carries (a binding may be+ armed under two spellings — the AltGr compatibility chord). Any combo+ down → ``True``; every combo answered "up" → ``False``; the backend+ cannot tell, is missing, or the binding is unknown → ``None``. The+ three-way answer is the whole contract: a consumer must never read+ ``None`` as "up" (see ``HotkeyBackend.chord_is_down``).+ """+ backend = self._backend+ probe = getattr(backend, "chord_is_down", None)+ if backend is None or not callable(probe):+ return None+ combos = self._bindings_cfg.get(event_name) or []+ if not combos:+ return None+ answered = False+ for combo in combos:+ try:+ answer = probe(_normalize_combo(combo))+ except Exception: # noqa: BLE001 — a failed probe is "unknown", never a crash+ log.debug("chord_is_down(%r) failed", combo, exc_info=True)+ return None+ if answer is True:+ return True+ if answer is False:+ answered = True+ return False if answered else None+def _push_nowait(self, event_name: str) -> None:try:self._queue.put_nowait(event_name)diff --git a/tests/contract/test_hotkey_backend_protocol.py b/tests/contract/test_hotkey_backend_protocol.pynew file mode 100644index 0000000000..b00b2811a1--- /dev/null+++ b/tests/contract/test_hotkey_backend_protocol.py@@ -0,0 +1,53 @@+"""Contract: every hotkey backend answers ``chord_is_down`` the same way.++The three-way answer is the whole contract (see ``HotkeyBackend.chord_is_down``):+``True`` / ``False`` when the backend can see the keyboard, ``None`` when it+cannot — and BEFORE it listens, every backend cannot. A consumer that reads+``None`` as "up" would invent a key release on a Wayland box or a not-yet+started listener, which is precisely the phantom this capability must never+produce (BUG-191). Constructing a backend touches no OS hook, so this runs on+every CI leg, headless included.+"""++from __future__ import annotations++import pytest++from jarvis.trigger.backends import HotkeyBackend+from tests.fakes.fake_hotkey_backend import FakeHotkeyBackend+++def _backend_factories():+ from jarvis.trigger.backends.global_hotkeys import GlobalHotkeysBackend+ from jarvis.trigger.backends.noop import NoopBackend+ from jarvis.trigger.backends.pynput import PynputBackend+ from jarvis.trigger.backends.quartz import QuartzHotkeyBackend++ return [+ pytest.param(GlobalHotkeysBackend, id="windows"),+ pytest.param(QuartzHotkeyBackend, id="macos"),+ pytest.param(PynputBackend, id="linux-x11"),+ pytest.param(NoopBackend, id="noop"),+ pytest.param(FakeHotkeyBackend, id="fake"),+ ]++[email protected]("factory", _backend_factories())+def test_every_backend_satisfies_the_protocol_including_the_key_state_probe(factory):+ backend = factory()+ assert isinstance(backend, HotkeyBackend)+ assert callable(getattr(backend, "chord_is_down", None))++[email protected]("factory", _backend_factories())+def test_a_backend_that_is_not_listening_answers_unknown_never_up(factory):+ """Not started → ``None``. ``False`` here would be a phantom release."""+ backend = factory()+ assert backend.chord_is_down("control + alt + j") is None+ assert backend.chord_is_down("control + window") is None++[email protected]("factory", _backend_factories())+def test_an_empty_combo_is_unknown_not_down(factory):+ backend = factory()+ assert backend.chord_is_down("") is Nonediff --git a/tests/fakes/fake_hotkey_backend.py b/tests/fakes/fake_hotkey_backend.pyindex 65f7dfbcf2..420be8055b 100644--- a/tests/fakes/fake_hotkey_backend.py+++ b/tests/fakes/fake_hotkey_backend.py@@ -33,6 +33,12 @@ class FakeHotkeyBackend:self.stop_calls = 0self._started = Falseself._got_event = False+ # Test knob for ``chord_is_down``: the physical key state per combo+ # (whitespace-stripped), or the module-wide answer when the combo is+ # not listed. ``None`` mirrors a backend that cannot see the keyboard.+ self.key_state: dict[str, bool | None] = {}+ self.key_state_default: bool | None = None+ self.key_state_queries: list[str] = []# ------------------------------------------------------------------# HotkeyBackend protocol surface@@ -60,6 +66,11 @@ class FakeHotkeyBackend:def received_any_event(self) -> bool:return self._got_event+ def chord_is_down(self, combo: str) -> bool | None:+ key = _norm(combo)+ self.key_state_queries.append(key)+ return self.key_state.get(key, self.key_state_default)+# ------------------------------------------------------------------# Test helpers (not part of the protocol)# ------------------------------------------------------------------diff --git a/tests/unit/trigger/test_hotkey_key_state.py b/tests/unit/trigger/test_hotkey_key_state.pynew file mode 100644index 0000000000..ec925aabf0--- /dev/null+++ b/tests/unit/trigger/test_hotkey_key_state.py@@ -0,0 +1,238 @@+"""``chord_is_down`` — the physical key-state probe behind the hold watchdog.++BUG-191: the press/release EDGES between the OS poller and the pipeline can be+lost, and a hold-to-record lane that only hears edges then records until its+cap. The probe asks the keyboard instead. Three answers: ``True`` / ``False``+when the backend can see the keyboard, ``None`` when it cannot — and ``None``+must never be read as "up", or the watchdog would invent a release.++Windows is exercised against a fake ``GetAsyncKeyState`` (the real one needs+pywin32 and a desktop); pynput and Quartz against their own held-set; the+trigger's aggregation against ``FakeHotkeyBackend``.+"""++from __future__ import annotations++import sys++import pytest++from tests.fakes.fake_global_hotkeys import FakeGlobalHotkeys+from tests.fakes.fake_hotkey_backend import FakeHotkeyBackend+++def fake_gh():+ """A fresh FakeGlobalHotkeys + a reset refcount, like the backend tests."""+ import jarvis.trigger.backends.global_hotkeys as ghb++ fake = FakeGlobalHotkeys()+ saved = sys.modules.get("global_hotkeys")+ sys.modules["global_hotkeys"] = fake+ ghb._reset_checker_state_for_tests()+ try:+ yield fake+ finally:+ ghb._reset_checker_state_for_tests()+ if saved is not None:+ sys.modules["global_hotkeys"] = saved+ else:+ sys.modules.pop("global_hotkeys", None)+++def key_state(monkeypatch):+ """Fake ``GetAsyncKeyState`` + a small VK table for the Windows backend."""+ import jarvis.trigger.backends.global_hotkeys as ghb++ down: set[int] = set()+ table = {"control": 0x11, "shift": 0x10, "alt": 0x12, "j": 0x4A, "f9": 0x78}+ monkeypatch.setattr(ghb, "_virtual_key_for", lambda token: table.get(token))+ monkeypatch.setattr(ghb, "_async_key_is_down", lambda vk: int(vk) in down)+ return down+++# ----------------------------------------------------------------------+# Windows+# ----------------------------------------------------------------------+++def test_windows_backend_reads_the_keyboard_not_its_edges(fake_gh, key_state):+ from jarvis.trigger.backends.global_hotkeys import GlobalHotkeysBackend++ backend = GlobalHotkeysBackend()+ backend.register([["control + window", lambda: None, lambda: None]])+ backend.start()++ assert backend.chord_is_down("control + window") is False+ key_state.update({0x11, 0x5B}) # Ctrl + LEFT Win+ assert backend.chord_is_down("control + window") is True+ key_state.discard(0x5B)+ assert backend.chord_is_down("control + window") is False+ key_state.add(0x5C) # Ctrl + RIGHT Win: "window" means either key+ assert backend.chord_is_down("control + window") is True+ key_state.discard(0x11)+ assert backend.chord_is_down("control + window") is False++ key_state.update({0x11, 0x12, 0x4A})+ assert backend.chord_is_down("control + alt + j") is True+ backend.stop()+ backend.unregister()+++def test_windows_backend_answers_unknown_for_a_token_it_cannot_name(fake_gh, key_state):+ from jarvis.trigger.backends.global_hotkeys import GlobalHotkeysBackend++ backend = GlobalHotkeysBackend()+ backend.register([["control + j", lambda: None, lambda: None]])+ backend.start()+ key_state.update({0x11})+ assert backend.chord_is_down("control + nosuchkey") is None+ assert backend.chord_is_down("") is None+++def test_windows_backend_answers_unknown_when_the_probe_itself_cannot(fake_gh, monkeypatch):+ """No pywin32 → the key probe is None → the answer is None, never False."""+ import jarvis.trigger.backends.global_hotkeys as ghb+ from jarvis.trigger.backends.global_hotkeys import GlobalHotkeysBackend++ monkeypatch.setattr(ghb, "_virtual_key_for", lambda token: 0x11)+ monkeypatch.setattr(ghb, "_async_key_is_down", lambda vk: None)+ backend = GlobalHotkeysBackend()+ backend.register([["control + j", lambda: None, lambda: None]])+ backend.start()+ assert backend.chord_is_down("control + j") is None+++def test_windows_backend_that_degraded_answers_unknown(key_state):+ """No package registered (``_gh`` is None) → nothing to read from."""+ from jarvis.trigger.backends.global_hotkeys import GlobalHotkeysBackend++ key_state.update({0x11, 0x4A})+ assert GlobalHotkeysBackend().chord_is_down("control + j") is None+++# ----------------------------------------------------------------------+# macOS / Linux-X11 / no-op+# ----------------------------------------------------------------------+++def test_pynput_backend_answers_from_its_held_set_only_while_listening():+ from jarvis.trigger.backends.pynput import PynputBackend++ backend = PynputBackend()+ backend.register([["control + alt + j", lambda: None, lambda: None]])+ backend._held.update({"ctrl", "alt", "j"})+ assert backend.chord_is_down("control + alt + j") is None, "not listening yet"++ backend._started = True+ backend._listener = object()+ assert backend.chord_is_down("control + alt + j") is True+ backend._held.discard("j")+ assert backend.chord_is_down("control + alt + j") is False+ # A right-hand modifier satisfies the generic token, as in the matcher.+ backend._held.add("j")+ backend._held.discard("alt")+ backend._held.add("alt_r")+ assert backend.chord_is_down("control + alt + j") is True+ assert backend.chord_is_down("") is None+++def test_quartz_backend_answers_from_its_held_set_only_while_tapping():+ from jarvis.trigger.backends.quartz import QuartzHotkeyBackend++ backend = QuartzHotkeyBackend()+ backend.register([["control + window", lambda: None, lambda: None]])+ backend._held.update({"ctrl", "cmd"})+ assert backend.chord_is_down("control + window") is None, "no tap yet"++ backend._started = True+ backend._tap = object()+ assert backend.chord_is_down("control + window") is True+ backend._held.discard("cmd")+ assert backend.chord_is_down("control + window") is False+ assert backend.chord_is_down("") is None+++def test_noop_backend_never_pretends_to_see_the_keyboard():+ from jarvis.trigger.backends.noop import NoopBackend++ backend = NoopBackend()+ backend.register([["control + j", lambda: None, lambda: None]])+ backend.start()+ assert backend.chord_is_down("control + j") is None+++# ----------------------------------------------------------------------+# The trigger asks its backend per armed combo+# ----------------------------------------------------------------------+++async def test_chord_is_down_aggregates_every_combo_of_a_binding(monkeypatch):+ """Any combo down → True; all answered up → False; nobody can tell → None.++ A binding may be armed under two spellings (the AltGr compatibility+ chord), and the physical answer is "is ANY of them down". ``None`` is+ reserved for "unknown" and survives aggregation: one combo answering+ ``False`` and the other ``None`` is still ``False`` (something WAS seen),+ but a binding where nothing was seen stays ``None``.+ """+ import jarvis.trigger.hotkey as hk++ fake = FakeHotkeyBackend()+ monkeypatch.setattr(hk, "make_hotkey_backend", lambda: fake)+ trig = hk.HotkeyTrigger({"dictate": ["ctrl+win", "f9"]}, push_to_talk={"dictate"})+ async with trig:+ assert trig.chord_is_down("dictate") is None, "a fake with no key state is unknown"+ fake.key_state_default = False+ assert trig.chord_is_down("dictate") is False+ assert sorted(set(fake.key_state_queries)) == ["control+window", "f9"]+ fake.key_state["f9"] = True+ assert trig.chord_is_down("dictate") is True+ fake.key_state = {"control+window": False}+ fake.key_state_default = None+ assert trig.chord_is_down("dictate") is False, "one seen answer is an answer"+ assert trig.chord_is_down("no_such_binding") is None+++def test_chord_is_down_without_a_backend_is_unknown():+ import jarvis.trigger.hotkey as hk++ trig = hk.HotkeyTrigger({"dictate": ["ctrl+win"]}, push_to_talk={"dictate"})+ assert trig.chord_is_down("dictate") is None # never entered: no backend+++async def test_a_backend_without_the_probe_is_unknown_not_up(monkeypatch):+ """An older / third-party backend that lacks ``chord_is_down`` degrades to+ edges-only; it must never read as a released key."""+ import jarvis.trigger.hotkey as hk++ class _Legacy(FakeHotkeyBackend):+ chord_is_down = None # type: ignore[assignment]++ fake = _Legacy()+ monkeypatch.setattr(hk, "make_hotkey_backend", lambda: fake)+ trig = hk.HotkeyTrigger({"dictate": ["ctrl+win"]}, push_to_talk={"dictate"})+ async with trig:+ assert trig.chord_is_down("dictate") is None+++def test_a_raising_backend_callback_never_kills_the_poller_thread():+ """The Windows poller calls handlers bare; an exception escaping ours+ would end the thread and every global shortcut with it (BUG-191)."""+ import jarvis.trigger.hotkey as hk++ trig = hk.HotkeyTrigger({"dictate": ["ctrl+win"]}, push_to_talk={"dictate"})++ class _ClosingLoop:+ def is_closed(self) -> bool:+ return False++ def call_soon_threadsafe(self, *_args) -> None:+ raise RuntimeError("Event loop is closed")++ trig._loop = _ClosingLoop() # type: ignore[assignment]+ handler = trig._make_handler("dictate_release")+ handler() # must not raise