Skip to content

The agent that grows with you

Port from paperclipai/paperclip#17349: reload once when a lazy chunk fails to load

Teknium640b2c21d32f
diff --git a/web/src/lib/chunk-load-recovery.test.ts b/web/src/lib/chunk-load-recovery.test.ts
new file mode 100644
index 00000000000..62851ca91aa
--- /dev/null
+++ b/web/src/lib/chunk-load-recovery.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it, vi } from "vitest";
+import { reloadForChunkLoadError } from "./chunk-load-recovery";
+
+function memoryStorage() {
+ const data = new Map<string, string>();
+ return {
+ getItem: (k: string) => data.get(k) ?? null,
+ setItem: (k: string, v: string) => void data.set(k, v),
+ };
+}
+
+const staleChunk = () =>
+ new Error("Failed to fetch dynamically imported module: http://127.0.0.1:9119/assets/ConfigPage-D09a41f-.js");
+
+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);
+ 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();
+ 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(reload).not.toHaveBeenCalled();
+ });
+});
diff --git a/web/src/lib/chunk-load-recovery.ts b/web/src/lib/chunk-load-recovery.ts
new file mode 100644
index 00000000000..03e30344fdc
--- /dev/null
+++ b/web/src/lib/chunk-load-recovery.ts
@@ -0,0 +1,61 @@
+// 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.
+
+const RELOAD_AT_KEY = "hermes.chunkLoadReloadAt";
+const RELOAD_GUARD_MS = 5 * 60 * 1000;
+
+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)",
+);
+
+type ReloadStorage = Pick<Storage, "getItem" | "setItem">;
+
+/** 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. */
+export function isChunkLoadError(error: unknown): boolean {
+ if (!(error instanceof Error) || !CHUNK_LOAD_ERROR.test(error.message)) return false;
+ const url = /https?:\/\/\S+|\/\S+/.exec(error.message)?.[0];
+ return !url || url.includes("/assets/");
+}
+
+function sessionStore(): ReloadStorage | null {
+ try {
+ return window.sessionStorage;
+ } catch {
+ return 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;
+ 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));
+ } catch {
+ return false;
+ }
+ reload();
+ return true;
+}
+
+/** Vite dispatches `vite:preloadError` for every failed lazy import and chunk
+ * CSS preload, including imports nobody awaits. The event is not cancelled,
+ * so the import still rejects as before when no reload happens. */
+export function startChunkLoadRecovery(target: Pick<Window, "addEventListener"> = window): void {
+ target.addEventListener("vite:preloadError", (event) => {
+ reloadForChunkLoadError((event as Event & { payload?: unknown }).payload);
+ });
+}
diff --git a/web/src/main.tsx b/web/src/main.tsx
index d0f448c3aa5..34a674011e3 100644
--- a/web/src/main.tsx
+++ b/web/src/main.tsx
@@ -8,6 +8,10 @@ import { I18nProvider } from "./i18n";
import { exposePluginSDK } from "./plugins";
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();
// Expose the plugin SDK before rendering so plugins loaded via <script>
// can access React, components, etc. immediately.