From 20ab6f315d1c3ae5dc1586cd5a991f9f28231939 Mon Sep 17 00:00:00 2001 From: nullStack65 <112618179+nullStack65@users.noreply.github.com> Date: Fri, 27 Nov 2026 12:45:57 +0000 Subject: [PATCH 1/3] fix(web): reload up to three times on a failed chunk instead of dead-ending A failed code chunk reloaded the page once per tab session and never again. If the reload hit the same network blip, the app stopped on "T3 Code failed to start", and a later blip in the same tab got no retry at all. On a busy host, 2 of 100 cold loads ended there, each after the one reload had already failed. The guard now allows three reloads in a 60 second window, 0.75 s apart and growing, counted per build. A chunk that is really gone still stops after three tries. A tab that stored the old bare build string is treated as having no record. Found by the CLO-1299 feature sweep as CLO-1310. Co-Authored-By: Claude Sonnet 5.5 --- apps/web/src/lib/chunkReloadGuard.test.ts | 40 +++++++++++++++------ apps/web/src/lib/chunkReloadGuard.ts | 44 +++++++++++++++++------ 2 files changed, 63 insertions(+), 21 deletions(-) diff --git a/apps/web/src/lib/chunkReloadGuard.test.ts b/apps/web/src/lib/chunkReloadGuard.test.ts index 3a16834abc383..85d2a26c842c8 100644 --- a/apps/web/src/lib/chunkReloadGuard.test.ts +++ b/apps/web/src/lib/chunkReloadGuard.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from "vite-plus/test"; -import { isChunkLoadError, reloadOnceForChunkLoadError } from "./chunkReloadGuard"; +import { isChunkLoadError, reloadForChunkLoadError } from "./chunkReloadGuard"; function createStorageStub(): Storage { const store = new Map(); @@ -20,26 +20,44 @@ function createStorageStub(): Storage { }; } -describe("reloadOnceForChunkLoadError", () => { - it("reloads on the first failure and lets the second one surface", () => { +describe("reloadForChunkLoadError", () => { + it("retries with growing delays, then lets the failure surface", () => { const storage = createStorageStub(); const reload = vi.fn(); + const reloadAt = (now: number) => reloadForChunkLoadError(() => storage, reload, "1.0.0", now); - expect(reloadOnceForChunkLoadError(() => storage, reload, "1.0.0")).toBe(true); - expect(reload).toHaveBeenCalledTimes(1); + expect(reloadAt(0)).toBe(true); + expect(reloadAt(5_000)).toBe(true); + expect(reloadAt(10_000)).toBe(true); + expect(reloadAt(15_000)).toBe(false); + expect(reload.mock.calls.map(([delay]) => delay)).toEqual([750, 1500, 2250]); + }); + + it("reloads again once the window has passed", () => { + const storage = createStorageStub(); + const reload = vi.fn(); + for (const now of [0, 1_000, 2_000]) + reloadForChunkLoadError(() => storage, reload, "1.0.0", now); - expect(reloadOnceForChunkLoadError(() => storage, reload, "1.0.0")).toBe(false); - expect(reload).toHaveBeenCalledTimes(1); + expect(reloadForChunkLoadError(() => storage, reload, "1.0.0", 70_000)).toBe(true); + expect(reload).toHaveBeenCalledTimes(4); }); it("reloads again once a deploy changed the build", () => { const storage = createStorageStub(); const reload = vi.fn(); + for (const now of [0, 1_000, 2_000]) + reloadForChunkLoadError(() => storage, reload, "1.0.0", now); - reloadOnceForChunkLoadError(() => storage, reload, "1.0.0"); + expect(reloadForChunkLoadError(() => storage, reload, "1.0.1", 3_000)).toBe(true); + }); + + it("treats the bare build string an older tab stored as no record", () => { + const storage = createStorageStub(); + storage.setItem("t3code:chunk-load-reloaded", "1.0.0"); + const reload = vi.fn(); - expect(reloadOnceForChunkLoadError(() => storage, reload, "1.0.1")).toBe(true); - expect(reload).toHaveBeenCalledTimes(2); + expect(reloadForChunkLoadError(() => storage, reload, "1.0.0", 0)).toBe(true); }); it("never reloads when storage is blocked, so a persistent failure cannot loop", () => { @@ -48,7 +66,7 @@ describe("reloadOnceForChunkLoadError", () => { throw new DOMException("blocked", "SecurityError"); }; - expect(reloadOnceForChunkLoadError(blocked, reload)).toBe(false); + expect(reloadForChunkLoadError(blocked, reload)).toBe(false); expect(reload).not.toHaveBeenCalled(); }); }); diff --git a/apps/web/src/lib/chunkReloadGuard.ts b/apps/web/src/lib/chunkReloadGuard.ts index 43034ccb578b3..08000264f2f54 100644 --- a/apps/web/src/lib/chunkReloadGuard.ts +++ b/apps/web/src/lib/chunkReloadGuard.ts @@ -1,23 +1,47 @@ -// Deploys and desktop server swaps can invalidate lazy chunks; one reload fetches the fresh index. -// Keyed by build and kept across boots: a chunk loaded after boot can fail on every visit. +// A deploy, a desktop server swap or a network change can fail the chunks a load needs. Browsers +// cache a failed dynamic import per document, so only a reload retries it. A few reloads in a short +// window, spaced out, ride out a flapping connection; the cap keeps a chunk that is really gone +// from looping. Keyed by build, kept across boots: a chunk loaded after boot can fail on every visit. const CHUNK_RELOAD_GUARD_KEY = "t3code:chunk-load-reloaded"; +const MAX_RELOADS = 3; +const RELOAD_WINDOW_MS = 60_000; +const RELOAD_DELAY_MS = 750; -export function reloadOnceForChunkLoadError( +interface ReloadRecord { + readonly build: string; + readonly at: ReadonlyArray; +} + +// A tab opened before this format holds the bare build string, which is not a record. +function readRecord(raw: string | null): Partial | undefined { + try { + return raw === null ? undefined : (JSON.parse(raw) as Partial); + } catch { + return undefined; + } +} + +export function reloadForChunkLoadError( getStorage: () => Storage = () => window.sessionStorage, - reload: () => void = () => window.location.reload(), + reload: (delayMs: number) => void = (delayMs) => + void setTimeout(() => window.location.reload(), delayMs), build = import.meta.env.APP_VERSION, + now = Date.now(), ): boolean { - let alreadyReloaded: boolean; + let recent: ReadonlyArray = []; try { const storage = getStorage(); - alreadyReloaded = storage.getItem(CHUNK_RELOAD_GUARD_KEY) === build; - if (!alreadyReloaded) storage.setItem(CHUNK_RELOAD_GUARD_KEY, build); + const record = readRecord(storage.getItem(CHUNK_RELOAD_GUARD_KEY)); + if (record?.build === build && Array.isArray(record.at)) { + recent = record.at.filter((at) => now - at < RELOAD_WINDOW_MS); + } + if (recent.length >= MAX_RELOADS) return false; + storage.setItem(CHUNK_RELOAD_GUARD_KEY, JSON.stringify({ build, at: [...recent, now] })); } catch { // Without storage, the reload guard cannot prevent an infinite loop. return false; } - if (alreadyReloaded) return false; - reload(); + reload(RELOAD_DELAY_MS * (recent.length + 1)); return true; } @@ -40,7 +64,7 @@ export const chunkLoadState = { reloadScheduled: false }; // Registered from the entry before main loads, so main-chunk and route-chunk failures share one decision. export function handleChunkLoadErrors() { window.addEventListener("vite:preloadError", (event) => { - if (reloadOnceForChunkLoadError()) { + if (reloadForChunkLoadError()) { chunkLoadState.reloadScheduled = true; event.preventDefault(); } From 11d9235244844f822c33b3182bf8bb6fa3b70459 Mon Sep 17 00:00:00 2001 From: nullStack65 <112618179+nullStack65@users.noreply.github.com> Date: Fri, 27 Nov 2026 13:13:19 +0000 Subject: [PATCH 2/3] fix(web): one reload per failed load, a ten minute window, tests for the new contract Review of the first commit found that one failed load raises a preload error per lost chunk, so a single document could spend all three reloads and arm three timers. Those events now share one scheduled reload. A 60 second window also let a load that hangs and then fails every 20 seconds reload forever; the window is ten minutes, so three tries cover a flapping network and a slow failure still stops. Stamps from a clock that moved back no longer hold the cap shut. bootstrap.test.ts and main.test.ts still asserted the one-reload contract and a bare build string; they now cover three tries, the spent budget, and the delayed reload. Co-Authored-By: Claude Sonnet 5.5 --- apps/web/src/bootstrap.test.ts | 18 +++++-- apps/web/src/lib/chunkReloadGuard.test.ts | 59 +++++++++++++++++++++-- apps/web/src/lib/chunkReloadGuard.ts | 15 +++--- apps/web/src/main.test.ts | 10 +++- 4 files changed, 87 insertions(+), 15 deletions(-) diff --git a/apps/web/src/bootstrap.test.ts b/apps/web/src/bootstrap.test.ts index 8421d5efe0fc8..bf6cccacf108c 100644 --- a/apps/web/src/bootstrap.test.ts +++ b/apps/web/src/bootstrap.test.ts @@ -32,8 +32,12 @@ function createStorageStub(initial: Record = {}): Storage { }; } +const NOW = 1_700_000_000_000; + async function bootWithFailingMainChunk(storage: Storage) { vi.resetModules(); + vi.useFakeTimers(); + vi.setSystemTime(NOW); mocks.showBootError.mockClear(); const reload = vi.fn().mockName("location.reload"); vi.stubGlobal( @@ -43,23 +47,31 @@ async function bootWithFailingMainChunk(storage: Storage) { try { const { boot } = await import("./bootstrap"); await boot; + // The reload waits a moment for the network to settle. + await vi.advanceTimersByTimeAsync(5_000); return { reload, showBootError: mocks.showBootError }; } finally { vi.unstubAllGlobals(); + vi.useRealTimers(); } } describe("bootstrap", () => { - it("reloads once instead of showing the boot error when the main chunk fails to load", async () => { + it("reloads, once for the whole failed load, instead of showing the boot error when the main chunk fails", async () => { const { reload, showBootError } = await bootWithFailingMainChunk(createStorageStub()); expect(reload).toHaveBeenCalledTimes(1); expect(showBootError).not.toHaveBeenCalled(); }); - it("shows the boot error when the main chunk fails again after the reload", async () => { + it("shows the boot error once the reloads are used up and the main chunk still fails", async () => { const { reload, showBootError } = await bootWithFailingMainChunk( - createStorageStub({ "t3code:chunk-load-reloaded": import.meta.env.APP_VERSION }), + createStorageStub({ + "t3code:chunk-load-reloaded": JSON.stringify({ + build: import.meta.env.APP_VERSION, + at: [NOW - 3_000, NOW - 2_000, NOW - 1_000], + }), + }), ); expect(reload).not.toHaveBeenCalled(); diff --git a/apps/web/src/lib/chunkReloadGuard.test.ts b/apps/web/src/lib/chunkReloadGuard.test.ts index 85d2a26c842c8..e808fcd072598 100644 --- a/apps/web/src/lib/chunkReloadGuard.test.ts +++ b/apps/web/src/lib/chunkReloadGuard.test.ts @@ -1,6 +1,11 @@ -import { describe, expect, it, vi } from "vite-plus/test"; +import { afterEach, describe, expect, it, vi } from "vite-plus/test"; -import { isChunkLoadError, reloadForChunkLoadError } from "./chunkReloadGuard"; +import { + chunkLoadState, + handleChunkLoadErrors, + isChunkLoadError, + reloadForChunkLoadError, +} from "./chunkReloadGuard"; function createStorageStub(): Storage { const store = new Map(); @@ -33,16 +38,36 @@ describe("reloadForChunkLoadError", () => { expect(reload.mock.calls.map(([delay]) => delay)).toEqual([750, 1500, 2250]); }); + it("keeps a load that fails slowly, every 20 seconds, from reloading forever", () => { + const storage = createStorageStub(); + const reload = vi.fn(); + const outcomes = [0, 20_000, 40_000, 60_000, 80_000].map((now) => + reloadForChunkLoadError(() => storage, reload, "1.0.0", now), + ); + + expect(outcomes).toEqual([true, true, true, false, false]); + }); + it("reloads again once the window has passed", () => { const storage = createStorageStub(); const reload = vi.fn(); for (const now of [0, 1_000, 2_000]) reloadForChunkLoadError(() => storage, reload, "1.0.0", now); - expect(reloadForChunkLoadError(() => storage, reload, "1.0.0", 70_000)).toBe(true); + expect(reloadForChunkLoadError(() => storage, reload, "1.0.0", 11 * 60_000)).toBe(true); expect(reload).toHaveBeenCalledTimes(4); }); + it("ignores stamps from a clock that has since moved back", () => { + const storage = createStorageStub(); + storage.setItem( + "t3code:chunk-load-reloaded", + JSON.stringify({ build: "1.0.0", at: [1_000_000, 1_001_000, 1_002_000] }), + ); + + expect(reloadForChunkLoadError(() => storage, vi.fn(), "1.0.0", 0)).toBe(true); + }); + it("reloads again once a deploy changed the build", () => { const storage = createStorageStub(); const reload = vi.fn(); @@ -71,6 +96,34 @@ describe("reloadForChunkLoadError", () => { }); }); +describe("handleChunkLoadErrors", () => { + afterEach(() => { + vi.useRealTimers(); + vi.unstubAllGlobals(); + chunkLoadState.reloadScheduled = false; + }); + + it("spends one reload on the many preload errors one failed load raises", () => { + vi.useFakeTimers(); + const storage = createStorageStub(); + const reload = vi.fn(); + const page = Object.assign(new EventTarget(), { + sessionStorage: storage, + location: { reload }, + }); + vi.stubGlobal("window", page); + handleChunkLoadErrors(); + + const events = [1, 2, 3, 4].map(() => new Event("vite:preloadError", { cancelable: true })); + for (const event of events) page.dispatchEvent(event); + vi.advanceTimersByTime(5_000); + + expect(events.every((event) => event.defaultPrevented)).toBe(true); + expect(reload).toHaveBeenCalledTimes(1); + expect(JSON.parse(storage.getItem("t3code:chunk-load-reloaded") ?? "{}").at).toHaveLength(1); + }); +}); + describe("isChunkLoadError", () => { it.each([ ["Failed to fetch dynamically imported module: t3code://app/assets/a.js", true], diff --git a/apps/web/src/lib/chunkReloadGuard.ts b/apps/web/src/lib/chunkReloadGuard.ts index 08000264f2f54..b63ca47d023ac 100644 --- a/apps/web/src/lib/chunkReloadGuard.ts +++ b/apps/web/src/lib/chunkReloadGuard.ts @@ -1,10 +1,9 @@ -// A deploy, a desktop server swap or a network change can fail the chunks a load needs. Browsers -// cache a failed dynamic import per document, so only a reload retries it. A few reloads in a short -// window, spaced out, ride out a flapping connection; the cap keeps a chunk that is really gone -// from looping. Keyed by build, kept across boots: a chunk loaded after boot can fail on every visit. +// A failed chunk is only retried by a reload, so a few spaced-out reloads ride out a flapping network. +// The cap stops a chunk that is gone, or a load that hangs and then fails, from looping. +// Keyed by build and kept across boots: a chunk loaded after boot can fail on every visit. const CHUNK_RELOAD_GUARD_KEY = "t3code:chunk-load-reloaded"; const MAX_RELOADS = 3; -const RELOAD_WINDOW_MS = 60_000; +const RELOAD_WINDOW_MS = 10 * 60_000; const RELOAD_DELAY_MS = 750; interface ReloadRecord { @@ -33,7 +32,8 @@ export function reloadForChunkLoadError( const storage = getStorage(); const record = readRecord(storage.getItem(CHUNK_RELOAD_GUARD_KEY)); if (record?.build === build && Array.isArray(record.at)) { - recent = record.at.filter((at) => now - at < RELOAD_WINDOW_MS); + // A stamp from the future (the clock moved back) would hold the cap shut, so it does not count. + recent = record.at.filter((at) => at <= now && now - at < RELOAD_WINDOW_MS); } if (recent.length >= MAX_RELOADS) return false; storage.setItem(CHUNK_RELOAD_GUARD_KEY, JSON.stringify({ build, at: [...recent, now] })); @@ -64,7 +64,8 @@ export const chunkLoadState = { reloadScheduled: false }; // Registered from the entry before main loads, so main-chunk and route-chunk failures share one decision. export function handleChunkLoadErrors() { window.addEventListener("vite:preloadError", (event) => { - if (reloadForChunkLoadError()) { + // One failed load raises this event for every chunk it lost; they share one reload. + if (chunkLoadState.reloadScheduled || reloadForChunkLoadError()) { chunkLoadState.reloadScheduled = true; event.preventDefault(); } diff --git a/apps/web/src/main.test.ts b/apps/web/src/main.test.ts index 11b9b68c867d1..8778559a09d39 100644 --- a/apps/web/src/main.test.ts +++ b/apps/web/src/main.test.ts @@ -8,6 +8,7 @@ vi.mock("react-dom/client", () => ({ default: { createRoot: () => ({ render: () // Boots the entry in a fresh page that shares the tab's sessionStorage, as a reload does. async function bootThenFailLazyChunk(sessionStorage: Map) { vi.resetModules(); + vi.useFakeTimers(); const reload = vi.fn().mockName("location.reload"); const page = Object.assign(new EventTarget(), { sessionStorage: { @@ -23,15 +24,20 @@ async function bootThenFailLazyChunk(sessionStorage: Map) { const { boot } = await import("./bootstrap"); await boot; page.dispatchEvent(new Event("vite:preloadError", { cancelable: true })); + // The reload waits a moment for the network to settle. + await vi.advanceTimersByTimeAsync(5_000); return reload; } finally { vi.unstubAllGlobals(); + vi.useRealTimers(); } } -it("reloads only once when a lazy chunk fails after every boot", async () => { +it("stops reloading after three tries when a lazy chunk fails after every boot", async () => { const sessionStorage = new Map(); - expect(await bootThenFailLazyChunk(sessionStorage)).toHaveBeenCalledTimes(1); + for (let boot = 0; boot < 3; boot++) { + expect(await bootThenFailLazyChunk(sessionStorage)).toHaveBeenCalledTimes(1); + } expect(await bootThenFailLazyChunk(sessionStorage)).not.toHaveBeenCalled(); }); From b777b9cc75606b6e47eeac72c08bf0f7d6ac15bc Mon Sep 17 00:00:00 2001 From: nullStack65 <112618179+nullStack65@users.noreply.github.com> Date: Fri, 27 Nov 2026 13:26:13 +0000 Subject: [PATCH 3/3] fix(web): narrow the stored reload record so the guard typechecks Co-Authored-By: Claude Sonnet 5.5 --- apps/web/src/lib/chunkReloadGuard.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/apps/web/src/lib/chunkReloadGuard.ts b/apps/web/src/lib/chunkReloadGuard.ts index b63ca47d023ac..c6cd4af00e5c7 100644 --- a/apps/web/src/lib/chunkReloadGuard.ts +++ b/apps/web/src/lib/chunkReloadGuard.ts @@ -31,9 +31,10 @@ export function reloadForChunkLoadError( try { const storage = getStorage(); const record = readRecord(storage.getItem(CHUNK_RELOAD_GUARD_KEY)); - if (record?.build === build && Array.isArray(record.at)) { + const stamps = record !== undefined && record.build === build ? record.at : undefined; + if (Array.isArray(stamps)) { // A stamp from the future (the clock moved back) would hold the cap shut, so it does not count. - recent = record.at.filter((at) => at <= now && now - at < RELOAD_WINDOW_MS); + recent = stamps.filter((at) => at <= now && now - at < RELOAD_WINDOW_MS); } if (recent.length >= MAX_RELOADS) return false; storage.setItem(CHUNK_RELOAD_GUARD_KEY, JSON.stringify({ build, at: [...recent, now] }));