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): recover a main window whose page hung instead of waiting forever

rubenluetke10-beepa26379c86670
diff --git a/jarvis/ui/window_watchdog.py b/jarvis/ui/window_watchdog.py
index a55defef18..8bef1c9468 100644
--- a/jarvis/ui/window_watchdog.py
+++ b/jarvis/ui/window_watchdog.py
@@ -73,6 +73,20 @@ RELOAD_BUDGET = 3
#: so this bounds the silence the user sees, not the recovery.
SILENT_PATIENCE_S = 45.0
+#: How long a window that already showed our page may leave the state probe
+#: unanswered, while the server is healthy, before it counts as hung. A busy
+#: but usable page misses a probe now and then; nine in a row (at ``POLL_S``)
+#: is a page whose main thread no longer runs anything. Live 2026-10-02: the
+#: main window's renderer sat at 100 % of a core for seven minutes and this
+#: guard waited the whole time, until the user closed the app.
+HUNG_PATIENCE_S = 45.0
+
+#: A renderer at or above this share of one core is spinning, not idling.
+HUNG_RENDERER_CPU_PERCENT = 80.0
+
+#: How long each renderer's CPU use is sampled before it is judged.
+HUNG_RENDERER_SAMPLE_S = 1.0
+
#: What the window is showing.
#:
#: ``up`` — our document is loaded (``#root`` exists). From here the page's
@@ -140,6 +154,10 @@ class Verdict:
action: Action
reason: BlankReason | None = None
after_up: bool = False
+ #: The page is not blank but hung: its renderer must be ended before the
+ #: reload, because a same-origin navigation is committed to that same busy
+ #: process and never arrives (reproduced with a ``while(true)`` page).
+ hung: bool = False
class BlankWindowPolicy:
@@ -157,14 +175,17 @@ class BlankWindowPolicy:
settle_s: float = RELOAD_SETTLE_S,
reload_budget: int = RELOAD_BUDGET,
silent_patience_s: float = SILENT_PATIENCE_S,
+ hung_patience_s: float = HUNG_PATIENCE_S,
) -> None:
self._grace_s = grace_s
self._settle_s = settle_s
self._budget = reload_budget
self._silent_patience_s = silent_patience_s
+ self._hung_patience_s = hung_patience_s
self._reloads_left = reload_budget
self._deadline: float | None = None
self._blank_since: float | None = None
+ self._unanswered_since: float | None = None
self._explained: BlankReason | None = None
self._was_healthy = True
self._seen_up = False
@@ -180,6 +201,7 @@ class BlankWindowPolicy:
self._reloads_left = self._budget
self._deadline = obs.now + self._grace_s
self._blank_since = None
+ self._unanswered_since = None
self._explained = None
self._was_healthy = obs.server_healthy
self._seen_up = True
@@ -197,7 +219,8 @@ class BlankWindowPolicy:
and self._blank_since is None
and obs.backend_alive
):
- return Verdict(Action.WAIT)
+ return self._judge_unanswered(obs)
+ self._unanswered_since = None
if self._blank_since is None:
# The grace measures how long the window has been EMPTY, not how
@@ -255,6 +278,29 @@ class BlankWindowPolicy:
# ---- internals ---------------------------------------------------------
+ def _judge_unanswered(self, obs: Observation) -> Verdict:
+ """A page that showed up earlier and now does not answer: busy or hung.
+
+ Short silences are waited out (see above). Only silence that outlasts
+ ``hung_patience_s`` while the server answers is a hung page, and that
+ one is recovered from the same budget as a blank window. The clock
+ restarts after each attempt, so a recovery that did not take gets the
+ full patience again before the next one.
+ """
+ if self._unanswered_since is None:
+ self._unanswered_since = obs.now
+ if not obs.server_healthy:
+ # The page may only be waiting on a blocked backend; a reload would
+ # land on the same silent server.
+ return Verdict(Action.WAIT)
+ if obs.now - self._unanswered_since < self._hung_patience_s:
+ return Verdict(Action.WAIT)
+ if self._reloads_left <= 0:
+ return Verdict(Action.WAIT)
+ self._reloads_left -= 1
+ self._unanswered_since = obs.now
+ return Verdict(Action.RELOAD, after_up=True, hung=True)
+
def _arm_after_reload(self, now: float) -> None:
# Escalating settle: 1x, 2x, 4x the base. A window that did not come
# back after one reload is loading slowly, not broken — burning the
@@ -454,6 +500,93 @@ def render_notice(
# ---------------------------------------------------------------------------
+# ---------------------------------------------------------------------------
+# Ending a hung renderer
+# ---------------------------------------------------------------------------
+
+
+def end_busy_renderers(
+ *,
+ cpu_percent: float = HUNG_RENDERER_CPU_PERCENT,
+ sample_s: float = HUNG_RENDERER_SAMPLE_S,
+) -> list[int]:
+ """End this app's web-view renderer processes that are spinning a core.
+
+ A page stuck in a JavaScript loop cannot be reloaded from outside: the
+ navigation is handed to the same busy process. Ending that process frees
+ the window, and the reload that follows starts a fresh one (verified with
+ WebView2 2026-10-02: ``load_url`` alone left the page hung; end + load
+ brought it back in under a second).
+
+ Only renderers of the WebView2 this process hosts are considered, and only
+ those measured busy — an idle renderer serving another window is left
+ alone. Elsewhere (WKWebView on macOS, WebKitGTK or Qt on Linux) there is no
+ such browser child: nothing is ended and the reload proceeds as before.
+ Returns the PIDs that were ended.
+ """
+ try:
+ import psutil # noqa: PLC0415 — only needed on this rare path
+ except ImportError:
+ logger.info("Hung window: psutil is unavailable, so its renderer cannot be ended.")
+ return []
+
+ candidates = []
+ for child in _own_web_view_renderers(psutil):
+ try:
+ child.cpu_percent(None)
+ except psutil.Error:
+ continue
+ candidates.append(child)
+ if not candidates:
+ return []
+ time.sleep(sample_s)
+ ended: list[int] = []
+ for child in candidates:
+ try:
+ busy = child.cpu_percent(None)
+ if busy < cpu_percent:
+ continue
+ child.kill()
+ except psutil.Error as exc:
+ logger.debug("Hung window: renderer {} could not be ended: {}", child.pid, exc)
+ continue
+ logger.warning(
+ "Hung window: ended web-view renderer pid={} ({:.0f} % CPU) so the window can reload.",
+ child.pid,
+ busy,
+ )
+ ended.append(child.pid)
+ return ended
+
+
+def _own_web_view_renderers(psutil: Any) -> list[Any]:
+ """Renderer processes of the web view THIS process hosts, nothing else.
+
+ The browser process of an embedded web view is a direct child of the app;
+ its renderers are that browser's children. A Chrome the app launched for
+ an agent, or the music player's own web view (a separate host process),
+ are deliberately out of reach: a busy page there is not a hung window here.
+ """
+ renderers = []
+ for browser in psutil.Process().children(recursive=False):
+ try:
+ browser_args = browser.cmdline()
+ except psutil.Error:
+ continue
+ if "--embedded-browser-webview=1" not in browser_args or any(
+ a.startswith("--type=") for a in browser_args
+ ):
+ continue
+ for child in browser.children(recursive=False):
+ try:
+ args = child.cmdline()
+ except psutil.Error:
+ continue
+ if "--type=renderer" in args and "--extension-process" not in args:
+ renderers.append(child)
+ return renderers
+
+
@dataclass
class _Slot:
"""One in-flight window call and its outcome."""
@@ -539,6 +672,7 @@ class BlankWindowWatchdog:
poll_s: float = POLL_S,
caller: _WindowCaller | None = None,
action_caller: _WindowCaller | None = None,
+ end_hung_renderer: Callable[[], list[int]] | None = None,
) -> None:
self._window = window
self._url = url
@@ -559,6 +693,7 @@ class BlankWindowWatchdog:
# the diagnosis.
self._caller = caller or _WindowCaller()
self._action_caller = action_caller or _WindowCaller()
+ self._end_hung_renderer = end_hung_renderer or end_busy_renderers
self._stop = threading.Event()
self._thread: threading.Thread | None = None
@@ -622,6 +757,8 @@ class BlankWindowWatchdog:
"""
detail = ""
if verdict.action is Action.RELOAD:
+ if verdict.hung:
+ self._recover_hung_page()
target = self._url
if verdict.after_up:
parts = urlsplit(target)
@@ -656,7 +793,9 @@ class BlankWindowWatchdog:
return False
# Logged only once it actually happened, so a window that is not there
# yet cannot fill the log with attempts nobody saw.
- if verdict.action is Action.RELOAD:
+ if verdict.action is Action.RELOAD and verdict.hung:
+ logger.warning("Desktop window was hung — reloaded it.")
+ elif verdict.action is Action.RELOAD:
logger.info("Desktop window is blank — reloading it (the server answers again).")
elif verdict.reason is not None:
logger.warning(
@@ -667,6 +806,21 @@ class BlankWindowWatchdog:
)
return True
+ def _recover_hung_page(self) -> None:
+ """Free a window whose page stopped answering, before it is reloaded.
+
+ The probe worker is replaced too: its last ``evaluate_js`` went into
+ the hung page and may never return, and a wedged worker refuses every
+ later probe — the guard would read a recovered window as still hung.
+ The old thread is a daemon parked in a native wait; it is left behind.
+ """
+ logger.warning(
+ "Desktop window stopped answering while the server is healthy — "
+ "its page is hung; ending its renderer and reloading."
+ )
+ self._safe(self._end_hung_renderer, default=[])
+ self._caller = _WindowCaller()
+
def _page_state(self, window: Any) -> PageState:
"""Ask the window what it is showing without guessing on a timeout."""
answered, value = self._caller.call(lambda: window.evaluate_js(PAGE_STATE_JS))
diff --git a/tests/unit/ui/test_blank_window_watchdog.py b/tests/unit/ui/test_blank_window_watchdog.py
index 0c1e43c118..18f90b0958 100644
--- a/tests/unit/ui/test_blank_window_watchdog.py
+++ b/tests/unit/ui/test_blank_window_watchdog.py
@@ -39,6 +39,7 @@ from jarvis.ui.window_watchdog import (
GRACE = 20.0
SETTLE = 20.0
PATIENCE = 40.0
+HUNG = 45.0
def _policy(**kw: Any) -> BlankWindowPolicy:
@@ -47,6 +48,7 @@ def _policy(**kw: Any) -> BlankWindowPolicy:
settle_s=kw.pop("settle_s", SETTLE),
reload_budget=kw.pop("reload_budget", 3),
silent_patience_s=kw.pop("silent_patience_s", PATIENCE),
+ hung_patience_s=kw.pop("hung_patience_s", HUNG),
)
@@ -99,11 +101,49 @@ def test_a_healthy_page_is_not_reloaded_when_webview_stops_answering_probes() ->
"""A busy WebView can miss several probes while the painted app stays live."""
p = _policy()
assert p.decide(_obs(0.0, page="up")).action is Action.WAIT
- for t in (10.0, GRACE + 1, GRACE * 10):
+ for t in (10.0, GRACE + 1, HUNG - 1):
assert p.decide(_obs(t, page="unknown")).action is Action.WAIT
- assert p.decide(_obs(GRACE * 10 + 1, page="up")).action is Action.WAIT
- assert p.decide(_obs(GRACE * 10 + 2, page="blank")).action is Action.WAIT
- assert p.decide(_obs(GRACE * 11 + 3, page="blank")).action is Action.RELOAD
+ assert p.decide(_obs(HUNG + 1, page="up")).action is Action.WAIT
+ # The silence ended: a fresh one gets the full patience again.
+ assert p.decide(_obs(HUNG + 2, page="unknown")).action is Action.WAIT
+ assert p.decide(_obs(2 * HUNG, page="unknown")).action is Action.WAIT
+ assert p.decide(_obs(2 * HUNG + 1, page="blank")).action is Action.WAIT
+ assert p.decide(_obs(2 * HUNG + GRACE + 2, page="blank")).action is Action.RELOAD
+
+
+def test_a_page_that_stays_silent_is_hung_and_recovered() -> None:
+ """Live 2026-10-02: the renderer spun a core for seven minutes, unhealed.
+
+ Silence that outlasts the patience while the server answers is not a busy
+ page any more — it is reloaded, flagged so the renderer is ended first.
+ """
+ p = _policy()
+ p.decide(_obs(0.0, page="up"))
+ assert p.decide(_obs(5.0, page="unknown")).action is Action.WAIT
+ verdict = p.decide(_obs(5.0 + HUNG, page="unknown"))
+ assert verdict.action is Action.RELOAD
+ assert verdict.hung is True
+ assert verdict.after_up is True
+ # The next attempt waits a full patience again, not one tick.
+ assert p.decide(_obs(10.0 + HUNG, page="unknown")).action is Action.WAIT
+ assert p.decide(_obs(5.0 + 2 * HUNG, page="unknown")).action is Action.RELOAD
+
+
+def test_hung_recoveries_are_budgeted() -> None:
+ """A page that hangs again after every reload must not be reloaded forever."""
+ p = _policy(reload_budget=2)
+ p.decide(_obs(0.0, page="up"))
+ p.decide(_obs(1.0, page="unknown"))
+ actions = [p.decide(_obs(1.0 + i * HUNG, page="unknown")).action for i in range(1, 6)]
+ assert actions.count(Action.RELOAD) == 2
+
+
+def test_a_silent_page_behind_a_silent_server_is_not_called_hung() -> None:
+ """The page may only be waiting on a blocked backend; reloading cannot help."""
+ p = _policy()
+ p.decide(_obs(0.0, page="up"))
+ for t in (5.0, HUNG, 3 * HUNG):
+ assert p.decide(_obs(t, page="unknown", healthy=False)).action is Action.WAIT
def test_confirmed_late_blank_recovers_even_when_later_probes_time_out() -> None:
@@ -411,6 +451,54 @@ def test_the_watchdog_reloads_the_configured_url() -> None:
assert window.loaded_urls == ["http://127.0.0.1:1234"]
+def test_a_hung_reload_ends_the_renderer_first_and_gets_a_fresh_probe() -> None:
+ """A same-origin reload is committed to the busy renderer and never lands."""
+ from jarvis.ui.window_watchdog import Verdict
+
+ window = _FakeWindow()
+ calls: list[str] = []
+
+ def _end() -> list[int]:
+ calls.append(f"end:{len(window.loaded_urls)}")
+ return [4242]
+
+ wd = _watchdog(window, end_hung_renderer=_end)
+ old_caller = wd._caller
+ assert wd._apply(window, Verdict(Action.RELOAD, after_up=True, hung=True))
+ assert calls == ["end:0"], "the renderer must be ended BEFORE the reload"
+ assert window.loaded_urls == ["http://127.0.0.1:47821?jarvis_recovery=1"]
+ assert wd._caller is not old_caller
+
+
+def test_an_ordinary_reload_never_ends_a_renderer() -> None:
+ from jarvis.ui.window_watchdog import Verdict
+
+ window = _FakeWindow()
+ calls: list[int] = []
+ wd = _watchdog(window, end_hung_renderer=lambda: calls.append(1) or [])
+ assert wd._apply(window, Verdict(Action.RELOAD))
+ assert calls == []
+
+
+def test_a_failing_renderer_end_still_reloads() -> None:
+ from jarvis.ui.window_watchdog import Verdict
+
+ def _boom() -> list[int]:
+ raise RuntimeError("access denied")
+
+ window = _FakeWindow()
+ wd = _watchdog(window, end_hung_renderer=_boom)
+ assert wd._apply(window, Verdict(Action.RELOAD, after_up=True, hung=True))
+ assert window.loaded_urls
+
+
+def test_ending_busy_renderers_without_any_renderer_is_a_no_op() -> None:
+ """In-process web views (macOS, Linux) and the test runner have no renderer child."""
+ from jarvis.ui.window_watchdog import end_busy_renderers
+
+ assert end_busy_renderers(sample_s=0.0) == []
+
+
def test_the_watchdog_writes_the_detail_it_was_given() -> None:
window = _FakeWindow()
wd = _watchdog(window, failure_detail=lambda: "ModuleNotFoundError: click")