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(ui): a window with no page at all is caught, healed, and explained

Harald88f6da1e31c6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e627f76252..ad24ed341a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,28 @@ versioning per [SemVer](https://semver.org/).
---
+## [Unreleased]
+
+### Fixed
+
+- **A window that never received a page is caught too.** The blank-window
+ watchdog shipped in 1.5.0 lives in `index.html`, so it can only act once a
+ page has arrived — and the window the maintainer kept seeing had none: a
+ frame, a title, the ground colour, nothing else. Three routes lead there,
+ all logged on one day: the backend's single event loop frozen inside a
+ native call, so the socket accepted the navigation and never answered it
+ (15 s, 20 s, 42 s, 61 s and 188 s measured, the long ones inside
+ PortAudio's stream close during a microphone restart); the backend thread
+ dying after the port was already up; and a web view that never navigated
+ at all. A guard now runs in the window process, outside the loop it
+ watches: it waits out a slow boot, reloads the moment the server answers
+ again, and when it cannot fix it, it puts the reason on the window with a
+ button — in the browser's language, since the bundle is exactly what is
+ missing. That page then polls the server and returns to the app by itself.
+ Closing the microphone no longer runs on the event loop either, which
+ removes the biggest freeze at its source: the loop now keeps serving while
+ a wedged native handle is shut down on a worker thread.
+
## [1.5.0] — 2026-08-20
### Added
@@ -144,23 +166,6 @@ versioning per [SemVer](https://semver.org/).
never becomes an app after twenty, and a second failure paints what went
wrong plus a Reload button instead of staying dark. The guard is released as
soon as the app is up, so a later rebuild in the same session still heals.
-- **A window that never received a page is caught too.** The watchdog above
- lives in the page, so it can only act once a page has arrived — and the
- window the maintainer kept seeing had none: a frame, a title, the ground
- colour, nothing else. Three routes lead there, all of them logged on one
- day: the backend's single event loop frozen inside a native call, so the
- socket accepted the navigation and never answered it (15 s, 20 s, 42 s,
- 61 s and 188 s measured, the long ones inside PortAudio's stream close
- during a microphone restart); the backend thread dying after the port was
- already up; and a web view that never navigated at all. A guard now runs in
- the window process, outside the loop it watches: it waits out a slow boot,
- reloads the moment the server answers again, and when it cannot fix it, it
- puts the reason on the window with a button — in the browser's language,
- since the bundle is exactly what is missing. That page then polls the
- server and returns to the app by itself. Closing the microphone no longer
- runs on the event loop either, which removes the biggest freeze at its
- source: the loop now keeps serving while a wedged native handle is shut
- down on a worker thread.
- **A granted macOS permission stops reading as missing.** Every start warned
that permissions were off, and the pane the warning linked to showed them
on. Three things kept that loop alive. Opening System Settings for Screen
diff --git a/jarvis/audio/capture.py b/jarvis/audio/capture.py
index 48053fe32a..d0dbaa431a 100644
--- a/jarvis/audio/capture.py
+++ b/jarvis/audio/capture.py
@@ -992,14 +992,11 @@ class MicrophoneCapture:
# Close that partial stream so PortAudio/CoreAudio does not keep
# a poisoned handle across every subsequent wake-loop retry.
if stream is not None:
- try:
- stream.close()
- except Exception as close_exc: # noqa: BLE001
- _log.debug(
- "Mic-Open cleanup for device={} ignored ({}).",
- attempt,
- close_exc,
- )
+ # Off-loop: a half-opened stream on a device that just
+ # disappeared closes as slowly as any other (see
+ # _discard_stream_off_loop), and this runs on the loop that
+ # serves the desktop window.
+ await self._discard_stream_off_loop(stream)
# A failed open means the cached/resolved device may be gone —
# force the next construction through a fresh full resolve, and
# ask the topology watcher to look NOW rather than at its next
@@ -1072,8 +1069,10 @@ class MicrophoneCapture:
if old_stream is not None:
# A stalled callback stream cannot drain gracefully — see
# ``_discard_stream`` (abort-first, CoreAudio ``stop()`` can
- # block for minutes after an endpoint transition).
- self._discard_stream(old_stream)
+ # block for minutes after an endpoint transition). Off-loop,
+ # because this watchdog runs on the loop that also serves the
+ # desktop window.
+ await self._discard_stream_off_loop(old_stream)
try:
await self._try_open_stream()
_log.info("Mic-Restart #{} succeeded.", self._restart_count)
@@ -1112,6 +1111,42 @@ class MicrophoneCapture:
time.monotonic() - self._STALL_THRESHOLD_S - 1.0,
)
+ #: How long a coroutine waits for a native stream to shut down before it
+ #: leaves the rest to a worker thread. Long enough that the ordinary close
+ #: (milliseconds) still finishes in order; short enough that a wedged one
+ #: cannot be mistaken for normal work.
+ _DISCARD_GRACE_S = 2.0
+
+ @classmethod
+ async def _discard_stream_off_loop(cls, stream: Any) -> None:
+ """Discard *stream* without ever freezing the event loop.
+
+ ``Pa_CloseStream`` is a synchronous native call, and after an endpoint
+ transition it can sit there for minutes — measured on Windows/WASAPI on
+ 2026-08-20: 61.7 s and 188.3 s, both from this watchdog. Every one of
+ those seconds froze the SINGLE asyncio loop this process has, which is
+ also the loop serving the desktop window's HTTP: the socket kept
+ accepting, nothing was answered, and a window opening in that gap stayed
+ blank with no error (see jarvis/ui/window_watchdog.py).
+
+ The dead stream's shutdown is not worth that. It runs in a worker
+ thread; the coroutine waits a short grace so the normal case keeps its
+ ordering, then moves on and lets the thread finish alone.
+ """
+ task = asyncio.create_task(asyncio.to_thread(cls._discard_stream, stream))
+ done, _pending = await asyncio.wait({task}, timeout=cls._DISCARD_GRACE_S)
+ if done:
+ return
+ # Left running on purpose. Consume the eventual result so a failure in
+ # a stream we already gave up on cannot surface as a stray "task
+ # exception was never retrieved".
+ task.add_done_callback(lambda t: t.exception() if not t.cancelled() else None)
+ _log.warning(
+ "Mic discard is still blocked after {:.0f}s (native close wedged) — "
+ "continuing without it; the event loop stays responsive.",
+ cls._DISCARD_GRACE_S,
+ )
+
@staticmethod
def _discard_stream(stream: Any) -> None:
"""Abort-then-close a (possibly wedged) native stream, never raising.
@@ -1119,6 +1154,9 @@ class MicrophoneCapture:
Abort discards the dead native stream immediately; CoreAudio can
leave ``stop()`` blocked for minutes after an endpoint transition.
The ``stop`` fallback keeps lightweight test doubles compatible.
+
+ Blocking by nature — callers ON the event loop must go through
+ :meth:`_discard_stream_off_loop`.
"""
discard_method = "abort"
try:
@@ -1162,18 +1200,18 @@ class MicrophoneCapture:
except Exception as exc: # noqa: BLE001
_log.debug("Mic-Watchdog cleanup swallow: {}", exc)
if self._stream is not None:
- try:
- self._stream.stop()
- self._stream.close()
- except Exception as exc: # noqa: BLE001
- _log.debug("Mic close swallow: {}", exc)
- finally:
- self._stream = None
- _log.info(
- "Mic closed (drops={}, restarts={}).",
- self._drops,
- self._restart_count,
- )
+ stream, self._stream = self._stream, None
+ # Same reason as the watchdog path: closing a microphone is a
+ # native call that can wedge, and every capture teardown runs on
+ # the loop that serves the window. The handover happens between
+ # wake and session on every single turn, so a freeze here is felt
+ # more often than anywhere else.
+ await self._discard_stream_off_loop(stream)
+ _log.info(
+ "Mic closed (drops={}, restarts={}).",
+ self._drops,
+ self._restart_count,
+ )
async def stream(self) -> AsyncIterator[AudioChunk]:
"""Yield audio chunks until __aexit__ is called.
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.py
index 5ab8e25734..63ee1a420c 100644
--- a/jarvis/ui/desktop_app.py
+++ b/jarvis/ui/desktop_app.py
@@ -1407,6 +1407,10 @@ class DesktopApp:
# _run_backend). The real app is delegated to it once built.
self._bootstrap: Any = None
self._window: Any = None
+ # Guards the window against staying blank in silence — a page that never
+ # arrives leaves nothing behind that could report it (see
+ # jarvis/ui/window_watchdog.py). Armed right after create_window.
+ self._blank_watchdog: Any = None
# Detached solo windows keyed by view id (see DETACHABLE_VIEWS). Only
# touched from worker threads (route handlers via asyncio.to_thread,
# pywebview event hooks, the tray bridge) — never from the asyncio
@@ -4352,9 +4356,26 @@ class DesktopApp:
def _window_background(self) -> str:
"""The theme-correct frame color, same derivation as the main window."""
- from jarvis.ui.theme import configured_theme, window_background
+ from jarvis.ui.theme import window_background
- return window_background(configured_theme(getattr(self, "cfg", None)))
+ return window_background(self._configured_theme())
+
+ def _configured_theme(self) -> str:
+ """The user's ``[ui] theme`` value — may still be ``system``."""
+ from jarvis.ui.theme import configured_theme
+
+ return configured_theme(getattr(self, "cfg", None))
+
+ def _resolved_theme(self) -> str:
+ """``dark`` or ``light`` — ``system`` resolved against the desktop.
+
+ The blank-window explanation page paints itself from this, so it lands
+ inside the native frame as one surface rather than a black rectangle in
+ a paper-white window.
+ """
+ from jarvis.ui.theme import resolve_theme
+
+ return resolve_theme(self._configured_theme())
def open_detached_window(self, view: str) -> dict[str, Any]:
"""Open ``view`` in its own solo window — MUST run on a worker thread.
@@ -4586,6 +4607,12 @@ class DesktopApp:
"""
self._window = None
self._window_visible = False
+ # getattr: this hook is also exercised against the minimal fakes the
+ # window-lifecycle tests build, which carry only the attributes the
+ # contract under test needs.
+ watchdog = getattr(self, "_blank_watchdog", None)
+ if watchdog is not None:
+ watchdog.detach()
def _ensure_main_window(self) -> None:
"""Show the main window, recreating it if it was closed — tray thread.
@@ -4608,6 +4635,9 @@ class DesktopApp:
)
self._hook_main_window_lifecycle()
self._window_visible = True
+ # A window reopened from the tray can arrive blank for exactly the
+ # same reasons as the boot one, so it gets the same guard.
+ self._arm_blank_window_watchdog(self._window)
except Exception: # noqa: BLE001
logger.opt(exception=True).warning(
"Reopening the main window failed — it stays closed."
@@ -4757,6 +4787,74 @@ class DesktopApp:
time.sleep(0.25)
return False
+ def _backend_healthy(self) -> bool:
+ """One quick ``/api/health`` probe — is the server answering right now?
+
+ Deliberately single-shot and short: the blank-window watchdog asks once
+ a second and needs the ANSWER, including the honest "no" while the loop
+ is frozen. ``_wait_for_backend``'s poll and the lock holder's four-try
+ probe both mean something else.
+ """
+ try:
+ import httpx
+
+ r = httpx.get(
+ f"http://127.0.0.1:{self.cfg.ui.admin_api_port}/api/health",
+ timeout=1.0,
+ )
+ return bool(r.status_code == 200)
+ except Exception: # noqa: BLE001 — an unreachable server is the answer
+ return False
+
+ def _backend_thread_alive(self) -> bool:
+ """Is the thread that serves this window still running?
+
+ A dead thread is the one blank-window cause a reload cannot fix (a lost
+ dependency mid-boot killed it on 2026-08-20), so the watchdog needs it
+ told apart from a merely busy one. Unknown counts as alive: guessing
+ "dead" would put a wrong explanation on a window that is only slow.
+ """
+ thread = self._backend_thread
+ return True if thread is None else bool(thread.is_alive())
+
+ def _arm_blank_window_watchdog(self, window: Any) -> None:
+ """Guard *window* against staying blank without a word — never raises.
+
+ Every path that creates the MAIN window funnels through here (boot and
+ the tray's reopen), so both are covered by one guard with one policy.
+ """
+ try:
+ from jarvis.ui.window_watchdog import BlankWindowWatchdog
+
+ if self._blank_watchdog is not None:
+ self._blank_watchdog.attach(window)
+ return
+ self._blank_watchdog = BlankWindowWatchdog(
+ window=window,
+ url=self._url(),
+ health_probe=self._backend_healthy,
+ backend_alive=self._backend_thread_alive,
+ failure_detail=self._blank_window_detail,
+ theme=self._resolved_theme,
+ )
+ self._blank_watchdog.start()
+ except Exception: # noqa: BLE001
+ from loguru import logger
+
+ logger.opt(exception=True).warning(
+ "Blank-window watchdog could not be armed — the window is "
+ "unguarded for this session."
+ )
+
+ def _blank_window_detail(self) -> str:
+ """The one technical line the explanation page shows, or nothing.
+
+ Only a captured boot exception is worth putting in front of the user;
+ without one, a guessed sentence would be noise on top of a failure.
+ """
+ exc = getattr(self, "_backend_boot_error", None)
+ return f"{type(exc).__name__}: {exc}" if exc is not None else ""
+
# ---- Main entry point ------------------------------------------------------
def run(self) -> int:
@@ -4881,6 +4979,11 @@ class DesktopApp:
# backend genuinely cannot start, and behave identically otherwise.
return self._degrade_to_browser_ui(exc)
self._window_visible = True
+ # From here the window is the user's only surface. If it never receives
+ # a page — a frozen loop, a dead backend thread, a view that did not
+ # navigate — nothing INSIDE it can report that, because there is no
+ # inside. This guard lives outside and heals or explains it.
+ self._arm_blank_window_watchdog(self._window)
# The X quits (when this is the last window) — see _on_window_closing —
# and the closed hook nulls the handle so detached windows can outlive
@@ -5432,6 +5535,14 @@ class DesktopApp:
self._shutdown_done = True
self._window_visible = False
+ # A shutting-down backend fails every health probe by design; without
+ # this the guard would read the teardown as a blank-window incident and
+ # paint an explanation over a window that is on its way out.
+ watchdog = getattr(self, "_blank_watchdog", None)
+ if watchdog is not None:
+ with suppress(Exception):
+ watchdog.stop()
+
# Hide the orb overlay first — the event path (pipeline → supervisor
# → bus → OrbBridge) doesn't reliably reach the bridge anymore during a
# hard loop stop. A direct hide() guarantees the desktop icon
diff --git a/jarvis/ui/window_watchdog.py b/jarvis/ui/window_watchdog.py
new file mode 100644
index 0000000000..8ae34e650f
--- /dev/null
+++ b/jarvis/ui/window_watchdog.py
@@ -0,0 +1,632 @@
+"""The desktop window's last line of defence: never stay blank in silence.
+
+``frontend/index.html`` already carries a watchdog, and it handles the case it
+was written for — the page loaded, then the app above it died. It cannot handle
+the case below it: a window in which **no page ever arrived**. Then there is no
+script to run, no ``#root`` to write into, and no splash. What the user gets is
+the native frame filled with the theme's ground colour, a title bar, and no way
+back except killing the app (maintainer screenshots 2026-08-18 → 2026-08-20).
+
+That state is reachable without anything being permanently broken, which is why
+it kept coming back:
+
+* **The server accepted but did not answer.** The whole backend — HTTP included
+ — runs on one asyncio loop. Any synchronous call on that loop freezes the
+ server without closing the socket, so the navigation gets no bytes and no
+ error either; WebView2 keeps waiting and paints nothing. Measured on the
+ maintainer's box the same day: 15 s, 20 s, 42 s, 61 s and 188 s of loop
+ blockage, the long ones inside PortAudio's ``Pa_CloseStream`` during a
+ microphone restart. ``_wait_for_backend`` had seen a healthy ``/api/health``
+ moments earlier, so the window was already open when the freeze began.
+* **The backend thread died after the port was up.** On 2026-08-20 13:45 an
+ ``import uvicorn`` lost its ``click`` dependency mid-boot; the thread died and
+ the window kept its ground colour for the rest of the process.
+* **The web view itself never navigated** — a broken profile, a backend that
+ could not start.
+
+So the watchdog goes where it still runs in all three: the window process,
+outside the loop it is watching. It asks the window what it is showing, waits
+out a slow boot, reloads when the server comes back, and — when it cannot fix
+it — puts the reason ON the window with a button, in the user's language. The
+window heals itself first and explains itself second; a dark rectangle with no
+words is the actual bug, whatever caused it.
+
+The policy is a pure state machine (:class:`BlankWindowPolicy`) so every branch
+is unit-testable without pywebview, a browser, or a clock.
+"""
+
+from __future__ import annotations
+
+import queue
+import threading
+import time
+from collections.abc import Callable
+from dataclasses import dataclass, field
+from enum import Enum
+from typing import Any, Literal
+
+from loguru import logger
+
+#: How often the window is asked what it is showing.
+POLL_S = 1.0
+
+#: How long a window may show nothing before that counts as a failure. A cold
+#: WebView2 on a busy machine needs several seconds before it paints the boot
+#: splash, and the splash itself is the proof that the page arrived — so this
+#: only has to outlast browser start-up, not bundle loading (which the page's
+#: own watchdog owns once it is running).
+FIRST_PAINT_GRACE_S = 25.0
+
+#: After a reload, the same grace applies again before judging the result.
+RELOAD_SETTLE_S = 25.0
+
+#: Automatic reloads per incident. Three is enough to ride out a long loop
+#: freeze; beyond that a reload is not the answer and the window says so.
+RELOAD_BUDGET = 3
+
+#: How long a silent server is tolerated before the window explains itself. The
+#: watchdog keeps watching afterwards and still reloads when the server returns,
+#: so this bounds the silence the user sees, not the recovery.
+SILENT_PATIENCE_S = 45.0
+
+#: What the window is showing.
+#:
+#: ``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"]
+
+#: 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 —
+#: whether React has mounted yet or not.
+PAGE_STATE_JS = (
+ "(function(){try{"
+ "if(window.__jarvisWatchdogNotice)return 'notice';"
+ "return document.getElementById('root')?'up':'blank';"
+ "}catch(e){return 'blank';}})()"
+)
+
+
+class BlankReason(Enum):
+ """Why a window is blank — each one is a different sentence to the user.
+
+ The ``value`` doubles as the key into the page's text table, so a new
+ reason cannot be added without a sentence to go with it.
+ """
+
+ #: The backend thread is gone; nothing will serve this window again.
+ BACKEND_DEAD = "backend_dead"
+ #: The thread lives but the server does not answer (blocked loop, or dead
+ #: listener). Recoverable: it usually comes back.
+ BACKEND_SILENT = "backend_silent"
+ #: The server answers, yet the window has no page — the web view did not
+ #: navigate, or lost what it had.
+ VIEW_EMPTY = "view_empty"
+
+
+class Action(Enum):
+ """What the watchdog does with this observation."""
+
+ WAIT = "wait"
+ RELOAD = "reload"
+ EXPLAIN = "explain"
+
+
+@dataclass(frozen=True, slots=True)
+class Observation:
+ """Everything one decision is made from."""
+
+ page: PageState
+ backend_alive: bool
+ server_healthy: bool
+ now: float
+
+
+@dataclass(frozen=True, slots=True)
+class Verdict:
+ """A decision plus the reason to show, when there is one."""
+
+ action: Action
+ reason: BlankReason | None = None
+
+
+class BlankWindowPolicy:
+ """Decides — from observations alone — when to wait, reload, or explain.
+
+ Kept free of threads, pywebview and wall-clock time so the awkward paths
+ (a freeze that outlasts the reload budget, a server that returns after the
+ explanation was shown) are ordinary unit tests.
+ """
+
+ def __init__(
+ self,
+ *,
+ grace_s: float = FIRST_PAINT_GRACE_S,
+ settle_s: float = RELOAD_SETTLE_S,
+ reload_budget: int = RELOAD_BUDGET,
+ silent_patience_s: float = SILENT_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._reloads_left = reload_budget
+ self._deadline: float | None = None
+ self._blank_since: float | None = None
+ self._explained: BlankReason | None = None
+ self._was_healthy = True
+
+ def decide(self, obs: Observation) -> Verdict:
+ if self._deadline is None:
+ self._deadline = obs.now + self._grace_s
+
+ if obs.page == "up":
+ # A live page: hand over to the page's own watchdog and re-arm, so a
+ # window that goes blank LATER in the same session is caught again
+ # with a full budget.
+ self._reloads_left = self._budget
+ self._deadline = obs.now + self._grace_s
+ self._blank_since = None
+ self._explained = None
+ self._was_healthy = obs.server_healthy
+ return Verdict(Action.WAIT)
+
+ if self._blank_since is None:
+ # The grace measures how long the window has been EMPTY, not how
+ # long ago it last held a page. A window that blanks after an hour
+ # of use gets the same patience as one at boot — and an in-flight
+ # navigation (which is briefly document-less) is not cut short.
+ self._blank_since = obs.now
+ self._deadline = obs.now + self._grace_s
+
+ # A backend thread that died takes every recovery with it: reloading
+ # would only refill the same empty window. Say it once, then stay quiet.
+ if not obs.backend_alive:
+ return self._explain_once(BlankReason.BACKEND_DEAD)
+
+ # An outage that just ended is a new event, not a repeat of the one the
+ # budget was spent on — so it always buys one more attempt. Without
+ # this, a window whose reloads were used up during a long freeze would
+ # sit on its explanation page while the server was healthy again.
+ if obs.server_healthy and not self._was_healthy:
+ self._reloads_left = max(self._reloads_left, 1)
+ self._deadline = min(self._deadline, obs.now)
+ self._was_healthy = obs.server_healthy
+
+ if obs.now < self._deadline:
+ return Verdict(Action.WAIT)
+
+ if not obs.server_healthy:
+ # A blocked loop is not a broken app — wait it out, but do not let
+ # the user sit in front of a wordless window forever. The
+ # explanation is already up in the ``notice`` case, so there is
+ # nothing left to say until something changes.
+ if obs.page != "notice" and obs.now - self._blank_since >= self._silent_patience_s:
+ return self._explain_once(BlankReason.BACKEND_SILENT)
+ return Verdict(Action.WAIT)
+
+ if self._reloads_left > 0:
+ self._reloads_left -= 1
+ self._arm_after_reload(obs.now)
+ return Verdict(Action.RELOAD)
+
+ # Out of attempts. The window keeps its explanation and the button on
+ # it; the watchdog keeps watching, so the next recovery still heals it.
+ if obs.page == "notice":
+ return Verdict(Action.WAIT)
+ return self._explain_once(BlankReason.VIEW_EMPTY)
+
+ # ---- internals ---------------------------------------------------------
+
+ def _arm_after_reload(self, now: float) -> None:
+ self._deadline = now + self._settle_s
+ self._blank_since = now
+ self._explained = None
+
+ def note_action_failed(self, action: Action) -> None:
+ """The window refused *action* — so it did not happen; undo the cost.
+
+ pywebview raises on a window that is created but whose GUI loop has not
+ started yet, which is exactly the window this guard is armed on (it is
+ started right after ``create_window``, because a failure BEFORE
+ ``webview.start`` is one of the cases it exists for). An attempt that
+ never reached the window must cost neither the explanation nor a slot
+ from the reload budget — otherwise the guard would spend itself on a
+ window that was not there to be fixed.
+ """
+ self._explained = None
+ if action is Action.RELOAD:
+ self._reloads_left += 1
+ if self._blank_since is not None:
+ self._deadline = self._blank_since
+
+ def _explain_once(self, reason: BlankReason) -> Verdict:
+ """Write the explanation the first time; afterwards keep watching.
+
+ Re-rendering the same page every second would fight the user's cursor
+ and hide that nothing changed, so only the transition is an action.
+ """
+ if self._explained == reason:
+ return Verdict(Action.WAIT, reason)
+ self._explained = reason
+ return Verdict(Action.EXPLAIN, reason)
+
+
+# ---------------------------------------------------------------------------
+# The explanation page
+# ---------------------------------------------------------------------------
+
+#: One entry per reason per language. German and Spanish are product surface
+#: (AGENTS.md §1): this page is shown TO the user, and it cannot reach the
+#: bundle's i18n — the bundle is exactly what failed to load. The language is
+#: picked in the page from ``navigator.language``, the same way
+#: ``frontend/index.html`` picks it, so both blank-window paths speak alike.
+_TEXTS: dict[str, dict[str, str]] = {
+ "en": {
+ "title": "The window stayed empty.",
+ "backend_dead": (
+ "Personal Jarvis is running, but the part that serves this window "
+ "has stopped. Restarting the app is the way back."
+ ),
+ "backend_silent": (
+ "Personal Jarvis is busy and is not answering this window yet. "
+ "It reloads by itself as soon as it answers again."
+ ),
+ "view_empty": ("Personal Jarvis is answering, but the window did not load its page."),
+ "button": "Reload",
+ "retrying": "Retrying…",
+ },
+ "de": {
+ # i18n-allow: product surface, no bundle available here.
+ "title": "Das Fenster ist leer geblieben.",
+ "backend_dead": (
+ "Personal Jarvis läuft, aber der Teil, der dieses Fenster "
+ "bedient, ist gestoppt. Ein Neustart der App hilft."
+ ),
+ "backend_silent": (
+ "Personal Jarvis ist beschäftigt und antwortet diesem Fenster "
+ "noch nicht. Es lädt von selbst neu, sobald wieder Antwort kommt."
+ ),
+ "view_empty": (
+ "Personal Jarvis antwortet, aber das Fenster hat seine Seite nicht geladen."
+ ),
+ "button": "Neu laden",
+ "retrying": "Neuer Versuch …",
+ },
+ "es": {
+ # i18n-allow: product surface, no bundle available here.
+ "title": "La ventana se quedó vacía.",
+ "backend_dead": (
+ "Personal Jarvis está en marcha, pero la parte que sirve esta "
+ "ventana se ha detenido. Reiniciar la aplicación es la salida."
+ ),
+ "backend_silent": (
+ "Personal Jarvis está ocupado y aún no responde a esta ventana. "
+ "Se recarga solo en cuanto vuelva a responder."
+ ),
+ "view_empty": ("Personal Jarvis responde, pero la ventana no cargó su página."),
+ "button": "Recargar",
+ "retrying": "Reintentando…",
+ },
+}
+
+
+def _js(value: Any) -> str:
+ """A Python value as a JS literal that is safe inside a ``<script>`` block.
+
+ ``json.dumps`` alone is not: it leaves ``</script>`` intact, and the detail
+ string this page prints comes from an exception message — arbitrary text
+ that must never be able to close the tag it lives in. The three escapes
+ below are the standard set for JSON embedded in HTML.
+ """
+ import json
+
+ return (
+ json.dumps(value, ensure_ascii=False)
+ .replace("</", "<\\/")
+ .replace("\u2028", "\\u2028")
+ .replace("\u2029", "\\u2029")
+ )
+
+
+def render_notice(
+ *,
+ reason: BlankReason,
+ url: str,
+ detail: str = "",
+ theme: str = "dark",
+) -> str:
+ """The page that replaces a blank window: what happened, and a way out.
+
+ Carries its own colours (from the same table the native frame is painted
+ from) because there is no stylesheet to inherit — a hardcoded dark page
+ would be a black rectangle inside a paper-white frame.
+ """
+ from jarvis.ui.theme import (
+ HOLDING_PAGE_FOREGROUND,
+ HOLDING_PAGE_MUTED,
+ WINDOW_BACKGROUND,
+ )
+
+ key = theme if theme in WINDOW_BACKGROUND else "dark"
+ bg = WINDOW_BACKGROUND[key]
+ fg = HOLDING_PAGE_FOREGROUND[key]
+ muted = HOLDING_PAGE_MUTED[key]
+
+ return (
+ '<!doctype html><html><head><meta charset="utf-8">'
+ f'<meta name="color-scheme" content="{key}">'
+ "<style>"
+ f"html,body{{margin:0;height:100%;background:{bg};color:{fg};"
+ "font-family:ui-sans-serif,system-ui,-apple-system,Segoe UI,sans-serif;"
+ "display:flex;align-items:center;justify-content:center}"
+ "main{text-align:center;max-width:52ch;padding:24px}"
+ "h1{font-weight:600;font-size:16px;margin:0 0 10px;letter-spacing:.02em}"
+ f"p{{margin:0 0 8px;color:{muted};font-size:13px;line-height:1.55}}"
+ f"code{{color:{muted};font-size:12px;word-break:break-word}}"
+ f"button{{margin-top:14px;padding:7px 16px;font:inherit;font-size:13px;"
+ f"cursor:pointer;color:{fg};background:transparent;"
+ f"border:1px solid {muted};border-radius:4px}}"
+ "</style></head><body><main>"
+ '<h1 id="t"></h1><p id="w"></p><p><code id="d"></code></p>'
+ '<button type="button" id="b"></button>'
+ "</main><script>"
+ # The marker the watchdog reads back, so it knows its own page and does
+ # not mistake it for a blank window (which would reload it in a loop).
+ "window.__jarvisWatchdogNotice=1;"
+ f"var T={_js(_TEXTS)};"
+ f"var R={_js(reason.value)};"
+ f"var U={_js(url)};"
+ f"var D={_js(detail)};"
+ "var l=(navigator.language||'en').slice(0,2);"
+ "var t=T[l]||T.en;"
+ "document.getElementById('t').textContent=t.title;"
+ "document.getElementById('w').textContent=t[R]||t.view_empty;"
+ "document.getElementById('d').textContent=D;"
+ "var b=document.getElementById('b');"
+ "b.textContent=t.button;"
+ "b.onclick=function(){go();};"
+ "function go(){b.textContent=t.retrying;b.disabled=true;location.href=U;}"
+ # The page returns by itself. This is not a duplicate of the watchdog's
+ # reload — it is the RELIABLE one: navigating from inside the document
+ # works on a window whose earlier navigation hung, where pywebview's
+ # load_url is accepted and then does nothing (measured live
+ # 2026-08-20). The watchdog gets the page in; the page gets itself out.
+ #
+ # ``no-cors`` because this document was written straight into the view
+ # and has no origin the server would answer a CORS preflight for: an
+ # opaque response still proves the server is answering, which is all
+ # this asks.
+ "var tries=0;"
+ "var timer=setInterval(function(){"
+ "if(tries++>600){clearInterval(timer);return;}"
+ "fetch(U,{mode:'no-cors',cache:'no-store'}).then(function(){"
+ "clearInterval(timer);go();}).catch(function(){});"
+ "},2000);"
+ "</script></body></html>"
+ )
+
+
+# ---------------------------------------------------------------------------
+# The watchdog thread
+# ---------------------------------------------------------------------------
+
+
+@dataclass
+class _Slot:
+ """One in-flight window call and its outcome."""
+
+ done: threading.Event = field(default_factory=threading.Event)
+ value: Any = None
+ error: BaseException | None = None
+
+
+class _WindowCaller:
+ """Calls into pywebview from one worker thread, with a deadline.
+
+ Necessary because pywebview does not merely *raise* on a window that is not
+ ready: before ``webview.start`` has run its GUI loop, ``evaluate_js``
+ BLOCKS, waiting for a ``shown`` event that a window stuck mid-navigation
+ never fires. Found live on 2026-08-20 — the watchdog thread froze on its
+ very first probe and never reported anything. A guard that can be frozen by
+ the thing it is guarding is not a guard.
+
+ One worker, never more. While a call is wedged, further calls are refused
+ instead of queueing behind it or getting a thread each; the wedged thread is
+ left alone (it sits in a native call nobody can cancel) and the caller
+ becomes usable again the moment it returns.
+ """
+
+ def __init__(self, *, timeout_s: float = 3.0) -> None:
+ self._timeout_s = timeout_s
+ self._work: queue.Queue[tuple[Callable[[], Any], _Slot]] = queue.Queue()
+ self._lock = threading.Lock()
+ self._inflight = 0
+ threading.Thread(target=self._run, name="blank-window-caller", daemon=True).start()
+
+ def call(self, fn: Callable[[], Any]) -> tuple[bool, Any]:
+ """Run *fn* on the worker. Returns ``(answered, result)``.
+
+ ``answered`` is False when the call raised, timed out, or was refused
+ because an earlier one is still wedged — to this guard all three mean
+ "the window did not respond", which is itself the symptom it acts on.
+ """
+ with self._lock:
+ if self._inflight:
+ return False, None
+ self._inflight += 1
+ slot = _Slot()
+ self._work.put((fn, slot))
+ if not slot.done.wait(self._timeout_s):
+ return False, None
+ return slot.error is None, slot.value
+
+ def _run(self) -> None:
+ while True:
+ fn, slot = self._work.get()
+ try:
+ slot.value = fn()
+ except Exception as exc: # noqa: BLE001 — reported, never raised on
+ slot.error = exc
+ finally:
+ slot.done.set()
+ with self._lock:
+ self._inflight -= 1
+
+
+class BlankWindowWatchdog:
+ """Runs :class:`BlankWindowPolicy` against a live pywebview window.
+
+ Its own daemon thread on purpose: the loop it is watching is the one that
+ freezes, and the GUI thread is busy being a window. Every call into
+ pywebview is guarded — a watchdog that raises has failed at the one job it
+ has, which is to be there when other things break.
+ """
+
+ def __init__(
+ self,
+ *,
+ window: Any,
+ url: str,
+ health_probe: Callable[[], bool],
+ backend_alive: Callable[[], bool],
+ failure_detail: Callable[[], str] | None = None,
+ theme: Callable[[], str] | None = None,
+ policy: BlankWindowPolicy | None = None,
+ poll_s: float = POLL_S,
+ caller: _WindowCaller | None = None,
+ action_caller: _WindowCaller | None = None,
+ ) -> None:
+ self._window = window
+ self._url = url
+ self._health_probe = health_probe
+ self._backend_alive = backend_alive
+ self._failure_detail = failure_detail or (lambda: "")
+ self._theme = theme or (lambda: "dark")
+ self._policy = policy or BlankWindowPolicy()
+ self._poll_s = poll_s
+ # Two callers, not one. pywebview's API waits up to 20 s on an internal
+ # event before it raises, and on a blank window the state probe waits
+ # out every one of those 20 s (``evaluate_js`` gates on ``loaded``,
+ # which a hung navigation never fires). Sharing one worker with the
+ # probe therefore starved the FIX: measured live 2026-08-20, 33
+ # consecutive attempts to write the explanation were dropped because
+ # the worker was always mid-probe. The repair must never queue behind
+ # the diagnosis.
+ self._caller = caller or _WindowCaller()
+ self._action_caller = action_caller or _WindowCaller()
+ self._stop = threading.Event()
+ self._thread: threading.Thread | None = None
+
+ def start(self) -> None:
+ if self._thread is not None:
+ return
+ self._thread = threading.Thread(target=self._run, name="blank-window-watchdog", daemon=True)
+ self._thread.start()
+
+ def stop(self) -> None:
+ self._stop.set()
+
+ def attach(self, window: Any) -> None:
+ """Point the watchdog at a newly created main window.
+
+ The tray can reopen a main window after the first one was closed
+ (``_ensure_main_window``); the replacement needs the same guard, and a
+ second thread would fight the first one over the same policy.
+ """
+ self._window = window
+ self._policy = BlankWindowPolicy()
+
+ def detach(self) -> None:
+ """Stop watching — the window is gone (closed, or being destroyed).
+
+ Questioning a destroyed window is at best noise and at worst a call
+ into a dead native handle, and "no window" is not a blank window.
+ """
+ self._window = None
+
+ # ---- the loop ----------------------------------------------------------
+
+ def _run(self) -> None:
+ while not self._stop.wait(self._poll_s):
+ window = self._window
+ if window is None:
+ continue
+ try:
+ verdict = self._policy.decide(
+ Observation(
+ page=self._page_state(window),
+ backend_alive=self._safe(self._backend_alive, default=True),
+ server_healthy=self._safe(self._health_probe, default=False),
+ now=time.monotonic(),
+ )
+ )
+ self._apply(window, verdict)
+ except Exception: # noqa: BLE001 — never let the guard be the crash
+ logger.opt(exception=True).debug("Blank-window watchdog tick failed.")
+
+ def _apply(self, window: Any, verdict: Verdict) -> bool:
+ """Carry out *verdict*. Returns whether the window accepted it.
+
+ A window whose GUI loop has not started yet refuses every call — by
+ raising, or by never returning — and that is a normal moment in this
+ guard's life: it is armed right after ``create_window`` and before
+ ``webview.start``, because a window that never navigates is one of the
+ failures it exists for. Either refusal is reported back so the policy
+ retries instead of counting it as done.
+ """
+ detail = ""
+ if verdict.action is Action.RELOAD:
+ answered, _ = self._action_caller.call(lambda: window.load_url(self._url))
+ elif verdict.action is Action.EXPLAIN and verdict.reason is not None:
+ detail = self._safe(self._failure_detail, default="")
+ html = render_notice(
+ reason=verdict.reason,
+ url=self._url,
+ detail=detail,
+ theme=self._safe(self._theme, default="dark"),
+ )
+ answered, _ = self._action_caller.call(lambda: window.load_html(html))
+ else:
+ return True
+ if not answered:
+ logger.debug(
+ "Blank-window watchdog: the window did not accept {}.",
+ verdict.action.value,
+ )
+ self._policy.note_action_failed(verdict.action)
+ 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:
+ logger.info("Desktop window is blank — reloading it (the server answers again).")
+ elif verdict.reason is not None:
+ logger.warning(
+ "Desktop window stayed blank ({}) — the window now says so "
+ "instead of showing nothing.{}",
+ verdict.reason.value,
+ f" Detail: {detail}" if detail else "",
+ )
+ return True
+
+ def _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.
+ """
+ answered, value = self._caller.call(lambda: window.evaluate_js(PAGE_STATE_JS))
+ if answered and value in ("up", "notice"):
+ return value # type: ignore[return-value]
+ return "blank"
+
+ @staticmethod
+ def _safe(probe: Callable[[], Any], *, default: Any) -> Any:
+ """Run a caller-supplied probe; its failure must not stop the guard."""
+ try:
+ return probe()
+ except Exception: # noqa: BLE001
+ return default
diff --git a/tests/unit/audio/test_capture_discard_off_loop.py b/tests/unit/audio/test_capture_discard_off_loop.py
new file mode 100644
index 0000000000..0516203f17
--- /dev/null
+++ b/tests/unit/audio/test_capture_discard_off_loop.py
@@ -0,0 +1,119 @@
+"""Closing a microphone must never freeze the process's only event loop.
+
+``Pa_CloseStream`` is a synchronous native call. After an audio endpoint
+transition — a headset unplugged, a monitor's audio device appearing — it can
+sit inside PortAudio for minutes. On 2026-08-20 the maintainer's box logged
+61.7 s and 188.3 s of it, both from the mic stall watchdog, and one 15 s from a
+capture teardown.
+
+Every one of those seconds froze the SINGLE asyncio loop this process has —
+which also serves the desktop window over HTTP. The socket kept accepting and
+nothing was answered, so a window opening in that gap received no bytes and no
+error, and stayed blank with no explanation (jarvis/ui/window_watchdog.py now
+catches the symptom; this is the cause).
+
+So the dead stream is shut down in a worker thread. The coroutine waits a short
+grace — the ordinary close is milliseconds and keeps its ordering — and then
+moves on. What must hold is that the loop keeps running throughout.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import threading
+import time
+
+import pytest
+
+from jarvis.audio.capture import MicrophoneCapture
+
+
+class _WedgedStream:
+ """A stream whose native close blocks — the endpoint-transition case."""
+
+ def __init__(self, block_s: float) -> None:
+ self._block_s = block_s
+ self.aborted = threading.Event()
+ self.closed = threading.Event()
+
+ def abort(self) -> None:
+ self.aborted.set()
+
+ def close(self) -> None:
+ time.sleep(self._block_s)
+ self.closed.set()
+
+
+class _QuickStream:
+ def __init__(self) -> None:
+ self.calls: list[str] = []
+
+ def abort(self) -> None:
+ self.calls.append("abort")
+
+ def close(self) -> None:
+ self.calls.append("close")
+
+
+async def test_a_wedged_close_does_not_stall_the_loop(monkeypatch) -> None:
+ """The point of the whole change: other work keeps running during a freeze."""
+ monkeypatch.setattr(MicrophoneCapture, "_DISCARD_GRACE_S", 0.05)
+ stream = _WedgedStream(block_s=0.6)
+
+ ticks = 0
+
+ async def _heartbeat() -> None:
+ # Stands in for the HTTP server sharing this loop.
+ nonlocal ticks
+ for _ in range(20):
+ await asyncio.sleep(0.02)
+ ticks += 1
+
+ beat = asyncio.create_task(_heartbeat())
+ started = time.monotonic()
+ await MicrophoneCapture._discard_stream_off_loop(stream)
+ spent = time.monotonic() - started
+
+ assert spent < 0.4, "the coroutine waited out the wedged native close"
+ assert ticks > 0, "the loop was frozen while the stream was closing"
+ await beat
+ assert ticks == 20
+
+
+async def test_a_normal_close_keeps_its_ordering(monkeypatch) -> None:
+ """The common case must still complete before the caller moves on.
+
+ A new stream is opened immediately after; letting the old one linger on the
+ same device would trade a frozen loop for a device conflict.
+ """
+ monkeypatch.setattr(MicrophoneCapture, "_DISCARD_GRACE_S", 2.0)
+ stream = _QuickStream()
+ await MicrophoneCapture._discard_stream_off_loop(stream)
+ assert stream.calls == ["abort", "close"]
+
+
+async def test_the_abandoned_close_still_finishes_on_its_own(monkeypatch) -> None:
+ """Giving up waiting is not giving up closing — the handle is still released."""
+ monkeypatch.setattr(MicrophoneCapture, "_DISCARD_GRACE_S", 0.05)
+ stream = _WedgedStream(block_s=0.3)
+ await MicrophoneCapture._discard_stream_off_loop(stream)
+ assert not stream.closed.is_set()
+ assert stream.closed.wait(timeout=3.0), "the worker thread never finished the close"
+
+
+async def test_a_raising_close_is_swallowed_not_propagated(monkeypatch) -> None:
+ """A dead handle failing to close is expected — it must not kill the caller."""
+ monkeypatch.setattr(MicrophoneCapture, "_DISCARD_GRACE_S", 2.0)
+
+ class _Hostile:
+ def abort(self) -> None:
+ raise RuntimeError("device gone")
+
+ def close(self) -> None:
+ raise RuntimeError("device gone")
+
+ await MicrophoneCapture._discard_stream_off_loop(_Hostile())
diff --git a/tests/unit/ui/test_blank_window_watchdog.py b/tests/unit/ui/test_blank_window_watchdog.py
new file mode 100644
index 0000000000..828bb503b7
--- /dev/null
+++ b/tests/unit/ui/test_blank_window_watchdog.py
@@ -0,0 +1,405 @@
+"""A window that shows nothing must heal itself, or say why it cannot.
+
+The page's own watchdog (``frontend/index.html``) covers the case where a page
+loaded and then the app above it died. This one covers the case underneath: a
+window in which NO page ever arrived, where there is no script left to notice
+anything. The maintainer hit it repeatedly on 2026-08-18…20 — a titled window
+filled with the theme's ground colour and nothing else.
+
+Three ways in, all reproduced in the logs of a single day:
+
+* the single asyncio loop froze inside a native call (``Pa_CloseStream``,
+ 188.3 s measured) — the socket still accepted, nothing was answered, and the
+ navigation received no bytes and no error;
+* the backend thread died after the port was already up (a lost ``click``
+ dependency mid-boot, 13:45);
+* the web view never navigated at all.
+
+The first is recoverable and must heal without the user doing anything; the
+second never heals and must be said out loud; the third is worth one reload
+before it is said. These tests pin all three, plus the loops that must NOT
+happen (an explanation re-rendered every second, a reload storm).
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+
+from jarvis.ui.window_watchdog import (
+ Action,
+ BlankReason,
+ BlankWindowPolicy,
+ BlankWindowWatchdog,
+ Observation,
+ render_notice,
+)
+
+GRACE = 20.0
+SETTLE = 20.0
+PATIENCE = 40.0
+
+
+def _policy(**kw: Any) -> BlankWindowPolicy:
+ return BlankWindowPolicy(
+ grace_s=kw.pop("grace_s", GRACE),
+ settle_s=kw.pop("settle_s", SETTLE),
+ reload_budget=kw.pop("reload_budget", 3),
+ silent_patience_s=kw.pop("silent_patience_s", PATIENCE),
+ )
+
+
+def _obs(
+ now: float,
+ *,
+ page: str = "blank",
+ alive: bool = True,
+ healthy: bool = True,
+) -> Observation:
+ return Observation(
+ page=page, # type: ignore[arg-type]
+ backend_alive=alive,
+ server_healthy=healthy,
+ now=now,
+ )
+
+
+# --- a healthy window is left alone ----------------------------------------
+
+
+def test_a_loading_window_is_given_its_grace() -> None:
+ """A cold WebView paints nothing for a few seconds — that is not a failure."""
+ p = _policy()
+ for t in (0.0, 5.0, 19.0):
+ assert p.decide(_obs(t)).action is Action.WAIT
+
+
+def test_a_live_page_is_never_touched() -> None:
+ """Once our document is there, the page's own watchdog owns the problem."""
+ p = _policy()
+ for t in (0.0, 30.0, 300.0):
+ assert p.decide(_obs(t, page="up")).action is Action.WAIT
+
+
+def test_a_page_that_dies_later_gets_a_full_budget_again() -> None:
+ """A window blanking after an hour of use is a new incident, not a used-up one."""
+ p = _policy()
+ p.decide(_obs(0.0, page="up"))
+ for _ in range(3):
+ p.decide(_obs(0.0, page="up"))
+ # It goes blank at t=100 and the grace runs from there, not from boot.
+ assert p.decide(_obs(100.0)).action is Action.WAIT
+ assert p.decide(_obs(100.0 + GRACE + 1)).action is Action.RELOAD
+
+
+# --- the recoverable freeze -------------------------------------------------
+
+
+def test_a_frozen_server_is_waited_out_not_reloaded() -> None:
+ """Reloading into a frozen loop only wastes the budget — wait for the answer."""
+ p = _policy()
+ v = p.decide(_obs(GRACE + 1, healthy=False))
+ assert v.action is Action.WAIT
+
+
+def test_the_window_reloads_itself_when_the_server_answers_again() -> None:
+ """The 188 s freeze: the user does nothing and the UI comes back by itself."""
+ p = _policy()
+ p.decide(_obs(0.0))
+ assert p.decide(_obs(30.0, healthy=False)).action is Action.WAIT
+ assert p.decide(_obs(190.0, healthy=True)).action is Action.RELOAD
+
+
+def test_a_long_freeze_is_explained_before_it_ends() -> None:
+ """Silence has a limit: the window says what is happening rather than nothing."""
+ p = _policy()
+ p.decide(_obs(0.0))
+ assert p.decide(_obs(PATIENCE - 1, healthy=False)).action is Action.WAIT
+ v = p.decide(_obs(PATIENCE + 1, healthy=False))
+ assert v.action is Action.EXPLAIN
+ assert v.reason is BlankReason.BACKEND_SILENT
+
+
+def test_the_explanation_gives_way_to_the_real_ui_when_the_server_returns() -> None:
+ """The notice is a stand-in, not a dead end — recovery still wins."""
+ p = _policy()
+ p.decide(_obs(0.0))
+ v = p.decide(_obs(PATIENCE + 1, healthy=False))
+ assert v.action is Action.EXPLAIN
+ # The notice is up now, and the server comes back.
+ assert p.decide(_obs(PATIENCE + 3, page="notice", healthy=False)).action is Action.WAIT
+ assert p.decide(_obs(PATIENCE + 9, page="notice", healthy=True)).action is Action.RELOAD
+
+
+def test_a_reload_that_did_not_take_is_tried_again() -> None:
+ """Found live: ``load_url`` can be accepted and change nothing.
+
+ If one attempt were the whole recovery, the user would sit on the
+ explanation page with a healthy server behind it.
+ """
+ p = _policy(reload_budget=3)
+ p.decide(_obs(0.0))
+ assert p.decide(_obs(GRACE + 1, healthy=False)).action is Action.WAIT
+ # Server returns, first reload fires and does not take: still "notice".
+ assert p.decide(_obs(50.0, page="notice", healthy=True)).action is Action.RELOAD
+ assert p.decide(_obs(50.0 + SETTLE + 1, page="notice")).action is Action.RELOAD
+
+
+def test_a_recovery_buys_an_attempt_even_with_an_empty_budget() -> None:
+ """A freeze that outlasted the budget must not cost the window its recovery."""
+ p = _policy(reload_budget=1)
+ p.decide(_obs(0.0))
+ assert p.decide(_obs(GRACE + 1)).action is Action.RELOAD # budget spent
+ v = p.decide(_obs(100.0, page="notice", healthy=False))
+ assert v.action is Action.WAIT
+ assert p.decide(_obs(101.0, page="notice", healthy=True)).action is Action.RELOAD
+
+
+def test_the_notice_is_written_once_not_every_second() -> None:
+ """Re-rendering each tick would fight the cursor and hide that nothing changed."""
+ p = _policy()
+ first = p.decide(_obs(0.0, alive=False))
+ assert first.action is Action.EXPLAIN
+ for t in (1.0, 2.0, 3.0, 60.0):
+ assert p.decide(_obs(t, page="notice", alive=False)).action is Action.WAIT
+
+
+# --- the unrecoverable death ------------------------------------------------
+
+
+def test_a_dead_backend_thread_is_said_immediately_not_reloaded() -> None:
+ """Nothing will serve this window again; a reload would only refill it empty."""
+ p = _policy()
+ v = p.decide(_obs(0.0, alive=False))
+ assert v.action is Action.EXPLAIN
+ assert v.reason is BlankReason.BACKEND_DEAD
+
+
+def test_a_dead_backend_is_reported_even_during_the_grace_period() -> None:
+ """Waiting out a grace for a thread that is already gone only delays the truth."""
+ p = _policy()
+ assert p.decide(_obs(1.0, alive=False)).reason is BlankReason.BACKEND_DEAD
+
+
+# --- the empty view ---------------------------------------------------------
+
+
+def test_a_healthy_server_and_an_empty_window_earns_a_reload() -> None:
+ p = _policy()
+ p.decide(_obs(0.0))
+ assert p.decide(_obs(GRACE + 1)).action is Action.RELOAD
+
+
+def test_reloads_are_budgeted_then_the_window_explains_itself() -> None:
+ """No reload storm: three tries, then words."""
+ p = _policy(reload_budget=2)
+ t = 0.0
+ p.decide(_obs(t))
+ actions = []
+ for _ in range(3):
+ t += GRACE + 1
+ v = p.decide(_obs(t))
+ actions.append(v)
+ t += 0.1
+ assert [a.action for a in actions[:2]] == [Action.RELOAD, Action.RELOAD]
+ assert actions[2].action is Action.EXPLAIN
+ assert actions[2].reason is BlankReason.VIEW_EMPTY
+
+
+def test_a_reload_is_given_time_to_settle_before_the_next_one() -> None:
+ """Back-to-back reloads would out-race the browser they are trying to fix."""
+ p = _policy()
+ p.decide(_obs(0.0))
+ assert p.decide(_obs(GRACE + 1)).action is Action.RELOAD
+ assert p.decide(_obs(GRACE + 2)).action is Action.WAIT
+ assert p.decide(_obs(GRACE + SETTLE + 2)).action is Action.RELOAD
+
+
+# --- the explanation page ---------------------------------------------------
+
+
[email protected]("reason", list(BlankReason))
+def test_every_reason_renders_a_page_that_can_leave_itself(reason: BlankReason) -> None:
+ html = render_notice(reason=reason, url="http://127.0.0.1:47821", theme="dark")
+ # The marker the watchdog reads back, so its own page is never mistaken for
+ # a blank one and reloaded in a loop.
+ assert "__jarvisWatchdogNotice" in html
+ # The way out, and the reason, both present without a bundle.
+ assert "http://127.0.0.1:47821" in html
+ assert reason.value in html
+
+
+def test_the_page_brings_itself_back_without_being_clicked() -> None:
+ """The reliable half of the recovery, found the hard way.
+
+ ``load_url`` from the watchdog is accepted and then does nothing on a window
+ whose first navigation hung (measured live 2026-08-20). Navigating from
+ INSIDE the document works, so the page polls the server and returns by
+ itself; the button is for the impatient, not the mechanism.
+ """
+ html = render_notice(reason=BlankReason.BACKEND_SILENT, url="http://127.0.0.1:47821")
+ assert "setInterval" in html
+ assert "fetch(" in html
+ # no-cors: a page written straight into the view has no origin the server
+ # would grant CORS to, and an opaque response still proves it answers.
+ assert "no-cors" in html
+ assert "location.href=U" in html
+ # Bounded, so a machine left alone overnight is not polling forever.
+ assert "tries++>" in html
+
+
+def test_the_page_carries_the_users_theme_not_a_hardcoded_dark() -> None:
+ """A black rectangle inside a paper-white frame is its own bug report."""
+ from jarvis.ui.theme import WINDOW_BACKGROUND
+
+ light = render_notice(reason=BlankReason.VIEW_EMPTY, url="http://x", theme="light")
+ assert WINDOW_BACKGROUND["light"] in light
+ assert WINDOW_BACKGROUND["dark"] not in light
+
+
+def test_the_page_speaks_german_and_spanish_too() -> None:
+ """It cannot reach the bundle's i18n — the bundle is what failed to load."""
+ html = render_notice(reason=BlankReason.BACKEND_SILENT, url="http://x")
+ assert "Das Fenster ist leer geblieben." in html
+ assert "La ventana se quedó vacía." in html
+ assert "navigator.language" in html
+
+
+def test_a_detail_string_cannot_break_out_of_the_page() -> None:
+ """The detail comes from an exception message — it is data, not markup."""
+ html = render_notice(
+ reason=BlankReason.BACKEND_DEAD,
+ url="http://x",
+ detail='</script><script>alert("x")</script>',
+ )
+ assert "</script><script>alert" not in html
+
+
+# --- the thread around the policy -------------------------------------------
+
+
+class _FakeWindow:
+ def __init__(self, state: str = "blank") -> None:
+ self.state = state
+ self.loaded_urls: list[str] = []
+ self.loaded_html: list[str] = []
+ self.raise_on_eval = False
+
+ def evaluate_js(self, _js: str) -> str:
+ if self.raise_on_eval:
+ raise RuntimeError("no document")
+ return self.state
+
+ def load_url(self, url: str) -> None:
+ self.loaded_urls.append(url)
+
+ def load_html(self, html: str) -> None:
+ self.loaded_html.append(html)
+ self.state = "notice"
+
+
+def _watchdog(window: _FakeWindow, **kw: Any) -> BlankWindowWatchdog:
+ return BlankWindowWatchdog(
+ window=window,
+ url=kw.pop("url", "http://127.0.0.1:47821"),
+ health_probe=kw.pop("health_probe", lambda: True),
+ backend_alive=kw.pop("backend_alive", lambda: True),
+ failure_detail=kw.pop("failure_detail", lambda: ""),
+ theme=kw.pop("theme", lambda: "dark"),
+ **kw,
+ )
+
+
+def test_an_unanswerable_window_counts_as_blank() -> None:
+ """``evaluate_js`` raising and a view with no document look the same to a user."""
+ window = _FakeWindow()
+ window.raise_on_eval = True
+ wd = _watchdog(window)
+ assert wd._page_state(window) == "blank"
+
+
+def test_the_watchdog_reloads_the_configured_url() -> None:
+ window = _FakeWindow()
+ wd = _watchdog(window, url="http://127.0.0.1:1234")
+ wd._apply(window, wd._policy.decide(_obs(0.0))) # WAIT, still in grace
+ assert window.loaded_urls == []
+ from jarvis.ui.window_watchdog import Verdict
+
+ wd._apply(window, Verdict(Action.RELOAD))
+ assert window.loaded_urls == ["http://127.0.0.1:1234"]
+
+
+def test_the_watchdog_writes_the_detail_it_was_given() -> None:
+ window = _FakeWindow()
+ wd = _watchdog(window, failure_detail=lambda: "ModuleNotFoundError: click")
+ from jarvis.ui.window_watchdog import Verdict
+
+ wd._apply(window, Verdict(Action.EXPLAIN, BlankReason.BACKEND_DEAD))
+ assert window.loaded_html
+ assert "ModuleNotFoundError: click" in window.loaded_html[0]
+
+
+def test_a_window_that_is_not_there_yet_costs_nothing() -> None:
+ """Found live: pywebview raises until ``webview.start`` has run.
+
+ The guard is armed before that on purpose — a window that never navigates
+ is one of the failures it exists for — so a refused call must cost neither
+ the explanation nor a reload from the budget.
+ """
+
+ class _NotYet:
+ def evaluate_js(self, _js: str) -> str:
+ raise RuntimeError("Main window failed to start")
+
+ def load_url(self, _url: str) -> None:
+ raise RuntimeError("Main window failed to start")
+
+ def load_html(self, _html: str) -> None:
+ raise RuntimeError("Main window failed to start")
+
+ window = _NotYet()
+ wd = _watchdog(window, policy=_policy()) # type: ignore[arg-type]
+ from jarvis.ui.window_watchdog import Verdict
+
+ wd._policy.decide(_obs(0.0))
+ assert wd._apply(window, Verdict(Action.RELOAD)) is False
+ assert wd._apply(window, Verdict(Action.EXPLAIN, BlankReason.VIEW_EMPTY)) is False
+ # Budget untouched: once the window is real, all three reloads are still there.
+ real = _FakeWindow()
+ wd._window = real
+ for i in range(3):
+ v = wd._policy.decide(_obs(GRACE + 1 + i * (SETTLE + 1)))
+ assert v.action is Action.RELOAD, f"reload {i + 1} was already spent"
+
+
+def test_a_probe_that_raises_cannot_stop_the_guard() -> None:
+ """A watchdog that dies on a failing probe has failed at its only job."""
+
+ def _boom() -> bool:
+ raise RuntimeError("probe exploded")
+
+ window = _FakeWindow()
+ wd = _watchdog(window, health_probe=_boom, backend_alive=_boom)
+ assert wd._safe(_boom, default=False) is False
+ assert wd._safe(_boom, default=True) is True
+
+
+def test_a_closed_window_is_not_a_blank_window() -> None:
+ """After detach the guard has nothing to watch and must not paint anything."""
+ window = _FakeWindow()
+ wd = _watchdog(window)
+ wd.detach()
+ assert wd._window is None
+
+
+def test_attaching_a_reopened_window_starts_a_fresh_incident() -> None:
+ """The tray can reopen main; the replacement deserves its own full budget."""
+ window = _FakeWindow()
+ wd = _watchdog(window)
+ wd._policy.decide(_obs(0.0))
+ wd._policy.decide(_obs(GRACE + 1)) # spends a reload
+ second = _FakeWindow()
+ wd.attach(second)
+ assert wd._window is second
+ assert wd._policy.decide(_obs(0.0)).action is Action.WAIT