Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: recover stale shell module failures safely

[._.]/ Adam Eivyde39a75ecf8f
diff --git a/client/src/components/ErrorBoundary.jsx b/client/src/components/ErrorBoundary.jsx
index 8d28602ec0..bb0ab9e497 100644
--- a/client/src/components/ErrorBoundary.jsx
+++ b/client/src/components/ErrorBoundary.jsx
@@ -14,14 +14,26 @@ export default class ErrorBoundary extends Component {
}
componentDidCatch(error, errorInfo) {
- if (isStaleChunkError(error) && reloadOnceForStaleChunk()) return;
- console.error(`💥 React Error: ${error.message}`, errorInfo);
- // `onError` lets a caller that owns chrome AROUND the failed subtree react
- // to the failure — an r3f `<Canvas>` can only degrade to `fallback={null}`
- // inside the scene, so the DOM-side message has to be rendered by the
- // parent from its own state (ThreejsModelPreview's spec-render panel).
- // Not called on the stale-chunk path above: that reloads the page.
- this.props.onError?.(error);
+ const report = () => {
+ console.error(`💥 React Error: ${error.message}`, errorInfo);
+ // `onError` lets a caller that owns chrome AROUND the failed subtree
+ // react to the failure — an r3f `<Canvas>` can only degrade to
+ // `fallback={null}` inside the scene, so the DOM-side message has to be
+ // rendered by the parent from its own state.
+ this.props.onError?.(error);
+ };
+
+ if (isStaleChunkError(error, { duringRender: true })) {
+ // React may catch missing runtime exports after import() already resolved.
+ // Recover only when the live shell confirms this page is stale; otherwise
+ // report the real render error to the owning boundary.
+ void reloadOnceForStaleChunk().then((reloaded) => {
+ if (!reloaded) report();
+ });
+ return;
+ }
+
+ report();
}
render() {
diff --git a/client/src/components/RouteErrorFallback.jsx b/client/src/components/RouteErrorFallback.jsx
index 6740967a68..daaaf9e049 100644
--- a/client/src/components/RouteErrorFallback.jsx
+++ b/client/src/components/RouteErrorFallback.jsx
@@ -17,7 +17,9 @@ export default function RouteErrorFallback() {
const message = getErrorMessage(error);
useEffect(() => {
- if (isStaleChunkError(error)) reloadOnceForStaleChunk();
+ if (isStaleChunkError(error, { duringRender: true })) {
+ void reloadOnceForStaleChunk();
+ }
}, [error]);
return (
diff --git a/client/src/components/RouteErrorFallback.test.jsx b/client/src/components/RouteErrorFallback.test.jsx
index 30631ec376..94a6a03033 100644
--- a/client/src/components/RouteErrorFallback.test.jsx
+++ b/client/src/components/RouteErrorFallback.test.jsx
@@ -48,7 +48,7 @@ describe('RouteErrorFallback', () => {
await renderRouteError(error);
- expect(isStaleChunkError).toHaveBeenCalledWith(error);
+ expect(isStaleChunkError).toHaveBeenCalledWith(error, { duringRender: true });
expect(reloadOnceForStaleChunk).toHaveBeenCalledOnce();
});
diff --git a/client/src/components/cos/CoSCanvasGuard.test.jsx b/client/src/components/cos/CoSCanvasGuard.test.jsx
index 117fcb3d30..005e1521fe 100644
--- a/client/src/components/cos/CoSCanvasGuard.test.jsx
+++ b/client/src/components/cos/CoSCanvasGuard.test.jsx
@@ -7,6 +7,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const webgl = vi.hoisted(() => ({ available: true }));
vi.mock('../../lib/webglSupport', () => ({ isWebGLAvailable: () => webgl.available }));
+const recovery = vi.hoisted(() => ({ attempt: vi.fn() }));
+vi.mock('../../utils/staleChunkReload', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, reloadOnceForStaleChunk: recovery.attempt };
+});
+
import CoSCanvasGuard from './CoSCanvasGuard';
const Boom = ({ error }) => { throw error; };
@@ -15,6 +21,7 @@ describe('CoSCanvasGuard', () => {
let logged;
beforeEach(() => {
webgl.available = true;
+ recovery.attempt.mockReset().mockResolvedValue(false);
logged = vi.spyOn(console, 'error').mockImplementation(() => {});
});
afterEach(() => {
@@ -69,6 +76,31 @@ describe('CoSCanvasGuard', () => {
expect(screen.getByText('something went sideways')).toBeInTheDocument();
});
+ it('checks for a newer build when an avatar render hits a missing runtime export', async () => {
+ render(
+ <CoSCanvasGuard>
+ <Boom error={new Error("undefined is not an object (evaluating 'rv.jsx')")} />
+ </CoSCanvasGuard>,
+ );
+
+ await vi.waitFor(() => expect(recovery.attempt).toHaveBeenCalledOnce());
+ await vi.waitFor(() => expect(screen.getByTestId('cos-avatar-asset-error')).toBeInTheDocument());
+ expect(screen.getByText(/undefined is not an object/i)).toBeInTheDocument();
+ });
+
+ it('leaves avatar error reporting to recovery when a newer build is confirmed', async () => {
+ recovery.attempt.mockResolvedValue(true);
+ render(
+ <CoSCanvasGuard>
+ <Boom error={new Error("undefined is not an object (evaluating 'rv.jsx')")} />
+ </CoSCanvasGuard>,
+ );
+
+ await vi.waitFor(() => expect(recovery.attempt).toHaveBeenCalledOnce());
+ expect(screen.queryByTestId('cos-avatar-asset-error')).not.toBeInTheDocument();
+ expect(logged).not.toHaveBeenCalledWith(expect.stringContaining('💥 React Error'), expect.anything());
+ });
+
// Without the resetKey the panel sticks forever: once it is up the boundary
// is unmounted, so nothing can retry. The mini-character wrappers switch
// `variant` (and with it the GLB URL) on the same guard instance.
diff --git a/client/src/main.jsx b/client/src/main.jsx
index e6747ddbb7..d5470a1960 100644
--- a/client/src/main.jsx
+++ b/client/src/main.jsx
@@ -17,19 +17,25 @@ import './index.css';
// only — no-op in dev and over plain-HTTP Tailnet). See lib/registerServiceWorker.
registerServiceWorker();
-// Vite emits `vite:preloadError` when a code-split chunk's preload 404s —
-// usually because the server rebuilt and the chunk filename changed while
-// this tab was still open. Catching it here reloads before React's error
-// boundary ever sees the failure.
+// Start checking for a newer build as soon as a chunk preload fails. Vite also
+// emits this for module evaluation errors, so the recovery helper reloads only
+// after the live shell confirms this tab is stale.
window.addEventListener('vite:preloadError', (event) => {
- if (reloadOnceForStaleChunk()) event.preventDefault?.();
+ if (isStaleChunkError(event.payload, { duringImport: true })) {
+ void reloadOnceForStaleChunk();
+ }
});
// Handle unhandled promise rejections — also a chance to catch stale chunks
// that surface as a rejected dynamic-import promise outside React's tree.
window.addEventListener('unhandledrejection', (event) => {
- if (isStaleChunkError(event.reason) && reloadOnceForStaleChunk()) {
+ if (isStaleChunkError(event.reason, { duringImport: true })) {
event.preventDefault();
+ void reloadOnceForStaleChunk().then((reloaded) => {
+ if (reloaded) return;
+ reportClientError({ type: 'unhandledrejection', reason: event.reason });
+ console.error('❌ Unhandled Promise Rejection:', event.reason);
+ });
return;
}
// Report first so a hostile `event.reason` (throwing toString / circular)
diff --git a/client/src/test/viteChunkGroups.test.js b/client/src/test/viteChunkGroups.test.js
index 5a6b3b8b4e..15453bcd9e 100644
--- a/client/src/test/viteChunkGroups.test.js
+++ b/client/src/test/viteChunkGroups.test.js
@@ -1,7 +1,10 @@
-import { existsSync, readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
+import { execFileSync } from 'node:child_process';
+import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
import { describe, expect, it } from 'vitest';
+import { build } from 'vite';
import { CHUNK_GROUPS } from '../../vite.chunkGroups.js';
import viteConfig from '../../vite.config.js';
@@ -94,6 +97,62 @@ describe('vite chunk groups', () => {
expect(resolved.build.rolldownOptions.output.strictExecutionOrder).toBe(true);
});
+ it('executes cross-chunk superclass modules before their lazy subclass', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'portos-chunk-order-'));
+ const outputDir = join(root, 'dist');
+
+ try {
+ writeFileSync(join(root, 'package.json'), '{"type":"module"}');
+ writeFileSync(join(root, 'entry.js'), "globalThis.__portosFeaturePromise = import('./feature.js');\n");
+ writeFileSync(join(root, 'base.js'), "globalThis.__portosChunkOrder.push('base'); export class Base {}\n");
+ writeFileSync(join(root, 'feature.js'), [
+ "import { Base } from './base.js';",
+ "globalThis.__portosChunkOrder.push('feature');",
+ 'export class Feature extends Base {}',
+ 'export { Base };',
+ ].join('\n'));
+ writeFileSync(join(root, 'run.mjs'), [
+ 'globalThis.__portosChunkOrder = [];',
+ "await import('./dist/entry.js');",
+ 'const { Base, Feature } = await globalThis.__portosFeaturePromise;',
+ "console.log(JSON.stringify({ order: globalThis.__portosChunkOrder, instanceOfBase: new Feature() instanceof Base }));",
+ ].join('\n'));
+
+ await build({
+ configFile: false,
+ root,
+ logLevel: 'silent',
+ build: {
+ outDir: outputDir,
+ emptyOutDir: true,
+ minify: false,
+ modulePreload: false,
+ rolldownOptions: {
+ input: resolve(root, 'entry.js'),
+ output: {
+ strictExecutionOrder: true,
+ entryFileNames: '[name].js',
+ chunkFileNames: '[name].js',
+ codeSplitting: {
+ groups: [{
+ name: 'shared-base',
+ test: (id) => /[/\\]base\.js$/.test(id),
+ includeDependenciesRecursively: false,
+ }],
+ },
+ },
+ },
+ },
+ });
+
+ expect(readdirSync(outputDir)).toContain('shared-base.js');
+ const result = execFileSync(process.execPath, [join(root, 'run.mjs')], { encoding: 'utf-8', timeout: 10_000 });
+ expect(JSON.parse(result)).toEqual({ order: ['base', 'feature'], instanceOfBase: true });
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+
it('keeps package names from bleeding across the separator', () => {
// A declared name must match a whole path segment: `react` must not swallow
// `react-redux`. The trailing separator is what enforces that.
diff --git a/client/src/utils/README.md b/client/src/utils/README.md
index f40a916aca..8bd3f5fa01 100644
--- a/client/src/utils/README.md
+++ b/client/src/utils/README.md
@@ -71,8 +71,8 @@ is where each shared table is re-exported from its `server/lib` leaf.
| Module | Purpose |
|---|---|
-| `lazyWithReload` | `React.lazy` wrapper that auto-reloads once on a stale-chunk import error (post-deploy hash mismatch). |
-| `staleChunkReload` | Detects stale dynamic-import chunk errors (`isStaleChunkError`) and triggers a one-time reload guard; `purgeOfflineCaches()` drops the service-worker caches so the recovery reload boots the fresh bundle. |
+| `lazyWithReload` | `React.lazy` wrapper that retries transient import failures and reloads only when a failed chunk belongs to an older build. |
+| `staleChunkReload` | Detects stale import/runtime-export errors at import and render boundaries, confirms the served build changed before reloading, and purges service-worker caches for that recovery. |
## File handling
diff --git a/client/src/utils/lazyWithReload.js b/client/src/utils/lazyWithReload.js
index fc4540b2a7..b727d9b769 100644
--- a/client/src/utils/lazyWithReload.js
+++ b/client/src/utils/lazyWithReload.js
@@ -30,8 +30,8 @@ export const importWithRetry = (importFn, retriesLeft = MAX_RETRIES) =>
// once to pick up the new bundle. Everything else re-throws so error boundaries
// can see it.
export const lazyWithReload = (importFn) => lazy(() =>
- importWithRetry(importFn).catch(err => {
- if (isStaleChunkError(err, { duringImport: true }) && reloadOnceForStaleChunk()) {
+ importWithRetry(importFn).catch(async (err) => {
+ if (isStaleChunkError(err, { duringImport: true }) && await reloadOnceForStaleChunk()) {
return new Promise(() => {});
}
throw err;
diff --git a/client/src/utils/staleChunkReload.js b/client/src/utils/staleChunkReload.js
index e70a366687..b411ec693f 100644
--- a/client/src/utils/staleChunkReload.js
+++ b/client/src/utils/staleChunkReload.js
@@ -18,11 +18,12 @@ const STALE_CHUNK_PATTERNS = [
// These can mean an old/new module graph supplied incompatible runtime exports,
// but the same messages can come from real application bugs. Match them only
-// while handling a rejected dynamic import, never from global error handlers.
+// at import/render boundaries; recovery still requires a confirmed newer build.
const MODULE_EVALUATION_PATTERNS = ['superclass is not a constructor'];
const SAFARI_RUNTIME_EXPORTS = ['useState', 'jsx'];
const RELOAD_FLAG = 'portos.staleChunkReloadAttempted';
+const reloadAttempts = new Map();
// The service worker names every cache it owns with this prefix
// (`portos-shell-v1`, `portos-assets-v1`, …). Mirrored from public/sw.js so the
@@ -30,15 +31,13 @@ const RELOAD_FLAG = 'portos.staleChunkReloadAttempted';
// between the page and its controlling worker on the same origin.
const CACHE_PREFIX = 'portos-';
-// Upper bound on how long we wait for the cache purge before reloading anyway.
-// A hung or absent Cache Storage (private mode, storage disabled/partitioned)
-// must never leave the user stuck on the error screen — reload regardless.
+// Bound both the live-build probe and a confirmed-new-build cache purge.
const PURGE_TIMEOUT_MS = 1500;
-export const isStaleChunkError = (err, { duringImport = false } = {}) => {
+export const isStaleChunkError = (err, { duringImport = false, duringRender = false } = {}) => {
const msg = (err?.message || String(err || '')).toLowerCase();
if (STALE_CHUNK_PATTERNS.some(p => msg.includes(p))) return true;
- if (!duringImport) return false;
+ if (!duringImport && !duringRender) return false;
return MODULE_EVALUATION_PATTERNS.some((p) => msg.includes(p))
|| (msg.includes('undefined is not an object')
@@ -110,34 +109,37 @@ export const fetchServerBuildId = async () => {
export const reloadOnceForStaleChunk = () => {
const buildId = getCurrentBuildId();
- const flag = buildId ? `${buildId}` : '1';
- // The stored flag IS the anti-loop guard, so it gets the sentinel treatment
- // (root AGENTS.md): a storage that cannot persist must not read back as
- // `no reload attempted yet`, which would reload on every stale-chunk error
- // forever. Write, then read back — a mismatch means storage is unavailable
- // (Safari private mode, blocked storage, disabled cookies) and the page stays
- // put. The guarded helpers also keep the throw itself from taking out the very
- // recovery path a stale bundle needs (#5689).
- if (safeReadSession(RELOAD_FLAG) === flag) return false;
- safeWriteSession(RELOAD_FLAG, flag);
- if (safeReadSession(RELOAD_FLAG) !== flag) {
- console.warn('🔄 Stale chunk detected but sessionStorage is unavailable — skipping reload to avoid a reload loop');
- return false;
- }
- console.warn(`🔄 Stale chunk detected (build ${buildId || 'unknown'}) — reloading to pick up new bundle`);
- // Purge the offline caches BEFORE reloading so the reload can't be handed the
- // stale shell/chunks back — but only when the server confirms a different
- // build exists (see fetchServerBuildId); a transient network failure must
- // not cost the user their valid offline shell. Bounded by PURGE_TIMEOUT_MS
- // so a hung probe or Cache Storage still reloads. `reload()` fires exactly
- // once — `Promise.race` settles once.
- withTimeout(
- fetchServerBuildId().then((serverBuildId) =>
- serverBuildId && serverBuildId !== buildId ? purgeOfflineCaches() : undefined
- ),
- PURGE_TIMEOUT_MS
- ).finally(() => {
+ if (!buildId) return Promise.resolve(false);
+ if (safeReadSession(RELOAD_FLAG) === buildId) return Promise.resolve(false);
+ if (reloadAttempts.has(buildId)) return reloadAttempts.get(buildId);
+
+ const attempt = (async () => {
+ // A rejected preload can be a transient network error, and a runtime export
+ // error can be an application bug. Reload only when the live shell proves
+ // this tab is running a different build; an offline/unknown/same-build
+ // result leaves the current page and its unsaved state intact.
+ const serverBuildId = await withTimeout(fetchServerBuildId(), PURGE_TIMEOUT_MS);
+ if (!serverBuildId || serverBuildId === buildId) return false;
+
+ // Persist the anti-loop guard only after confirming a newer build. A
+ // same-build or offline probe must remain eligible for a later deployment.
+ safeWriteSession(RELOAD_FLAG, buildId);
+ if (safeReadSession(RELOAD_FLAG) !== buildId) {
+ console.warn('🔄 A newer build is available but sessionStorage is unavailable — skipping reload to avoid a reload loop');
+ return false;
+ }
+
+ console.warn(`🔄 Stale chunk detected (page build ${buildId}, server build ${serverBuildId}) — reloading`);
+ // Purge the offline caches before reloading so the new server shell cannot
+ // be replaced by stale cached assets. The server build mismatch is already
+ // confirmed, so a hung cache purge gets the bounded timeout and reloads.
+ await withTimeout(purgeOfflineCaches(), PURGE_TIMEOUT_MS);
window.location.reload();
+ return true;
+ })().catch(() => false).finally(() => {
+ reloadAttempts.delete(buildId);
});
- return true;
+
+ reloadAttempts.set(buildId, attempt);
+ return attempt;
};
diff --git a/client/src/utils/staleChunkReload.test.js b/client/src/utils/staleChunkReload.test.js
index 08a232fe27..0a17721f59 100644
--- a/client/src/utils/staleChunkReload.test.js
+++ b/client/src/utils/staleChunkReload.test.js
@@ -49,6 +49,7 @@ beforeEach(() => {
});
afterEach(() => {
+ vi.useRealTimers();
vi.unstubAllGlobals();
document.head.innerHTML = '';
});
@@ -67,15 +68,17 @@ describe('isStaleChunkError', () => {
'The superclass is not a constructor.',
"undefined is not an object (evaluating 'A.useState')",
"undefined is not an object (evaluating '$.jsx')",
- ])('treats %s as stale only in dynamic-import recovery', (msg) => {
+ ])('treats %s as stale only in module-load or render recovery', (msg) => {
const error = new Error(msg);
expect(isStaleChunkError(error)).toBe(false);
expect(isStaleChunkError(error, { duringImport: true })).toBe(true);
+ expect(isStaleChunkError(error, { duringRender: true })).toBe(true);
});
- it('does not treat unrelated Safari undefined-object errors as stale imports', () => {
+ it('does not treat unrelated Safari undefined-object errors as stale module errors', () => {
const error = new Error("undefined is not an object (evaluating 'A.someValue')");
expect(isStaleChunkError(error, { duringImport: true })).toBe(false);
+ expect(isStaleChunkError(error, { duringRender: true })).toBe(false);
});
it('is case-insensitive and accepts non-Error values', () => {
@@ -159,7 +162,7 @@ describe('fetchServerBuildId', () => {
});
describe('reloadOnceForStaleChunk', () => {
- it('purges caches then reloads once for a given build', async () => {
+ it('purges caches and reloads only after confirming a newer server build', async () => {
stubSessionStorage();
stubFetch();
const reload = stubReload();
@@ -172,13 +175,12 @@ describe('reloadOnceForStaleChunk', () => {
}),
});
- expect(reloadOnceForStaleChunk()).toBe(true);
- // Reload is deferred until the purge settles.
- await vi.waitFor(() => expect(reload).toHaveBeenCalledTimes(1));
+ await expect(reloadOnceForStaleChunk()).resolves.toBe(true);
+ expect(reload).toHaveBeenCalledTimes(1);
expect(deleted).toEqual(['portos-shell-v1']);
});
- it('skips the purge but still reloads when the server is unreachable', async () => {
+ it('keeps the current page when the server build cannot be checked', async () => {
stubSessionStorage();
stubFetch(() => Promise.reject(new TypeError('Failed to fetch')));
const reload = stubReload();
@@ -188,18 +190,17 @@ describe('reloadOnceForStaleChunk', () => {
delete: cacheDelete,
});
- expect(reloadOnceForStaleChunk()).toBe(true);
- await vi.waitFor(() => expect(reload).toHaveBeenCalledTimes(1));
- // Offline: the (possibly current-build) offline shell must survive so the
- // reload can boot it — purging would strand the user on a network error page.
+ await expect(reloadOnceForStaleChunk()).resolves.toBe(false);
+ expect(reload).not.toHaveBeenCalled();
+ // An offline or unverified probe is not evidence that a reload can recover.
expect(cacheDelete).not.toHaveBeenCalled();
});
- it('skips the purge when the server still serves the SAME build (transient failure)', async () => {
+ it('does not reload on the same build, and remains eligible when a newer build appears', async () => {
stubSessionStorage();
- // Server reachable, but serving the build the page already runs — the
- // import error was a network blip, not a stale deployment.
- stubFetch(() =>
+ // A same-build response means this may be a transient failure or a real
+ // application bug; keep the page in place and leave the guard unset.
+ const fetch = stubFetch(() =>
Promise.resolve({ ok: true, text: () => Promise.resolve(shellHtml('build-abc')) })
);
const reload = stubReload();
@@ -209,9 +210,16 @@ describe('reloadOnceForStaleChunk', () => {
delete: cacheDelete,
});
- expect(reloadOnceForStaleChunk()).toBe(true);
- await vi.waitFor(() => expect(reload).toHaveBeenCalledTimes(1));
+ await expect(reloadOnceForStaleChunk()).resolves.toBe(false);
+ expect(reload).not.toHaveBeenCalled();
expect(cacheDelete).not.toHaveBeenCalled();
+
+ fetch.mockImplementationOnce(() =>
+ Promise.resolve({ ok: true, text: () => Promise.resolve(shellHtml('build-new')) })
+ );
+ await expect(reloadOnceForStaleChunk()).resolves.toBe(true);
+ expect(reload).toHaveBeenCalledTimes(1);
+ expect(cacheDelete).toHaveBeenCalledWith('portos-shell-v1');
});
it('does not reload twice for the same build id', async () => {
@@ -220,10 +228,10 @@ describe('reloadOnceForStaleChunk', () => {
const reload = stubReload();
vi.stubGlobal('caches', undefined);
- expect(reloadOnceForStaleChunk()).toBe(true);
- await vi.waitFor(() => expect(reload).toHaveBeenCalledTimes(1));
+ await expect(reloadOnceForStaleChunk()).resolves.toBe(true);
+ expect(reload).toHaveBeenCalledTimes(1);
// Second stale error in the SAME build → guard blocks it.
- expect(reloadOnceForStaleChunk()).toBe(false);
+ await expect(reloadOnceForStaleChunk()).resolves.toBe(false);
expect(reload).toHaveBeenCalledTimes(1);
});
@@ -238,9 +246,8 @@ describe('reloadOnceForStaleChunk', () => {
const reload = stubReload();
vi.stubGlobal('caches', undefined);
- expect(reloadOnceForStaleChunk()).toBe(false);
- expect(reloadOnceForStaleChunk()).toBe(false);
- await Promise.resolve();
+ await expect(reloadOnceForStaleChunk()).resolves.toBe(false);
+ await expect(reloadOnceForStaleChunk()).resolves.toBe(false);
expect(reload).not.toHaveBeenCalled();
});
@@ -250,18 +257,18 @@ describe('reloadOnceForStaleChunk', () => {
const reload = stubReload();
vi.stubGlobal('caches', undefined);
- expect(reloadOnceForStaleChunk()).toBe(true);
- await vi.waitFor(() => expect(reload).toHaveBeenCalledTimes(1));
+ await expect(reloadOnceForStaleChunk()).resolves.toBe(true);
+ expect(reload).toHaveBeenCalledTimes(1);
setBuildId('build-def');
- expect(reloadOnceForStaleChunk()).toBe(true);
- await vi.waitFor(() => expect(reload).toHaveBeenCalledTimes(2));
+ await expect(reloadOnceForStaleChunk()).resolves.toBe(true);
+ expect(reload).toHaveBeenCalledTimes(2);
});
- it('still reloads when the reachability probe hangs (timeout backstop)', async () => {
+ it('does not reload when the build probe times out', async () => {
vi.useFakeTimers();
stubSessionStorage();
- // Probe never resolves → the whole purge chain would hang without the timeout.
+ // A timed out probe cannot confirm that reloading will recover.
stubFetch(() => new Promise(() => {}));
const reload = stubReload();
vi.stubGlobal('caches', {
@@ -269,11 +276,11 @@ describe('reloadOnceForStaleChunk', () => {
delete: vi.fn(),
});
- expect(reloadOnceForStaleChunk()).toBe(true);
+ const attempt = reloadOnceForStaleChunk();
expect(reload).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(1500);
- expect(reload).toHaveBeenCalledTimes(1);
- vi.useRealTimers();
+ await expect(attempt).resolves.toBe(false);
+ expect(reload).not.toHaveBeenCalled();
});
it('still reloads when the cache purge hangs (timeout backstop)', async () => {
@@ -287,10 +294,22 @@ describe('reloadOnceForStaleChunk', () => {
delete: vi.fn(),
});
- expect(reloadOnceForStaleChunk()).toBe(true);
+ const attempt = reloadOnceForStaleChunk();
+ await vi.advanceTimersByTimeAsync(0);
expect(reload).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(1500);
+ await expect(attempt).resolves.toBe(true);
expect(reload).toHaveBeenCalledTimes(1);
- vi.useRealTimers();
+ });
+
+ it('does not probe or reload without the current page build id', async () => {
+ stubSessionStorage();
+ const fetch = stubFetch();
+ const reload = stubReload();
+ setBuildId(null);
+
+ await expect(reloadOnceForStaleChunk()).resolves.toBe(false);
+ expect(fetch).not.toHaveBeenCalled();
+ expect(reload).not.toHaveBeenCalled();
});
});