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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(desktop): distinguish interface reloads from assistant startup (#207)
Ruben Lütkec7f1a4a220a2
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.pyindex f01565969b..99afc5d4e0 100644--- a/jarvis/ui/desktop_app.py+++ b/jarvis/ui/desktop_app.py@@ -3135,7 +3135,9 @@ class DesktopApp:returnself._auto_recovery_used = True- scheduled, detail = self._schedule_restart(drop_elevation=False)+ scheduled, detail = self._schedule_restart(+ drop_elevation=False, reason="backend_recovery"+ )if scheduled:logger.warning("Backend died — restarting the app automatically.")else:@@ -3536,7 +3538,7 @@ class DesktopApp:(no window to restart). Fully guarded — a spawn failure leaves the apprunning rather than half-quitting."""- return self._schedule_restart(drop_elevation=False)[0]+ return self._schedule_restart(drop_elevation=False, reason="desktop_request")[0]def request_unelevated_restart(self) -> tuple[bool, str]:"""Restart WITHOUT the administrator rights this process is carrying.@@ -3554,9 +3556,11 @@ class DesktopApp:comes back is strictly worse than the problem being fixed, and thedetail string is what the UI shows instead of a silent dead button."""- return self._schedule_restart(drop_elevation=True)+ return self._schedule_restart(drop_elevation=True, reason="input_isolation")- def _schedule_restart(self, *, drop_elevation: bool) -> tuple[bool, str]:+ def _schedule_restart(+ self, *, drop_elevation: bool, reason: str = "unspecified"+ ) -> tuple[bool, str]:"""Spawn the detached relauncher, then quit — optionally droppingelevation on the way out.@@ -3635,8 +3639,9 @@ class DesktopApp:threading.Thread(target=_quit_soon, name="jarvis-restart-quit", daemon=True).start()logger.info(- "Self-restart scheduled (relauncher spawned{}; quitting in ~0.2 s, "+ "Self-restart scheduled (reason={}; relauncher spawned{}; quitting in ~0.2 s, ""independent hard-exit watchdog at ~0.9 s).",+ reason," WITHOUT administrator rights" if drop_elevation else "",)return (True, "restart scheduled")diff --git a/jarvis/ui/web/frontend/index.html b/jarvis/ui/web/frontend/index.htmlindex fbacdad959..db98767a21 100644--- a/jarvis/ui/web/frontend/index.html+++ b/jarvis/ui/web/frontend/index.html@@ -140,6 +140,34 @@} catch (e) {/* storage blocked (private mode) — keep the neutral fallback */}+ var updating = false;+ var recoveryQuery = new URLSearchParams(location.search);+ var recoveryFromQuery = recoveryQuery.get("jarvis_recovery") === "1";+ var recoveryFromHash = location.hash === "#jarvis-interface-recovery";+ var recovering = recoveryFromQuery || recoveryFromHash;+ try {+ updating = sessionStorage.getItem("jarvis:interface-update") === "1";+ recovering = recovering || sessionStorage.getItem("jarvis:interface-recovery") === "1";+ sessionStorage.removeItem("jarvis:interface-update");+ sessionStorage.removeItem("jarvis:interface-recovery");+ } catch (e) {+ /* storage blocked — the native recovery fragment still works */+ }+ if (recoveryFromQuery || recoveryFromHash) {+ try {+ recoveryQuery.delete("jarvis_recovery");+ var remaining = recoveryQuery.toString();+ history.replaceState(+ null, "", location.pathname + (remaining ? "?" + remaining : "") ++ (recoveryFromHash ? "" : location.hash)+ );+ } catch (e) {+ /* a restricted view may keep the marker until it navigates again */+ }+ }+ var status = document.querySelector("#jarvis-boot-splash .sub");+ if (status && updating) status.textContent = "Updating interface…";+ else if (status && recovering) status.textContent = "Restoring interface…";})();</script><script>@@ -221,12 +249,20 @@// window would load, confirm those files answer, and only then go.// Never gives up — showing the app that is already here beats showing// nothing. Mirrors src/lib/safeReload.ts.+ function reloadRecovering() {+ try {+ sessionStorage.setItem("jarvis:interface-recovery", "1");+ } catch (e) {+ location.hash = "jarvis-interface-recovery";+ }+ location.reload();+ }function safeReload() {var f = typeof fetch === "function" ? fetch : null;if (!f) {// No way to check (very old engine) — the old behaviour is still// better than never reloading at all.- location.reload();+ reloadRecovering();return;}var tries = 0;@@ -263,7 +299,7 @@left--;if (left > 0) return;if (bad) again();- else location.reload();+ else reloadRecovering();});});})diff --git a/jarvis/ui/web/frontend/src/lib/bootWatchdog.test.ts b/jarvis/ui/web/frontend/src/lib/bootWatchdog.test.tsindex bff122f335..d0f77dd9a5 100644--- a/jarvis/ui/web/frontend/src/lib/bootWatchdog.test.ts+++ b/jarvis/ui/web/frontend/src/lib/bootWatchdog.test.ts@@ -28,6 +28,56 @@ function indexHtmlPath(): string {const HTML = readFileSync(indexHtmlPath(), "utf8");+test("an interface reload identifies itself without claiming the assistant restarted", () => {+ const script = (HTML.match(/<script>([\s\S]*?)<\/script>/g) ?? []).find((s) =>+ s.includes('localStorage.getItem("jarvis.assistantName")'),+ );+ expect(script).toBeDefined();+ document.body.innerHTML =+ '<div id="jarvis-boot-splash"><div class="name"></div><div class="sub">Starting…</div></div>';+ const session = new Map([["jarvis:interface-update", "1"]]);+ const sessionStub = {+ getItem: (key: string) => session.get(key) ?? null,+ removeItem: (key: string) => void session.delete(key),+ };+ // eslint-disable-next-line no-new-func+ new Function("localStorage", "sessionStorage", script!.slice(8, -9))(+ { getItem: () => "Nova" },+ sessionStub,+ );+ expect(document.querySelector("#jarvis-boot-splash .name")?.textContent).toBe("Nova");+ expect(document.querySelector("#jarvis-boot-splash .sub")?.textContent).toBe(+ "Updating interface…",+ );+ expect(session.size).toBe(0);+});++test("a native recovery query identifies a late reload and is cleared", () => {+ const script = (HTML.match(/<script>([\s\S]*?)<\/script>/g) ?? []).find((s) =>+ s.includes('localStorage.getItem("jarvis.assistantName")'),+ );+ expect(script).toBeDefined();+ document.body.innerHTML =+ '<div id="jarvis-boot-splash"><div class="name"></div><div class="sub">Starting…</div></div>';+ const replaceState = vi.fn();+ const locationStub = {+ hash: "",+ pathname: "/",+ search: "?dev=1&jarvis_recovery=1",+ };+ // eslint-disable-next-line no-new-func+ new Function("localStorage", "sessionStorage", "location", "history", script!.slice(8, -9))(+ { getItem: () => "Nova" },+ { getItem: () => null, removeItem: () => undefined },+ locationStub,+ { replaceState },+ );+ expect(document.querySelector("#jarvis-boot-splash .sub")?.textContent).toBe(+ "Restoring interface…",+ );+ expect(replaceState).toHaveBeenCalledWith(null, "", "/?dev=1");+});+/** The one inline script that owns the reload guard. */function watchdogSource(): string {const scripts = HTML.match(/<script>([\s\S]*?)<\/script>/g) ?? [];@@ -138,6 +188,7 @@ describe("the blank-window watchdog in index.html", () => {const run = runWatchdog({ served: built });await vi.advanceTimersByTimeAsync(3_000);expect(run.reloads()).toBe(1);+ expect(run.store.get("jarvis:interface-recovery")).toBe("1");});test("an emptied root is a crash, and does not wait twenty seconds for it", async () => {diff --git a/jarvis/ui/web/frontend/src/lib/safeReload.ts b/jarvis/ui/web/frontend/src/lib/safeReload.tsindex 810d975260..a22abc57e1 100644--- a/jarvis/ui/web/frontend/src/lib/safeReload.ts+++ b/jarvis/ui/web/frontend/src/lib/safeReload.ts@@ -147,7 +147,16 @@ export function browserSafeReloadDeps(): SafeReloadDeps {fetch(url, { method: "HEAD", cache: "no-store" }).then((response) => response.ok).catch(() => false),- reload: () => window.location.reload(),+ reload: () => {+ // A rebuilt frontend reloads the document, not the assistant process.+ // Tell the dependency-free splash which transition brought it back.+ try {+ sessionStorage.setItem("jarvis:interface-update", "1");+ } catch {+ // Storage can be disabled; the navigation still works.+ }+ window.location.reload();+ },defer: (fn, ms) => {window.setTimeout(fn, ms);},diff --git a/jarvis/ui/web/onboarding_routes.py b/jarvis/ui/web/onboarding_routes.pyindex 76309e063b..1acad12920 100644--- a/jarvis/ui/web/onboarding_routes.py+++ b/jarvis/ui/web/onboarding_routes.py@@ -137,6 +137,7 @@ def _schedule_fresh_restart(request: Request) -> bool:if not callable(fn):return Falsetry:+ log.info("Desktop restart requested by onboarding completion")return bool(fn())except Exception: # noqa: BLE001 — completing onboarding must never 500 herelog.warning("post-onboarding fresh restart failed; staying up", exc_info=True)diff --git a/jarvis/ui/web/settings_routes.py b/jarvis/ui/web/settings_routes.pyindex b45cac226c..9f8f2f576d 100644--- a/jarvis/ui/web/settings_routes.py+++ b/jarvis/ui/web/settings_routes.py@@ -2488,6 +2488,7 @@ async def restart_app(request: Request, force: bool = False) -> dict[str, objectraise HTTPException(status_code=503, detail="self-restart unavailable on this host")+ log.info("Desktop restart requested through settings route (force=%s)", force)# Off the shared default pool — a restart must survive a pool exhausted by# hung threads (see ``_run_off_pool``). ``asyncio.to_thread`` would queue# behind the dead pool and hang the POST forever.diff --git a/jarvis/ui/window_watchdog.py b/jarvis/ui/window_watchdog.pyindex 0d881f8335..a55defef18 100644--- a/jarvis/ui/window_watchdog.py+++ b/jarvis/ui/window_watchdog.py@@ -44,6 +44,7 @@ from collections.abc import Callablefrom dataclasses import dataclass, fieldfrom enum import Enumfrom typing import Any, Literal+from urllib.parse import urlsplit, urlunsplitfrom loguru import logger@@ -77,8 +78,9 @@ SILENT_PATIENCE_S = 45.0#: ``up`` — our document is loaded (``#root`` exists). From here the page's#: own watchdog is in charge; this one only guards the frame.#: ``notice`` — the explanation page this watchdog wrote.-#: ``blank`` — no document of ours: nothing ever arrived, or the view is empty.-PageState = Literal["up", "notice", "blank"]+#: ``blank`` — a responding view confirms that our document is absent.+#: ``unknown`` — the view did not answer the probe; it may still be painting.+PageState = Literal["up", "notice", "blank", "unknown"]#: One expression, because it runs in a document that may be barely alive.#: ``#root`` is in the static HTML, so its presence proves our page arrived —@@ -137,6 +139,7 @@ class Verdict:action: Actionreason: BlankReason | None = None+ after_up: bool = Falseclass BlankWindowPolicy:@@ -164,6 +167,7 @@ class BlankWindowPolicy:self._blank_since: float | None = Noneself._explained: BlankReason | None = Noneself._was_healthy = True+ self._seen_up = Falsedef decide(self, obs: Observation) -> Verdict:if self._deadline is None:@@ -178,6 +182,21 @@ class BlankWindowPolicy:self._blank_since = Noneself._explained = Noneself._was_healthy = obs.server_healthy+ self._seen_up = True+ return Verdict(Action.WAIT)++ # evaluate_js can time out while WebView2 is busy even though the app+ # remains painted and usable. Once this window has shown our page,+ # silence from the probe is not evidence that it went blank. A confirmed+ # blank response still takes the recovery path below. Before first+ # paint, keep the original cold-boot recovery for a view that never+ # navigated and therefore cannot answer at all.+ if (+ obs.page == "unknown"+ and self._seen_up+ and self._blank_since is None+ and obs.backend_alive+ ):return Verdict(Action.WAIT)if self._blank_since is None:@@ -226,7 +245,7 @@ class BlankWindowPolicy:if self._reloads_left > 0:self._reloads_left -= 1self._arm_after_reload(obs.now)- return Verdict(Action.RELOAD)+ return Verdict(Action.RELOAD, after_up=self._seen_up)# Out of attempts. The window keeps its explanation and the button on# it; the watchdog keeps watching, so the next recovery still heals it.@@ -603,7 +622,20 @@ class BlankWindowWatchdog:"""detail = ""if verdict.action is Action.RELOAD:- answered, _ = self._action_caller.call(lambda: window.load_url(self._url))+ target = self._url+ if verdict.after_up:+ parts = urlsplit(target)+ query = f"{parts.query}&" if parts.query else ""+ target = urlunsplit(+ (+ parts.scheme,+ parts.netloc,+ parts.path,+ f"{query}jarvis_recovery=1",+ parts.fragment,+ )+ )+ answered, _ = self._action_caller.call(lambda: window.load_url(target))elif verdict.action is Action.EXPLAIN and verdict.reason is not None:detail = self._safe(self._failure_detail, default="")html = render_notice(@@ -636,17 +668,11 @@ class BlankWindowWatchdog:return Truedef _page_state(self, window: Any) -> PageState:- """Ask the window what it is showing; an unanswerable window is blank.-- Every way the question can fail — ``None`` from a view with no- document, an exception, or no answer at all within the deadline — means- the same thing to the person looking at the frame: there is nothing- there. Which is precisely the state this guard acts on.- """+ """Ask the window what it is showing without guessing on a timeout."""answered, value = self._caller.call(lambda: window.evaluate_js(PAGE_STATE_JS))- if answered and value in ("up", "notice"):+ if answered and value in ("up", "notice", "blank"):return value # type: ignore[return-value]- return "blank"+ return "unknown"@staticmethoddef _safe(probe: Callable[[], Any], *, default: Any) -> Any:diff --git a/tests/unit/ui/test_blank_window_watchdog.py b/tests/unit/ui/test_blank_window_watchdog.pyindex e6b8e9a913..0c1e43c118 100644--- a/tests/unit/ui/test_blank_window_watchdog.py+++ b/tests/unit/ui/test_blank_window_watchdog.py@@ -95,6 +95,40 @@ def test_a_page_that_dies_later_gets_a_full_budget_again() -> None:assert p.decide(_obs(100.0 + GRACE + 1)).action is Action.RELOAD+def test_a_healthy_page_is_not_reloaded_when_webview_stops_answering_probes() -> None:+ """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):+ 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+++def test_confirmed_late_blank_recovers_even_when_later_probes_time_out() -> None:+ """A known empty view must not be stuck by subsequent probe timeouts."""+ window = _FakeWindow()+ wd = _watchdog(window, policy=_policy())+ assert wd._policy.decide(_obs(0.0, page="up")).action is Action.WAIT+ assert wd._policy.decide(_obs(10.0, page="blank")).action is Action.WAIT+ verdict = wd._policy.decide(_obs(10.0 + GRACE + 1, page="unknown"))+ assert verdict.action is Action.RELOAD+ assert verdict.after_up is True+ assert wd._apply(window, verdict)+ assert window.loaded_urls == ["http://127.0.0.1:47821?jarvis_recovery=1"]+++def test_late_recovery_preserves_existing_url_query() -> None:+ window = _FakeWindow()+ wd = _watchdog(window, url="http://127.0.0.1:47821/?dev=1", policy=_policy())+ wd._policy.decide(_obs(0.0, page="up"))+ wd._policy.decide(_obs(10.0, page="blank"))+ verdict = wd._policy.decide(_obs(10.0 + GRACE + 1, page="blank"))+ assert wd._apply(window, verdict)+ assert window.loaded_urls == ["http://127.0.0.1:47821/?dev=1&jarvis_recovery=1"]++# --- the recoverable freeze -------------------------------------------------@@ -354,12 +388,16 @@ def _watchdog(window: _FakeWindow, **kw: Any) -> BlankWindowWatchdog:)-def test_an_unanswerable_window_counts_as_blank() -> None:- """``evaluate_js`` raising and a view with no document look the same to a user."""+def test_an_unanswerable_window_is_unknown() -> None:+ """A timed-out probe cannot establish whether the painted page is blank."""window = _FakeWindow()window.raise_on_eval = Truewd = _watchdog(window)- assert wd._page_state(window) == "blank"+ assert wd._page_state(window) == "unknown"+ # Before first paint a never-navigated view still receives recovery.+ p = _policy()+ p.decide(_obs(0.0, page="unknown"))+ assert p.decide(_obs(GRACE + 1, page="unknown")).action is Action.RELOADdef test_the_watchdog_reloads_the_configured_url() -> None:diff --git a/tests/unit/ui/test_desktop_backend_death.py b/tests/unit/ui/test_desktop_backend_death.pyindex 1539d82203..eb95c78e09 100644--- a/tests/unit/ui/test_desktop_backend_death.py+++ b/tests/unit/ui/test_desktop_backend_death.py@@ -48,12 +48,16 @@ class _FakeApp:self._detached_windows: dict[str, Any] = {}self._auto_recovery_used = Falseself.restart_calls: list[bool] = []+ self.restart_reasons: list[str] = []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]:+ def _schedule_restart(+ self, *, drop_elevation: bool, reason: str = "unspecified"+ ) -> tuple[bool, str]:self.restart_calls.append(drop_elevation)+ self.restart_reasons.append(reason)return self.restart_result@@ -70,6 +74,7 @@ def test_unexpected_death_restarts_the_app() -> None:_note(app)assert app.restart_calls == [False]+ assert app.restart_reasons == ["backend_recovery"]assert app._auto_recovery_used is Truediff --git a/tests/unit/ui/test_restart_launch_context.py b/tests/unit/ui/test_restart_launch_context.pyindex 406574a637..654dc450fc 100644--- a/tests/unit/ui/test_restart_launch_context.py+++ b/tests/unit/ui/test_restart_launch_context.py@@ -133,6 +133,8 @@ def test_invalid_helper_overrides_do_not_start_or_stop_any_process(args):def test_desktop_sends_context_to_detached_helper_without_running_it(monkeypatch):+ from loguru import logger+import jarvisfrom jarvis.ui import desktop_app@@ -151,7 +153,14 @@ def test_desktop_sends_context_to_detached_helper_without_running_it(monkeypatchmonkeypatch.setattr(desktop_app.threading, "Thread", DeferredThread)app = SimpleNamespace(_window=object())- assert desktop_app.DesktopApp._schedule_restart(app, drop_elevation=False)[0]+ messages: list[str] = []+ sink = logger.add(lambda message: messages.append(message.record["message"]), level="INFO")+ try:+ assert desktop_app.DesktopApp._schedule_restart(+ app, drop_elevation=False, reason="desktop_request"+ )[0]+ finally:+ logger.remove(sink)command, kwargs = spawned[0]root = str(Path(jarvis.__file__).resolve().parent.parent)assert command == [@@ -167,3 +176,4 @@ def test_desktop_sends_context_to_detached_helper_without_running_it(monkeypatch]assert kwargs == {"cwd": root, "env": {"JARVIS_INSTANCE": "dev"}}assert len(threads) == 1 and threads[0]["daemon"] is True+ assert any("reason=desktop_request" in message for message in messages)diff --git a/tests/unit/ui/test_restart_route.py b/tests/unit/ui/test_restart_route.pyindex 4c3aeeb66c..3a39a513fe 100644--- a/tests/unit/ui/test_restart_route.py+++ b/tests/unit/ui/test_restart_route.py@@ -2,6 +2,7 @@from __future__ import annotationsimport asyncio+import loggingimport threadingfrom types import SimpleNamespace@@ -36,19 +37,21 @@ def _manager_with_prompts(prompts):return SimpleNamespace(mission=mission)-def test_restart_schedules_when_window_present():+def test_restart_schedules_when_window_present(caplog):calls = {"n": 0}def request_restart():calls["n"] += 1return True- r = _client(SimpleNamespace(request_restart=request_restart)).post(- "/api/settings/restart-app"- )+ with caplog.at_level(logging.INFO, logger="jarvis.ui.web.settings_routes"):+ r = _client(SimpleNamespace(request_restart=request_restart)).post(+ "/api/settings/restart-app"+ )assert r.status_code == 200assert r.json() == {"ok": True, "restarting": True}assert calls["n"] == 1+ assert "Desktop restart requested through settings route (force=False)" in caplog.textdef test_restart_rejects_control_bearer_even_when_forced():