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): stop the backend from dying in silence

rubenluetke10-beepea08ca027644
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.py
index d027db13e1..6e43df220f 100644
--- a/jarvis/ui/desktop_app.py
+++ b/jarvis/ui/desktop_app.py
@@ -101,6 +101,13 @@ _REALTIME_WARM_VOICE_GATE_S = 45.0
#: account once per call.
_REALTIME_WARM_MIN_INTERVAL_S = 20.0
+#: How long the backend must have been serving before its death is treated as
+#: an accident worth recovering from (see ``_note_backend_stopped``). Below
+#: this it reads as a boot failure — the fresh process would hit the same wall
+#: and relaunch again, so the app stays down and says why instead. Comfortably
+#: above a full cold boot, including model prefetch on a cold disk.
+_BACKEND_MIN_UPTIME_FOR_RECOVERY_S = 120.0
+
def _local_voice_permission_granted(
*,
@@ -431,6 +438,78 @@ def _install_desktop_log_sink(log_path: Path) -> None:
logger.info("Desktop log sink active: {}", log_path)
+_CRASH_HOOKS_INSTALLED = False
+
+
+def _build_crash_hooks(
+ previous_thread_hook: Any, previous_main_hook: Any
+) -> tuple[Any, Any]:
+ """Build the ``(threading.excepthook, sys.excepthook)`` pair.
+
+ Split out from the installer so the behaviour can be tested without
+ swapping two process-wide hooks — a test that does that leaks into every
+ test after it.
+ """
+ from loguru import logger
+
+ def _thread_hook(args: Any) -> None:
+ # A thread torn down during interpreter shutdown reports SystemExit
+ # with no traceback. That is an exit, not a crash.
+ if args.exc_type is not SystemExit:
+ logger.opt(
+ exception=(args.exc_type, args.exc_value, args.exc_traceback)
+ ).critical(
+ "Thread '{}' died on an unhandled exception — whatever it was "
+ "serving is gone for the rest of this process.",
+ getattr(args.thread, "name", "<unnamed>"),
+ )
+ try:
+ previous_thread_hook(args)
+ except Exception: # noqa: BLE001, S110 — the fallback reporter is
+ # best-effort; we already have the line that matters.
+ pass
+
+ def _main_hook(exc_type: Any, exc_value: Any, exc_tb: Any) -> None:
+ if not issubclass(exc_type, KeyboardInterrupt):
+ logger.opt(exception=(exc_type, exc_value, exc_tb)).critical(
+ "Main thread died on an unhandled exception."
+ )
+ try:
+ previous_main_hook(exc_type, exc_value, exc_tb)
+ except Exception: # noqa: BLE001, S110 — see above.
+ pass
+
+ return _thread_hook, _main_hook
+
+
+def _install_crash_hooks() -> None:
+ """Route a thread or main-thread crash into the log file.
+
+ The sink above only catches what someone *logs*. An exception that escapes
+ a thread's target goes to :data:`threading.excepthook`, and one that
+ escapes the main thread goes to :data:`sys.excepthook` — both of which
+ print to ``sys.stderr``, which ``pythonw.exe`` does not have. So the
+ loudest failure this app can suffer is also its quietest one.
+
+ That is exactly how the backend can end mid-session and leave nothing
+ behind but the pending tasks asyncio destroys on the way out: the window
+ stays up, every socket is gone, the sidebar flips to OFFLINE, and the log
+ holds no reason at all (live incident 2026-08-09, 15:44:45 — eighteen
+ "Task was destroyed but it is pending" lines and not one word of cause).
+
+ Both hooks chain to whatever was installed before, so a debugger's own
+ reporting still runs. Idempotent.
+ """
+ global _CRASH_HOOKS_INSTALLED
+ if _CRASH_HOOKS_INSTALLED:
+ return
+ _CRASH_HOOKS_INSTALLED = True
+
+ threading.excepthook, sys.excepthook = _build_crash_hooks(
+ threading.excepthook, sys.excepthook
+ )
+
+
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
@@ -1111,9 +1190,20 @@ class DesktopApp:
# calling add() with an identical sink would duplicate it, hence the
# module-global guard.
_install_desktop_log_sink(DATA_DIR / "jarvis_desktop.log")
+ # ...and the sink alone is not enough: it only records what someone
+ # logs. A thread that dies on an exception reports to a stderr that
+ # does not exist here, so the crash that matters most is the one the
+ # log never mentions. See _install_crash_hooks.
+ _install_crash_hooks()
self._backend_thread: threading.Thread | None = None
self._backend_loop: asyncio.AbstractEventLoop | None = None
+ # Monotonic stamp of the moment the backend loop began serving, and a
+ # one-shot latch — together they gate the automatic recovery in
+ # _note_backend_stopped so a crash-on-boot can never become a
+ # relaunch loop.
+ self._backend_serving_since: float | None = None
+ self._auto_recovery_used = False
# Off-loop stall reporter, armed once the backend loop starts serving.
self._loop_watchdog: Any = None
self._server: WebServer | None = None
@@ -2315,7 +2405,26 @@ class DesktopApp:
# and a sampling profiler attached to the live process was the only
# way to learn it was a TOML parse). Costs one sleeping thread.
self._start_loop_watchdog(loop)
- loop.run_forever()
+ self._backend_serving_since = time.monotonic()
+ # run_forever() has exactly one legitimate way out: shutdown()
+ # calling loop.stop(). Every OTHER way out — a BaseException from
+ # a callback, a stop nobody asked for — takes the whole backend
+ # with it and leaves the window standing in front of a dead
+ # process. Naming which of the two happened is the difference
+ # between a diagnosable incident and a grey OFFLINE dot.
+ try:
+ loop.run_forever()
+ except BaseException as exc: # noqa: BLE001 — re-raising here
+ # would only reach the excepthook; we want it in the log WITH
+ # the recovery decision that follows, then a clean unwind.
+ from loguru import logger as _crash_log
+
+ _crash_log.opt(exception=exc).critical(
+ "Backend event loop crashed out of run_forever()."
+ )
+ self._note_backend_stopped(f"{type(exc).__name__}: {exc}")
+ else:
+ self._note_backend_stopped("the loop was stopped")
finally:
self._stop_loop_watchdog()
try:
@@ -2362,6 +2471,87 @@ class DesktopApp:
except Exception: # noqa: BLE001, S110 — teardown of a diagnostic
pass
+ # ---- Backend death -------------------------------------------------------
+
+ def _note_backend_stopped(self, reason: str) -> None:
+ """The backend loop has ended. Say so, and refuse to be a ghost.
+
+ Two very different situations reach this point:
+
+ * The user quit or restarted. ``shutdown()`` set the flag, the window
+ is on its way out, and there is nothing to report.
+ * Nobody asked. The loop is gone but the GUI thread keeps the window
+ on screen, so the app is still *there* — it just cannot serve a
+ single request. Every live surface goes dark at once and the only
+ thing the user is told is a grey OFFLINE dot in the sidebar, with no
+ reason and no way back short of killing the app by hand. That is the
+ state reported 2026-08-09, and an app that can enter it silently is
+ the actual defect, not the crash that started it.
+
+ For the second case: log it as the incident it is, then use the same
+ relauncher the in-app Restart button uses to bring the process back.
+ Two guards keep that from becoming a loop — it fires at most once per
+ process, and only for a backend that had genuinely been serving. A
+ backend that dies during boot therefore fails visibly and stays
+ failed, which is the honest outcome: restarting it would just crash
+ the same way, forever.
+ """
+ from loguru import logger
+
+ # Every read is a getattr: this runs on the way OUT, including out of a
+ # backend that never finished coming up, and a half-built instance must
+ # not turn a crash report into a second crash.
+ if getattr(self, "_shutdown_done", False) or getattr(
+ self, "_user_requested_quit", False
+ ):
+ logger.debug("Backend loop ended as part of shutdown ({}).", reason)
+ return
+
+ started = getattr(self, "_backend_serving_since", None)
+ served_s = 0.0 if started is None else time.monotonic() - started
+ logger.critical(
+ "Backend loop ended after {:.0f}s WITHOUT a shutdown request "
+ "({}). Every socket, route and voice surface is gone; the window "
+ "is still on screen.",
+ served_s,
+ reason,
+ )
+
+ window_up = getattr(self, "_window", None) is not None or bool(
+ getattr(self, "_detached_windows", None)
+ )
+ if not window_up:
+ # Headless, or the window is already down: the process is ending
+ # anyway and a relaunch would fight the exit path.
+ logger.info("No window left to rescue — letting the process end.")
+ return
+ if getattr(self, "_auto_recovery_used", False):
+ logger.error(
+ "Automatic recovery was already used this process — not "
+ "restarting again. Please restart the app."
+ )
+ return
+ if served_s < _BACKEND_MIN_UPTIME_FOR_RECOVERY_S:
+ logger.error(
+ "Backend survived only {:.0f}s (< {:.0f}s) — treating this as "
+ "a boot failure and NOT restarting, so a broken build cannot "
+ "relaunch itself forever.",
+ served_s,
+ _BACKEND_MIN_UPTIME_FOR_RECOVERY_S,
+ )
+ return
+
+ self._auto_recovery_used = True
+ scheduled, detail = self._schedule_restart(drop_elevation=False)
+ if scheduled:
+ logger.warning("Backend died — restarting the app automatically.")
+ else:
+ logger.error(
+ "Backend died and the automatic restart could not be "
+ "scheduled ({}). The window will stay up but stay offline.",
+ detail,
+ )
+
def _start_virtual_cursor(self) -> None:
"""Arm the Jarvis cursor identity and (optionally) the click-pulse overlay.
diff --git a/tests/unit/ui/test_desktop_backend_death.py b/tests/unit/ui/test_desktop_backend_death.py
new file mode 100644
index 0000000000..be6ec19d47
--- /dev/null
+++ b/tests/unit/ui/test_desktop_backend_death.py
@@ -0,0 +1,271 @@
+"""The backend is not allowed to die quietly.
+
+Everything the user touches — every route, every WebSocket frame, every voice
+turn — is serialized through one asyncio loop on one thread. When that thread
+ends, the pywebview window keeps running on its own thread, so the app is still
+on screen while being unable to answer a single request. All the user gets is a
+grey OFFLINE dot in the sidebar (live report 2026-08-09): no reason, no
+traceback, and no way back short of killing the app by hand.
+
+Two holes made that possible, and these tests pin both shut:
+
+1. An exception escaping a thread goes to ``threading.excepthook``, which
+ prints to ``sys.stderr`` — and ``pythonw.exe`` has none. The loudest
+ failure in the app was also its most invisible one.
+2. Nothing acted on the death. ``run_forever()`` returning is either a
+ shutdown someone asked for or an accident, and the two were indistinguishable.
+"""
+
+from __future__ import annotations
+
+import sys
+import threading
+import time
+from typing import Any
+
+import pytest
+
+from jarvis.ui import desktop_app
+from jarvis.ui.desktop_app import DesktopApp
+
+# --- the recovery decision -------------------------------------------------
+
+
+class _FakeApp:
+ """The attribute surface ``_note_backend_stopped`` actually reads.
+
+ Building a real ``DesktopApp`` would boot a log sink, a config load and a
+ session token; the decision under test needs none of that.
+ """
+
+ def __init__(self, **overrides: Any) -> None:
+ self._shutdown_done = False
+ self._user_requested_quit = False
+ self._backend_serving_since = time.monotonic() - 3600.0
+ self._window = object()
+ self._detached_windows: dict[str, Any] = {}
+ self._auto_recovery_used = False
+ self.restart_calls: list[bool] = []
+ self.restart_result: tuple[bool, str] = (True, "restart scheduled")
+ for key, value in overrides.items():
+ setattr(self, key, value)
+
+ def _schedule_restart(self, *, drop_elevation: bool) -> tuple[bool, str]:
+ self.restart_calls.append(drop_elevation)
+ return self.restart_result
+
+
+def _note(app: _FakeApp, reason: str = "boom") -> None:
+ DesktopApp._note_backend_stopped(app, reason) # type: ignore[arg-type]
+
+
+def test_unexpected_death_restarts_the_app() -> None:
+ # The case from the report: a backend that had been serving for an hour is
+ # suddenly gone while the window is still up. Nobody asked for that, so the
+ # app brings itself back rather than sitting there as a shell.
+ app = _FakeApp()
+
+ _note(app)
+
+ assert app.restart_calls == [False]
+ assert app._auto_recovery_used is True
+
+
+def test_shutdown_is_not_a_crash() -> None:
+ # The user quit or hit Restart. The loop ending is the point, and
+ # relaunching here would fight the exit path.
+ app = _FakeApp(_shutdown_done=True)
+
+ _note(app, "the loop was stopped")
+
+ assert app.restart_calls == []
+
+
+def test_user_requested_quit_is_not_a_crash() -> None:
+ # Same, one step earlier: the quit is marked before shutdown() runs.
+ app = _FakeApp(_user_requested_quit=True)
+
+ _note(app, "the loop was stopped")
+
+ assert app.restart_calls == []
+
+
+def test_a_boot_failure_is_not_restarted() -> None:
+ # A backend that dies seconds after starting would die the same way in the
+ # fresh process. Restarting it is an infinite relaunch loop with a window
+ # flashing on and off — worse than staying down and saying why.
+ app = _FakeApp(_backend_serving_since=time.monotonic() - 5.0)
+
+ _note(app)
+
+ assert app.restart_calls == []
+ assert app._auto_recovery_used is False
+
+
+def test_recovery_fires_at_most_once_per_process() -> None:
+ # Belt to the uptime brace: even a long-lived backend that somehow reaches
+ # this twice gets exactly one rescue.
+ app = _FakeApp(_auto_recovery_used=True)
+
+ _note(app)
+
+ assert app.restart_calls == []
+
+
+def test_no_window_means_nothing_to_rescue() -> None:
+ # Headless, or the window is already gone: the process is on its way out
+ # and a relauncher would race the exit.
+ app = _FakeApp(_window=None)
+
+ _note(app)
+
+ assert app.restart_calls == []
+
+
+def test_a_detached_window_still_counts_as_a_window() -> None:
+ # The main window can be closed while a detached view (IDE / Voice) is the
+ # one thing still on screen. That surface is just as dead without a
+ # backend, so it earns the same rescue.
+ app = _FakeApp(_window=None, _detached_windows={"agentic": object()})
+
+ _note(app)
+
+ assert app.restart_calls == [False]
+
+
+def test_a_half_built_instance_does_not_crash_the_reporter() -> None:
+ # This runs on the way OUT, including out of a backend that never finished
+ # coming up — so the instance may be missing half its attributes. A crash
+ # report that itself crashes reports nothing at all.
+ class _Bare:
+ def _schedule_restart(self, *, drop_elevation: bool) -> tuple[bool, str]:
+ raise AssertionError("must not be reached without a window")
+
+ DesktopApp._note_backend_stopped(_Bare(), "died during boot") # type: ignore[arg-type]
+
+
+def test_a_refused_restart_leaves_the_app_up() -> None:
+ # The relauncher could not be spawned. Half-quitting would leave the user
+ # with nothing at all; staying up (offline) is the lesser failure, and the
+ # log carries the detail.
+ app = _FakeApp(restart_result=(False, "relauncher spawn failed"))
+
+ _note(app)
+
+ assert app.restart_calls == [False]
+
+
+# --- the crash hooks -------------------------------------------------------
+#
+# Exercised through the pure builder. Swapping the real process-wide hooks in a
+# test leaks into every test that runs after it, which is a poor trade for
+# coverage of two assignments.
+
+
+class _Args:
+ """The shape ``threading.excepthook`` is handed."""
+
+ def __init__(self, exc: BaseException, name: str) -> None:
+ self.exc_type = type(exc)
+ self.exc_value = exc
+ self.exc_traceback = exc.__traceback__
+ self.thread = threading.Thread(name=name)
+
+
+def _captured_criticals(fn: Any) -> list[str]:
+ from loguru import logger
+
+ seen: list[str] = []
+ sink_id = logger.add(lambda m: seen.append(m), level="CRITICAL")
+ try:
+ fn()
+ finally:
+ logger.remove(sink_id)
+ return seen
+
+
+def test_a_dying_thread_reaches_the_log() -> None:
+ thread_hook, _ = desktop_app._build_crash_hooks(lambda _args: None, lambda *_: None)
+
+ seen = _captured_criticals(
+ lambda: thread_hook(_Args(RuntimeError("the backend loop fell over"), "jarvis-backend"))
+ )
+
+ # The thread name and the original exception both have to survive — a bare
+ # "a thread died" is not something anyone can act on.
+ assert any("jarvis-backend" in line for line in seen)
+ assert any("the backend loop fell over" in line for line in seen)
+
+
+def test_a_thread_exiting_via_systemexit_is_not_an_incident() -> None:
+ # Interpreter shutdown tears daemon threads down with SystemExit and no
+ # traceback. Logging that as CRITICAL would cry wolf on every clean quit.
+ thread_hook, _ = desktop_app._build_crash_hooks(lambda _args: None, lambda *_: None)
+
+ seen = _captured_criticals(lambda: thread_hook(_Args(SystemExit(), "jarvis-backend")))
+
+ assert seen == []
+
+
+def test_the_previous_thread_hook_still_runs() -> None:
+ # Chaining, not replacing: a debugger or a harness that installed its own
+ # reporter must keep seeing crashes.
+ calls: list[Any] = []
+ thread_hook, _ = desktop_app._build_crash_hooks(calls.append, lambda *_: None)
+
+ args = _Args(ValueError("chained"), "chained-thread")
+ _captured_criticals(lambda: thread_hook(args))
+
+ assert calls == [args]
+
+
+def test_a_broken_previous_hook_does_not_swallow_the_report() -> None:
+ # Our line is written first, so a fallback reporter that itself raises
+ # costs nothing that matters.
+ def _broken(_args: Any) -> None:
+ raise RuntimeError("the old reporter is broken too")
+
+ thread_hook, _ = desktop_app._build_crash_hooks(_broken, lambda *_: None)
+
+ seen = _captured_criticals(
+ lambda: thread_hook(_Args(RuntimeError("the real problem"), "jarvis-backend"))
+ )
+
+ assert any("the real problem" in line for line in seen)
+
+
+def test_a_dying_main_thread_reaches_the_log() -> None:
+ chained: list[Any] = []
+ _, main_hook = desktop_app._build_crash_hooks(
+ lambda _args: None, lambda t, v, tb: chained.append(v)
+ )
+ exc = RuntimeError("the window thread fell over")
+
+ seen = _captured_criticals(lambda: main_hook(type(exc), exc, exc.__traceback__))
+
+ assert any("the window thread fell over" in line for line in seen)
+ assert chained == [exc]
+
+
+def test_ctrl_c_is_not_an_incident() -> None:
+ # KeyboardInterrupt is how a developer stops the app from a terminal.
+ _, main_hook = desktop_app._build_crash_hooks(lambda _args: None, lambda *_: None)
+ exc = KeyboardInterrupt()
+
+ seen = _captured_criticals(lambda: main_hook(type(exc), exc, None))
+
+ assert seen == []
+
+
+def test_installing_twice_does_not_stack_hooks(monkeypatch: pytest.MonkeyPatch) -> None:
+ # Two DesktopApp instances (tests do this) must not double-report. The
+ # process hooks are restored by monkeypatch, so this stays hermetic.
+ monkeypatch.setattr(desktop_app, "_CRASH_HOOKS_INSTALLED", False)
+ monkeypatch.setattr(threading, "excepthook", threading.excepthook)
+ monkeypatch.setattr(sys, "excepthook", sys.excepthook)
+
+ desktop_app._install_crash_hooks()
+ first = threading.excepthook
+ desktop_app._install_crash_hooks()
+
+ assert threading.excepthook is first