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(audio,trigger): serialize PortAudio re-init + preflight macOS event tap (BUG-058)

Ruben Lütkebafc00f67448
diff --git a/docs/BUGS.md b/docs/BUGS.md
index f93ce6b34a..ae3fcf6554 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -4183,3 +4183,59 @@ quit unexpectedly" dialog looks identical for every native abort — fixing
one crash site just reveals the next one down the boot path. Audit the
WHOLE boot path for off-main-thread UI creation at once (as done here),
never one dialog at a time.
+
+## BUG-058: Third macOS first-boot abort at onboarding start — unserialized PortAudio re-init + ungated Quartz event tap (HIGH, HARDENED 2026-07-14, on-device confirmation pending)
+
+**Symptom.** With BUG-056+057 shipped, a fresh Mac boot now shows the
+desktop window and enters first-launch onboarding — then "Python quit
+unexpectedly" again, seconds in, before any meaningful interaction. No
+terminal log captured yet, so this entry hardens the audited candidates
+rather than a log-confirmed line.
+
+**Audit (full onboarding-window trace).** The onboarding routes themselves
+are pure state-file writes — zero native code. In the same time window two
+UNGATED native touches fire with NO user interaction:
+
+1. **Concurrent PortAudio teardown/re-init.** The boot prefetch
+ (``start_audio_device_prefetch``, daemon thread) and the voice pipeline's
+ Phase-A ``_stabilize_audio_devices`` both run the settle loop; when the
+ pipeline arrives while the prefetch is still polling (it runs up to
+ ~8 s), two threads interleave ``sd._terminate()``/``sd._initialize()``.
+ Windows WASAPI tolerates that; macOS CoreAudio's HAL can fault natively
+ on concurrent teardown/re-init. Timing matches the crash exactly.
+2. **pynput Quartz event tap without the Accessibility grant.** The hotkey
+ trigger arms unconditionally at ``pipeline.run()``; pynput's darwin
+ backend creates a CGEventTap on its own internal thread — Python-level
+ try/except around ``Listener.start()`` cannot catch a native abort
+ there, and on a fresh Mac the grant never exists.
+
+Known but interaction-gated (NOT hardened here, documented for the next
+log): the wake-word step's mic test / wake save opens a CoreAudio INPUT
+stream (``sd.InputStream``) — on a TCC-killed process that is a SIGABRT.
+Ruled out by audit: notifications, AppKit dialogs, prompting permission
+probes, Keychain, the LaunchAgent write (plist + subprocess only), and all
+BUG-056/057 gates (verified in place).
+
+**Hardening (2026-07-14).**
+
+- ``device_init._REINIT_LOCK`` serializes every terminate→initialize→query
+ sequence (hard safety, all platforms), and
+ ``wait_for_stable_audio_devices`` now JOINS an in-flight prefetch
+ (single-flight) instead of racing it with a second poll loop.
+- ``PynputBackend.start()`` preflights the non-prompting
+ ``AXIsProcessTrusted`` probe on darwin and fails CLOSED (None =
+ unverifiable → treated as not granted) with an honest English message
+ naming the System Settings path; hotkeys re-arm normally once granted.
+ Off-darwin behavior is byte-identical (guard test).
+
+Guards: ``tests/unit/audio/test_device_init_single_flight.py``,
+``tests/unit/trigger/test_hotkey_backends.py`` (4 new darwin-preflight
+tests).
+
+**Class rule.** Native init that "has always been fine" on Windows is not
+cross-platform evidence: CoreAudio punishes concurrent re-init, Quartz
+punishes ungranted event taps — both below Python. Any native engine
+init/teardown must be serialized behind a lock, and any macOS
+permission-gated native surface (mic, event tap, screen) must preflight a
+non-prompting probe and degrade honestly instead of letting the OS kill
+the process.
diff --git a/jarvis/audio/device_init.py b/jarvis/audio/device_init.py
index ecdcce129b..a7ccf5d2a0 100644
--- a/jarvis/audio/device_init.py
+++ b/jarvis/audio/device_init.py
@@ -48,20 +48,28 @@ def _get_sd() -> Any | None:
return sd
+# Serializes every PortAudio teardown/re-init sequence. Two threads
+# interleaving _terminate/_initialize (boot prefetch vs. the pipeline's
+# Phase-A stabilize) is a native fault on macOS CoreAudio's HAL — the
+# process dies below Python ("Python quit unexpectedly", BUG-058).
+_REINIT_LOCK = threading.Lock()
+
+
def _refresh_device_count(sd: Any) -> int:
"""Force PortAudio to re-enumerate and return the count of real I/O
devices. Re-init is the only way to escape a frozen partial table inside
a single process; a bare ``query_devices`` returns the cached list."""
# _terminate before the first _initialize is harmless; both can fail
# benignly on odd PortAudio states — re-enumeration is best-effort.
- with contextlib.suppress(Exception):
- sd._terminate()
- with contextlib.suppress(Exception):
- sd._initialize()
- try:
- devices = sd.query_devices()
- except Exception: # noqa: BLE001 — PortAudio can throw mid-scan
- return 0
+ with _REINIT_LOCK:
+ with contextlib.suppress(Exception):
+ sd._terminate()
+ with contextlib.suppress(Exception):
+ sd._initialize()
+ try:
+ devices = sd.query_devices()
+ except Exception: # noqa: BLE001 — PortAudio can throw mid-scan
+ return 0
return sum(
1
for d in devices
@@ -92,6 +100,33 @@ def wait_for_stable_audio_devices(
Diagnostics dict: ``available`` (sounddevice present), ``device_count``,
``stable`` (settled vs. timed out), ``polls``, ``reinits``, ``waited_s``.
"""
+ # Single-flight (BUG-058): if the boot prefetch is still polling, JOIN it
+ # instead of racing it with a second concurrent poll loop — concurrent
+ # PortAudio re-init is a native CoreAudio fault on macOS. On a join
+ # timeout we fall through to our own poll; _REINIT_LOCK still serializes
+ # the dangerous sequence itself.
+ if _PREFETCH_STARTED and not _PREFETCH_EVENT.is_set():
+ joined = _PREFETCH_EVENT.wait(timeout=max_wait_s)
+ if joined and _PREFETCH_RESULT is not None:
+ return _PREFETCH_RESULT
+ return _poll_until_stable(
+ max_wait_s=max_wait_s,
+ stable_window_s=stable_window_s,
+ poll_interval_s=poll_interval_s,
+ monotonic=monotonic,
+ sleep=sleep,
+ )
+
+
+def _poll_until_stable(
+ *,
+ max_wait_s: float = 8.0,
+ stable_window_s: float = 1.5,
+ poll_interval_s: float = 0.5,
+ monotonic: Callable[[], float] = time.monotonic,
+ sleep: Callable[[float], None] = time.sleep,
+) -> dict[str, Any]:
+ """The actual settle loop — see :func:`wait_for_stable_audio_devices`."""
sd = _get_sd()
if sd is None:
return {
@@ -138,23 +173,28 @@ def wait_for_stable_audio_devices(
# settled and the warm-up reuses the result instead of paying the wait again.
_PREFETCH_EVENT = threading.Event()
_PREFETCH_RESULT: dict[str, Any] | None = None
+_PREFETCH_STARTED = False
def start_audio_device_prefetch() -> threading.Thread | None:
- """Run :func:`wait_for_stable_audio_devices` eagerly in a daemon thread.
+ """Run the settle loop eagerly in a daemon thread.
Returns ``None`` when sounddevice is unavailable (headless VPS / no
``[desktop]`` extra) — nothing to settle. Never raises; audio robustness
must not break boot. The result is published for
- :func:`get_prefetched_audio_result`.
+ :func:`get_prefetched_audio_result`, and while it is in flight every
+ :func:`wait_for_stable_audio_devices` caller joins it (BUG-058).
"""
+ global _PREFETCH_STARTED
if _get_sd() is None:
return None
+ _PREFETCH_STARTED = True
def _run() -> None:
global _PREFETCH_RESULT
try:
- _PREFETCH_RESULT = wait_for_stable_audio_devices()
+ # The impl directly — the public function would join ourselves.
+ _PREFETCH_RESULT = _poll_until_stable()
except Exception: # noqa: BLE001 — never break boot
_PREFETCH_RESULT = None
finally:
diff --git a/jarvis/trigger/backends/pynput.py b/jarvis/trigger/backends/pynput.py
index 1c9d4bfa95..21b9306f76 100644
--- a/jarvis/trigger/backends/pynput.py
+++ b/jarvis/trigger/backends/pynput.py
@@ -36,6 +36,7 @@ kill-switch) from spawning two OS listeners on the same process.
from __future__ import annotations
import logging
+import sys
import threading
log = logging.getLogger(__name__)
@@ -178,6 +179,32 @@ class PynputBackend:
self._listener = None
return
+ if sys.platform == "darwin":
+ # pynput's darwin backend creates a Quartz event tap on its own
+ # internal thread; without the Accessibility grant that native
+ # init is useless at best and a process-level abort at worst
+ # (uncatchable, BUG-058 class). Preflight the non-prompting
+ # AXIsProcessTrusted probe and fail CLOSED (None = unverifiable
+ # -> treat as not granted) instead of touching pynput.
+ granted: bool | None = None
+ try:
+ from jarvis.platform.probes import ax_permission_granted
+
+ granted = ax_permission_granted()
+ except Exception: # noqa: BLE001 — the probe must never crash the trigger
+ granted = None
+ if granted is not True:
+ log.warning(
+ "Global hotkeys disabled on macOS: the Accessibility "
+ "permission is %s. Grant it under System Settings > "
+ "Privacy & Security > Accessibility for the app you "
+ "launch Jarvis from, then restart Jarvis — voice still "
+ "works via the wake word.",
+ "not granted" if granted is False else "not verifiable",
+ )
+ self._listener = None
+ return
+
try:
listener = keyboard.Listener(
on_press=self._on_press_key,
diff --git a/tests/unit/audio/test_device_init.py b/tests/unit/audio/test_device_init.py
index 45167ae76f..39872419ae 100644
--- a/tests/unit/audio/test_device_init.py
+++ b/tests/unit/audio/test_device_init.py
@@ -161,6 +161,7 @@ def test_respects_max_wait_when_never_stable(monkeypatch) -> None:
def _reset_prefetch() -> None:
di._PREFETCH_EVENT.clear()
di._PREFETCH_RESULT = None
+ di._PREFETCH_STARTED = False
def test_prefetch_result_none_before_any_prefetch() -> None:
@@ -186,7 +187,9 @@ def test_prefetch_publishes_settled_result(monkeypatch) -> None:
_reset_prefetch()
sentinel = {"available": True, "device_count": 7, "stable": True}
monkeypatch.setattr(di, "_get_sd", lambda: object()) # sounddevice "present"
- monkeypatch.setattr(di, "wait_for_stable_audio_devices", lambda: sentinel)
+ # The prefetch thread calls the impl directly (the public function would
+ # join the prefetch's own in-flight event — BUG-058 single-flight).
+ monkeypatch.setattr(di, "_poll_until_stable", lambda: sentinel)
thread = di.start_audio_device_prefetch()
assert thread is not None
@@ -203,7 +206,7 @@ def test_prefetch_swallows_settle_failure(monkeypatch) -> None:
raise RuntimeError("portaudio exploded mid-scan")
monkeypatch.setattr(di, "_get_sd", lambda: object())
- monkeypatch.setattr(di, "wait_for_stable_audio_devices", _boom)
+ monkeypatch.setattr(di, "_poll_until_stable", _boom)
thread = di.start_audio_device_prefetch()
assert thread is not None
diff --git a/tests/unit/audio/test_device_init_single_flight.py b/tests/unit/audio/test_device_init_single_flight.py
new file mode 100644
index 0000000000..6268dc320c
--- /dev/null
+++ b/tests/unit/audio/test_device_init_single_flight.py
@@ -0,0 +1,106 @@
+"""PortAudio re-init must be serialized and single-flight (BUG-058).
+
+The boot prefetch (``start_audio_device_prefetch``) and the pipeline's
+Phase-A ``_stabilize_audio_devices`` both call
+``wait_for_stable_audio_devices``; when the pipeline arrives while the
+prefetch is still polling, two threads used to interleave
+``sd._terminate()`` / ``sd._initialize()``. Windows WASAPI tolerates that;
+macOS CoreAudio's HAL answers concurrent teardown/re-init with a NATIVE
+fault ("Python quit unexpectedly") — it fires seconds after the window
+appears, right as first-launch onboarding starts. Two defenses:
+
+1. ``_refresh_device_count`` holds a module lock around the whole
+ terminate → initialize → query sequence (hard safety).
+2. ``wait_for_stable_audio_devices`` JOINS an in-flight prefetch instead
+ of starting a second concurrent poll loop (no duplicate re-init work).
+"""
+from __future__ import annotations
+
+import threading
+
+from jarvis.audio import device_init
+
+
+class _ReentrancySD:
+ """Fake sounddevice that records overlapping re-init sequences."""
+
+ def __init__(self) -> None:
+ self._lock = threading.Lock()
+ self._inside = 0
+ self.max_concurrency = 0
+
+ def _enter(self) -> None:
+ with self._lock:
+ self._inside += 1
+ self.max_concurrency = max(self.max_concurrency, self._inside)
+
+ def _exit(self) -> None:
+ with self._lock:
+ self._inside -= 1
+
+ def _terminate(self) -> None:
+ self._enter()
+
+ def _initialize(self) -> None:
+ pass
+
+ def query_devices(self):
+ try:
+ return [{"max_input_channels": 1, "max_output_channels": 0}]
+ finally:
+ self._exit()
+
+
+def test_refresh_device_count_serializes_reinit_across_threads() -> None:
+ sd = _ReentrancySD()
+ errors: list[BaseException] = []
+
+ def _hammer() -> None:
+ try:
+ for _ in range(50):
+ device_init._refresh_device_count(sd)
+ except BaseException as exc: # noqa: BLE001
+ errors.append(exc)
+
+ threads = [threading.Thread(target=_hammer) for _ in range(4)]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join(timeout=10)
+ assert errors == []
+ assert sd.max_concurrency == 1 # never two re-init sequences interleaved
+
+
+def test_wait_joins_inflight_prefetch_instead_of_polling(monkeypatch) -> None:
+ event = threading.Event()
+ monkeypatch.setattr(device_init, "_PREFETCH_EVENT", event)
+ monkeypatch.setattr(device_init, "_PREFETCH_STARTED", True)
+ polls: list[str] = []
+ monkeypatch.setattr(
+ device_init,
+ "_poll_until_stable",
+ lambda **_kw: polls.append("poll") or {"available": True},
+ )
+ sentinel = {"available": True, "device_count": 7, "stable": True}
+
+ def _finish_prefetch() -> None:
+ device_init._PREFETCH_RESULT = sentinel
+ event.set()
+
+ monkeypatch.setattr(device_init, "_PREFETCH_RESULT", None)
+ t = threading.Timer(0.05, _finish_prefetch)
+ t.start()
+ try:
+ result = device_init.wait_for_stable_audio_devices(max_wait_s=5.0)
+ finally:
+ t.cancel()
+ assert result is sentinel # joined the prefetch...
+ assert polls == [] # ...and never started a second concurrent poll loop
+
+
+def test_wait_polls_itself_when_no_prefetch_running(monkeypatch) -> None:
+ monkeypatch.setattr(device_init, "_PREFETCH_EVENT", threading.Event())
+ monkeypatch.setattr(device_init, "_PREFETCH_STARTED", False)
+ sentinel = {"available": True, "device_count": 3, "stable": True}
+ monkeypatch.setattr(device_init, "_poll_until_stable", lambda **_kw: sentinel)
+ assert device_init.wait_for_stable_audio_devices() is sentinel
diff --git a/tests/unit/trigger/test_hotkey_backends.py b/tests/unit/trigger/test_hotkey_backends.py
index ece70d4e71..69b341c8ed 100644
--- a/tests/unit/trigger/test_hotkey_backends.py
+++ b/tests/unit/trigger/test_hotkey_backends.py
@@ -386,3 +386,89 @@ def test_pynput_backend_real_listener_lifecycle():
backend.start()
backend.stop()
assert backend._listener is None
+
+
+# ----------------------------------------------------------------------
+# macOS Accessibility preflight (BUG-058) — pure logic, runs on every leg.
+# ----------------------------------------------------------------------
+
+
+def _install_fake_pynput(monkeypatch, built: list) -> None:
+ import types
+
+ class _FakeListener:
+ def __init__(self, **kwargs) -> None:
+ built.append(kwargs)
+
+ def start(self) -> None: ...
+
+ def stop(self) -> None: ...
+
+ fake_pynput = types.ModuleType("pynput")
+ fake_pynput.keyboard = types.SimpleNamespace(Listener=_FakeListener)
+ monkeypatch.setitem(sys.modules, "pynput", fake_pynput)
+
+
+def test_pynput_backend_darwin_without_ax_grant_degrades(monkeypatch, caplog):
+ # pynput's darwin backend creates a Quartz event tap on its own internal
+ # thread; without the Accessibility grant that native init can abort the
+ # whole process (uncatchable — BUG-058 class). The backend must preflight
+ # AXIsProcessTrusted and degrade instead of touching pynput at all.
+ import jarvis.platform.probes as probes
+ from jarvis.trigger.backends.pynput import PynputBackend
+
+ built: list = []
+ _install_fake_pynput(monkeypatch, built)
+ monkeypatch.setattr("sys.platform", "darwin")
+ monkeypatch.setattr(probes, "ax_permission_granted", lambda: False)
+ backend = PynputBackend()
+ with caplog.at_level(logging.WARNING):
+ backend.start()
+ assert built == [] # no Listener constructed under the missing grant
+ assert "accessibility" in caplog.text.lower()
+
+
+def test_pynput_backend_darwin_unverifiable_grant_degrades(monkeypatch, caplog):
+ # pyobjc absent -> probe returns None -> fail closed on darwin.
+ import jarvis.platform.probes as probes
+ from jarvis.trigger.backends.pynput import PynputBackend
+
+ built: list = []
+ _install_fake_pynput(monkeypatch, built)
+ monkeypatch.setattr("sys.platform", "darwin")
+ monkeypatch.setattr(probes, "ax_permission_granted", lambda: None)
+ backend = PynputBackend()
+ with caplog.at_level(logging.WARNING):
+ backend.start()
+ assert built == []
+
+
+def test_pynput_backend_darwin_with_grant_starts_listener(monkeypatch):
+ import jarvis.platform.probes as probes
+ from jarvis.trigger.backends.pynput import PynputBackend
+
+ built: list = []
+ _install_fake_pynput(monkeypatch, built)
+ monkeypatch.setattr("sys.platform", "darwin")
+ monkeypatch.setattr(probes, "ax_permission_granted", lambda: True)
+ backend = PynputBackend()
+ backend.start()
+ assert len(built) == 1 # grant present -> hotkeys arm normally
+
+
+def test_pynput_backend_off_darwin_needs_no_probe(monkeypatch):
+ # AD-7: the preflight is darwin-only; Linux/Windows never consult it.
+ import jarvis.platform.probes as probes
+ from jarvis.trigger.backends.pynput import PynputBackend
+
+ built: list = []
+ _install_fake_pynput(monkeypatch, built)
+ monkeypatch.setattr("sys.platform", "linux")
+
+ def _boom() -> None:
+ raise AssertionError("probe consulted off darwin")
+
+ monkeypatch.setattr(probes, "ax_permission_granted", _boom)
+ backend = PynputBackend()
+ backend.start()
+ assert len(built) == 1