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 self-reload waits for a whole build instead of going black

rubenluetke10-beep0790478a909b
diff --git a/jarvis/ui/web/fast_bootstrap.py b/jarvis/ui/web/fast_bootstrap.py
index 5043a6c04a..0bae3e4654 100644
--- a/jarvis/ui/web/fast_bootstrap.py
+++ b/jarvis/ui/web/fast_bootstrap.py
@@ -29,6 +29,7 @@ from contextlib import suppress
from pathlib import Path
from typing import Any
+from .spa_build import build_is_complete, holding_page_html
from .surface_security import SurfaceSecurity
# The built React frontend lives next to this module (jarvis/ui/web/dist),
@@ -296,6 +297,28 @@ class FastBootstrap:
await send({"type": "websocket.accept"})
await send({"type": "websocket.close", "code": 1013})
+ @staticmethod
+ async def _rebuilding(scope: dict, send: Any) -> None:
+ """Answer with the holding splash while dist/ is half-written."""
+ body = holding_page_html().encode("utf-8")
+ await send(
+ {
+ "type": "http.response.start",
+ "status": 200,
+ "headers": [
+ (b"content-type", b"text/html; charset=utf-8"),
+ (b"content-length", str(len(body)).encode("latin-1")),
+ (b"cache-control", b"no-store, max-age=0"),
+ ],
+ }
+ )
+ await send(
+ {
+ "type": "http.response.body",
+ "body": b"" if scope.get("method") == "HEAD" else body,
+ }
+ )
+
# ---- static frontend (served while warming, no black screen) -----------
async def _serve_static(self, scope: dict, send: Any) -> bool:
@@ -304,6 +327,13 @@ class FastBootstrap:
target = self._resolve_static_file(scope.get("path", "/"))
if target is None:
return False
+ if target.name == "index.html" and not build_is_complete(target, self._dist_dir):
+ # A rebuild is between deleting dist/assets and writing the new
+ # ones. Handing out this index.html gives the window a boot splash
+ # whose entry bundle 404s — no React, no self-healing, and a
+ # twenty-second wait before anything notices (see spa_build.py).
+ await self._rebuilding(scope, send)
+ return True
try:
data = await asyncio.to_thread(target.read_bytes)
except OSError:
diff --git a/jarvis/ui/web/frontend/index.html b/jarvis/ui/web/frontend/index.html
index 94c26c438e..fea0f29dad 100644
--- a/jarvis/ui/web/frontend/index.html
+++ b/jarvis/ui/web/frontend/index.html
@@ -172,6 +172,11 @@
var CRASH_GRACE_MS = 2500;
var LOAD_GRACE_MS = 20000;
var POLL_MS = 500;
+ var RETRY_MS = 700;
+ var SLOW_RETRY_MS = 3000;
+ var FAST_TRIES = 20;
+ // Mirrors HOLDING_MARKER in jarvis/ui/web/spa_build.py.
+ var HOLDING = "jarvis-build-holding";
var KEY = "jarvis:blank-reloaded";
var started = Date.now();
var lastError = "";
@@ -188,6 +193,97 @@
lastError = (r && (r.message || String(r))) || lastError;
});
+ // Reload ONLY once the server can hand out a whole build.
+ //
+ // A reload is a one-way door: once the navigation starts, this script
+ // is gone too. `npm run build` runs with emptyOutDir, so dist/ passes
+ // through a state where assets/ is deleted and the previous index.html
+ // is not — measured at 1.8 s against the live server on 2026-08-22.
+ // Reloading into that gives the window a splash whose module script
+ // 404s and nothing at all left to notice it. So: ask what a fresh
+ // 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 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();
+ return;
+ }
+ var tries = 0;
+ function again() {
+ setTimeout(look, tries < FAST_TRIES ? RETRY_MS : SLOW_RETRY_MS);
+ }
+ function look() {
+ tries++;
+ f("/", { cache: "no-store", headers: { Accept: "text/html" } })
+ .then(function (r) {
+ return r.ok ? r.text() : "";
+ })
+ .then(function (html) {
+ if (!html || html.indexOf(HOLDING) !== -1) {
+ again();
+ return;
+ }
+ var refs = html.match(/\/assets\/[A-Za-z0-9._-]+/g) || [];
+ if (!refs.length) {
+ again();
+ return;
+ }
+ var left = refs.length;
+ var bad = false;
+ refs.forEach(function (url) {
+ f(url, { method: "HEAD", cache: "no-store" })
+ .then(function (r) {
+ if (!r.ok) bad = true;
+ })
+ ["catch"](function () {
+ bad = true;
+ })
+ .then(function () {
+ left--;
+ if (left > 0) return;
+ if (bad) again();
+ else location.reload();
+ });
+ });
+ })
+ ["catch"](function () {
+ again();
+ });
+ }
+ look();
+ }
+
+ // Put the splash back while we wait for a build worth reloading into.
+ // An emptied #root is the one state with nothing on screen at all, and
+ // the wait for a rebuild to finish can be tens of seconds — the window
+ // has to say something for all of it.
+ function waiting() {
+ var root = document.getElementById("root");
+ if (!root || root.childElementCount > 0) return;
+ var box = document.createElement("div");
+ box.id = "jarvis-boot-splash";
+ var ring = document.createElement("div");
+ ring.className = "ring";
+ var name = document.createElement("div");
+ name.className = "name";
+ try {
+ name.textContent = (localStorage.getItem("jarvis.assistantName") || "").trim();
+ } catch (e) {
+ /* storage blocked — the spinner alone is enough */
+ }
+ var sub = document.createElement("div");
+ sub.className = "sub";
+ sub.textContent = "Updating…";
+ box.appendChild(ring);
+ box.appendChild(name);
+ box.appendChild(sub);
+ root.appendChild(box);
+ }
+
function state() {
var root = document.getElementById("root");
if (!root || root.childElementCount === 0) return "empty";
@@ -264,7 +360,11 @@
} catch (e) {
/* storage blocked — the reload still happens */
}
- location.reload();
+ // Same door, same rule: a person who clicks Reload during a
+ // rebuild must not be handed the black window this card replaced.
+ root.innerHTML = "";
+ waiting();
+ safeReload();
};
box.appendChild(h);
box.appendChild(why);
@@ -326,7 +426,8 @@
report();
return;
}
- location.reload();
+ waiting();
+ safeReload();
return;
}
report();
diff --git a/jarvis/ui/web/frontend/src/lib/bootWatchdog.test.ts b/jarvis/ui/web/frontend/src/lib/bootWatchdog.test.ts
index 4eaaf7501f..c43136619f 100644
--- a/jarvis/ui/web/frontend/src/lib/bootWatchdog.test.ts
+++ b/jarvis/ui/web/frontend/src/lib/bootWatchdog.test.ts
@@ -40,11 +40,28 @@ interface Run {
store: Map<string, string>;
}
+/** A served index.html the watchdog would consider safe to reload into. */
+const WHOLE_BUILD =
+ '<!doctype html><html><head><script type="module" src="/assets/index-abc.js">' +
+ '</script></head><body><div id="root"></div></body></html>';
+
+/** What the server hands out while a rebuild is between two states on disk. */
+const HOLDING = '<html><div data-state="jarvis-build-holding"></div></html>';
+
/**
- * Run the watchdog against this document, with `location` and `sessionStorage`
- * shadowed by test doubles (jsdom's own `location.reload` cannot be spied on).
+ * Run the watchdog against this document, with `location`, `sessionStorage`
+ * and `fetch` shadowed by test doubles (jsdom's own `location.reload` cannot
+ * be spied on).
+ *
+ * `fetch` is a double rather than absent because the watchdog no longer
+ * reloads blindly: it asks the server whether a whole build is on disk first,
+ * which is the difference between healing the window and blanking it for
+ * twenty seconds. `served` is the entry document; `assetOk` decides whether
+ * the hashed files it points at answer.
*/
-function runWatchdog(): Run {
+function runWatchdog(
+ options: { served?: string; assetOk?: boolean } = {},
+): Run {
let reloads = 0;
const store = new Map<string, string>();
const sessionStorageStub = {
@@ -53,10 +70,19 @@ function runWatchdog(): Run {
removeItem: (k: string) => void store.delete(k),
};
const locationStub = { reload: () => void (reloads += 1) };
+ const served = options.served ?? WHOLE_BUILD;
+ const assetOk = options.assetOk ?? true;
+ const fetchStub = (_url: string, init?: { method?: string }) =>
+ Promise.resolve(
+ init?.method === "HEAD"
+ ? { ok: assetOk, text: () => Promise.resolve("") }
+ : { ok: true, text: () => Promise.resolve(served) },
+ );
// eslint-disable-next-line no-new-func
- new Function("sessionStorage", "location", watchdogSource())(
+ new Function("sessionStorage", "location", "fetch", watchdogSource())(
sessionStorageStub,
locationStub,
+ fetchStub,
);
return { reloads: () => reloads, store };
}
@@ -87,23 +113,50 @@ describe("the blank-window watchdog in index.html", () => {
expect(run.store.has("jarvis:blank-reloaded")).toBe(false);
});
- test("a splash still spinning gets the long grace, then one reload", () => {
+ test("a splash still spinning gets the long grace, then one reload", async () => {
setRoot(SPLASH);
const run = runWatchdog();
- vi.advanceTimersByTime(10_000);
+ await vi.advanceTimersByTimeAsync(10_000);
expect(run.reloads()).toBe(0);
- vi.advanceTimersByTime(11_000);
+ await vi.advanceTimersByTimeAsync(11_000);
expect(run.reloads()).toBe(1);
});
- test("an emptied root is a crash, and does not wait twenty seconds for it", () => {
+ test("an emptied root is a crash, and does not wait twenty seconds for it", async () => {
setRoot("");
const run = runWatchdog();
- vi.advanceTimersByTime(3_000);
+ await vi.advanceTimersByTimeAsync(3_000);
expect(run.reloads()).toBe(1);
expect(run.store.get("jarvis:blank-reloaded")).toBe("1");
});
+ test("it puts the splash back rather than waiting on an empty window", async () => {
+ // While the server check runs — and it can run for as long as a rebuild
+ // takes — #root is the one state with nothing on screen at all.
+ setRoot("");
+ runWatchdog({ served: HOLDING });
+ await vi.advanceTimersByTimeAsync(3_000);
+ const root = document.getElementById("root")!;
+ expect(root.querySelector("#jarvis-boot-splash")).not.toBeNull();
+ expect(root.textContent).toContain("Updating");
+ });
+
+ test("it does NOT reload into a build that is half-written", async () => {
+ // The measured 1.8 s window: index.html is served, its entry bundle 404s.
+ // Reloading here is the black window this whole guard exists to prevent.
+ setRoot("");
+ const run = runWatchdog({ assetOk: false });
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(run.reloads()).toBe(0);
+ });
+
+ test("it does NOT reload while the server says a rebuild is in flight", async () => {
+ setRoot("");
+ const run = runWatchdog({ served: HOLDING });
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(run.reloads()).toBe(0);
+ });
+
test("the second failure says what happened instead of reloading again", () => {
setRoot("");
const run = runWatchdog();
@@ -130,7 +183,7 @@ describe("the blank-window watchdog in index.html", () => {
);
});
- test("it keeps watching after the app is up, and catches a LATER crash", () => {
+ test("it keeps watching after the app is up, and catches a LATER crash", async () => {
// The section-switch failure, in order: the app paints, the user works for
// a while, then a lazy chunk throws above every error boundary and empties
// #root. The watchdog used to clearInterval() on the first healthy poll,
@@ -142,11 +195,11 @@ describe("the blank-window watchdog in index.html", () => {
expect(run.reloads()).toBe(0);
setRoot("");
- vi.advanceTimersByTime(3_000);
+ await vi.advanceTimersByTimeAsync(3_000);
expect(run.reloads()).toBe(1);
});
- test("a healthy app that empties later still gets its full grace period", () => {
+ test("a healthy app that empties later still gets its full grace period", async () => {
// The grace must be measured from when the window went blank, not from
// page load — otherwise a stopwatch running since boot condemns the very
// first poll after a crash and reloads on a momentary gap.
@@ -156,9 +209,9 @@ describe("the blank-window watchdog in index.html", () => {
vi.advanceTimersByTime(60_000);
setRoot("");
- vi.advanceTimersByTime(1_000);
+ await vi.advanceTimersByTimeAsync(1_000);
expect(run.reloads()).toBe(0);
- vi.advanceTimersByTime(2_000);
+ await vi.advanceTimersByTimeAsync(2_000);
expect(run.reloads()).toBe(1);
});
@@ -177,12 +230,13 @@ describe("the blank-window watchdog in index.html", () => {
);
});
- test("the reload button clears the guard, so the fresh page may heal itself", () => {
+ test("the reload button clears the guard, so the fresh page may heal itself", async () => {
setRoot("");
const run = runWatchdog();
run.store.set("jarvis:blank-reloaded", "1");
- vi.advanceTimersByTime(3_000);
+ await vi.advanceTimersByTimeAsync(3_000);
document.getElementById("root")!.querySelector("button")!.click();
+ await vi.advanceTimersByTimeAsync(0);
expect(run.reloads()).toBe(1);
expect(run.store.has("jarvis:blank-reloaded")).toBe(false);
});
diff --git a/jarvis/ui/web/frontend/src/lib/safeReload.test.ts b/jarvis/ui/web/frontend/src/lib/safeReload.test.ts
new file mode 100644
index 0000000000..2648e8397d
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/safeReload.test.ts
@@ -0,0 +1,143 @@
+import { describe, expect, test } from "vitest";
+import {
+ entryAssets,
+ HOLDING_MARKER,
+ looksBootable,
+ reloadWhenServable,
+ type SafeReloadDeps,
+} from "./safeReload";
+
+const INDEX = `<!doctype html><html><head>
+<script type="module" crossorigin src="/assets/index-abc123.js"></script>
+<link rel="stylesheet" href="/assets/index-def456.css">
+</head><body><div id="root"></div></body></html>`;
+
+/**
+ * A deps double whose timers run immediately, so a test can watch the retry
+ * loop converge without a clock. `defer` is counted rather than delayed —
+ * what matters is that it keeps asking and does NOT reload.
+ */
+function harness(pages: string[], assets: (url: string) => boolean) {
+ let reloads = 0;
+ let waits = 0;
+ const asked: string[] = [];
+ const deps: SafeReloadDeps = {
+ fetchIndex: () => Promise.resolve(pages.length > 1 ? pages.shift()! : pages[0]),
+ assetOk: (url) => {
+ asked.push(url);
+ return Promise.resolve(assets(url));
+ },
+ reload: () => {
+ reloads += 1;
+ },
+ defer: (fn) => {
+ waits += 1;
+ // Bounded so a test that never converges fails instead of hanging.
+ if (waits < 12) void Promise.resolve().then(fn);
+ },
+ };
+ return {
+ deps,
+ reloads: () => reloads,
+ waits: () => waits,
+ asked: () => asked,
+ };
+}
+
+/** Let every queued microtask (the fetch chains) run. */
+const settle = () => new Promise((r) => setTimeout(r, 0));
+
+describe("entryAssets", () => {
+ test("finds every hashed build output once", () => {
+ expect(entryAssets(INDEX)).toEqual([
+ "/assets/index-abc123.js",
+ "/assets/index-def456.css",
+ ]);
+ });
+
+ test("a document with no build outputs yields nothing", () => {
+ expect(entryAssets("<html><body>nothing here</body></html>")).toEqual([]);
+ });
+});
+
+describe("looksBootable", () => {
+ test("a real index is bootable", () => {
+ expect(looksBootable(INDEX)).toBe(true);
+ });
+
+ test("a failed request is not", () => {
+ expect(looksBootable("")).toBe(false);
+ });
+
+ test("the server's holding page is not — it says a build is in flight", () => {
+ expect(looksBootable(`<html><div data-state="${HOLDING_MARKER}"></div></html>`)).toBe(
+ false,
+ );
+ });
+});
+
+describe("reloadWhenServable", () => {
+ test("a whole build on disk is reloaded into", async () => {
+ const h = harness([INDEX], () => true);
+ reloadWhenServable(h.deps);
+ await settle();
+ expect(h.reloads()).toBe(1);
+ expect(h.asked()).toEqual(["/assets/index-abc123.js", "/assets/index-def456.css"]);
+ });
+
+ test("an index whose entry bundle 404s is NOT reloaded into", async () => {
+ // The 1.8 s window a real rebuild opens: index.html still on disk, its
+ // assets already deleted. This is the black window, and the whole point.
+ const h = harness([INDEX], (url) => !url.endsWith(".js"));
+ reloadWhenServable(h.deps);
+ await settle();
+ expect(h.reloads()).toBe(0);
+ expect(h.waits()).toBeGreaterThan(0);
+ });
+
+ test("the holding page is waited out, never reloaded into", async () => {
+ const h = harness([`<html><div data-state="${HOLDING_MARKER}"></div></html>`], () => true);
+ reloadWhenServable(h.deps);
+ await settle();
+ expect(h.reloads()).toBe(0);
+ });
+
+ test("a server that is not answering keeps the page that is on screen", async () => {
+ const h = harness([""], () => true);
+ reloadWhenServable(h.deps);
+ await settle();
+ expect(h.reloads()).toBe(0);
+ expect(h.waits()).toBeGreaterThan(0);
+ });
+
+ test("it reloads as soon as the build lands, not before", async () => {
+ const pages = [
+ `<html><div data-state="${HOLDING_MARKER}"></div></html>`,
+ `<html><div data-state="${HOLDING_MARKER}"></div></html>`,
+ INDEX,
+ ];
+ const h = harness(pages, () => true);
+ reloadWhenServable(h.deps);
+ await settle();
+ expect(h.reloads()).toBe(1);
+ });
+
+ test("a fetch that throws is a retry, never a reload", async () => {
+ let reloads = 0;
+ let waits = 0;
+ const deps: SafeReloadDeps = {
+ fetchIndex: () => Promise.reject(new Error("connection refused")),
+ assetOk: () => Promise.resolve(true),
+ reload: () => {
+ reloads += 1;
+ },
+ defer: () => {
+ waits += 1;
+ },
+ };
+ reloadWhenServable(deps);
+ await settle();
+ expect(reloads).toBe(0);
+ expect(waits).toBe(1);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/lib/safeReload.ts b/jarvis/ui/web/frontend/src/lib/safeReload.ts
new file mode 100644
index 0000000000..7420637461
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/safeReload.ts
@@ -0,0 +1,140 @@
+/**
+ * Reload only when a reload will land on something that runs.
+ *
+ * Three separate mechanisms in this app reload the window by themselves — the
+ * bundle watch when a rebuild is published, the preload recovery when a lazy
+ * chunk has been deleted under it, and the blank-window watchdog in
+ * `index.html` when `#root` goes empty. Every one of them called
+ * `location.reload()` unconditionally, and that is a one-way door: the moment
+ * the navigation starts, the running bundle is gone. If the document that
+ * comes back cannot boot, there is no JavaScript left to try again — the
+ * window is whatever the browser painted, and it stays that way.
+ *
+ * That is not hypothetical. `npm run build` runs with `emptyOutDir`, so
+ * `dist/` passes through a state where `dist/assets/` is already deleted while
+ * the previous `index.html` is still on disk. Measured against the live server
+ * with a 200 ms poll during a real rebuild (2026-08-22): 1.8 s of exactly that
+ * document, then 5.2 s with no index at all, then the new build. A window that
+ * reloads into that first window gets the boot splash and a `<script
+ * type="module">` that 404s — no React, no bundle watch, no preload recovery —
+ * and the only thing left is the watchdog's twenty-second clock. Twenty
+ * seconds of a near-black window with a small spinner is what gets reported as
+ * "it goes black when it reloads by itself".
+ *
+ * The server side now refuses to serve that document at all (see
+ * `jarvis/ui/web/spa_build.py`). This is the other half, and it is the half
+ * that also covers a server which is restarting, a machine that just woke, and
+ * every future way the entry document can be briefly unavailable: ask what a
+ * fresh window would load, confirm those files actually answer, and only then
+ * spend the reload.
+ *
+ * It never gives up and it never reloads out of impatience. A window that keeps
+ * showing the app it already has is strictly better than one showing nothing.
+ */
+
+/** Marks the server's holding page. Mirrors `HOLDING_MARKER` in spa_build.py. */
+export const HOLDING_MARKER = "jarvis-build-holding";
+
+/** Delay between checks while a build is in flight. */
+export const RETRY_MS = 700;
+
+/** Delay after {@link FAST_TRIES} checks, so a long outage polls gently. */
+export const SLOW_RETRY_MS = 3_000;
+
+/** How many quick checks before backing off to {@link SLOW_RETRY_MS}. */
+export const FAST_TRIES = 20;
+
+export interface SafeReloadDeps {
+ /** Fetch the SPA entry document, or "" when the request failed. */
+ fetchIndex: () => Promise<string>;
+ /** Does this URL answer with a real file? */
+ assetOk: (url: string) => Promise<boolean>;
+ /** Perform the actual navigation. */
+ reload: () => void;
+ /** Schedule the next check. */
+ defer: (fn: () => void, ms: number) => void;
+}
+
+/**
+ * The hashed build outputs *html* tells a browser to load.
+ *
+ * Mirrors `referenced_assets` in spa_build.py — the same question asked from
+ * the other side of the wire.
+ */
+export function entryAssets(html: string): string[] {
+ return [...new Set(html.match(/\/assets\/[A-Za-z0-9._-]+/g) ?? [])];
+}
+
+/**
+ * Could this document boot a window?
+ *
+ * False for an empty/failed response, for the server's holding page, and for
+ * an index that references nothing — none of which is a build a window can
+ * run. The files themselves are checked separately, because their absence is
+ * exactly the failure this module exists for.
+ */
+export function looksBootable(html: string): boolean {
+ if (!html || html.includes(HOLDING_MARKER)) return false;
+ return entryAssets(html).length > 0;
+}
+
+/**
+ * Reload as soon as — and not before — the server can hand out a whole build.
+ *
+ * Returns immediately; the work continues on the deps' timer. Calling it twice
+ * simply runs two checks, so callers that can fire repeatedly should guard
+ * themselves (the bundle watch and the preload recovery both already do).
+ */
+export function reloadWhenServable(deps: SafeReloadDeps): void {
+ let tries = 0;
+
+ const again = () => {
+ deps.defer(check, tries < FAST_TRIES ? RETRY_MS : SLOW_RETRY_MS);
+ };
+
+ const check = () => {
+ tries += 1;
+ void deps
+ .fetchIndex()
+ .then(async (html) => {
+ if (!looksBootable(html)) {
+ again();
+ return;
+ }
+ for (const asset of entryAssets(html)) {
+ if (!(await deps.assetOk(asset))) {
+ // A rebuild is mid-flight: the index is new, its files are not all
+ // written. Reloading now is the twenty-second black window.
+ again();
+ return;
+ }
+ }
+ deps.reload();
+ })
+ .catch(() => {
+ // The server restarting, a dropped socket, a sleeping machine: keep the
+ // page that is on screen and ask again.
+ again();
+ });
+ };
+
+ check();
+}
+
+/** The deps a real browser window uses. Kept here so every caller agrees. */
+export function browserSafeReloadDeps(): SafeReloadDeps {
+ return {
+ fetchIndex: () =>
+ fetch("/", { cache: "no-store", headers: { Accept: "text/html" } })
+ .then((response) => (response.ok ? response.text() : ""))
+ .catch(() => ""),
+ assetOk: (url) =>
+ fetch(url, { method: "HEAD", cache: "no-store" })
+ .then((response) => response.ok)
+ .catch(() => false),
+ reload: () => window.location.reload(),
+ defer: (fn, ms) => {
+ window.setTimeout(fn, ms);
+ },
+ };
+}
diff --git a/jarvis/ui/web/frontend/src/main.tsx b/jarvis/ui/web/frontend/src/main.tsx
index 5982b37620..3ad7c0242a 100644
--- a/jarvis/ui/web/frontend/src/main.tsx
+++ b/jarvis/ui/web/frontend/src/main.tsx
@@ -7,6 +7,7 @@ import { ViewErrorBoundary } from "./components/ViewErrorBoundary";
import { AuthGate } from "./components/AuthGate";
import { installPreloadRecovery } from "./lib/preloadRecovery";
import { installBundleWatch } from "./lib/bundleWatch";
+import { browserSafeReloadDeps, reloadWhenServable } from "./lib/safeReload";
import "./index.css";
// When the frontend is rebuilt while the window is open, the old main bundle
@@ -18,7 +19,11 @@ import "./index.css";
// missing chunk and the window ends up cycling. See lib/preloadRecovery.
installPreloadRecovery({
storage: sessionStorage,
- reload: () => window.location.reload(),
+ // Never a bare location.reload(). The chunk went missing because a rebuild
+ // is running, which is precisely when the entry document is also briefly
+ // unservable — reloading into that leaves the window with no JavaScript and
+ // nothing left to recover with. See lib/safeReload.
+ reload: () => reloadWhenServable(browserSafeReloadDeps()),
defer: (fn, ms) => {
window.setTimeout(fn, ms);
},
@@ -43,7 +48,7 @@ installPreloadRecovery({
fetch("/", { cache: "no-store", headers: { Accept: "text/html" } }).then(
(response) => (response.ok ? response.text() : ""),
),
- reload: () => window.location.reload(),
+ reload: () => reloadWhenServable(browserSafeReloadDeps()),
idleFor: () => (lastInput === null ? null : Date.now() - lastInput),
visible: () => document.visibilityState !== "hidden",
every: (fn, ms) => window.setInterval(fn, ms),
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index 6e8e4b58c8..cf08329329 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -55,6 +55,7 @@ from .schema import (
WSWelcome,
event_to_ws_envelope,
)
+from .spa_build import build_is_complete, holding_page_html
from .surface_security import SurfaceSecurity, set_browser_login_required
from .wallpapers import register_wallpaper_routes
@@ -346,6 +347,7 @@ class WebServer:
from .computer_use_routes import router as computer_use_router
from .contacts_routes import router as contacts_router
from .control_routes import router as control_router
+ from .deck_routes import router as deck_router
from .desktop_routes import router as desktop_router
from .diagnostics_routes import router as diagnostics_router
from .dictation_routes import router as dictation_router
@@ -378,7 +380,6 @@ class WebServer:
from .profile_routes import router as profile_router
from .provider_routes import router as provider_router
from .review_routes import router as review_router
- from .deck_routes import router as deck_router
from .screen_context_routes import router as screen_context_router
from .self_mod_routes import router as self_mod_router
from .sessions_routes import router as sessions_router
@@ -2076,7 +2077,16 @@ class WebServer:
return self._spa_index_response()
def _spa_index_response(self) -> FileResponse | HTMLResponse:
- if INDEX_FILE.is_file():
+ # An index.html whose own entry bundle is not on disk is worse than no
+ # index.html at all: the window paints the boot splash, the module
+ # script 404s, and nothing further runs — no React, no bundle watch, no
+ # preload recovery — so the only thing left is the 20-second blank-window
+ # watchdog. A rebuild deletes dist/assets while leaving the previous
+ # index.html in place for about two seconds (measured 2026-08-22), and
+ # every window that loads during those two seconds is stuck there. The
+ # holding page below says what is happening and comes back on its own.
+ # See jarvis/ui/web/spa_build.py.
+ if INDEX_FILE.is_file() and build_is_complete(INDEX_FILE, DIST_DIR):
return FileResponse(
str(INDEX_FILE),
headers={
@@ -2088,48 +2098,23 @@ class WebServer:
@staticmethod
def _spa_placeholder_response() -> HTMLResponse:
- # This page has no bundle behind it, so it carries its own theme. It is
- # served INSIDE the native window, whose ground was already painted from
- # [ui] theme — a hardcoded dark page here would be a black rectangle in
- # a paper-white frame for the whole rebuild.
- from jarvis.ui.theme import (
- HOLDING_PAGE_FOREGROUND,
- HOLDING_PAGE_MUTED,
- WINDOW_BACKGROUND,
- configured_theme,
- resolve_theme,
- )
-
- try:
- from jarvis.core.config import load_config
-
- theme = resolve_theme(configured_theme(load_config()))
- except Exception: # noqa: BLE001 — a holding page never fails on config
- theme = "dark"
-
- bg = WINDOW_BACKGROUND[theme]
- fg = HOLDING_PAGE_FOREGROUND[theme]
- muted = HOLDING_PAGE_MUTED[theme]
- body = (
- "<!doctype html><html lang=\"en\"><head>"
- "<meta charset=\"utf-8\">"
- "<title>Jarvis</title>"
- "<meta http-equiv=\"refresh\" content=\"2\">"
- f"<meta name=\"color-scheme\" content=\"{theme}\">"
- f"<style>html,body{{margin:0;height:100%;background:{bg};"
- f"color:{fg};font-family:ui-sans-serif,system-ui,sans-serif;"
- "display:flex;align-items:center;justify-content:center}"
- "main{text-align:center;max-width:480px;padding:24px}"
- "h1{font-weight:500;font-size:18px;margin:0 0 12px}"
- f"p{{margin:0;color:{muted};font-size:14px;line-height:1.5}}</style>"
- "</head><body><main>"
- "<h1>Jarvis is starting…</h1>"
- "<p>The frontend is currently being built or reloaded. "
- "This page refreshes automatically.</p>"
- "</main></body></html>"
- )
+ """The boot splash, while dist/ is between two builds.
+
+ It is deliberately the SAME splash the window opens with — same ground,
+ same ring, same assistant name — because a rebuild is not a different
+ program taking over the window. Resolving the theme is left to a two-line
+ inline script reading the very key `frontend/index.html` reads, which
+ also takes a synchronous `load_config()` off the one event loop that is
+ simultaneously serving every asset of the build that is landing.
+
+ It waits for a COMPLETE build instead of reloading on a timer: the page
+ polls the entry document and reloads only once the answer is no longer
+ itself. A blind `<meta http-equiv="refresh">` reloads into the same
+ half-written dist over and over, which is the flicker rather than the
+ cure.
+ """
return HTMLResponse(
- content=body,
+ content=holding_page_html(),
status_code=200,
headers={
"Cache-Control": "no-store, max-age=0",
diff --git a/jarvis/ui/web/spa_build.py b/jarvis/ui/web/spa_build.py
new file mode 100644
index 0000000000..9a24f1ce51
--- /dev/null
+++ b/jarvis/ui/web/spa_build.py
@@ -0,0 +1,155 @@
+"""Is the frontend build on disk whole enough to hand to a browser?
+
+``index.html`` and the hashed bundles it points at are written by separate
+steps of one ``npm run build``, and Vite runs with ``emptyOutDir: true`` — so
+``dist/`` passes through a state where ``index.html`` is still the OLD one
+while ``dist/assets/`` has already been deleted. Measured on 2026-08-22 with a
+200 ms poll against the live server during a real rebuild:
+
+* 1.8 s serving the previous ``index.html`` whose ``<script type="module">``
+ answered 404,
+* then 5.2 s with no ``index.html`` at all (the holding page),
+* then the new build.
+
+The middle 5.2 s are harmless: the holding page refreshes itself. The first
+1.8 s are not. A window that loads that document gets the boot splash, its
+entry bundle 404s, and NOTHING further runs — no React, no bundle watch, no
+preload recovery. The only thing left is the blank-window watchdog in
+``index.html``, which allows a splash 20 seconds before it acts. Twenty seconds
+of a near-black window with a small spinner is what gets reported as "it goes
+black when it reloads by itself".
+
+The fix is to never serve that document. An ``index.html`` whose own entry
+assets are not on disk is not a page, it is a trap: the caller falls back to
+the holding page, which says what is happening and comes back on its own.
+
+Deliberately un-cached. The whole point is that ``index.html`` can stay
+byte-identical while the files underneath it disappear, so a result keyed on
+its mtime would be exactly wrong. Costs one small read plus a handful of
+``stat`` calls, on a route a window hits when it loads and once per bundle-watch
+poll.
+"""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+__all__ = ["referenced_assets", "build_is_complete", "holding_page_html", "HOLDING_MARKER"]
+
+# Present in the holding page and in nothing else, so a page that is waiting
+# for a build can tell — from the document alone — whether the server is ready
+# to hand it a real one yet. Both the page below and the frontend's automatic
+# reloads test for it.
+HOLDING_MARKER = "jarvis-build-holding"
+
+# Every hashed build output index.html points at. Mirrors the frontend's own
+# `bundleFingerprint` (src/lib/bundleWatch.ts) — keep the two patterns in
+# lockstep, they are answering the same question from opposite ends.
+_ASSET_REF = re.compile(r"/assets/[A-Za-z0-9._-]+")
+
+
+def referenced_assets(html: str) -> list[str]:
+ """The ``/assets/...`` URLs *html* asks the browser to load.
+
+ Order-preserving and de-duplicated, so a caller can report the first
+ missing one without a second pass.
+ """
+ seen: dict[str, None] = {}
+ for ref in _ASSET_REF.findall(html):
+ seen.setdefault(ref, None)
+ return list(seen)
+
+
+def build_is_complete(index_file: Path, dist_dir: Path) -> bool:
+ """True when *index_file* and every asset it references exist on disk.
+
+ False for a missing/unreadable index, and false while a rebuild has taken
+ the assets out from under an index that is still there. A build that
+ references no assets at all is treated as complete — that is a hand-written
+ or placeholder page, not a half-written Vite output.
+ """
+ try:
+ html = index_file.read_text(encoding="utf-8", errors="replace")
+ except OSError:
+ return False
+ for ref in referenced_assets(html):
+ candidate = dist_dir / ref.lstrip("/")
+ try:
+ if not candidate.is_file():
+ return False
+ except OSError:
+ return False
+ return True
+
+
+def holding_page_html() -> str:
+ """The page a window gets while a rebuild is between two states on disk.
+
+ It is the boot splash, deliberately: the same ground, the same ring, the
+ same theme resolution from the same ``localStorage`` key as
+ ``frontend/index.html`` — so a rebuild looks like the app starting rather
+ than like a different program taking over the window. Keep the colours and
+ the storage key in lockstep with that file.
+
+ It does NOT use ``<meta http-equiv="refresh">``. A blind timer reloads into
+ the same half-written build over and over, which is the flicker this whole
+ area keeps producing. Instead it asks the server for the entry document and
+ reloads only once the answer is no longer this page — meaning a complete
+ build is on disk and a reload will land on something that runs.
+ """
+ return (
+ "<!doctype html>"
+ '<html lang="en" class="dark"><head>'
+ '<meta charset="utf-8">'
+ '<meta name="viewport" content="width=device-width, initial-scale=1.0">'
+ "<title>Assistant</title>"
+ "<script>(function(){var m='dark';try{var s=(localStorage.getItem("
+ "'jarvis.theme')||'').trim();if(s==='light'||s==='dark'){m=s;}"
+ "else if(s==='system'){m=window.matchMedia('(prefers-color-scheme: light)')"
+ ".matches?'light':'dark';}}catch(e){}"
+ "var r=document.documentElement;r.classList.toggle('dark',m==='dark');"
+ "r.style.colorScheme=m;})();</script>"
+ "<style>"
+ ":root{--jbs-bg:#fcfbf8;--jbs-accent:#a86b00;"
+ "--jbs-ring:rgba(168,107,0,0.22);--jbs-name:#2b2b33;--jbs-sub:#6b6b76}"
+ ":root.dark{--jbs-bg:#0a0e14;--jbs-accent:#e7c46e;"
+ "--jbs-ring:rgba(231,196,110,0.2);--jbs-name:#e6e6e6;--jbs-sub:#9aa3ad}"
+ "html,body{margin:0;height:100%;background:var(--jbs-bg)}"
+ "#s{position:fixed;inset:0;display:flex;flex-direction:column;"
+ "align-items:center;justify-content:center;gap:18px;"
+ "background:var(--jbs-bg);color:var(--jbs-accent);"
+ "font-family:ui-sans-serif,system-ui,-apple-system,Segoe UI,sans-serif}"
+ "#s .ring{width:38px;height:38px;border-radius:50%;"
+ "border:3px solid var(--jbs-ring);border-top-color:var(--jbs-accent);"
+ "animation:sp 0.8s linear infinite}"
+ "#s .name{font-size:15px;font-weight:600;letter-spacing:0.04em;"
+ "color:var(--jbs-name)}"
+ "#s .sub{font-size:12px;color:var(--jbs-sub);letter-spacing:0.06em;"
+ "text-transform:uppercase}"
+ "@keyframes sp{to{transform:rotate(360deg)}}"
+ "</style></head><body>"
+ f'<div id="s" data-state="{HOLDING_MARKER}">'
+ '<div class="ring"></div>'
+ '<div class="name"></div>'
+ '<div class="sub">Updating…</div>'
+ "</div>"
+ "<script>(function(){try{var n=(localStorage.getItem("
+ "'jarvis.assistantName')||'').trim();if(n){"
+ "document.querySelector('#s .name').textContent=n;document.title=n;}}"
+ "catch(e){}})();</script>"
+ "<script>(function(){"
+ "var tries=0;"
+ "function look(){"
+ "tries++;"
+ "fetch('/',{cache:'no-store',headers:{Accept:'text/html'}})"
+ f".then(function(r){{return r.ok?r.text():'{HOLDING_MARKER}';}})"
+ f".then(function(t){{if(t.indexOf('{HOLDING_MARKER}')===-1){{"
+ "location.reload();return;}"
+ "setTimeout(look, tries<20?700:3000);})"
+ "['catch'](function(){setTimeout(look, tries<20?700:3000);});"
+ "}"
+ "setTimeout(look,700);"
+ "})();</script>"
+ "</body></html>"
+ )
diff --git a/tests/unit/ui/web/test_spa_build_completeness.py b/tests/unit/ui/web/test_spa_build_completeness.py
new file mode 100644
index 0000000000..fa457608db
--- /dev/null
+++ b/tests/unit/ui/web/test_spa_build_completeness.py
@@ -0,0 +1,211 @@
+"""A half-written frontend build must never be handed to a window.
+
+``npm run build`` runs with ``emptyOutDir``, so ``dist/`` passes through a
+state where ``dist/assets/`` has been deleted while the previous
+``index.html`` is still on disk. Measured against the live server with a
+200 ms poll during a real rebuild on 2026-08-22: 1.8 s of exactly that
+document, then 5.2 s with no index at all, then the new build.
+
+Serving that document is the defect. The window paints the boot splash, its
+``<script type="module">`` answers 404, and NOTHING else runs — no React, no
+bundle watch, no preload recovery — leaving only the blank-window watchdog's
+twenty-second clock. Twenty seconds of a near-black window with a small
+spinner is the "it goes black when it reloads by itself" report.
+
+These tests pin both halves: the completeness check itself, and the two places
+that serve the SPA (the real app and the fast-boot bootstrap) falling back to
+the holding page instead.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from jarvis.ui.web.fast_bootstrap import FastBootstrap
+from jarvis.ui.web.spa_build import (
+ HOLDING_MARKER,
+ build_is_complete,
+ holding_page_html,
+ referenced_assets,
+)
+
+_INDEX = (
+ "<!doctype html><html><head>"
+ '<script type="module" crossorigin src="/assets/index-abc123.js"></script>'
+ '<link rel="stylesheet" href="/assets/index-def456.css">'
+ "</head><body><div id=\"root\"></div></body></html>"
+)
+
+
+def _dist(tmp_path: Path, *, assets: bool = True, index: bool = True) -> Path:
+ dist = tmp_path / "dist"
+ (dist / "assets").mkdir(parents=True)
+ if index:
+ (dist / "index.html").write_text(_INDEX, encoding="utf-8")
+ if assets:
+ (dist / "assets" / "index-abc123.js").write_text("//", encoding="utf-8")
+ (dist / "assets" / "index-def456.css").write_text("/**/", encoding="utf-8")
+ return dist
+
+
+class TestReferencedAssets:
+ def test_finds_every_hashed_output_once(self) -> None:
+ assert referenced_assets(_INDEX) == [
+ "/assets/index-abc123.js",
+ "/assets/index-def456.css",
+ ]
+
+ def test_a_page_with_no_build_outputs_yields_nothing(self) -> None:
+ assert referenced_assets("<html><body>plain</body></html>") == []
+
+
+class TestBuildIsComplete:
+ def test_a_whole_build_is_complete(self, tmp_path: Path) -> None:
+ dist = _dist(tmp_path)
+ assert build_is_complete(dist / "index.html", dist) is True
+
+ def test_an_index_whose_entry_bundle_is_gone_is_not(self, tmp_path: Path) -> None:
+ # The measured 1.8 s window, exactly.
+ dist = _dist(tmp_path)
+ (dist / "assets" / "index-abc123.js").unlink()
+ assert build_is_complete(dist / "index.html", dist) is False
+
+ def test_a_missing_index_is_not_complete(self, tmp_path: Path) -> None:
+ dist = _dist(tmp_path, index=False)
+ assert build_is_complete(dist / "index.html", dist) is False
+
+ def test_it_is_never_cached_because_the_files_move_under_it(
+ self, tmp_path: Path
+ ) -> None:
+ # index.html stays byte-identical while dist/assets is emptied — a
+ # result keyed on its mtime would be exactly wrong here.
+ dist = _dist(tmp_path)
+ assert build_is_complete(dist / "index.html", dist) is True
+ (dist / "assets" / "index-abc123.js").unlink()
+ assert build_is_complete(dist / "index.html", dist) is False
+
+ def test_a_page_referencing_no_assets_is_left_alone(self, tmp_path: Path) -> None:
+ dist = tmp_path / "dist"
+ dist.mkdir()
+ (dist / "index.html").write_text("<html><body>hi</body></html>", encoding="utf-8")
+ assert build_is_complete(dist / "index.html", dist) is True
+
+
+class TestHoldingPage:
+ def test_it_carries_the_marker_a_waiting_window_looks_for(self) -> None:
+ assert HOLDING_MARKER in holding_page_html()
+
+ def test_it_never_reloads_on_a_blind_timer(self) -> None:
+ # A meta refresh reloads into the same half-written build over and over.
+ assert "http-equiv" not in holding_page_html()
+
+ def test_it_never_paints_a_trademarked_name(self) -> None:
+ # The splash shows the user's own assistant name or nothing at all.
+ assert "Jarvis" not in holding_page_html()
+
+ def test_it_resolves_the_theme_without_asking_the_backend(self) -> None:
+ # Reading [ui] theme meant a synchronous load_config() on the one event
+ # loop that is simultaneously serving every asset of the landing build.
+ page = holding_page_html()
+ assert "jarvis.theme" in page
+ assert ":root.dark" in page
+
+
+async def _drive(app: Any, scope: dict) -> list[dict]:
+ sent: list[dict] = []
+
+ async def send(msg: dict) -> None:
+ sent.append(msg)
+
+ async def receive() -> dict:
+ return {"type": "http.request", "body": b"", "more_body": False}
+
+ await app(scope, receive, send)
+ return sent
+
+
+def _get(path: str = "/") -> dict:
+ return {
+ "type": "http",
+ "method": "GET",
+ "path": path,
+ "scheme": "http",
+ "client": ("127.0.0.1", 50000),
+ "headers": [(b"host", b"127.0.0.1:47821")],
+ }
+
+
+class TestFastBootstrapServesTheHoldingPage:
+ @pytest.mark.asyncio
+ async def test_a_whole_build_is_served_as_is(self, tmp_path: Path) -> None:
+ dist = _dist(tmp_path)
+ bs = FastBootstrap(dist_dir=dist)
+ sent = await _drive(bs._asgi, _get())
+ body = b"".join(m.get("body", b"") for m in sent if m["type"] == "http.response.body")
+ assert sent[0]["status"] == 200
+ assert b"index-abc123.js" in body
+
+ @pytest.mark.asyncio
+ async def test_a_half_written_build_gets_the_holding_page(
+ self, tmp_path: Path
+ ) -> None:
+ dist = _dist(tmp_path)
+ (dist / "assets" / "index-abc123.js").unlink()
+ bs = FastBootstrap(dist_dir=dist)
+ sent = await _drive(bs._asgi, _get())
+ body = b"".join(m.get("body", b"") for m in sent if m["type"] == "http.response.body")
+ assert sent[0]["status"] == 200
+ assert HOLDING_MARKER.encode() in body
+ # And crucially NOT the document whose script tag would 404.
+ assert b"index-abc123.js" not in body
+
+
+class TestTheRealAppServesTheHoldingPage:
+ """The same rule on the route a running window actually hits.
+
+ ``WebServer._spa_index_response`` is a method rather than a free function,
+ but it reads only module-level paths — so the check can be driven without
+ building the whole FastAPI app, which would need a config, a bus and a
+ terminal manager for a decision about two files on disk.
+ """
+
+ @staticmethod
+ def _response(monkeypatch: pytest.MonkeyPatch, dist: Path) -> Any:
+ from jarvis.ui.web import server as server_mod
+
+ monkeypatch.setattr(server_mod, "DIST_DIR", dist)
+ monkeypatch.setattr(server_mod, "INDEX_FILE", dist / "index.html")
+ # The class stands in for an instance: the method reads module-level
+ # paths and one static helper, nothing off `self`.
+ return server_mod.WebServer._spa_index_response(server_mod.WebServer)
+
+ def test_a_whole_build_is_served_from_disk(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ from fastapi.responses import FileResponse
+
+ dist = _dist(tmp_path)
+ assert isinstance(self._response(monkeypatch, dist), FileResponse)
+
+ def test_a_half_written_build_gets_the_holding_page(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ from fastapi.responses import HTMLResponse
+
+ dist = _dist(tmp_path)
+ (dist / "assets" / "index-abc123.js").unlink()
+ response = self._response(monkeypatch, dist)
+ assert isinstance(response, HTMLResponse)
+ assert HOLDING_MARKER.encode() in response.body
+ assert b"index-abc123.js" not in response.body
+
+ def test_a_missing_build_still_gets_the_holding_page(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ from fastapi.responses import HTMLResponse
+
+ dist = _dist(tmp_path, index=False)
+ assert isinstance(self._response(monkeypatch, dist), HTMLResponse)