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.

fix(macos): main-thread keyboard-layout snapshot closes the remaining pynput TSM hole (BUG-065)

Joana Lütkebe8e2e38c86a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7fd095a150..a2e7e0915f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,16 @@ versioning per [SemVer](https://semver.org/lang/de/).
### Fixed
+- **macOS 15 no longer kills the app when hotkeys arm or Computer-Use types
+ ("Personal Jarvis quit unexpectedly", SIGILL).** pynput resolved the
+ keyboard layout through HIToolbox TSM calls on background threads, which
+ modern macOS aborts with an uncatchable illegal-instruction trap. Two-layer
+ fix: global hotkeys now use a TSM-free Quartz event-tap backend, and a
+ main-thread keyboard-layout snapshot is captured at boot so any remaining
+ pynput keyboard path (e.g. `keyboard.Controller()` in Computer-Use
+ actuation) reuses it instead of touching TSM off-main — degrading to the
+ pyautogui fallback, never crashing (BUG-065).
+
- **macOS installer no longer dies with a bare exit code on uv-provisioned
Pythons.** The app bundle's native launcher is now an in-repo compiled C
stub linked against the exact Python runtime in use — replacing the py2app
diff --git a/docs/BUGS.md b/docs/BUGS.md
index 0a4615994a..451c4ede21 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -5483,6 +5483,27 @@ 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``.
+**Follow-up — the same TSM hole in ``keyboard.Controller`` (2026-07-17).**
+The Quartz backend removed pynput from the darwin *hotkey* path, but
+``pynput.keyboard.Controller()`` (Computer-Use keyboard actuation,
+``jarvis/cu/actuate/posix.py``) builds its keycode map through the identical
+``keycode_context()`` TIS calls on whatever thread constructs it — the
+backend thread — so the first CU type/press action could still SIGILL the
+app. Closed by ``jarvis/platform/macos_input_source.py``: the desktop boot
+chokepoint (``run_window_only``, provably main-thread) snapshots the tiny
+immutable ``(keyboard_type, layout_data)`` tuple via raw ctypes
+(microseconds, AP-26-clean), and ``ensure_pynput_layout_guard()`` patches
+pynput's ``keycode_context`` so off-main callers reuse that snapshot and
+never touch TIS; with no snapshot available the patched call raises an
+ordinary ``RuntimeError`` — the posix actuator's existing except-clause then
+drops to the pyautogui fallback instead of the OS killing the process. The
+``PynputBackend`` darwin branch (unreachable via the factory since the
+Quartz fix, but constructible directly) now also refuses to start its
+listener without a main-thread snapshot. Guards:
+``tests/unit/platform/test_macos_input_source.py`` (off-main never touches
+TIS, cache reuse, no-snapshot raise, main-thread pass-through) and the
+degrade tests 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
diff --git a/jarvis/cu/actuate/posix.py b/jarvis/cu/actuate/posix.py
index e49d834fef..0c1786c749 100644
--- a/jarvis/cu/actuate/posix.py
+++ b/jarvis/cu/actuate/posix.py
@@ -85,6 +85,18 @@ class PosixActuator(Actuator):
try:
from pynput import keyboard, mouse # noqa: PLC0415
+ if sys.platform == "darwin":
+ # BUG-065: ``keyboard.Controller()`` builds its keycode map
+ # via the TIS APIs, and on macOS 15 an off-main-thread TIS
+ # call kills the whole process (SIGILL). The guard makes the
+ # constructor reuse the main-thread layout snapshot — or
+ # raise an ordinary exception that drops us to the pyautogui
+ # fallback below instead of crashing the app.
+ from jarvis.platform.macos_input_source import ( # noqa: PLC0415
+ ensure_pynput_layout_guard,
+ )
+
+ ensure_pynput_layout_guard()
self._mouse = mouse.Controller()
self._keyboard = keyboard.Controller()
self._keys = _pynput_key_table(keyboard)
diff --git a/jarvis/platform/macos_input_source.py b/jarvis/platform/macos_input_source.py
new file mode 100644
index 0000000000..b3df0b13f2
--- /dev/null
+++ b/jarvis/platform/macos_input_source.py
@@ -0,0 +1,241 @@
+"""macOS keyboard-layout (TIS) main-thread guard (BUG-065).
+
+macOS 15 enforces that the Text Input Source Services APIs
+(``TISCopyCurrentKeyboardInputSource`` / ``TSMGetInputSourceProperty``,
+HIToolbox) run on the MAIN thread: called from any other thread they trip
+``dispatch_assert_queue`` and the OS kills the whole process with an
+uncatchable SIGILL ("Personal Jarvis quit unexpectedly"). ``pynput`` calls
+exactly these functions off-main — ``keyboard.Listener._run`` enters
+``keycode_context()`` on the listener thread, and ``keyboard.Controller()``
+builds its keycode map on whatever thread constructs it (the jarvis backend
+thread) — so arming global hotkeys or the CU keyboard tool crashed the app.
+
+The layout context pynput needs is a tiny immutable value:
+``(keyboard_type: int, layout_data: bytes)``. So:
+
+1. :func:`prime_keyboard_layout_cache` captures that tuple ONCE while
+ provably on the main thread — direct ctypes, microseconds, no pynput
+ import on the boot path (AP-26). Called from the desktop window
+ chokepoint (``run_window_only``, the one place every boot path runs on
+ the main thread) and opportunistically from any caller that happens to
+ be on the main thread (headless boots).
+2. :func:`install_pynput_layout_guard` patches pynput's ``keycode_context``
+ so off-main callers reuse the cached tuple and never touch TIS; on the
+ main thread the original still runs (and refreshes the cache). With no
+ cache available an off-main call raises an honest ``RuntimeError``
+ instead of letting the OS SIGILL the process — callers degrade (hotkeys
+ off / pyautogui fallback) per AD-6.
+
+Staleness (user switches keyboard layout after boot) is acceptable: pynput
+itself snapshots the layout once per listener run, so the pre-fix behavior
+was equally static; a restart refreshes the snapshot.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import logging
+import sys
+import threading
+
+log = logging.getLogger(__name__)
+
+_CACHE_LOCK = threading.Lock()
+# ``(keyboard_type, layout_data)`` exactly as pynput's ``keycode_context``
+# yields it; ``None`` until a main-thread capture succeeded.
+_LAYOUT_CACHE: tuple[int | None, bytes | None] | None = None
+_GUARD_INSTALLED = False
+
+
+def _on_main_thread() -> bool:
+ return threading.current_thread() is threading.main_thread()
+
+
+def _capture_layout_context() -> tuple[int | None, bytes | None]:
+ """Read ``(keyboard_type, layout_data)`` via raw ctypes.
+
+ MUST run on the main thread (the whole point of this module). Mirrors
+ pynput's ``keycode_context`` source preference: current keyboard input
+ source first, ASCII-capable layout as fallback.
+ """
+ import ctypes # noqa: PLC0415 - darwin-only, keep module import cheap
+ import ctypes.util # noqa: PLC0415
+
+ carbon_path = ctypes.util.find_library("Carbon")
+ cf_path = ctypes.util.find_library("CoreFoundation")
+ if not carbon_path or not cf_path:
+ raise OSError("Carbon / CoreFoundation framework not found")
+ carbon = ctypes.cdll.LoadLibrary(carbon_path)
+ cf = ctypes.cdll.LoadLibrary(cf_path)
+
+ carbon.TISCopyCurrentKeyboardInputSource.argtypes = []
+ carbon.TISCopyCurrentKeyboardInputSource.restype = ctypes.c_void_p
+ carbon.TISCopyCurrentASCIICapableKeyboardLayoutInputSource.argtypes = []
+ carbon.TISCopyCurrentASCIICapableKeyboardLayoutInputSource.restype = (
+ ctypes.c_void_p
+ )
+ carbon.TISGetInputSourceProperty.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
+ carbon.TISGetInputSourceProperty.restype = ctypes.c_void_p
+ carbon.LMGetKbdType.argtypes = []
+ carbon.LMGetKbdType.restype = ctypes.c_uint32
+ layout_data_key = ctypes.c_void_p.in_dll(
+ carbon, "kTISPropertyUnicodeKeyLayoutData"
+ )
+ cf.CFDataGetLength.argtypes = [ctypes.c_void_p]
+ cf.CFDataGetLength.restype = ctypes.c_long
+ cf.CFDataGetBytePtr.argtypes = [ctypes.c_void_p]
+ cf.CFDataGetBytePtr.restype = ctypes.c_void_p
+ cf.CFRelease.argtypes = [ctypes.c_void_p]
+
+ keyboard_type: int | None = None
+ layout_data: bytes | None = None
+ for source_fn in (
+ carbon.TISCopyCurrentKeyboardInputSource,
+ carbon.TISCopyCurrentASCIICapableKeyboardLayoutInputSource,
+ ):
+ source = source_fn()
+ if not source:
+ continue
+ try:
+ keyboard_type = int(carbon.LMGetKbdType())
+ # Get-rule reference owned by ``source`` — copy the bytes out
+ # BEFORE the CFRelease below.
+ data = carbon.TISGetInputSourceProperty(source, layout_data_key)
+ if data:
+ length = cf.CFDataGetLength(data)
+ ptr = cf.CFDataGetBytePtr(data)
+ if ptr and length > 0:
+ layout_data = ctypes.string_at(ptr, length)
+ finally:
+ cf.CFRelease(source)
+ if layout_data is not None:
+ break
+ return keyboard_type, layout_data
+
+
+def keyboard_layout_cache_ready() -> bool:
+ """True once a main-thread layout snapshot is cached (darwin only)."""
+ return _LAYOUT_CACHE is not None
+
+
+def _store_layout(context: tuple[int | None, bytes | None]) -> None:
+ global _LAYOUT_CACHE
+ # A context without layout bytes would NULL-deref inside UCKeyTranslate
+ # later — only a complete snapshot is worth caching.
+ if context[1] is None:
+ return
+ with _CACHE_LOCK:
+ _LAYOUT_CACHE = context
+
+
+def prime_keyboard_layout_cache() -> bool:
+ """Snapshot the keyboard layout if we are on the darwin main thread.
+
+ No-op ``True`` off darwin, no-op ``False`` off the main thread (the
+ capture itself would trip the very assertion this module exists to
+ avoid). Never raises.
+ """
+ if sys.platform != "darwin":
+ return True
+ if _LAYOUT_CACHE is not None:
+ return True
+ if not _on_main_thread():
+ return False
+ try:
+ context = _capture_layout_context()
+ except Exception: # noqa: BLE001 - a failed probe must never crash boot
+ log.warning(
+ "Could not snapshot the macOS keyboard layout on the main "
+ "thread — global hotkeys / keyboard actuation will be disabled "
+ "to avoid the TIS off-main-thread crash.",
+ exc_info=True,
+ )
+ return False
+ _store_layout(context)
+ if _LAYOUT_CACHE is None:
+ log.warning(
+ "macOS returned no keyboard layout data — global hotkeys / "
+ "keyboard actuation will be disabled for this session."
+ )
+ return False
+ return True
+
+
+def install_pynput_layout_guard() -> bool:
+ """Patch pynput's ``keycode_context`` with the main-thread guard.
+
+ Idempotent; returns ``True`` when the guard is (already) installed.
+ Off darwin this is a no-op ``True``. Never raises.
+ """
+ global _GUARD_INSTALLED
+ if sys.platform != "darwin":
+ return True
+ if _GUARD_INSTALLED:
+ return True
+ try:
+ from pynput._util import darwin as pynput_darwin # noqa: PLC0415
+ except Exception: # noqa: BLE001 - optional [desktop] extra absent
+ log.debug("pynput not importable — layout guard not installed.")
+ return False
+
+ original_keycode_context = pynput_darwin.keycode_context
+
+ @contextlib.contextmanager
+ def _guarded_keycode_context():
+ """Main thread: real TIS call (refreshes the cache). Off-main:
+ cached snapshot only — TIS off-main is an uncatchable SIGILL."""
+ if _on_main_thread():
+ with original_keycode_context() as context:
+ _store_layout(context)
+ yield context
+ return
+ cached = _LAYOUT_CACHE
+ if cached is None:
+ raise RuntimeError(
+ "macOS keyboard layout was not captured on the main thread; "
+ "refusing to call the TIS APIs off-main (the OS would kill "
+ "the process with SIGILL, BUG-065)."
+ )
+ yield cached
+
+ pynput_darwin.keycode_context = _guarded_keycode_context
+ # ``pynput.keyboard._darwin`` imports the symbol by name — rebind it
+ # there too if that module is (or becomes) loaded.
+ try:
+ from pynput.keyboard import _darwin as pynput_kbd_darwin # noqa: PLC0415
+
+ pynput_kbd_darwin.keycode_context = _guarded_keycode_context
+ except Exception: # noqa: BLE001 - keyboard submodule may be absent
+ log.debug(
+ "pynput.keyboard._darwin not importable — util-level guard only.",
+ exc_info=True,
+ )
+ _GUARD_INSTALLED = True
+ return True
+
+
+def ensure_pynput_layout_guard() -> bool:
+ """Prime (when possible) + install the guard; ``True`` when pynput's
+ keyboard paths are safe to use from any thread on this host."""
+ if sys.platform != "darwin":
+ return True
+ prime_keyboard_layout_cache()
+ if not install_pynput_layout_guard():
+ return False
+ return keyboard_layout_cache_ready()
+
+
+def _reset_for_tests() -> None:
+ """Drop the cache + installed flag — test-isolation hook only."""
+ global _LAYOUT_CACHE, _GUARD_INSTALLED
+ with _CACHE_LOCK:
+ _LAYOUT_CACHE = None
+ _GUARD_INSTALLED = False
+
+
+__all__ = [
+ "ensure_pynput_layout_guard",
+ "install_pynput_layout_guard",
+ "keyboard_layout_cache_ready",
+ "prime_keyboard_layout_cache",
+]
diff --git a/jarvis/trigger/backends/pynput.py b/jarvis/trigger/backends/pynput.py
index 24a0555ad6..6109a2d0bb 100644
--- a/jarvis/trigger/backends/pynput.py
+++ b/jarvis/trigger/backends/pynput.py
@@ -50,6 +50,21 @@ def _macos_hotkey_permissions_granted() -> bool:
return get_system_permission_port().runtime_feature_ready("global_hotkeys")
+
+def _macos_layout_guard_ready() -> bool:
+ """Prime + install the TIS main-thread layout guard (BUG-065).
+
+ macOS 15 kills the process with an uncatchable SIGILL when pynput's
+ listener thread calls the TIS keyboard-layout APIs off the main thread.
+ ``True`` only when a main-thread layout snapshot exists and pynput is
+ patched to use it, i.e. the listener is safe to start.
+ """
+ from jarvis.platform.macos_input_source import ( # noqa: PLC0415
+ ensure_pynput_layout_guard,
+ )
+
+ return ensure_pynput_layout_guard()
+
# global-hotkeys modifier token -> canonical pynput modifier name (the attribute
# on ``pynput.keyboard.Key``). Anything not here is a literal key (e.g. "j") or
# an F-key (e.g. "f1", which is also a ``Key`` attribute).
@@ -220,6 +235,28 @@ class PynputBackend:
return
self._permission_check = _macos_hotkey_permissions_granted
+ # BUG-065: pynput's listener thread calls the TIS keyboard-layout
+ # APIs (HIToolbox) as it starts; on macOS 15 an off-main-thread
+ # TIS call is an uncatchable process kill (SIGILL, "Personal
+ # Jarvis quit unexpectedly"). Only start the listener once a
+ # main-thread layout snapshot is cached and pynput is patched to
+ # reuse it; otherwise degrade — voice still works via wake word.
+ guard_ready = False
+ try:
+ guard_ready = _macos_layout_guard_ready()
+ except Exception: # noqa: BLE001 — the guard must never crash the trigger
+ guard_ready = False
+ if not guard_ready:
+ log.warning(
+ "Global hotkeys disabled on macOS: the keyboard-layout "
+ "snapshot could not be captured on the main thread, and "
+ "starting the listener without it would crash the app "
+ "(TIS main-thread assertion). Voice still works via the "
+ "wake word; restarting Jarvis re-attempts the snapshot.",
+ )
+ self._listener = None
+ return
+
try:
listener = keyboard.Listener(
on_press=self._on_press_key,
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.py
index 0d47f789bd..dbf122f302 100644
--- a/jarvis/ui/desktop_app.py
+++ b/jarvis/ui/desktop_app.py
@@ -3254,6 +3254,18 @@ class DesktopApp:
def run_window_only(self) -> int:
"""The main-thread pywebview window. Assumes the backend thread is
already running (started by :meth:`run` or the fast-boot launcher)."""
+ if sys.platform == "darwin":
+ # BUG-065: snapshot the keyboard layout HERE — the one chokepoint
+ # every desktop boot path runs on the main thread — so pynput
+ # (global hotkeys, CU keyboard actuation) never has to call the
+ # TIS APIs from a worker thread. On macOS 15 an off-main TIS call
+ # is an uncatchable process kill (SIGILL). Microseconds, ctypes
+ # only — no heavy import (AP-26).
+ from jarvis.platform.macos_input_source import (
+ prime_keyboard_layout_cache,
+ )
+
+ prime_keyboard_layout_cache()
# Hide an *accidental* console. When the app is launched by the
# console-subsystem ``python.exe`` (a scheduled task / shortcut / double
# click that resolved to python.exe instead of the windowless
diff --git a/tests/unit/platform/test_macos_input_source.py b/tests/unit/platform/test_macos_input_source.py
new file mode 100644
index 0000000000..c384883973
--- /dev/null
+++ b/tests/unit/platform/test_macos_input_source.py
@@ -0,0 +1,207 @@
+"""Tests for the macOS TIS main-thread layout guard (BUG-065).
+
+macOS 15 kills the process with an uncatchable SIGILL when the TIS
+keyboard-layout APIs run off the main thread — which is where pynput calls
+them (listener thread / backend-thread ``Controller()``). The guard caches a
+main-thread layout snapshot and patches pynput to reuse it off-main.
+
+All platform branches are exercised from any host: ``sys.platform`` is
+monkeypatched and the raw ctypes capture is replaced by a fake, so no test
+touches a real macOS framework.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import sys
+import threading
+import types
+
+import pytest
+
+from jarvis.platform import macos_input_source as mis
+
+FAKE_CONTEXT = (44, b"layout-bytes")
+
+
[email protected](autouse=True)
+def _clean_state():
+ mis._reset_for_tests()
+ yield
+ mis._reset_for_tests()
+
+
+def _force_darwin(monkeypatch):
+ monkeypatch.setattr("sys.platform", "darwin")
+
+
+def _install_fake_pynput_util(monkeypatch, tis_calls: list):
+ """A fake ``pynput._util.darwin`` whose ``keycode_context`` records that
+ the real (TIS-touching) implementation ran."""
+
+ @contextlib.contextmanager
+ def _original_keycode_context():
+ tis_calls.append("tis")
+ yield FAKE_CONTEXT
+
+ util_darwin = types.ModuleType("pynput._util.darwin")
+ util_darwin.keycode_context = _original_keycode_context
+ util_pkg = types.ModuleType("pynput._util")
+ util_pkg.darwin = util_darwin
+ kbd_darwin = types.ModuleType("pynput.keyboard._darwin")
+ kbd_darwin.keycode_context = _original_keycode_context
+ kbd_pkg = types.ModuleType("pynput.keyboard")
+ kbd_pkg._darwin = kbd_darwin
+ pynput_pkg = types.ModuleType("pynput")
+ pynput_pkg._util = util_pkg
+ pynput_pkg.keyboard = kbd_pkg
+ monkeypatch.setitem(sys.modules, "pynput", pynput_pkg)
+ monkeypatch.setitem(sys.modules, "pynput._util", util_pkg)
+ monkeypatch.setitem(sys.modules, "pynput._util.darwin", util_darwin)
+ monkeypatch.setitem(sys.modules, "pynput.keyboard", kbd_pkg)
+ monkeypatch.setitem(sys.modules, "pynput.keyboard._darwin", kbd_darwin)
+ return util_darwin, kbd_darwin
+
+
+# --- prime_keyboard_layout_cache -------------------------------------------
+
+
+def test_prime_is_noop_true_off_darwin(monkeypatch):
+ monkeypatch.setattr("sys.platform", "linux")
+ assert mis.prime_keyboard_layout_cache() is True
+ assert mis.keyboard_layout_cache_ready() is False
+
+
+def test_prime_refuses_off_main_thread(monkeypatch):
+ _force_darwin(monkeypatch)
+ monkeypatch.setattr(mis, "_on_main_thread", lambda: False)
+ monkeypatch.setattr(
+ mis,
+ "_capture_layout_context",
+ lambda: pytest.fail("TIS capture must never run off the main thread"),
+ )
+ assert mis.prime_keyboard_layout_cache() is False
+ assert mis.keyboard_layout_cache_ready() is False
+
+
+def test_prime_caches_on_main_thread(monkeypatch):
+ _force_darwin(monkeypatch)
+ monkeypatch.setattr(mis, "_capture_layout_context", lambda: FAKE_CONTEXT)
+ assert mis.prime_keyboard_layout_cache() is True
+ assert mis.keyboard_layout_cache_ready() is True
+ # Second call is a cache hit — no re-capture.
+ monkeypatch.setattr(
+ mis, "_capture_layout_context", lambda: pytest.fail("re-captured")
+ )
+ assert mis.prime_keyboard_layout_cache() is True
+
+
+def test_prime_survives_capture_failure(monkeypatch, caplog):
+ _force_darwin(monkeypatch)
+
+ def _boom():
+ raise OSError("no Carbon here")
+
+ monkeypatch.setattr(mis, "_capture_layout_context", _boom)
+ assert mis.prime_keyboard_layout_cache() is False
+ assert mis.keyboard_layout_cache_ready() is False
+
+
+def test_prime_rejects_snapshot_without_layout_bytes(monkeypatch):
+ # A (keyboard_type, None) context would NULL-deref in UCKeyTranslate
+ # later — it must not be cached.
+ _force_darwin(monkeypatch)
+ monkeypatch.setattr(mis, "_capture_layout_context", lambda: (44, None))
+ assert mis.prime_keyboard_layout_cache() is False
+ assert mis.keyboard_layout_cache_ready() is False
+
+
+# --- install_pynput_layout_guard -------------------------------------------
+
+
+def test_guard_noop_true_off_darwin(monkeypatch):
+ monkeypatch.setattr("sys.platform", "linux")
+ assert mis.install_pynput_layout_guard() is True
+
+
+def test_guard_false_when_pynput_missing(monkeypatch):
+ _force_darwin(monkeypatch)
+ for name in list(sys.modules):
+ if name == "pynput" or name.startswith("pynput."):
+ monkeypatch.delitem(sys.modules, name)
+ monkeypatch.setitem(sys.modules, "pynput", None) # force ImportError
+ assert mis.install_pynput_layout_guard() is False
+
+
+def test_guarded_context_off_main_uses_cache_never_tis(monkeypatch):
+ _force_darwin(monkeypatch)
+ tis_calls: list = []
+ util_darwin, kbd_darwin = _install_fake_pynput_util(monkeypatch, tis_calls)
+ monkeypatch.setattr(mis, "_capture_layout_context", lambda: FAKE_CONTEXT)
+ assert mis.ensure_pynput_layout_guard() is True
+ tis_calls.clear()
+
+ # Both import sites must be rebound to the guard.
+ assert util_darwin.keycode_context is kbd_darwin.keycode_context
+
+ result: dict = {}
+
+ def _off_main():
+ with util_darwin.keycode_context() as context:
+ result["context"] = context
+
+ worker = threading.Thread(target=_off_main)
+ worker.start()
+ worker.join()
+ assert result["context"] == FAKE_CONTEXT
+ assert tis_calls == [] # the real TIS path never ran off-main
+
+
+def test_guarded_context_off_main_without_cache_raises(monkeypatch):
+ _force_darwin(monkeypatch)
+ tis_calls: list = []
+ util_darwin, _ = _install_fake_pynput_util(monkeypatch, tis_calls)
+ assert mis.install_pynput_layout_guard() is True
+
+ raised: dict = {}
+
+ def _off_main():
+ try:
+ with util_darwin.keycode_context():
+ pass
+ except RuntimeError as exc:
+ raised["exc"] = exc
+
+ worker = threading.Thread(target=_off_main)
+ worker.start()
+ worker.join()
+ assert "main thread" in str(raised["exc"])
+ assert tis_calls == []
+
+
+def test_guarded_context_on_main_runs_original_and_refreshes_cache(monkeypatch):
+ _force_darwin(monkeypatch)
+ tis_calls: list = []
+ util_darwin, _ = _install_fake_pynput_util(monkeypatch, tis_calls)
+ assert mis.install_pynput_layout_guard() is True
+
+ with util_darwin.keycode_context() as context:
+ assert context == FAKE_CONTEXT
+ assert tis_calls == ["tis"]
+ # The main-thread pass-through primed the cache as a side effect.
+ assert mis.keyboard_layout_cache_ready() is True
+
+
+def test_ensure_reports_false_without_cache(monkeypatch):
+ # Off the main thread with no snapshot: the guard installs (so a later
+ # Controller() raises instead of SIGILLing) but ensure() reports unsafe.
+ _force_darwin(monkeypatch)
+ tis_calls: list = []
+ _install_fake_pynput_util(monkeypatch, tis_calls)
+ monkeypatch.setattr(mis, "_on_main_thread", lambda: False)
+ assert mis.ensure_pynput_layout_guard() is False
+
+
+def test_ensure_true_off_darwin(monkeypatch):
+ monkeypatch.setattr("sys.platform", "linux")
+ assert mis.ensure_pynput_layout_guard() is True