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): stop the window from reloading itself in a loop after a rebuild

Ruben Lütked78f1dfe5b5d
diff --git a/jarvis/ui/web/frontend/src/lib/preloadRecovery.test.ts b/jarvis/ui/web/frontend/src/lib/preloadRecovery.test.ts
new file mode 100644
index 0000000000..cc79db7617
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/preloadRecovery.test.ts
@@ -0,0 +1,133 @@
+/**
+ * The reload that heals a rebuilt bundle must never become the reload loop.
+ *
+ * The loop is the live failure this module was written for (2026-07-28 18:51):
+ * a rebuild deletes the old chunks before writing the new ones, so a reload
+ * lands on the same missing chunk, asks for another reload, and the window
+ * flickers between "Checking access…", the boot shell and a brief
+ * "Ready for commands" for as long as the build runs.
+ */
+
+import { describe, expect, it, vi } from "vitest";
+
+import {
+ RELOAD_GUARD_KEY,
+ SETTLE_MS,
+ handlePreloadError,
+ installPreloadRecovery,
+ type PreloadRecoveryDeps,
+} from "./preloadRecovery";
+
+/** A sessionStorage stand-in that survives across simulated reloads. */
+function makeStorage(initial: Record<string, string> = {}) {
+ const data = new Map(Object.entries(initial));
+ return {
+ data,
+ getItem: (k: string) => data.get(k) ?? null,
+ setItem: (k: string, v: string) => {
+ data.set(k, v);
+ },
+ removeItem: (k: string) => {
+ data.delete(k);
+ },
+ };
+}
+
+function makeDeps(storage = makeStorage()) {
+ const reload = vi.fn();
+ const deferred: Array<{ fn: () => void; ms: number }> = [];
+ const deps: PreloadRecoveryDeps = {
+ storage,
+ reload,
+ defer: (fn, ms) => {
+ deferred.push({ fn, ms });
+ },
+ };
+ return { deps, storage, reload, deferred };
+}
+
+describe("preload recovery", () => {
+ it("reloads once so a rebuilt bundle is picked up", () => {
+ const { deps, reload, storage } = makeDeps();
+
+ expect(handlePreloadError(deps)).toBe(true);
+
+ expect(reload).toHaveBeenCalledTimes(1);
+ expect(storage.getItem(RELOAD_GUARD_KEY)).toBe("1");
+ });
+
+ it("does NOT reload again when the fresh page hits the same missing chunk", () => {
+ // The guard is written before the reload, so the page that comes back
+ // starts with it already set — this is the loop's second pass.
+ const { deps, reload } = makeDeps(makeStorage({ [RELOAD_GUARD_KEY]: "1" }));
+
+ expect(handlePreloadError(deps)).toBe(false);
+ expect(reload).not.toHaveBeenCalled();
+ });
+
+ it("the guard is NOT released by the page finishing its load", () => {
+ // The regression: the release used to hang off `window.load`, which fires
+ // before any lazy chunk is imported and therefore before the error it was
+ // supposed to bound. Installing must not clear the guard by itself.
+ const { deps, storage, deferred } = makeDeps(
+ makeStorage({ [RELOAD_GUARD_KEY]: "1" }),
+ );
+ const target = { addEventListener: vi.fn() };
+
+ installPreloadRecovery(deps, target);
+
+ expect(storage.getItem(RELOAD_GUARD_KEY)).toBe("1");
+ // Released only on the settle timer, not on any page lifecycle event.
+ expect(deferred).toHaveLength(1);
+ expect(deferred[0].ms).toBe(SETTLE_MS);
+ });
+
+ it("releases the guard once the page has survived the settle window", () => {
+ // A LATER rebuild in the same session must still heal on its own.
+ const { deps, storage, deferred, reload } = makeDeps(
+ makeStorage({ [RELOAD_GUARD_KEY]: "1" }),
+ );
+
+ installPreloadRecovery(deps, { addEventListener: vi.fn() });
+ deferred[0].fn();
+
+ expect(storage.getItem(RELOAD_GUARD_KEY)).toBeNull();
+ expect(handlePreloadError(deps)).toBe(true);
+ expect(reload).toHaveBeenCalledTimes(1);
+ });
+
+ it("listens for the preload error and keeps Vite from reloading on its own", () => {
+ const { deps, reload } = makeDeps();
+ const listeners: EventListener[] = [];
+ installPreloadRecovery(deps, {
+ addEventListener: ((_name: string, fn: EventListener) => {
+ listeners.push(fn);
+ }) as Window["addEventListener"],
+ });
+
+ const preventDefault = vi.fn();
+ listeners[0]({ preventDefault } as unknown as Event);
+
+ expect(preventDefault).toHaveBeenCalledTimes(1);
+ expect(reload).toHaveBeenCalledTimes(1);
+ });
+
+ it("never reloads when the guard cannot be remembered", () => {
+ // No storage means no way to bound a loop, so no loop is started.
+ const reload = vi.fn();
+ const blocked: PreloadRecoveryDeps = {
+ storage: {
+ getItem: () => null,
+ setItem: () => {
+ throw new Error("storage is full");
+ },
+ removeItem: () => undefined,
+ },
+ reload,
+ defer: () => undefined,
+ };
+
+ expect(handlePreloadError(blocked)).toBe(false);
+ expect(reload).not.toHaveBeenCalled();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/lib/preloadRecovery.ts b/jarvis/ui/web/frontend/src/lib/preloadRecovery.ts
new file mode 100644
index 0000000000..0113460a63
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/preloadRecovery.ts
@@ -0,0 +1,114 @@
+/**
+ * Recover from a lazy chunk that is no longer on disk — exactly once.
+ *
+ * When the frontend is rebuilt while the desktop window is open, the running
+ * main bundle still asks for lazy chunks by their previous content hash. Those
+ * URLs are gone, the dynamic `import()` rejects, and whichever view tried to
+ * load hard-crashes. Vite announces precisely this case as `vite:preloadError`,
+ * and reloading once picks up the fresh bundle — `index.html` is served
+ * `no-store`, so a reload really does get the new hashes.
+ *
+ * The danger is the other half: a rebuild is not instantaneous. While
+ * `npm run build` runs, `dist/` passes through a state where the old chunks are
+ * already deleted and the new ones are not written yet, so a reload lands on
+ * the same missing chunk and asks for another reload. That is a loop measured
+ * on 2026-07-28 18:51 — the window cycled through "Checking access…", the
+ * boot shell and a brief "Ready for commands" several times within about three
+ * seconds, which is what a user sees as a violently flickering app that never
+ * finishes starting.
+ *
+ * A guard existed for that loop and could not work: it was cleared on the
+ * window's `load` event, which fires when the document and its static
+ * resources are done — always BEFORE a lazy chunk is imported, and therefore
+ * always before the error it was meant to bound. Every pass through the loop
+ * found the guard freshly cleared.
+ *
+ * So the release is tied to evidence instead of to `load`: the guard is lifted
+ * only once the app has run {@link SETTLE_MS} without a preload error, which
+ * means this page is healthy and a LATER rebuild may heal itself the same way.
+ * A second failure inside that window is the loop, and it stops there — the
+ * failed import surfaces through the view's error boundary, which is a
+ * readable card instead of a flicker.
+ */
+
+/** sessionStorage key holding "a reload has already been spent on this". */
+export const RELOAD_GUARD_KEY = "jarvis:preload-reloaded";
+
+/**
+ * How long a page must survive before another automatic reload is allowed.
+ *
+ * Long enough to cover a rebuild in progress (Vite's window with chunks
+ * deleted and not yet rewritten is seconds, not tens of seconds), short enough
+ * that a second rebuild later in the same session still heals on its own.
+ */
+export const SETTLE_MS = 30_000;
+
+export interface PreloadRecoveryDeps {
+ /** Where the one-reload-per-incident mark lives. Survives a reload. */
+ storage: Pick<Storage, "getItem" | "setItem" | "removeItem">;
+ /** What to do when a reload is warranted. */
+ reload: () => void;
+ /** Defer the settle release. Returns nothing — this is never cancelled. */
+ defer: (fn: () => void, ms: number) => void;
+}
+
+/**
+ * Decide what a preload error means right now, and act on it.
+ *
+ * Returns whether a reload was triggered — the caller does not need it, but a
+ * test does, and it keeps the decision inspectable.
+ */
+export function handlePreloadError(deps: PreloadRecoveryDeps): boolean {
+ let alreadySpent: string | null = null;
+ try {
+ alreadySpent = deps.storage.getItem(RELOAD_GUARD_KEY);
+ } catch {
+ // A storage that refuses to be read (private mode, a locked profile) must
+ // not turn a recoverable chunk error into an unrecoverable one. Treating
+ // it as "already spent" is the safe side: no reload, no loop.
+ return false;
+ }
+ if (alreadySpent) return false;
+ try {
+ deps.storage.setItem(RELOAD_GUARD_KEY, "1");
+ } catch {
+ // Cannot remember that a reload was spent → cannot bound the loop → do
+ // not start one.
+ return false;
+ }
+ deps.reload();
+ return true;
+}
+
+/**
+ * Wire the recovery up to the page.
+ *
+ * Registers the listener and schedules the settle release. Safe in any
+ * environment: without `window` it does nothing at all.
+ */
+export function installPreloadRecovery(
+ deps: PreloadRecoveryDeps,
+ target: Pick<Window, "addEventListener"> | undefined = typeof window === "undefined"
+ ? undefined
+ : window,
+): void {
+ if (!target) return;
+
+ target.addEventListener("vite:preloadError", ((event: Event) => {
+ // Vite's default for an unhandled preload error is to reload the page
+ // itself; preventing it keeps the decision here, where it is bounded.
+ event.preventDefault();
+ handlePreloadError(deps);
+ }) as EventListener);
+
+ // This page has been up for a while without a single preload failure, so
+ // whatever was mid-rebuild is finished and the bundle it is running is
+ // coherent. A future rebuild gets its own reload.
+ deps.defer(() => {
+ try {
+ deps.storage.removeItem(RELOAD_GUARD_KEY);
+ } catch {
+ /* nothing to release */
+ }
+ }, SETTLE_MS);
+}
diff --git a/jarvis/ui/web/frontend/src/main.tsx b/jarvis/ui/web/frontend/src/main.tsx
index f44bbd7c56..56b7978192 100644
--- a/jarvis/ui/web/frontend/src/main.tsx
+++ b/jarvis/ui/web/frontend/src/main.tsx
@@ -5,24 +5,22 @@ import App from "./App";
import { ThemeProvider } from "./hooks/useTheme";
import { ViewErrorBoundary } from "./components/ViewErrorBoundary";
import { AuthGate } from "./components/AuthGate";
+import { installPreloadRecovery } from "./lib/preloadRecovery";
import "./index.css";
-// When the frontend is rebuilt while a tab is open, the old main bundle still
-// references lazy chunks by their previous content hash; those URLs now 404 and
-// the dynamic import() rejects, hard-crashing whichever view tried to load
-// (e.g. the Wiki page's ObsidianButton). Vite fires `vite:preloadError` for
-// exactly this case — reload once to pick up the fresh bundle. The
-// sessionStorage guard prevents a reload loop if the chunk is missing for some
-// other reason. A successful load clears the flag.
-window.addEventListener("vite:preloadError", (event) => {
- event.preventDefault();
- if (!sessionStorage.getItem("jarvis:preload-reloaded")) {
- sessionStorage.setItem("jarvis:preload-reloaded", "1");
- window.location.reload();
- }
-});
-window.addEventListener("load", () => {
- sessionStorage.removeItem("jarvis:preload-reloaded");
+// When the frontend is rebuilt while the window is open, the old main bundle
+// still references lazy chunks by their previous content hash; those URLs now
+// 404 and the dynamic import() rejects, hard-crashing whichever view tried to
+// load (e.g. the Wiki page's ObsidianButton). Vite fires `vite:preloadError`
+// for exactly this case — reload once to pick up the fresh bundle, and only
+// once per incident, because a rebuild in progress hands the reload the same
+// missing chunk and the window ends up cycling. See lib/preloadRecovery.
+installPreloadRecovery({
+ storage: sessionStorage,
+ reload: () => window.location.reload(),
+ defer: (fn, ms) => {
+ window.setTimeout(fn, ms);
+ },
});
// Say it out loud when the main thread stops answering the user. In a WebView