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: retry failed routes with clean asset cache

[._.]/ Adam Eivy58f978008610
diff --git a/client/src/components/RouteErrorFallback.jsx b/client/src/components/RouteErrorFallback.jsx
index daaaf9e049..30068ec938 100644
--- a/client/src/components/RouteErrorFallback.jsx
+++ b/client/src/components/RouteErrorFallback.jsx
@@ -16,6 +16,14 @@ export default function RouteErrorFallback() {
const navigate = useNavigate();
const message = getErrorMessage(error);
+ const retry = async () => {
+ if (isStaleChunkError(error, { duringRender: true })) {
+ const reloaded = await reloadOnceForStaleChunk({ forceCachePurge: true });
+ if (reloaded) return;
+ }
+ window.location.reload();
+ };
+
useEffect(() => {
if (isStaleChunkError(error, { duringRender: true })) {
void reloadOnceForStaleChunk();
@@ -38,7 +46,7 @@ export default function RouteErrorFallback() {
<div className="flex flex-col sm:flex-row gap-2">
<button
type="button"
- onClick={() => window.location.reload()}
+ onClick={retry}
className="flex-1 px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-port-on-accent rounded-lg transition-colors"
>
Try again
diff --git a/client/src/components/RouteErrorFallback.test.jsx b/client/src/components/RouteErrorFallback.test.jsx
index 94a6a03033..2aa4ddd3a5 100644
--- a/client/src/components/RouteErrorFallback.test.jsx
+++ b/client/src/components/RouteErrorFallback.test.jsx
@@ -87,4 +87,21 @@ describe('RouteErrorFallback', () => {
expect(reload).toHaveBeenCalledOnce();
vi.unstubAllGlobals();
});
+
+ it('requests a cached-asset purge when retrying a stale runtime error', async () => {
+ const error = new Error('The superclass is not a constructor.');
+ isStaleChunkError.mockReturnValue(true);
+ reloadOnceForStaleChunk.mockResolvedValue(false);
+ const reload = vi.fn();
+ vi.stubGlobal('location', { reload });
+ const user = userEvent.setup();
+ await renderRouteError(error);
+
+ reloadOnceForStaleChunk.mockResolvedValue(true);
+ await user.click(screen.getByRole('button', { name: 'Try again' }));
+
+ expect(reloadOnceForStaleChunk).toHaveBeenLastCalledWith({ forceCachePurge: true });
+ expect(reload).not.toHaveBeenCalled();
+ vi.unstubAllGlobals();
+ });
});
diff --git a/client/src/utils/README.md b/client/src/utils/README.md
index 8bd3f5fa01..0e05267a46 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 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. |
+| `lazyWithReload` | `React.lazy` wrapper that retries transient import failures and reloads only when a failed chunk belongs to an older build; the route error screen can explicitly purge PortOS asset caches before retrying a runtime import failure. |
+| `staleChunkReload` | Detects stale import/runtime-export errors at import and render boundaries, confirms a newer served build before automatic reload, and purges PortOS caches for that recovery; an explicit route-error retry can also purge them when the live shell is reachable. |
## File handling
diff --git a/client/src/utils/staleChunkReload.js b/client/src/utils/staleChunkReload.js
index b411ec693f..b0cd3dc3e4 100644
--- a/client/src/utils/staleChunkReload.js
+++ b/client/src/utils/staleChunkReload.js
@@ -107,32 +107,52 @@ export const fetchServerBuildId = async () => {
return (el && el.getAttribute('content')) || null;
};
-export const reloadOnceForStaleChunk = () => {
+export const reloadOnceForStaleChunk = ({ forceCachePurge = false } = {}) => {
const buildId = getCurrentBuildId();
if (!buildId) return Promise.resolve(false);
if (safeReadSession(RELOAD_FLAG) === buildId) return Promise.resolve(false);
- if (reloadAttempts.has(buildId)) return reloadAttempts.get(buildId);
+ if (reloadAttempts.has(buildId)) {
+ const inFlight = reloadAttempts.get(buildId);
+ if (!forceCachePurge) return inFlight;
+ // The route fallback can be retried while its automatic, conservative
+ // check is still probing. If that check finds the same build, continue the
+ // user's explicit retry with a cache purge instead of falling back to a
+ // plain reload.
+ return inFlight.then((reloaded) => (
+ reloaded ? true : reloadOnceForStaleChunk({ forceCachePurge: true })
+ ));
+ }
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.
+ // result leaves the current page and its unsaved state intact unless the
+ // user explicitly requested a fresh-asset retry.
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.
+ if (!serverBuildId) return false;
+ const newerBuildAvailable = serverBuildId !== buildId;
+ const explicitRetryCanRecover = forceCachePurge
+ && !newerBuildAvailable
+ && !(typeof navigator !== 'undefined' && navigator.onLine === false);
+ if (!newerBuildAvailable && !explicitRetryCanRecover) return false;
+
+ // Persist the anti-loop guard after confirming either a newer build or an
+ // explicit, online retry. An automatic same-build or offline probe remains
+ // 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');
+ console.warn('🔄 A stale chunk was detected 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.
+ console.warn(newerBuildAvailable
+ ? `🔄 Stale chunk detected (page build ${buildId}, server build ${serverBuildId}) — reloading`
+ : `🔄 Clearing cached PortOS assets after explicit retry (build ${buildId}) — reloading`);
+ // Purge the offline caches before reloading so a stale shell or asset does
+ // not get served again. The normal automatic path gets here only after a
+ // build mismatch; the explicit retry gets here only after the live shell
+ // responds and the browser is not known to be offline.
await withTimeout(purgeOfflineCaches(), PURGE_TIMEOUT_MS);
window.location.reload();
return true;
diff --git a/client/src/utils/staleChunkReload.test.js b/client/src/utils/staleChunkReload.test.js
index 0a17721f59..53cf271815 100644
--- a/client/src/utils/staleChunkReload.test.js
+++ b/client/src/utils/staleChunkReload.test.js
@@ -222,6 +222,47 @@ describe('reloadOnceForStaleChunk', () => {
expect(cacheDelete).toHaveBeenCalledWith('portos-shell-v1');
});
+ it('clears cached assets on an explicit retry when the server is reachable on the same build', async () => {
+ stubSessionStorage();
+ stubFetch(() =>
+ Promise.resolve({ ok: true, text: () => Promise.resolve(shellHtml('build-abc')) })
+ );
+ const reload = stubReload();
+ const deleted = [];
+ vi.stubGlobal('caches', {
+ keys: vi.fn().mockResolvedValue(['portos-shell-v1', 'other-app-cache']),
+ delete: vi.fn((name) => {
+ deleted.push(name);
+ return Promise.resolve(true);
+ }),
+ });
+
+ await expect(reloadOnceForStaleChunk({ forceCachePurge: true })).resolves.toBe(true);
+ expect(reload).toHaveBeenCalledOnce();
+ expect(deleted).toEqual(['portos-shell-v1']);
+ // The explicit retry is still one-shot for this page build.
+ await expect(reloadOnceForStaleChunk({ forceCachePurge: true })).resolves.toBe(false);
+ expect(reload).toHaveBeenCalledOnce();
+ });
+
+ it('does not clear cached assets on an explicit retry when the browser is offline', async () => {
+ stubSessionStorage();
+ stubFetch(() =>
+ Promise.resolve({ ok: true, text: () => Promise.resolve(shellHtml('build-abc')) })
+ );
+ vi.stubGlobal('navigator', { onLine: false });
+ const reload = stubReload();
+ const cacheDelete = vi.fn();
+ vi.stubGlobal('caches', {
+ keys: vi.fn().mockResolvedValue(['portos-shell-v1']),
+ delete: cacheDelete,
+ });
+
+ await expect(reloadOnceForStaleChunk({ forceCachePurge: true })).resolves.toBe(false);
+ expect(reload).not.toHaveBeenCalled();
+ expect(cacheDelete).not.toHaveBeenCalled();
+ });
+
it('does not reload twice for the same build id', async () => {
stubSessionStorage();
stubFetch();