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
fix(macos): TSM-free Quartz hotkey backend — pynput SIGILLs the app on macOS 15
Joana Lütke93e4fe073b62
diff --git a/docs/BUGS.md b/docs/BUGS.mdindex 9b174c73ed..0a4615994a 100644--- a/docs/BUGS.md+++ b/docs/BUGS.md@@ -5445,3 +5445,48 @@ stubs against the RUNTIME the install actually uses, probed at build time.And an installer must never reduce a failed subprocess to its exit code:persist and print the captured stderr, or the next such bug is againundiagnosable in the field.++---++## BUG-065: pynput's darwin keyboard listener aborts the whole app with SIGILL on macOS 15 — hotkeys replaced with a TSM-free Quartz tap backend (HIGH, FIXED 2026-07-17)++**Symptom.** During the first real Intel-Mac onboarding (macOS 15.7), the+desktop app died twice within seconds of the hotkey trigger arming — a native+``EXC_BAD_INSTRUCTION`` / ``SIGILL`` crash, not a Python traceback. Crash+reports show ``dispatch_assert_queue_fail`` under+``TSMGetInputSourceProperty`` called via ctypes from a worker thread.++**Root cause.** pynput's darwin keyboard listener resolves the keyboard+layout through HIToolbox Text Services Manager calls+(``TISCopyCurrentKeyboardInputSource`` / ``TSMGetInputSourceProperty``)+inside its own listener thread (``pynput/_util/darwin.py::keycode_context``,+entered by ``keyboard/_darwin.py::Listener._run``). Modern macOS asserts+that TSM runs on the main dispatch queue and aborts the process —+uncatchable from Python. The BUG-058 permission preflight gated the tap+correctly, but once Accessibility + Input Monitoring were GRANTED the+listener started and the TSM assertion killed the app. The main thread+belongs to pywebview, so the listener can never be hosted there: pynput's+keyboard listener is structurally unusable in this process on macOS 15.++**Fix (2026-07-17).** New ``jarvis/trigger/backends/quartz.py``+(``QuartzHotkeyBackend``): a listen-only ``CGEventTap`` on a dedicated+CFRunLoop thread (taps are legal off the main thread), matching chords by+PHYSICAL key — a fixed ANSI virtual-keycode table plus the CGEventFlags+modifier word. No TIS/TSM call anywhere. Same combo vocabulary, edge+semantics, permission fail-closed gate, and ``received_any_event()`` as the+pynput backend; ``make_hotkey_backend`` selects it on darwin while Linux-X11+keeps ``PynputBackend`` and Windows stays byte-identical (AD-7). Documented+trade-offs: letters match ANSI key positions on exotic layouts;+``right_control`` folds into ``ctrl``.++Guards: ``tests/unit/trigger/test_quartz_backend.py`` (edge semantics,+fail-closed permission gate, degrade without Quartz, keycode-table coverage)+and the factory-selection test in ``test_hotkey_backends.py``.++**Class rule.** On macOS, ANY third-party library that touches AppKit,+HIToolbox, or TSM from a background thread is a process-abort risk that a+permission gate cannot catch — the assertion fires AFTER permissions are+granted. Before hosting such a library off the main thread, read its native+call path; if it needs main-queue services the process cannot provide, build+the narrow native path in-repo (Quartz-only, keycode-level) instead of+wrapping the crash in try/except that can never catch a SIGILL.diff --git a/docs/plans/cross-platform-mac-linux/FIX-TRACKER.md b/docs/plans/cross-platform-mac-linux/FIX-TRACKER.mdindex 361b59ed18..7ea83d68b5 100644--- a/docs/plans/cross-platform-mac-linux/FIX-TRACKER.md+++ b/docs/plans/cross-platform-mac-linux/FIX-TRACKER.md@@ -14,12 +14,13 @@ and `docs/BUGS.md` (BUG-056, BUG-057).| macOS audio ducking | Done 2026-07-17 | AppleScript (`osascript`) ducking of known players (Music, Spotify) with an opt-in master-volume fallback; every call wrapped, degrades per player (`jarvis/audio/ducking/macos.py`). || WebRTC VAD tier | Done 2026-07-17 | The middle fallback tier (Silero ONNX → WebRTC VAD → RMS energy) is actually wired in `jarvis/audio/vad.py` — previously aspirational (BUG-061 follow-up). || Native stub launcher | Done 2026-07-17 | In-repo compiled C stub (`jarvis/setup/macos_stub_launcher.c`) linked against the exact runtime dylib replaces py2app; launches on framework AND uv-standalone Pythons (BUG-076; numbered BUG-064 on the Mac line before the registers were merged). |+| TSM-free hotkey backend | Done 2026-07-17 | `QuartzHotkeyBackend` (listen-only `CGEventTap`, physical-keycode matching) replaces pynput on darwin — pynput's keyboard listener SIGILLs the whole app on macOS 15 (BUG-077; numbered BUG-065 on the Mac line). |## Open| Item | Notes ||---|---|-| BUG-058 on-device confirmation | The PortAudio single-flight + Quartz event-tap hardening is audit-based; a real-Mac first-boot run through onboarding is still pending. |+| BUG-058 on-device confirmation | Partially confirmed 2026-07-17 on a real Intel Mac (macOS 15.7): first boot survives PortAudio init and reaches a listening backend with no native abort. The pynput event-tap half was superseded by the BUG-065 Quartz backend; a full onboarding pass with all permissions granted is still pending. || Full-screen-Spaces overlay limitation | The subprocess bar/orb does not appear over full-screen Spaces; needs an NSWindow collection-behavior host to join Spaces. || Browser/VLC not ducked | The AppleScript ducking tier only covers players with a scriptable app volume (Music, Spotify); browsers and VLC fall through to the opt-in master-volume fallback. || Template-style tray icon | The menu-bar icon should ship a macOS template image so it adapts to dark/light menu bars instead of a fixed-color bitmap. |diff --git a/jarvis/trigger/backends/__init__.py b/jarvis/trigger/backends/__init__.pyindex c130f070f8..a826cd3b4c 100644--- a/jarvis/trigger/backends/__init__.py+++ b/jarvis/trigger/backends/__init__.py@@ -77,7 +77,8 @@ def make_hotkey_backend() -> HotkeyBackend:"""Select the hotkey backend for this host (AD-8).* ``win32`` → ``GlobalHotkeysBackend`` (relocated Windows logic, AD-7).- * else if ``capabilities.has_hotkey`` → ``PynputBackend`` (macOS / Linux-X11).+ * else if ``capabilities.has_hotkey`` → ``QuartzHotkeyBackend`` on macOS+ (TSM-free event tap, BUG-065) or ``PynputBackend`` on Linux-X11.* else → ``NoopBackend`` (Wayland or no ``pynput``; logged-once no-op, AD-8).Never raises and never returns ``GlobalHotkeysBackend`` off Windows — the@@ -96,6 +97,15 @@ def make_hotkey_backend() -> HotkeyBackend:caps = detect_capabilities()if caps.has_hotkey:+ if platform == "darwin":+ # pynput's darwin keyboard listener resolves the keyboard layout+ # via HIToolbox TSM calls from its listener thread; modern macOS+ # asserts those run on the main queue and aborts the process with+ # an uncatchable SIGILL (BUG-065). The Quartz tap backend matches+ # by physical keycode and never touches TSM.+ from jarvis.trigger.backends.quartz import QuartzHotkeyBackend++ return QuartzHotkeyBackend()from jarvis.trigger.backends.pynput import PynputBackendreturn PynputBackend()diff --git a/jarvis/trigger/backends/quartz.py b/jarvis/trigger/backends/quartz.pynew file mode 100644index 0000000000..369b98aecc--- /dev/null+++ b/jarvis/trigger/backends/quartz.py@@ -0,0 +1,314 @@+"""macOS hotkey backend via a Quartz ``CGEventTap`` (AD-8, BUG-065).++Why not pynput on macOS: pynput's darwin keyboard listener resolves the+keyboard layout through the HIToolbox Text Services Manager+(``TISCopyCurrentKeyboardInputSource`` / ``TSMGetInputSourceProperty``) from+its own listener thread. Modern macOS asserts that those calls run on the main+dispatch queue and kills the whole process with an uncatchable SIGILL+(``dispatch_assert_queue_fail``) — observed live on macOS 15.7 during the+first Intel-Mac onboarding. The main thread belongs to pywebview, so the only+safe path is to avoid the TSM APIs entirely.++This backend listens with a listen-only ``CGEventTap`` on a dedicated+CFRunLoop thread (event taps are legal off the main thread; the BUG-058 gate+already preflights the Accessibility + Input Monitoring grants that a tap+needs) and matches chords by PHYSICAL key: a fixed ANSI virtual-keycode table+plus the modifier flags word. No layout translation, no TSM, no main-queue+assertion.++Known trade-offs (documented, honest):++* Letter tokens match the ANSI/QWERTY key positions. On a non-ANSI layout the+ chord follows the physical key, not the printed label — the same behavior+ as most native hotkey utilities.+* ``right_control`` matches either Control key (the flags word does not carry+ a portable left/right distinction).++The combo vocabulary, edge semantics (press fires on the chord-down+transition, release only for push-to-talk rows), the permission fail-closed+gate, and ``received_any_event()`` mirror ``PynputBackend`` exactly, so the+``HotkeyTrigger`` call site stays platform-agnostic (AD-7).+"""++from __future__ import annotations++import logging+import threading++from jarvis.trigger.backends.pynput import (+ _macos_hotkey_permissions_granted,+ _parse_combo_tokens,+)++log = logging.getLogger(__name__)++# Fixed ANSI virtual keycodes (Carbon kVK_ANSI_* / kVK_* constants) -> the+# canonical lowercase tokens `_parse_combo_tokens` produces. Physical-position+# matching keeps this table layout-independent and TSM-free.+_KEYCODE_TO_TOKEN: dict[int, str] = {+ 0x00: "a", 0x0B: "b", 0x08: "c", 0x02: "d", 0x0E: "e", 0x03: "f",+ 0x05: "g", 0x04: "h", 0x22: "i", 0x26: "j", 0x28: "k", 0x25: "l",+ 0x2E: "m", 0x2D: "n", 0x1F: "o", 0x23: "p", 0x0C: "q", 0x0F: "r",+ 0x01: "s", 0x11: "t", 0x20: "u", 0x09: "v", 0x0D: "w", 0x07: "x",+ 0x10: "y", 0x06: "z",+ 0x1D: "0", 0x12: "1", 0x13: "2", 0x14: "3", 0x15: "4", 0x17: "5",+ 0x16: "6", 0x1A: "7", 0x1C: "8", 0x19: "9",+ 0x31: "space", 0x24: "enter", 0x35: "esc", 0x30: "tab",+ 0x33: "backspace", 0x75: "delete",+ 0x7A: "f1", 0x78: "f2", 0x63: "f3", 0x76: "f4", 0x60: "f5", 0x61: "f6",+ 0x62: "f7", 0x64: "f8", 0x65: "f9", 0x6D: "f10", 0x67: "f11", 0x6F: "f12",+ 0x7B: "left", 0x7C: "right", 0x7D: "down", 0x7E: "up",+}++# CGEventFlags modifier masks -> canonical modifier tokens. `ctrl_r` is folded+# into `ctrl` (the portable flags word carries no left/right distinction).+_FLAG_MASK_TO_TOKEN: tuple[tuple[int, str], ...] = (+ (1 << 17, "shift"), # kCGEventFlagMaskShift+ (1 << 18, "ctrl"), # kCGEventFlagMaskControl+ (1 << 19, "alt"), # kCGEventFlagMaskAlternate+ (1 << 20, "cmd"), # kCGEventFlagMaskCommand+)+++class QuartzHotkeyBackend:+ """Quartz event-tap hotkey backend for macOS (AD-8).++ Satisfies the ``HotkeyBackend`` ``Protocol``: receives the same normalized+ ``[combo_str, on_press, on_release]`` rows as every other backend.+ """++ def __init__(self) -> None:+ # Each entry: tokens (frozenset), on_press, on_release, down (bool).+ self._combos: list[dict] = []+ self._started = False+ self._got_event = False+ self._held: set[str] = set()+ self._permission_check = _macos_hotkey_permissions_granted+ self._tap: object | None = None+ self._runloop: object | None = None+ self._thread: threading.Thread | None = None++ # ------------------------------------------------------------------+ # Registration + chord matching (mirrors PynputBackend semantics)+ # ------------------------------------------------------------------++ def register(self, bindings, on_event=None) -> None:+ """Stash binding rows as token-set combos. Never raises (AD-6)."""+ combos: list[dict] = []+ for row in bindings:+ combo = row[0]+ on_press = row[1] if len(row) > 1 else None+ on_release = row[2] if len(row) > 2 else None+ tokens = {+ # This backend cannot tell right from left Control.+ "ctrl" if t == "ctrl_r" else t+ for t in _parse_combo_tokens(combo)+ }+ combos.append(+ {+ "tokens": frozenset(tokens),+ "on_press": on_press,+ "on_release": on_release,+ "down": False,+ }+ )+ self._combos = combos++ def _reconcile(self) -> None:+ """Fire press/release handlers on chord down/up transitions."""+ try:+ permitted = self._permission_check()+ except Exception: # noqa: BLE001 — the probe must never kill the tap+ permitted = False+ if permitted is not True:+ # A grant can be revoked while the tap thread is alive: clear every+ # partial chord and refuse the callback (same contract as pynput).+ self._held.clear()+ for combo in self._combos:+ combo["down"] = False+ return+ for combo in self._combos:+ is_down = combo["tokens"].issubset(self._held)+ if is_down and not combo["down"]:+ combo["down"] = True+ self._got_event = True+ handler = combo["on_press"] or combo["on_release"]+ if handler is not None:+ handler()+ elif not is_down and combo["down"]:+ combo["down"] = False+ self._got_event = True+ # Only a push-to-talk binding (both edges set) fires on release.+ if combo["on_press"] is not None and combo["on_release"] is not None:+ combo["on_release"]()++ def _handle_key_down(self, keycode: int) -> None:+ token = _KEYCODE_TO_TOKEN.get(keycode)+ if token is None:+ return+ self._held.add(token)+ self._reconcile()++ def _handle_key_up(self, keycode: int) -> None:+ token = _KEYCODE_TO_TOKEN.get(keycode)+ 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:+ if flags & mask:+ self._held.add(token)+ else:+ # Release edges must be observed before the token drops.+ if token in self._held:+ self._reconcile()+ self._held.discard(token)+ self._reconcile()++ # ------------------------------------------------------------------+ # Tap lifecycle+ # ------------------------------------------------------------------++ def start(self) -> None:+ """Create the listen-only event tap on its own CFRunLoop thread.++ Degrades to a logged no-op on any failure — missing pyobjc/Quartz,+ missing permissions, or a tap-creation refusal (AD-6).+ """+ if self._started:+ return++ granted = False+ try:+ granted = self._permission_check()+ except Exception: # noqa: BLE001 — the probe must never crash the trigger+ granted = False+ if granted is not True:+ log.warning(+ "Global hotkeys disabled on macOS: the Accessibility "+ "and Input Monitoring permissions are not both granted. "+ "Use Personal Jarvis > Settings > Permissions, then "+ "re-arm the shortcut or restart Jarvis — voice still "+ "works via the wake word.",+ )+ return++ try:+ import Quartz # type: ignore[import-untyped] # lazy (HN-7)+ except Exception as exc: # noqa: BLE001 — optional [desktop-macos] extra+ log.warning(+ "pyobjc Quartz unavailable (%s) — hotkeys disabled; voice "+ "still works via wake word. Install the [full] profile to "+ "enable global hotkeys.",+ exc,+ )+ return++ def _callback(_proxy, event_type, event, _refcon):+ try:+ if event_type == Quartz.kCGEventKeyDown:+ keycode = Quartz.CGEventGetIntegerValueField(+ event, Quartz.kCGKeyboardEventKeycode+ )+ self._handle_key_down(int(keycode))+ elif event_type == Quartz.kCGEventKeyUp:+ keycode = Quartz.CGEventGetIntegerValueField(+ event, Quartz.kCGKeyboardEventKeycode+ )+ self._handle_key_up(int(keycode))+ elif event_type == Quartz.kCGEventFlagsChanged:+ self._handle_flags(int(Quartz.CGEventGetFlags(event)))+ elif event_type in (+ Quartz.kCGEventTapDisabledByTimeout,+ Quartz.kCGEventTapDisabledByUserInput,+ ):+ tap = self._tap+ if tap is not None:+ Quartz.CGEventTapEnable(tap, True)+ except Exception: # noqa: BLE001 — a callback error must not kill the tap+ log.debug("Quartz hotkey callback error (non-fatal)", exc_info=True)+ return event++ try:+ mask = (+ Quartz.CGEventMaskBit(Quartz.kCGEventKeyDown)+ | Quartz.CGEventMaskBit(Quartz.kCGEventKeyUp)+ | Quartz.CGEventMaskBit(Quartz.kCGEventFlagsChanged)+ )+ tap = Quartz.CGEventTapCreate(+ Quartz.kCGSessionEventTap,+ Quartz.kCGHeadInsertEventTap,+ Quartz.kCGEventTapOptionListenOnly,+ mask,+ _callback,+ None,+ )+ if tap is None:+ raise RuntimeError(+ "CGEventTapCreate returned None (permission or session "+ "restriction)"+ )+ source = Quartz.CFMachPortCreateRunLoopSource(None, tap, 0)+ except Exception: # noqa: BLE001 — degrade, never crash the pipeline+ log.error(+ "Quartz event tap could not be created — hotkeys disabled for "+ "this session; voice still works via wake word.",+ exc_info=True,+ )+ self._tap = None+ return++ self._tap = tap+ ready = threading.Event()++ def _run() -> None:+ loop = Quartz.CFRunLoopGetCurrent()+ self._runloop = loop+ Quartz.CFRunLoopAddSource(loop, source, Quartz.kCFRunLoopCommonModes)+ Quartz.CGEventTapEnable(tap, True)+ ready.set()+ Quartz.CFRunLoopRun()++ thread = threading.Thread(+ target=_run, name="jarvis-hotkey-tap", daemon=True+ )+ thread.start()+ ready.wait(timeout=5.0)+ self._thread = thread+ self._started = True++ def stop(self) -> None:+ """Stop the run loop and drop the tap. Idempotent, never raises."""+ runloop = self._runloop+ if runloop is not None:+ try:+ import Quartz # type: ignore[import-untyped]++ Quartz.CFRunLoopStop(runloop)+ except Exception: # noqa: BLE001 — teardown must never propagate+ log.debug("CFRunLoopStop failed (non-fatal)", exc_info=True)+ thread = self._thread+ if thread is not None:+ thread.join(timeout=2.0)+ self._runloop = None+ self._thread = None+ self._tap = None+ self._held.clear()+ for combo in self._combos:+ combo["down"] = False+ self._started = False++ def unregister(self) -> None:+ """Drop the armed bindings. The tap is torn down in ``stop``."""+ self._combos = []++ def received_any_event(self) -> bool:+ """True once any bound chord has fired (AD-8 macOS permission hint)."""+ return self._got_event+++__all__ = ["QuartzHotkeyBackend"]diff --git a/tests/unit/trigger/test_hotkey_backends.py b/tests/unit/trigger/test_hotkey_backends.pyindex 5b63bcf8e0..a22c37d1c0 100644--- a/tests/unit/trigger/test_hotkey_backends.py+++ b/tests/unit/trigger/test_hotkey_backends.py@@ -71,13 +71,16 @@ def test_factory_selects_global_hotkeys_on_windows(patch_platform):assert isinstance(backend, GlobalHotkeysBackend)-def test_factory_selects_pynput_on_macos_with_hotkey(patch_platform):+def test_factory_selects_quartz_on_macos_with_hotkey(patch_platform):+ """macOS gets the TSM-free Quartz tap backend, never pynput (BUG-065)."""from jarvis.trigger.backends import make_hotkey_backendfrom jarvis.trigger.backends.pynput import PynputBackend+ from jarvis.trigger.backends.quartz import QuartzHotkeyBackendpatch_platform("darwin", has_hotkey=True)backend = make_hotkey_backend()- assert isinstance(backend, PynputBackend)+ assert isinstance(backend, QuartzHotkeyBackend)+ assert not isinstance(backend, PynputBackend)def test_factory_selects_pynput_on_linux_x11(patch_platform):@@ -455,11 +458,52 @@ def test_pynput_backend_darwin_with_grant_starts_listener(monkeypatch):_install_fake_pynput(monkeypatch, built)monkeypatch.setattr("sys.platform", "darwin")monkeypatch.setattr(pynput_backend, "_macos_hotkey_permissions_granted", lambda: True)+ monkeypatch.setattr(pynput_backend, "_macos_layout_guard_ready", lambda: True)backend = PynputBackend()backend.start()assert len(built) == 1 # grant present -> hotkeys arm normally+def test_pynput_backend_darwin_without_layout_snapshot_degrades(monkeypatch, caplog):+ # BUG-065: macOS 15 kills the process (uncatchable SIGILL) when pynput's+ # listener thread calls the TIS keyboard-layout APIs off the main thread.+ # With no main-thread layout snapshot the backend must degrade — no+ # Listener at all — instead of letting the OS abort the app.+ import jarvis.trigger.backends.pynput as pynput_backend+ from jarvis.trigger.backends.pynput import PynputBackend++ built: list = []+ _install_fake_pynput(monkeypatch, built)+ monkeypatch.setattr("sys.platform", "darwin")+ monkeypatch.setattr(pynput_backend, "_macos_hotkey_permissions_granted", lambda: True)+ monkeypatch.setattr(pynput_backend, "_macos_layout_guard_ready", lambda: False)+ backend = PynputBackend()+ with caplog.at_level(logging.WARNING):+ backend.start()+ assert built == []+ assert "keyboard-layout" in caplog.text+++def test_pynput_backend_darwin_layout_guard_crash_degrades(monkeypatch, caplog):+ # A raising guard must never propagate out of start() (AD-6).+ import jarvis.trigger.backends.pynput as pynput_backend+ from jarvis.trigger.backends.pynput import PynputBackend++ built: list = []+ _install_fake_pynput(monkeypatch, built)+ monkeypatch.setattr("sys.platform", "darwin")+ monkeypatch.setattr(pynput_backend, "_macos_hotkey_permissions_granted", lambda: True)++ def _boom() -> bool:+ raise RuntimeError("guard exploded")++ monkeypatch.setattr(pynput_backend, "_macos_layout_guard_ready", _boom)+ backend = PynputBackend()+ with caplog.at_level(logging.WARNING):+ backend.start()+ assert built == []++def test_pynput_backend_off_darwin_needs_no_probe(monkeypatch):# AD-7: the preflight is darwin-only; Linux/Windows never consult it.import jarvis.trigger.backends.pynput as pynput_backend@@ -491,6 +535,7 @@ def test_pynput_backend_revoked_permission_suppresses_live_callback(monkeypatch)"_macos_hotkey_permissions_granted",lambda: allowed["value"],)+ monkeypatch.setattr(pynput_backend, "_macos_layout_guard_ready", lambda: True)fired: list[str] = []backend = PynputBackend()backend.register([["control + j", lambda: fired.append("call"), None]])diff --git a/tests/unit/trigger/test_quartz_backend.py b/tests/unit/trigger/test_quartz_backend.pynew file mode 100644index 0000000000..55e0ae0b6f--- /dev/null+++ b/tests/unit/trigger/test_quartz_backend.py@@ -0,0 +1,135 @@+"""QuartzHotkeyBackend contract: TSM-free chord matching + fail-closed gates.++BUG-065: pynput's darwin keyboard listener dies with an uncatchable SIGILL on+modern macOS (HIToolbox TSM calls off the main queue). The Quartz backend+matches physical keycodes + modifier flags and must never import pynput's+listener machinery. These tests drive the chord matcher directly and pin the+degrade paths; the live tap is exercised on macOS hardware/CI only.+"""++from __future__ import annotations++from jarvis.trigger.backends.quartz import (+ _FLAG_MASK_TO_TOKEN,+ _KEYCODE_TO_TOKEN,+ QuartzHotkeyBackend,+)++_KC_J = 0x26+_KC_SPACE = 0x31+_FLAG_CTRL = 1 << 18+_FLAG_ALT = 1 << 19+++def _backend_with_permission(granted: bool = True) -> QuartzHotkeyBackend:+ backend = QuartzHotkeyBackend()+ backend._permission_check = lambda: granted+ return backend+++def test_chord_fires_on_down_edge_only_once() -> None:+ fired: list[str] = []+ backend = _backend_with_permission()+ backend.register([["control + alt + j", lambda: fired.append("press"), None]])++ backend._handle_flags(_FLAG_CTRL | _FLAG_ALT)+ assert fired == []+ backend._handle_key_down(_KC_J)+ assert fired == ["press"]+ # Holding the chord does not re-fire.+ backend._handle_key_down(_KC_J)+ assert fired == ["press"]+ assert backend.received_any_event() is True+++def test_push_to_talk_fires_both_edges() -> None:+ events: list[str] = []+ backend = _backend_with_permission()+ backend.register(+ [["control + space", lambda: events.append("down"), lambda: events.append("up")]]+ )++ backend._handle_flags(_FLAG_CTRL)+ backend._handle_key_down(_KC_SPACE)+ assert events == ["down"]+ backend._handle_key_up(_KC_SPACE)+ assert events == ["down", "up"]+++def test_modifier_release_breaks_the_chord() -> None:+ events: list[str] = []+ backend = _backend_with_permission()+ backend.register(+ [["control + j", lambda: events.append("down"), lambda: events.append("up")]]+ )++ backend._handle_flags(_FLAG_CTRL)+ backend._handle_key_down(_KC_J)+ backend._handle_flags(0) # ctrl released while j still held+ assert events == ["down", "up"]+++def test_right_control_folds_to_ctrl() -> None:+ fired: list[str] = []+ backend = _backend_with_permission()+ backend.register([["right_control + j", lambda: fired.append("press"), None]])++ backend._handle_flags(_FLAG_CTRL)+ backend._handle_key_down(_KC_J)+ assert fired == ["press"]+++def test_permission_revocation_clears_chords_and_blocks_handlers() -> None:+ fired: list[str] = []+ backend = _backend_with_permission()+ backend.register([["control + j", lambda: fired.append("press"), None]])++ backend._permission_check = lambda: False+ backend._handle_flags(_FLAG_CTRL)+ backend._handle_key_down(_KC_J)+ assert fired == []+ assert backend._held == set()+++def test_start_without_permission_is_a_noop(caplog) -> None:+ backend = _backend_with_permission(granted=False)+ backend.start()+ assert backend._started is False+ assert backend._tap is None+ assert any("hotkeys disabled" in r.message.lower() for r in caplog.records)+++def test_start_without_quartz_degrades(monkeypatch, caplog) -> None:+ import sys++ backend = _backend_with_permission(granted=True)+ monkeypatch.setitem(sys.modules, "Quartz", None) # import -> ImportError+ backend.start()+ assert backend._started is False+ assert backend._tap is None+++def test_unknown_keycode_is_ignored() -> None:+ backend = _backend_with_permission()+ backend.register([["control + j", lambda: None, None]])+ backend._handle_key_down(0xFF) # not in the table+ assert backend._held == set()+++def test_keycode_table_covers_the_combo_vocabulary() -> None:+ """Every letter, digit, and F-key token has a physical-key mapping."""+ tokens = set(_KEYCODE_TO_TOKEN.values())+ for ch in "abcdefghijklmnopqrstuvwxyz0123456789":+ assert ch in tokens+ for n in range(1, 13):+ assert f"f{n}" in tokens+ assert {"space", "enter", "esc", "tab"} <= tokens+ # Modifier flags cover the four canonical modifier tokens.+ assert {t for _, t in _FLAG_MASK_TO_TOKEN} == {"shift", "ctrl", "alt", "cmd"}+++def test_stop_is_idempotent_without_start() -> None:+ backend = _backend_with_permission()+ backend.stop()+ backend.stop()+ assert backend._started is False