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(desktop): keep blocking pywebview calls off the asyncio loop

rubenluetke10-beep4f49081dade4
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.py
index 90d745a8af..4928c7b43e 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -273,10 +273,20 @@ class _LoopLagProbe:
_INTERVAL_S = 0.25
_WINDOW_S = 30.0
+ # A scheduling gap this long on the loop that pumps realtime audio means a
+ # blocking call ran ON the loop (live 2026-08-06 17:40: a pywebview
+ # ``evaluate_js`` probe held it ~15 s twice and the WebRTC mic sender fell
+ # 40 s behind wall clock — the provider then reset the call). The probe is
+ # the one task positioned to name that class of culprit while it is
+ # happening, so it warns — bounded by a cooldown so a stall storm cannot
+ # flood the log.
+ _LOOP_STALL_WARN_MS = 500.0
+ _WARN_COOLDOWN_S = 30.0
def __init__(self) -> None:
self._samples: deque[tuple[float, float]] = deque()
self._task: asyncio.Task[None] | None = None
+ self._last_warn_at = float("-inf")
def start(self) -> None:
if self._task is None or self._task.done():
@@ -296,10 +306,25 @@ class _LoopLagProbe:
await asyncio.sleep(self._INTERVAL_S)
now = time.monotonic()
lag_ms = max(0.0, (now - before - self._INTERVAL_S) * 1_000.0)
- self._samples.append((now, lag_ms))
- cutoff = now - self._WINDOW_S
- while self._samples and self._samples[0][0] < cutoff:
- self._samples.popleft()
+ self._note_sample(now, lag_ms)
+
+ def _note_sample(self, now: float, lag_ms: float) -> None:
+ """Record one lag sample; warn on a stall-grade gap (rate-limited)."""
+ self._samples.append((now, lag_ms))
+ cutoff = now - self._WINDOW_S
+ while self._samples and self._samples[0][0] < cutoff:
+ self._samples.popleft()
+ if (
+ lag_ms >= self._LOOP_STALL_WARN_MS
+ and now - self._last_warn_at >= self._WARN_COOLDOWN_S
+ ):
+ self._last_warn_at = now
+ log.warning(
+ "realtime event loop stalled %.0f ms during a live voice "
+ "session — a blocking call ran on the loop; microphone "
+ "pacing, barge-in and the provider socket all waited it out",
+ lag_ms,
+ )
def max_lag_ms(self, window_s: float) -> float:
"""Worst scheduling lag observed within the last ``window_s``."""
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.py
index 401d37b275..10687f7736 100644
--- a/jarvis/ui/desktop_app.py
+++ b/jarvis/ui/desktop_app.py
@@ -1890,7 +1890,8 @@ class DesktopApp:
# Overlay right-click (bar OR mascot) → raise the main desktop window.
# OrbBusBridge publishes ShowWindowRequested from the Tk thread; the
- # handler runs on the asyncio loop and pywebview.show() is thread-safe.
+ # handler runs on the asyncio loop and immediately thread-hops, because
+ # pywebview calls block their calling thread (see _on_show_window_requested).
server.bus.subscribe(ShowWindowRequested, self._on_show_window_requested)
self._install_focus_route(server)
@@ -3791,26 +3792,37 @@ class DesktopApp:
if desktop is None or desktop._window is None:
return {"ok": False, "reason": "no_window"}
try:
- # pywebview window methods are thread-safe — they dispatch
- # internally to the GUI thread.
- desktop._window.show()
- desktop._window.restore()
- desktop._window_visible = True
- focused = _bring_window_to_front_by_title(WINDOW_TITLE)
- # Restore the persistent bar if a prior minimise cleared it.
- desktop._restore_overlay_for_visible_window()
- if focused:
- return {"ok": True, "focused": True}
- return {
- "ok": False,
- "focused": False,
- "reason": "foreground_lock",
- }
+ # Off the event loop: pywebview window methods are thread-safe
+ # (they dispatch internally to the GUI thread) but they BLOCK
+ # the calling thread while the GUI thread services them — the
+ # same class of on-loop stall that starved the realtime mic
+ # sender on 2026-08-06. The route thread-hops instead.
+ return await asyncio.to_thread(desktop._focus_window_now)
except Exception as exc: # noqa: BLE001
# Not swallowed: the reason travels back to the caller in the
# response body and surfaces in the focus API result.
return {"ok": False, "reason": f"{type(exc).__name__}: {exc}"}
+ def _focus_window_now(self) -> dict[str, Any]:
+ """Show + raise the desktop window, synchronously, on the CALLING thread.
+
+ Blocking by design — callers on the asyncio loop must thread-hop
+ (``asyncio.to_thread``); the tray bridge and worker threads may call it
+ directly. Split out of the ``/api/window/focus`` route so tests can pin
+ the off-loop contract without a running server.
+ """
+ if self._window is None:
+ return {"ok": False, "reason": "no_window"}
+ self._window.show()
+ self._window.restore()
+ self._window_visible = True
+ focused = _bring_window_to_front_by_title(WINDOW_TITLE)
+ # Restore the persistent bar if a prior minimise cleared it.
+ self._restore_overlay_for_visible_window()
+ if focused:
+ return {"ok": True, "focused": True}
+ return {"ok": False, "focused": False, "reason": "foreground_lock"}
+
# ---- WebView hooks -------------------------------------------------------
def _inject_token(self, window: Any) -> None:
@@ -4336,11 +4348,19 @@ class DesktopApp:
Coroutine because ``EventBus._safe_dispatch`` does ``await handler(event)``
— a plain ``def`` would still run but trip ``await None`` → a swallowed
- TypeError on every click. Raises the main desktop window;
- ``_safe_window_show`` is null-safe, so on a headless / VPS runtime (no
- window) this is a no-op.
+ TypeError on every click. Raises the main desktop window.
+
+ The whole show path runs in a worker thread: pywebview window calls
+ BLOCK the calling thread while the GUI thread services them, and
+ ``_reload_window_if_stale``'s ``evaluate_js`` probe waits up to ~20 s
+ (pywebview ``event.wait(20)``). Run on the asyncio loop, that probe
+ starved the realtime WebRTC mic sender 40 s behind wall clock and the
+ provider reset the call (live 2026-08-06 17:40). The tray bridge
+ already runs this same function on a plain thread, so off-loop is its
+ proven habitat. ``_safe_window_show`` is null-safe, so on a headless /
+ VPS runtime (no window) this is a no-op.
"""
- self._safe_window_show()
+ await asyncio.to_thread(self._safe_window_show)
def _safe_window_show(self) -> None:
if self._window is None:
diff --git a/tests/unit/realtime/test_audio_stall_attribution.py b/tests/unit/realtime/test_audio_stall_attribution.py
index 0a30f7d066..1c35f5681a 100644
--- a/tests/unit/realtime/test_audio_stall_attribution.py
+++ b/tests/unit/realtime/test_audio_stall_attribution.py
@@ -104,3 +104,39 @@ async def test_loop_lag_probe_stays_quiet_on_a_healthy_loop() -> None:
assert probe.max_lag_ms(window_s=5.0) < 200.0
finally:
probe.stop()
+
+
+def _stall_warns(caplog) -> list[str]:
+ return [
+ record.getMessage()
+ for record in caplog.records
+ if record.levelno >= logging.WARNING
+ and "event loop stalled" in record.getMessage()
+ ]
+
+
+def test_loop_stall_warns_loudly_and_rate_limited(caplog) -> None:
+ """A stall-grade gap names the on-loop-blocker class WHILE it happens.
+
+ Live 2026-08-06 17:40: an on-loop pywebview ``evaluate_js`` held the loop
+ ~15 s twice, the WebRTC mic sender fell 40 s behind wall clock and the
+ provider reset the call — the only trace was indirect. The probe now says
+ it outright, bounded by a cooldown so a stall storm cannot flood the log.
+ """
+ probe = _LoopLagProbe()
+ with caplog.at_level(logging.WARNING, logger="jarvis.realtime.session"):
+ probe._note_sample(now=100.0, lag_ms=15_000.0) # noqa: SLF001
+ probe._note_sample(now=101.0, lag_ms=900.0) # noqa: SLF001 — cooldown
+ probe._note_sample(now=131.0, lag_ms=800.0) # noqa: SLF001 — past it
+
+ warns = _stall_warns(caplog)
+ assert len(warns) == 2, "one warn per cooldown window, storms stay bounded"
+ assert "15000 ms" in warns[0]
+
+
+def test_loop_stall_warn_ignores_ordinary_scheduling_jitter(caplog) -> None:
+ probe = _LoopLagProbe()
+ with caplog.at_level(logging.WARNING, logger="jarvis.realtime.session"):
+ probe._note_sample(now=100.0, lag_ms=350.0) # noqa: SLF001
+
+ assert _stall_warns(caplog) == []
diff --git a/tests/unit/ui/test_desktop_show_window.py b/tests/unit/ui/test_desktop_show_window.py
index 93890a4240..2ef16388f1 100644
--- a/tests/unit/ui/test_desktop_show_window.py
+++ b/tests/unit/ui/test_desktop_show_window.py
@@ -9,10 +9,20 @@ The handler MUST be a coroutine: ``EventBus._safe_dispatch`` does
``await None`` raises a ``TypeError`` that the bus swallows as a WARNING — so
every right-click would spam a traceback. These tests round-trip through the
real bus so that mismatch cannot slip through (a direct call would not).
+
+The show path must also leave the EVENT LOOP alone: pywebview window calls
+block their calling thread (``evaluate_js`` waits up to ~20 s), and run on the
+asyncio loop that starved the realtime WebRTC mic sender 40 s behind wall
+clock until the provider reset the call (live 2026-08-06 17:40). The off-loop
+tests below pin the thread-hop for both entry points — the bus subscriber and
+the ``/api/window/focus`` body ``_focus_window_now``.
"""
from __future__ import annotations
import inspect
+import threading
+
+import pytest
from jarvis.core.bus import EventBus
from jarvis.core.events import ShowWindowRequested
@@ -48,3 +58,81 @@ async def test_show_window_handler_runs_through_real_bus() -> None:
await bus.publish(ShowWindowRequested(source="overlay_rightclick"))
assert calls == [True]
+
+
+async def test_show_window_handler_hops_off_the_event_loop() -> None:
+ """The subscriber must run the (blocking) show path in a worker thread.
+
+ ``_reload_window_if_stale`` inside ``_safe_window_show`` probes the WebView
+ with ``evaluate_js``, which pywebview bounds at ~20 s — executed on the
+ asyncio loop it stalls every socket, watchdog and the realtime audio pumps
+ at once (the 2026-08-06 session-death signature).
+ """
+ app = DesktopApp.__new__(DesktopApp)
+ loop_thread = threading.current_thread()
+ show_threads: list[threading.Thread] = []
+ app._safe_window_show = lambda: show_threads.append( # type: ignore[method-assign] # noqa: SLF001
+ threading.current_thread()
+ )
+
+ await app._on_show_window_requested( # noqa: SLF001
+ ShowWindowRequested(source="overlay_rightclick")
+ )
+
+ assert show_threads, "the show path never ran"
+ assert show_threads[0] is not loop_thread, (
+ "_safe_window_show ran on the event loop — a stale-frame probe there "
+ "blocks audio, barge-in and the provider socket for up to 20 s"
+ )
+
+
+class _RecordingWindow:
+ """Minimal pywebview stand-in recording which thread serviced each call."""
+
+ def __init__(self) -> None:
+ self.calls: list[tuple[str, threading.Thread]] = []
+
+ def show(self) -> None:
+ self.calls.append(("show", threading.current_thread()))
+
+ def restore(self) -> None:
+ self.calls.append(("restore", threading.current_thread()))
+
+
+async def test_focus_window_now_completes_the_visibility_dance(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """``_focus_window_now`` is the synchronous ``/api/window/focus`` body: it
+ shows + restores + raises the window and restores the overlay, and reports
+ the foreground verdict honestly. The route wraps it in ``asyncio.to_thread``
+ — pinned here by running it exactly as the route does and asserting the
+ window calls landed off the loop thread."""
+ app = DesktopApp.__new__(DesktopApp)
+ window = _RecordingWindow()
+ app._window = window # noqa: SLF001
+ overlay_restored: list[bool] = []
+ app._restore_overlay_for_visible_window = ( # type: ignore[method-assign] # noqa: SLF001
+ lambda: overlay_restored.append(True)
+ )
+ monkeypatch.setattr(
+ "jarvis.ui.desktop_app._bring_window_to_front_by_title",
+ lambda _title: True,
+ )
+
+ import asyncio
+
+ loop_thread = threading.current_thread()
+ result = await asyncio.to_thread(app._focus_window_now) # noqa: SLF001
+
+ assert result == {"ok": True, "focused": True}
+ assert app._window_visible is True # noqa: SLF001
+ assert overlay_restored == [True]
+ assert [name for name, _ in window.calls] == ["show", "restore"]
+ assert all(thread is not loop_thread for _, thread in window.calls)
+
+
+def test_focus_window_now_without_window_reports_no_window() -> None:
+ app = DesktopApp.__new__(DesktopApp)
+ app._window = None # noqa: SLF001
+
+ assert app._focus_window_now() == {"ok": False, "reason": "no_window"} # noqa: SLF001