diff --git a/ui/src/lib/chunk-load-recovery.test.ts b/ui/src/lib/chunk-load-recovery.test.ts index bc611c1f675..65f5ed62e2b 100644 --- a/ui/src/lib/chunk-load-recovery.test.ts +++ b/ui/src/lib/chunk-load-recovery.test.ts @@ -212,6 +212,82 @@ describe("reloadForChunkLoadError", () => { }); }); +describe("readChunkLoadRecoveryOutcome", () => { + afterEach(() => { + vi.useRealTimers(); + }); + + const moduleScriptError = () => new TypeError("Importing a module script failed."); + + it("records a reload that the page abandoned, for each error waiting on it", () => { + vi.useFakeTimers(); + const recovery = createChunkLoadRecovery({ storage: () => memoryStorage(), reload: vi.fn() }); + const first = moduleScriptError(); + const second = moduleScriptError(); + recovery.reloadForChunkLoadError(first); + recovery.reloadForChunkLoadError(second); + expect(recovery.readChunkLoadRecoveryOutcome(first)).toBe("reload_pending"); + expect(recovery.readChunkLoadRecoveryOutcome(second)).toBe("reload_pending"); + + let reportedOutcome: string | undefined; + recovery.onChunkLoadReloadAbandoned(() => { + reportedOutcome = recovery.readChunkLoadRecoveryOutcome(first); + }); + vi.advanceTimersByTime(RELOAD_ABANDONED_MS); + expect(reportedOutcome).toBe("reload_abandoned"); + expect(recovery.readChunkLoadRecoveryOutcome(second)).toBe("reload_abandoned"); + + const later = moduleScriptError(); + recovery.reloadForChunkLoadError(later); + expect(recovery.readChunkLoadRecoveryOutcome(later)).toBe("disabled_after_abandon"); + }); + + it("records why the error surfaced without a reload", () => { + const storage = memoryStorage(); + let now = 1_000_000; + for (let attempt = 0; attempt < RELOAD_DELAYS_MS.length; attempt += 1) { + createChunkLoadRecovery({ storage: () => storage, reload: vi.fn(), now: () => now }).reloadForChunkLoadError(cssPreloadError); + now += 10_000; + } + const exhausted = createChunkLoadRecovery({ storage: () => storage, reload: vi.fn(), now: () => now }); + const error = moduleScriptError(); + exhausted.reloadForChunkLoadError(error); + expect(exhausted.readChunkLoadRecoveryOutcome(error)).toBe("retries_exhausted"); + + const noStorage = createChunkLoadRecovery({ storage: () => null, reload: vi.fn() }); + const unguarded = moduleScriptError(); + noStorage.reloadForChunkLoadError(unguarded); + expect(noStorage.readChunkLoadRecoveryOutcome(unguarded)).toBe("storage_unavailable"); + + const throwing = createChunkLoadRecovery({ + storage: () => ({ + getItem: () => { throw new Error("SecurityError"); }, + setItem: () => { throw new Error("SecurityError"); }, + }), + reload: vi.fn(), + }); + const blocked = moduleScriptError(); + throwing.reloadForChunkLoadError(blocked); + expect(throwing.readChunkLoadRecoveryOutcome(blocked)).toBe("storage_unavailable"); + }); + + it("records a cancelled delayed retry and ignores errors it never handled", () => { + vi.useFakeTimers(); + const storage = memoryStorage({ "paperclip:chunk-load-reload-at": "1000000" }); + const recovery = createChunkLoadRecovery({ storage: () => storage, reload: vi.fn(), now: () => 1_010_000 }); + const error = moduleScriptError(); + recovery.reloadForChunkLoadError(error); + recovery.cancelPendingChunkLoadReload(); + expect(recovery.readChunkLoadRecoveryOutcome(error)).toBe("reload_cancelled"); + + const renderError = new Error("boom"); + recovery.reloadForChunkLoadError(renderError); + expect(recovery.readChunkLoadRecoveryOutcome(renderError)).toBeUndefined(); + expect(recovery.readChunkLoadRecoveryOutcome(moduleScriptError())).toBeUndefined(); + expect(recovery.readChunkLoadRecoveryOutcome("Importing a module script failed.")).toBeUndefined(); + }); +}); + describe("startChunkLoadRecovery", () => { it("reloads for a Vite preload failure without cancelling the rejection", () => { const target = new EventTarget(); diff --git a/ui/src/lib/chunk-load-recovery.ts b/ui/src/lib/chunk-load-recovery.ts index 8d541d80a0f..f23570cb45d 100644 --- a/ui/src/lib/chunk-load-recovery.ts +++ b/ui/src/lib/chunk-load-recovery.ts @@ -24,6 +24,18 @@ export function isChunkLoadError(error: unknown): boolean { type ReloadStorage = Pick; +/** + * Why a chunk-load error did or did not lead to a page reload. Error reports + * carry it so a report can tell which recovery step gave up. + */ +export type ChunkLoadRecoveryOutcome = + | "reload_pending" + | "reload_abandoned" + | "reload_cancelled" + | "retries_exhausted" + | "storage_unavailable" + | "disabled_after_abandon"; + function isPositiveTime(value: number): boolean { return Number.isFinite(value) && value > 0; } @@ -60,11 +72,30 @@ export function createChunkLoadRecovery(options: ChunkLoadRecoveryOptions = {}) let pendingReloadTimer: ReturnType | null = null; let abandonTimer: ReturnType | null = null; const abandonedListeners = new Set<() => void>(); + const outcomes = new WeakMap(); + const waitingErrors = new Set(); + + function settleWaitingErrors(outcome: ChunkLoadRecoveryOutcome) { + for (const error of waitingErrors) outcomes.set(error, outcome); + waitingErrors.clear(); + } + + function giveUp(error: Error, outcome: ChunkLoadRecoveryOutcome): false { + outcomes.set(error, outcome); + return false; + } + + function waitForReload(error: Error): true { + outcomes.set(error, "reload_pending"); + waitingErrors.add(error); + return true; + } function abandonReload() { abandonTimer = null; reloading = false; reloadAbandoned = true; + settleWaitingErrors("reload_abandoned"); const listeners = [...abandonedListeners]; abandonedListeners.clear(); for (const listener of listeners) listener(); @@ -72,25 +103,28 @@ export function createChunkLoadRecovery(options: ChunkLoadRecoveryOptions = {}) function reloadForChunkLoadError(error: unknown): boolean { if (!isChunkLoadError(error)) return false; - if (reloading) return true; - if (reloadAbandoned) return false; + // isChunkLoadError accepts Error instances only. + const chunkError = error as Error; + if (reloading) return waitForReload(chunkError); + if (reloadAbandoned) return giveUp(chunkError, "disabled_after_abandon"); const storage = readStorage(); - if (!storage) return false; + if (!storage) return giveUp(chunkError, "storage_unavailable"); const at = now(); let delayMs: number; try { const startedAt = Number(storage.getItem(RELOAD_AT_KEY)); const inWindow = isPositiveTime(startedAt) && at - startedAt < RELOAD_GUARD_MS; const attempt = inWindow ? readAttempts(storage.getItem(RELOAD_ATTEMPTS_KEY), startedAt) : 0; - if (attempt >= RELOAD_DELAYS_MS.length) return false; + if (attempt >= RELOAD_DELAYS_MS.length) return giveUp(chunkError, "retries_exhausted"); delayMs = RELOAD_DELAYS_MS[attempt]!; const windowStartedAt = inWindow ? startedAt : at; if (!inWindow) storage.setItem(RELOAD_AT_KEY, String(windowStartedAt)); storage.setItem(RELOAD_ATTEMPTS_KEY, `${windowStartedAt}:${attempt + 1}`); } catch { - return false; + return giveUp(chunkError, "storage_unavailable"); } reloading = true; + waitForReload(chunkError); if (delayMs > 0) { pendingReloadTimer = globalThis.setTimeout(() => { pendingReloadTimer = null; @@ -113,9 +147,15 @@ export function createChunkLoadRecovery(options: ChunkLoadRecoveryOptions = {}) abandonTimer = null; reloading = false; abandonedListeners.clear(); + settleWaitingErrors("reload_cancelled"); return true; } + /** The recovery decision recorded for this exact error, if it was a chunk-load error. */ + function readChunkLoadRecoveryOutcome(error: unknown): ChunkLoadRecoveryOutcome | undefined { + return error instanceof Error ? outcomes.get(error) : undefined; + } + function onChunkLoadReloadAbandoned(listener: () => void): () => void { if (!reloading) { listener(); @@ -135,7 +175,13 @@ export function createChunkLoadRecovery(options: ChunkLoadRecoveryOptions = {}) return () => target.removeEventListener("vite:preloadError", onPreloadError); } - return { reloadForChunkLoadError, cancelPendingChunkLoadReload, onChunkLoadReloadAbandoned, startChunkLoadRecovery }; + return { + reloadForChunkLoadError, + cancelPendingChunkLoadReload, + onChunkLoadReloadAbandoned, + readChunkLoadRecoveryOutcome, + startChunkLoadRecovery, + }; } const browserRecovery = createChunkLoadRecovery(); @@ -143,4 +189,5 @@ const browserRecovery = createChunkLoadRecovery(); export const reloadForChunkLoadError = browserRecovery.reloadForChunkLoadError; export const cancelPendingChunkLoadReload = browserRecovery.cancelPendingChunkLoadReload; export const onChunkLoadReloadAbandoned = browserRecovery.onChunkLoadReloadAbandoned; +export const readChunkLoadRecoveryOutcome = browserRecovery.readChunkLoadRecoveryOutcome; export const startChunkLoadRecovery = browserRecovery.startChunkLoadRecovery; diff --git a/ui/src/lib/sentry.test.ts b/ui/src/lib/sentry.test.ts index 7e40f9b083c..0718f9abbe5 100644 --- a/ui/src/lib/sentry.test.ts +++ b/ui/src/lib/sentry.test.ts @@ -659,6 +659,29 @@ describe("buildBrowserSentryInitOptions", () => { expect(host?.tags).not.toHaveProperty("browser_plugin_module"); }); + it("tags a chunk-load error with the reload recovery step that gave up", async () => { + const { buildBrowserSentryInitOptions } = await importFreshSentry(); + const recovery = await import("./chunk-load-recovery"); + window.sessionStorage.clear(); + const beforeSend = buildBrowserSentryInitOptions(DSN).beforeSend!; + const eventFor = () => ({ + exception: { values: [{ type: "TypeError", mechanism: { type: "generic", handled: true } }] }, + }); + + // Earlier reloads in this tab already used every retry in the guard window. + const exhaustedPage = new TypeError("Importing a module script failed."); + const seeded = Date.now(); + window.sessionStorage.setItem("paperclip:chunk-load-reload-at", String(seeded)); + window.sessionStorage.setItem("paperclip:chunk-load-reload-attempts", `${seeded}:3`); + expect(recovery.reloadForChunkLoadError(exhaustedPage)).toBe(false); + const tagged = await beforeSend(eventFor() as never, { originalException: exhaustedPage }); + expect(tagged?.tags).toMatchObject({ browser_chunk_reload: "retries_exhausted" }); + + const renderError = await beforeSend(eventFor() as never, { originalException: new Error("boom") }); + expect(renderError?.tags).not.toHaveProperty("browser_chunk_reload"); + window.sessionStorage.clear(); + }); + it("adds diagnostics without a transaction filter", async () => { const { buildBrowserSentryInitOptions } = await importFreshSentry(); diff --git a/ui/src/lib/sentry.ts b/ui/src/lib/sentry.ts index a6c97a3480b..038b9eba816 100644 --- a/ui/src/lib/sentry.ts +++ b/ui/src/lib/sentry.ts @@ -63,6 +63,7 @@ import { readFetchWrapperState, startFetchRejectionDiagnostics, } from "./fetch-rejection-origin"; +import { readChunkLoadRecoveryOutcome } from "./chunk-load-recovery"; import { isIntentionalAbortReason } from "./intentional-abort"; import { readPluginModuleOrigin } from "./plugin-module-origins"; @@ -285,6 +286,10 @@ export function buildBrowserSentryInitOptions( // whose module holds the innermost such frame, never the URL. const pluginModule = readPluginModuleOrigin(event.exception?.values); if (pluginModule) event.tags.browser_plugin_module = pluginModule; + // A lazy chunk that failed to load normally reloads the page. Record + // which recovery step gave up, so a report shows why it still surfaced. + const chunkReload = readChunkLoadRecoveryOutcome(hint.originalException); + if (chunkReload) event.tags.browser_chunk_reload = chunkReload; if (isGlobalOnError(event)) { event.tags.browser_thrown_kind = classifyThrownValue(hint.originalException); }