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): keep startup shell visible until browser paint

Ruben Lütke784c25c78abc
diff --git a/docs/BUGS.md b/docs/BUGS.md
index 19a48de1bb..413cd6b917 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -3296,3 +3296,45 @@ depend on the same executor used by un-cancellable native inference. Opening
the microphone early is necessary but not sufficient: every prerequisite for
the eventual audio consumer must also remain schedulable while the default
pool is exhausted.
+
+## BUG-044: Desktop window is blank during a cold or busy startup (HIGH, 2026-07-12)
+
+**Symptom.** First observed as a regression again on 2026-07-12: after the PC
+starts and the desktop app opens, the entire client area is a featureless dark
+surface. No navigation, loading indicator, assistant name, or error message is
+visible. The normal React UI eventually appears after the machine finishes its
+startup work, but the delay looks like a crashed JavaScript app and is highly
+confusing for users. The screenshot captured at 12:04 shows WebView's native
+background rather than the product's existing HTML boot shell.
+
+**Root cause.** The serve-first backend waited for
+`FastBootstrap.wait_shell_served(timeout=2.0)` before starting its import and
+model-prefetch storm. That event fired when the entry JavaScript bytes left the
+local HTTP server, not when the browser painted them. On a cold WebView or a
+busy/weak CPU, two seconds could expire before the browser had produced its
+first frame. OpenWakeWord, TTS, audio, STT, FastAPI, and route imports then
+competed for the GIL/import lock while the window was already visible, leaving
+only the native background until that work released the browser/server path.
+The race was machine-load dependent, so a fast maintainer machine could miss
+it while another computer or operating system exposed it.
+
+**Fix.** The dependency-free boot page now sends `POST
+/api/ui/shell-painted` only after two `requestAnimationFrame` callbacks. The
+bootstrap records that browser-originated paint acknowledgment, and the desktop
+backend waits on it (with a bounded failure backstop) before launching any
+heavy prefetch or import. The original asset-served event remains available for
+transport diagnostics but no longer gates visible readiness. Both the source
+and packaged `dist/index.html` carry the same paint handshake, so installed and
+development builds behave identically on Windows, macOS, and Linux.
+
+**Guards.** `tests/unit/ui/web/test_fast_bootstrap.py` proves that serving the
+entry JavaScript alone cannot release the paint gate, that the warm-up endpoint
+does release it with HTTP 204, and that the build-source boot page acknowledges
+only after two animation frames. `tests/unit/ui/test_desktop_backend_start_order.py`
+keeps the desktop orchestration compatible with the stronger readiness signal.
+
+**Class rule.** Network delivery is not visual readiness. Any startup path that
+shows a WebView before heavy process initialization must wait for a signal from
+an actually rendered browser frame, never a server-side response, asset-read,
+or fixed sleep. The wait must remain bounded so a broken GUI cannot deadlock a
+headless or degraded backend.
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.py
index a54defff50..d1a6bdacb8 100644
--- a/jarvis/ui/desktop_app.py
+++ b/jarvis/ui/desktop_app.py
@@ -827,71 +827,61 @@ class DesktopApp:
self._bootstrap = bootstrap
_db_boot_ready() # /api/health is servable now → window can appear
- # Fire the heavy OpenWakeWord/onnxruntime import NOW, in a daemon thread,
- # BEFORE the WebServer + brain build + subsystem boot storm grab the
- # Python import lock. The wake-critical Phase-A warm-up gates
- # VoiceBootStatus(ready=True) — the UI's "VOICE STARTING…" → listening
- # flip — on the OWW model load, whose dominant cost is this ~3 s import
- # (not the ~0.1 s parse). Inside the serve-first boot storm it otherwise
- # starves on the import lock to 7-24 s. Prefetching it here means Phase A
- # finds openwakeword already in sys.modules. No-op on a headless VPS /
- # JARVIS_VOICE=0; never slower than today (worst case Phase A waits on
- # the same import it would have triggered itself).
+ def _log_unhandled_async(loop_: asyncio.AbstractEventLoop, context: dict) -> None:
+ exc = context.get("exception")
+ msg = context.get("message", "<no message>")
+ from loguru import logger as _logger
+ if exc is not None:
+ _logger.opt(exception=exc).error("Unhandled asyncio exception: {}", msg)
+ else:
+ _logger.error("Asyncio event context: {}", msg)
+
+ loop.set_exception_handler(_log_unhandled_async)
+
+ # Let the window OPEN and genuinely PAINT before any GIL-heavy import or
+ # model-prefetch thread starts. The previous two-second wait ended when
+ # the entry JS bytes were served, which was not a browser-readiness
+ # signal: on a cold or busy machine it expired before WebView painted,
+ # then the import storm left a blank native window until the CPU freed.
+ # The boot page now acknowledges after two animation frames. Twelve
+ # seconds is only a failure backstop; the normal path releases as soon
+ # as the visible shell paints, while a broken GUI can never deadlock the
+ # backend forever.
+ if self._bootstrap is not None:
+ loop.run_until_complete(self._bootstrap.wait_shell_painted(timeout=12.0))
+
+ # Fire the heavy OpenWakeWord/onnxruntime import now, in a daemon thread,
+ # before the WebServer + brain build + subsystem boot storm grab the
+ # Python import lock, but only after the user has a visible boot shell.
+ # The wake-critical Phase-A warm-up gates VoiceBootStatus(ready=True) on
+ # this import; prefetching still overlaps all subsequent backend work.
from jarvis.speech.warmup_prefetch import (
start_tts_import_prefetch,
start_wake_import_prefetch,
)
+
start_wake_import_prefetch()
- # Same idea for the default TTS SDK (google-genai): the deferred warm-up
- # loader gates honest readiness on the TTS client, and its dominant cost
- # is the ``from google import genai`` import (~4-11 s when starved in the
- # boot storm). Prefetch it now in a daemon thread (disjoint from the wake
- # import — no torch/shield interaction) so ``_ensure_client`` later hits
- # a warm sys.modules. No-op for non-Gemini TTS / JARVIS_VOICE=0.
+ # Same idea for the default TTS SDK (google-genai). This is disjoint
+ # from the wake import and remains a logged no-op for another provider
+ # or a headless host without the optional dependency.
start_tts_import_prefetch()
- # Same idea for the audio-device settle: the BUG-014 guard
- # (wait_for_stable_audio_devices) is a blocking ~1.5 s poll that gates
- # the voice Phase-A warm-up. Start it NOW in a daemon thread so it
- # settles concurrently with the brain build + server.start(); Phase A
- # then reuses the result instead of re-paying the wait. No-op on a
- # headless host without sounddevice.
+ # Start the audio-device settle after the shell paint too. Phase A then
+ # reuses the result instead of re-paying the blocking stability poll.
from jarvis.audio.device_init import start_audio_device_prefetch
+
start_audio_device_prefetch()
- # Wake-MODEL prefetch (TTU iteration 10): the instrumented timeline
- # showed the ~3.1 s fast-first wake-model load running strictly AFTER
- # the import mountain + WebServer ctor. Start it NOW in a daemon
- # thread so it overlaps them; the deferred warm-up later ADOPTS the
- # loaded engine (FasterWhisperProvider._ensure_model) instead of
- # loading again. No-op on JARVIS_VOICE=0 / any failure.
+ # Wake-model prefetch overlaps the heavy backend build and is adopted by
+ # the later provider warm-up. It is a no-op when voice is disabled and
+ # must never make the visible desktop startup load-bearing.
try:
from jarvis.plugins.stt import start_wake_model_prefetch
+
start_wake_model_prefetch(self.cfg.stt)
- except Exception: # noqa: BLE001 — a prefetch must never break boot
+ except Exception: # noqa: BLE001, S110 — prefetch never blocks boot
pass
- def _log_unhandled_async(loop_: asyncio.AbstractEventLoop, context: dict) -> None:
- exc = context.get("exception")
- msg = context.get("message", "<no message>")
- from loguru import logger as _logger
- if exc is not None:
- _logger.opt(exception=exc).error("Unhandled asyncio exception: {}", msg)
- else:
- _logger.error("Asyncio event context: {}", msg)
-
- loop.set_exception_handler(_log_unhandled_async)
-
- # Let the window OPEN and PAINT (fetch /api/health, then index.html +
- # the entry JS bundle from the bootstrap) BEFORE the GIL-heavy build
- # starts. The WebServer ctor + its C-extension imports (fastapi, the
- # route schemas) hold the GIL in long blocks; if they run first they
- # starve the loop and the user stares at a blank window. Serving the
- # shell first means the rendered UI is up before the warm-up storm.
- # Bounded (2 s) so a headless run with no window never stalls the build.
- if self._bootstrap is not None:
- loop.run_until_complete(self._bootstrap.wait_shell_served(timeout=2.0))
-
# Heavy imports — done NOW (after the shell has painted) so their
# GIL-holding C-level work no longer starves the bootstrap loop while
# the window is still rendering. See the note at the top of _run_backend.
diff --git a/jarvis/ui/web/fast_bootstrap.py b/jarvis/ui/web/fast_bootstrap.py
index 9b4b5998cc..4c0c1d6f60 100644
--- a/jarvis/ui/web/fast_bootstrap.py
+++ b/jarvis/ui/web/fast_bootstrap.py
@@ -60,11 +60,14 @@ class FastBootstrap:
self._supervisor_task: asyncio.Task | None = None
self._supervise_interval = 5.0
# Set once the window's critical shell assets (index.html + the entry
- # JS bundle) have been served. The backend build waits briefly on this
- # so the heavy, GIL-holding imports don't starve the loop while the UI
- # is still painting — i.e. the user sees the rendered UI, not a blank
- # window, before the warm-up storm begins.
+ # JS bundle) have been served. This only proves that bytes left the
+ # server; it does not prove that the browser had a chance to paint.
self._shell_served = asyncio.Event()
+ # Set by the boot page after two requestAnimationFrame callbacks. The
+ # desktop backend waits on this stronger signal before starting heavy,
+ # GIL-holding imports, so slow WebView initialization cannot regress to
+ # a blank native window while the browser main thread is still cold.
+ self._shell_painted = asyncio.Event()
# ---- the ASGI callable -------------------------------------------------
@@ -97,6 +100,19 @@ class FastBootstrap:
await self._ok_health(send)
return
+ # The static boot page sends this only after the browser has completed
+ # at least one visual frame. Keep it dependency-free and available
+ # during warm-up; once the real app is registered, the delegation branch
+ # above owns all requests again.
+ if (
+ kind == "http"
+ and scope.get("method") == "POST"
+ and scope.get("path") == "/api/ui/shell-painted"
+ ):
+ self._shell_painted.set()
+ await self._no_content(send)
+ return
+
# First-run onboarding must render from the first second — the gate's
# state/terms/step/complete calls are answered here (stdlib-only
# handler, shared with the real routes) instead of being held. Once
@@ -171,6 +187,17 @@ class FastBootstrap:
)
await send({"type": "http.response.body", "body": body})
+ @staticmethod
+ async def _no_content(send: Any) -> None:
+ await send(
+ {
+ "type": "http.response.start",
+ "status": 204,
+ "headers": [(b"cache-control", b"no-store")],
+ }
+ )
+ await send({"type": "http.response.body", "body": b""})
+
@staticmethod
async def _warming(scope: dict, send: Any, *, unavailable: bool = False) -> None:
kind = scope["type"]
@@ -219,21 +246,19 @@ class FastBootstrap:
await send({"type": "http.response.start", "status": 200, "headers": headers})
body = b"" if scope.get("method") == "HEAD" else data
await send({"type": "http.response.body", "body": body})
- # Mark the shell as served once the entry JS bundle has gone out (the
- # SPA can render after that). index.html alone is a blank #root, so wait
- # for a .js asset — the backend build holds off its GIL-heavy imports
- # until this fires so the UI paints first.
+ # Mark the transport milestone once an entry JS bundle has gone out.
+ # This remains useful for diagnostics, but visible readiness uses the
+ # separate browser-originated paint acknowledgment below.
if target.name.endswith(".js"):
self._shell_served.set()
return True
async def wait_shell_served(self, timeout: float) -> bool: # noqa: ASYNC109 — bounded readiness wait, conventional param
- """Block until the window has fetched the shell's entry JS (so the UI
- can paint), or *timeout* elapses. Returns True if the shell was served.
+ """Wait until the window has fetched the shell's entry JavaScript.
- Lets the backend defer its GIL-heavy build until the visible UI is up.
- A no-op-fast return when already set; bounded so a headless run (no
- window, no JS request) never stalls the build.
+ This is a transport diagnostic only: callers that need visual
+ readiness must use :meth:`wait_shell_painted`. The wait remains bounded
+ so a client that never requests JavaScript cannot stall its caller.
"""
if self._shell_served.is_set():
return True
@@ -243,6 +268,23 @@ class FastBootstrap:
except TimeoutError:
return False
+ async def wait_shell_painted(self, timeout: float) -> bool: # noqa: ASYNC109 — bounded readiness wait, conventional param
+ """Wait until the browser confirms that the boot shell was painted.
+
+ Unlike :meth:`wait_shell_served`, this signal comes from the rendered
+ page after two animation frames. It therefore remains honest when a
+ cold WebView or a busy machine receives the JS bytes before its browser
+ main thread has displayed anything. The wait is bounded so a missing or
+ broken GUI never prevents the backend from eventually continuing.
+ """
+ if self._shell_painted.is_set():
+ return True
+ try:
+ await asyncio.wait_for(self._shell_painted.wait(), timeout=timeout)
+ return True
+ except TimeoutError:
+ return False
+
def _resolve_static_file(self, path: str) -> Path | None:
"""Map a request path to a real file under dist, or the SPA index.html
fallback. Returns None when no build exists (caller holds instead).
diff --git a/jarvis/ui/web/frontend/index.html b/jarvis/ui/web/frontend/index.html
index f8f7968c87..5755c8a314 100644
--- a/jarvis/ui/web/frontend/index.html
+++ b/jarvis/ui/web/frontend/index.html
@@ -76,6 +76,25 @@
}
})();
</script>
+ <script>
+ // Do not release the desktop's heavy backend warm-up merely because the
+ // HTML or entry bundle was sent. A cold WebView can receive those bytes
+ // before its browser main thread paints anything. Two animation frames
+ // prove that the user has seen this dependency-free boot shell first.
+ (function () {
+ var acknowledgePaint = function () {
+ fetch("/api/ui/shell-painted", {
+ method: "POST",
+ cache: "no-store",
+ }).catch(function () {
+ /* The full app may already own the route; startup remains bounded. */
+ });
+ };
+ requestAnimationFrame(function () {
+ requestAnimationFrame(acknowledgePaint);
+ });
+ })();
+ </script>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
diff --git a/tests/unit/ui/test_desktop_backend_start_order.py b/tests/unit/ui/test_desktop_backend_start_order.py
index 7b37b2d849..f0f9365357 100644
--- a/tests/unit/ui/test_desktop_backend_start_order.py
+++ b/tests/unit/ui/test_desktop_backend_start_order.py
@@ -67,7 +67,7 @@ class _FakeBootstrap:
def set_app(self, app: Any) -> None:
self.app_set = app
- async def wait_shell_served(self, timeout: float = 0.0) -> bool: # noqa: ASYNC109
+ async def wait_shell_painted(self, timeout: float = 0.0) -> bool: # noqa: ASYNC109
return True
async def stop(self) -> None:
diff --git a/tests/unit/ui/web/test_fast_bootstrap.py b/tests/unit/ui/web/test_fast_bootstrap.py
index ec9915ada1..1d207a7214 100644
--- a/tests/unit/ui/web/test_fast_bootstrap.py
+++ b/tests/unit/ui/web/test_fast_bootstrap.py
@@ -11,6 +11,7 @@ the ASGI callable directly (no socket) to prove that behavior.
from __future__ import annotations
import asyncio
+from pathlib import Path
from typing import Any
import pytest
@@ -172,6 +173,30 @@ async def test_shell_served_event_fires_after_js_bundle(tmp_path) -> None:
assert await bs.wait_shell_served(timeout=0.05)
+async def test_shell_paint_requires_browser_ack_not_just_js_bytes(tmp_path) -> None:
+ # Sending the bundle does not prove the browser painted it. The desktop
+ # backend must stay clear of heavy imports until the boot page confirms a
+ # visual frame through the dedicated warm-up endpoint.
+ bs = FastBootstrap(dist_dir=_seed_dist(tmp_path))
+ await _drive(bs.app, _http("/"))
+ await _drive(bs.app, _http("/assets/app.js"))
+ assert not await bs.wait_shell_painted(timeout=0.05)
+
+ sent = await _drive(bs.app, _http("/api/ui/shell-painted", method="POST"))
+
+ assert _status(sent) == 204
+ assert await bs.wait_shell_painted(timeout=0.05)
+
+
+def test_boot_page_acknowledges_after_two_frames() -> None:
+ repo_root = Path(__file__).resolve().parents[4]
+ page = repo_root / "jarvis/ui/web/frontend/index.html"
+ html = page.read_text(encoding="utf-8")
+ assert "/api/ui/shell-painted" in html
+ assert html.count("requestAnimationFrame") >= 2
+
+
# --- listener self-healing (the lock-zombie root cause) ---------------------
# Forensic 2026-06-26: a transient Windows socket error (OSError WinError 64,
# "the network name is no longer available") killed the asyncio proactor accept