The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(web): reload for a failed chunk only into a newer build, once per build
Teknium6da3e5641e1a
diff --git a/web/src/lib/chunk-load-recovery.test.ts b/web/src/lib/chunk-load-recovery.test.tsindex b00f90ef4ef..b8dee3efd15 100644--- a/web/src/lib/chunk-load-recovery.test.ts+++ b/web/src/lib/chunk-load-recovery.test.ts@@ -1,5 +1,10 @@import { describe, expect, it, vi } from "vitest";-import { reloadForChunkLoadError, startChunkLoadRecovery } from "./chunk-load-recovery";+import {+ type ChunkLoadRecoveryDeps,+ entryFromIndexHtml,+ reloadForChunkLoadError,+ startChunkLoadRecovery,+} from "./chunk-load-recovery";function memoryStorage() {const data = new Map<string, string>();@@ -12,28 +17,101 @@ function memoryStorage() {const staleChunk = () =>new Error("Failed to fetch dynamically imported module: http://127.0.0.1:9119/assets/ConfigPage-D09a41f-.js");+const entry = (build: string) => `http://127.0.0.1:9119/assets/index-${build}.js`;++/** A tab running build `running` while the server publishes build `published`. */+function builds(running: string, published: string | null, extra: ChunkLoadRecoveryDeps = {}) {+ const reload = vi.fn();+ const deps = {+ storage: memoryStorage(),+ reload,+ online: () => true,+ runningEntry: () => entry(running),+ publishedEntry: vi.fn(async () => (published ? entry(published) : null)),+ ...extra,+ };+ return { deps, reload };+}+describe("reloadForChunkLoadError", () => {- it("reloads once for a missing build chunk, then not again within the guard window", () => {- const storage = memoryStorage();- const reload = vi.fn();- const t0 = 1_000_000;- expect(reloadForChunkLoadError(staleChunk(), storage, reload, t0)).toBe(true);- expect(reloadForChunkLoadError(staleChunk(), storage, reload, t0 + 60_000)).toBe(false);+ it("reloads once per running build: a repeat on the same build is suppressed", async () => {+ const { deps, reload } = builds("A", "B");+ expect(await reloadForChunkLoadError(staleChunk(), deps)).toBe(true);+ expect(await reloadForChunkLoadError(staleChunk(), deps)).toBe(false);expect(reload).toHaveBeenCalledTimes(1);- expect(reloadForChunkLoadError(staleChunk(), storage, reload, t0 + 6 * 60_000)).toBe(true);- expect(reload).toHaveBeenCalledTimes(2);});- it("ignores plugin bundles, ordinary errors, and tabs without session storage", () => {- const reload = vi.fn();+ it("ignores plugin bundles, ordinary errors, and tabs without session storage", async () => {+ const { deps, reload } = builds("A", "B");const plugin = new Error("Failed to fetch dynamically imported module: http://127.0.0.1:9119/dashboard-plugins/kanban/dist/index.js",);- expect(reloadForChunkLoadError(plugin, memoryStorage(), reload)).toBe(false);- expect(reloadForChunkLoadError(new Error("boom"), memoryStorage(), reload)).toBe(false);- expect(reloadForChunkLoadError(staleChunk(), null, reload)).toBe(false);+ expect(await reloadForChunkLoadError(plugin, { ...deps, storage: memoryStorage() })).toBe(false);+ expect(await reloadForChunkLoadError(new Error("boom"), { ...deps, storage: memoryStorage() })).toBe(false);+ expect(await reloadForChunkLoadError(staleChunk(), { ...deps, storage: null })).toBe(false);+ expect(reload).not.toHaveBeenCalled();+ });++ it("does not reload for a network failure when the build has not changed", async () => {+ const { deps, reload } = builds("A", "A");+ expect(await reloadForChunkLoadError(staleChunk(), deps)).toBe(false);+ expect(deps.publishedEntry).toHaveBeenCalledTimes(1);+ expect(reload).not.toHaveBeenCalled();+ });++ it("does not reload when the fresh index cannot be fetched", async () => {+ const { deps, reload } = builds("A", null);+ expect(await reloadForChunkLoadError(staleChunk(), deps)).toBe(false);+ expect(reload).not.toHaveBeenCalled();+ });++ it("does not reload, or even ask the server, while offline", async () => {+ const { deps, reload } = builds("A", "B", { online: () => false });+ expect(await reloadForChunkLoadError(staleChunk(), deps)).toBe(false);+ expect(deps.publishedEntry).not.toHaveBeenCalled();expect(reload).not.toHaveBeenCalled();});++ it("recovers again when a later build lands inside the same session (A -> B -> C)", async () => {+ const storage = memoryStorage();+ const onA = builds("A", "B", { storage });+ expect(await reloadForChunkLoadError(staleChunk(), onA.deps)).toBe(true);+ // The reload landed on B; C is published before B's lazy page is opened.+ const onB = builds("B", "C", { storage });+ expect(await reloadForChunkLoadError(staleChunk(), onB.deps)).toBe(true);+ expect(await reloadForChunkLoadError(staleChunk(), onB.deps)).toBe(false);+ expect(onA.reload).toHaveBeenCalledTimes(1);+ expect(onB.reload).toHaveBeenCalledTimes(1);+ });++ it("does not loop when the reload lands on the same build again", async () => {+ const storage = memoryStorage();+ expect(await reloadForChunkLoadError(staleChunk(), builds("A", "B", { storage }).deps)).toBe(true);+ // A stale index came back after the reload: still A, server still says B.+ const again = builds("A", "B", { storage });+ expect(await reloadForChunkLoadError(staleChunk(), again.deps)).toBe(false);+ expect(again.reload).not.toHaveBeenCalled();+ });++ it("starts one reload for concurrent failures on the same build", async () => {+ const { deps, reload } = builds("A", "B");+ const results = await Promise.all([+ reloadForChunkLoadError(staleChunk(), deps),+ reloadForChunkLoadError(staleChunk(), deps),+ ]);+ expect(results.filter(Boolean)).toHaveLength(1);+ expect(reload).toHaveBeenCalledTimes(1);+ });+});++describe("entryFromIndexHtml", () => {+ it("resolves the built module entry, base path included", () => {+ const html =+ '<script>window.__HERMES_SESSION_TOKEN__="t";</script>' ++ '<script type="module" crossorigin src="/hermes/assets/index-Bx1.js"></script>';+ expect(entryFromIndexHtml(html, "https://host/hermes/sessions")).toBe("https://host/hermes/assets/index-Bx1.js");+ expect(entryFromIndexHtml("<p>gateway error</p>", "https://host/")).toBeNull();+ });});describe("startChunkLoadRecovery", () => {@@ -41,13 +119,14 @@ describe("startChunkLoadRecovery", () => {return Object.assign(new Event("vite:preloadError"), { payload });}- it("turns vite:preloadError into one reload, then suppresses the next one", () => {+ it("turns vite:preloadError into one reload, then suppresses the next one", async () => {const target = new EventTarget();- const reload = vi.fn();- startChunkLoadRecovery(target as unknown as Window, { storage: memoryStorage(), reload });+ const { deps, reload } = builds("A", "B");+ startChunkLoadRecovery(target as unknown as Window, deps);target.dispatchEvent(preloadError(staleChunk()));- expect(reload).toHaveBeenCalledTimes(1);+ await vi.waitFor(() => expect(reload).toHaveBeenCalledTimes(1));target.dispatchEvent(preloadError(staleChunk()));+ await new Promise((r) => setTimeout(r, 0));expect(reload).toHaveBeenCalledTimes(1);});@@ -55,17 +134,16 @@ describe("startChunkLoadRecovery", () => {["chunk CSS", "Unable to preload CSS for /assets/ConfigPage-D09a41f-.css"],["Safari, no URL", "Importing a module script failed."],["Firefox", "error loading dynamically imported module: http://127.0.0.1:9119/assets/ConfigPage-D09a41f-.js"],- ])("reloads for a %s failure", (_name, message) => {+ ])("reloads for a %s failure", async (_name, message) => {const target = new EventTarget();- const reload = vi.fn();- startChunkLoadRecovery(target as unknown as Window, { storage: memoryStorage(), reload });+ const { deps, reload } = builds("A", "B");+ startChunkLoadRecovery(target as unknown as Window, deps);target.dispatchEvent(preloadError(new Error(message)));- expect(reload).toHaveBeenCalledTimes(1);+ await vi.waitFor(() => expect(reload).toHaveBeenCalledTimes(1));});- it("never reloads when session storage throws", () => {+ it("never reloads when session storage throws", async () => {const target = new EventTarget();- const reload = vi.fn();const throwing = {getItem: () => {throw new DOMException("denied", "SecurityError");@@ -74,8 +152,10 @@ describe("startChunkLoadRecovery", () => {throw new DOMException("denied", "SecurityError");},};- startChunkLoadRecovery(target as unknown as Window, { storage: throwing, reload });+ const { deps, reload } = builds("A", "B", { storage: throwing });+ startChunkLoadRecovery(target as unknown as Window, deps);target.dispatchEvent(preloadError(staleChunk()));+ await new Promise((r) => setTimeout(r, 0));expect(reload).not.toHaveBeenCalled();});});diff --git a/web/src/lib/chunk-load-recovery.ts b/web/src/lib/chunk-load-recovery.tsindex 76ad8aba6bc..c45145fa582 100644--- a/web/src/lib/chunk-load-recovery.ts+++ b/web/src/lib/chunk-load-recovery.ts@@ -1,19 +1,36 @@// A tab opened before `hermes update` rebuilt the SPA still references the old// hashed chunks; the rebuild deleted them, so the first lazy page it opens 404s// and React unmounts the whole app (blank page). A reload picks up the new-// index.html, which is served no-store. One reload per 5 minutes per tab keeps a-// chunk that is really broken from looping.+// index.html, which is served no-store.+//+// A failed chunk request looks the same whether the build changed or the+// network dropped, so the reload happens only when a fresh index.html names a+// different entry than the one running. Each build reloads at most once per+// tab session: a reload that lands on the same build again (a stale index, a+// chunk that is really broken) keeps the error visible instead of looping,+// while a later build can still recover.-const RELOAD_AT_KEY = "hermes.chunkLoadReloadAt";-const RELOAD_GUARD_MS = 5 * 60 * 1000;+const RELOADED_FROM_KEY = "hermes.chunkLoadReloadedFrom";const CHUNK_LOAD_ERROR = new RegExp("^(Unable to preload CSS for |Failed to fetch dynamically imported module|" +"error loading dynamically imported module|Importing a module script failed)",);+const ENTRY_SCRIPT = /<script\b[^>]*\btype=["']module["'][^>]*\bsrc=["']([^"']+)["']/i;+type ReloadStorage = Pick<Storage, "getItem" | "setItem">;+export interface ChunkLoadRecoveryDeps {+ storage?: ReloadStorage | null;+ reload?: () => void;+ /** Absolute URL of the entry script this document runs. */+ runningEntry?: () => string | null;+ /** Absolute URL of the entry script a fresh index.html names; null when unknown. */+ publishedEntry?: () => Promise<string | null>;+ online?: () => boolean;+}+/** A failed load of one of our own build chunks. Safari's message carries no* URL; the others must point at the build's `/assets/`, so a broken plugin* bundle under `/dashboard-plugins/` never triggers a reload. */@@ -23,6 +40,12 @@ export function isChunkLoadError(error: unknown): boolean {return !url || url.includes("/assets/");}+/** The built entry an index.html references, resolved against `base`. */+export function entryFromIndexHtml(html: string, base: string): string | null {+ const src = ENTRY_SCRIPT.exec(html)?.[1];+ return src ? new URL(src, base).href : null;+}+function sessionStore(): ReloadStorage | null {try {return window.sessionStorage;@@ -31,22 +54,62 @@ function sessionStore(): ReloadStorage | null {}}-/** Reload once for a chunk load failure. Returns whether a reload started. */-export function reloadForChunkLoadError(- error: unknown,- storage: ReloadStorage | null = sessionStore(),- reload: () => void = () => window.location.reload(),- now: number = Date.now(),-): boolean {- // Without storage there is no loop guard, so keep the error visible instead.- if (!storage || !isChunkLoadError(error)) return false;+function documentEntry(): string | null {+ const script = document.querySelector<HTMLScriptElement>('script[type="module"][src*="/assets/"]');+ return script?.src || null;+}++/** Fetches the URL a reload would load, so both see the same index.html. */+async function freshIndexEntry(): Promise<string | null> {+ const url = window.location.href.split("#")[0];+ try {+ const res = await fetch(url, { cache: "no-store", credentials: "same-origin" });+ return res.ok ? entryFromIndexHtml(await res.text(), res.url || url) : null;+ } catch {+ return null;+ }+}++/** The entry this tab last reloaded away from; undefined when storage throws. */+function reloadedFrom(storage: ReloadStorage): string | null | undefined {+ try {+ return storage.getItem(RELOADED_FROM_KEY);+ } catch {+ return undefined;+ }+}++function markReloadedFrom(storage: ReloadStorage, entry: string): boolean {try {- const last = Number(storage.getItem(RELOAD_AT_KEY));- if (last > 0 && now - last < RELOAD_GUARD_MS) return false;- storage.setItem(RELOAD_AT_KEY, String(now));+ storage.setItem(RELOADED_FROM_KEY, entry);+ return true;} catch {return false;}+}++/** Reload into a newer build after a chunk load failure. Resolves to whether a+ * reload started. */+export async function reloadForChunkLoadError(+ error: unknown,+ {+ storage = sessionStore(),+ reload = () => window.location.reload(),+ runningEntry = documentEntry,+ publishedEntry = freshIndexEntry,+ online = () => navigator.onLine !== false,+ }: ChunkLoadRecoveryDeps = {},+): Promise<boolean> {+ // Without storage there is no loop guard, so keep the error visible instead.+ if (!storage || !isChunkLoadError(error) || !online()) return false;+ const running = runningEntry();+ if (!running) return false;+ const guard = reloadedFrom(storage);+ if (guard === undefined || guard === running) return false;+ const published = await publishedEntry();+ if (!published || published === running) return false;+ // Re-check after the fetch: a concurrent failure may already be reloading.+ if (reloadedFrom(storage) === running || !markReloadedFrom(storage, running)) return false;reload();return true;}@@ -56,9 +119,9 @@ export function reloadForChunkLoadError(* so the import still rejects as before when no reload happens. */export function startChunkLoadRecovery(target: Pick<Window, "addEventListener"> = window,- { storage, reload }: { storage?: ReloadStorage | null; reload?: () => void } = {},+ deps: ChunkLoadRecoveryDeps = {},): void {target.addEventListener("vite:preloadError", (event) => {- reloadForChunkLoadError((event as Event & { payload?: unknown }).payload, storage, reload);+ void reloadForChunkLoadError((event as Event & { payload?: unknown }).payload, deps);});}diff --git a/web/src/main.tsx b/web/src/main.tsxindex 34a674011e3..8242b0d6d8e 100644--- a/web/src/main.tsx+++ b/web/src/main.tsx@@ -10,8 +10,9 @@ import { ThemeProvider } from "./themes";import { HERMES_BASE_PATH } from "./lib/api";import { startChunkLoadRecovery } from "./lib/chunk-load-recovery";-// Before the first render, so the first lazy route is covered too.-startChunkLoadRecovery();+// Before the first render, so the first lazy route is covered too. The dev+// server has no hashed build to go stale.+if (import.meta.env.PROD) startChunkLoadRecovery();// Expose the plugin SDK before rendering so plugins loaded via <script>// can access React, components, etc. immediately.