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

address review (codex): purge only when the server confirms a different build id, not mere reachability

[._.]/ Adam Eivycfcd7cf14746
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index bae5624be7..1825e6fdf6 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -41,7 +41,7 @@
- **pr-watcher now works on GitHub Enterprise hosts and resolves "self" against the repo's actual host.** The `pr-watcher` task gated on `getOriginInfo().isGithub`, which is github.com-only, so it silently no-op'd (`not-a-github-repo`) on self-hosted GitHub Enterprise (`github.*`) repos. Worse, its self/others author gate resolved the operator login via `gh api user` with no `--hostname` — which always targets github.com regardless of the repo — and cached one login process-wide, so on an enterprise repo it compared PR authors against the wrong identity (a user is commonly a different login per host). The gate now classifies GitHub-family hosts via the shared `hostToWorkTracker` (the same rule the claim-issue router uses; `gitlab.*` still falls through as not-a-github-repo), the default-branch and PR-list `gh` calls pass a host-qualified `--repo HOST/OWNER/REPO` selector (enterprise-correct, and deterministic on a fork+upstream multi-remote checkout where cwd-based detection would ambiguously resolve to the parent), and `getSelfLogin(host)` resolves identity with an explicit `--hostname` and caches per host. Covered by `prWatcher.test.js`.
- **Retry lazy route chunks before failing on flaky mobile networks.** Lazy-loaded pages fetch their JS chunk on demand, and on a weak cellular/Wi-Fi link that fetch can fail on a transient blip ("Importing a module script failed" on Safari, "Failed to fetch dynamically imported module" on Chrome) even though the chunk still exists — a page reload can't fix a network hiccup, so once the one-shot stale-chunk reload was spent for a build, the next blip stranded the user on the error screen. `lazyWithReload` now retries the dynamic import twice with a short backoff before treating the failure as terminal, so a transient mobile-network failure recovers silently without a jarring reload; a genuinely stale chunk (renamed by a rebuild) still 404s on each quick retry and falls through to the existing reload-once path. New `importWithRetry` helper with unit coverage.
-- **Clear the offline (service-worker) cache before the stale-chunk recovery reload.** When a genuinely stale chunk (renamed by a rebuild) triggered the one-shot reload, the reload could be served the *old* bundle right back — the service worker serves `/assets/*` cache-first, and on a flaky mobile link its network-first navigation falls back to the cached (old) app shell. That re-loaded the very code that just 404'd and burned the build-scoped reload guard, so the user stayed stuck on "Importing a module script failed" even after the reload and even on the latest build. `reloadOnceForStaleChunk` now purges the SW's `portos-*` caches (app shell + hashed asset chunks) via the page-side Cache Storage API before reloading, so the recovery reload is guaranteed to boot fresh code; the purge is bounded by a 1.5s timeout so a hung/disabled Cache Storage still reloads. The purge is gated on a server-reachability probe (`HEAD /`, which the SW never intercepts): a fully offline device produces the same import-error messages as a stale chunk, and purging there would destroy the valid offline shell and strand the user on the browser's connection-error page — when unreachable, the caches are kept and the reload boots the SW's cached shell instead. New `purgeOfflineCaches` + `isServerReachable` helpers with unit coverage (`staleChunkReload.test.js`).
+- **Clear the offline (service-worker) cache before the stale-chunk recovery reload.** When a genuinely stale chunk (renamed by a rebuild) triggered the one-shot reload, the reload could be served the *old* bundle right back — the service worker serves `/assets/*` cache-first, and on a flaky mobile link its network-first navigation falls back to the cached (old) app shell. That re-loaded the very code that just 404'd and burned the build-scoped reload guard, so the user stayed stuck on "Importing a module script failed" even after the reload and even on the latest build. `reloadOnceForStaleChunk` now purges the SW's `portos-*` caches (app shell + hashed asset chunks) via the page-side Cache Storage API before reloading, so the recovery reload is guaranteed to boot fresh code; the purge is bounded by a 1.5s timeout so a hung/disabled Cache Storage still reloads. The purge is gated on a build-id check: a flaky/offline network produces the same import-error messages as a stale chunk, and purging on a transient failure would destroy the valid current-build offline shell (if the link drops again during the recovery reload, the SW has no fallback and the user lands on the browser's connection-error page). `fetchServerBuildId` re-fetches the shell with `cache: 'no-store'` and reads the `portos-build-id` meta the server stamps into it — the caches are dropped only when the server confirms a *different* build; unreachable, non-ok, same-build, and unstamped responses all keep the caches so the reload can boot the SW's cached shell. New `purgeOfflineCaches` + `fetchServerBuildId` helpers with unit coverage (`staleChunkReload.test.js`).
- **[issue-2643] De-flake the Wiki vault-default test under full-suite load.** `Wiki.test.jsx`'s "defaults to the first vault" (and the sibling "restores the selected vault") assertions checked `scanNotesVault` synchronously right after `await waitFor(...)` on the rendered vault id. That mock call is fired by a *separate* `useEffect` keyed on the selected vault, so the committed overview render can land before the passive effect flushes — reliably true in isolation, but on a CPU-saturated full client run the bare assertion raced ahead of the effect and failed (`expected vi.fn() to be called with arguments`). The two mock-call assertions now sit inside their own `waitFor`, awaiting the async side-effect instead of sampling it. Test-only change (no `test.retry` or timeout inflation) — no runtime behavior change.
diff --git a/client/src/utils/staleChunkReload.js b/client/src/utils/staleChunkReload.js
index 903ad9a37b..cd6506bd14 100644
--- a/client/src/utils/staleChunkReload.js
+++ b/client/src/utils/staleChunkReload.js
@@ -68,18 +68,26 @@ const withTimeout = (promise, ms) =>
new Promise((resolve) => setTimeout(resolve, ms)),
]);
-// A dead network produces the same import-error messages as a genuinely stale
-// chunk, but the purge only helps when the server can hand back fresh code.
-// If the device is offline, purging would destroy the (possibly current-build)
-// offline shell and strand the user on the browser's connection-error page —
-// so probe first and keep the caches when unreachable; the recovery reload then
-// falls back to the service worker's cached shell, which is the correct offline
-// behavior. HEAD is never intercepted by the service worker (it handles GET
-// only), so this probe cannot be satisfied from cache.
-export const isServerReachable = async () => {
- if (typeof navigator !== 'undefined' && navigator.onLine === false) return false;
- const res = await fetch('/', { method: 'HEAD', cache: 'no-store' }).catch(() => null);
- return Boolean(res && res.ok);
+// A flaky or dead network produces the same import-error messages as a
+// genuinely stale chunk, but the purge only helps when the server actually has
+// a NEW build to hand back. Purging on a transient failure would destroy the
+// valid current-build offline shell — if the link then drops again during the
+// recovery reload, the service worker has no fallback and the user lands on
+// the browser's connection-error page instead of the offline app. So before
+// purging, fetch the server's live shell and read the build id it stamps into
+// index.html (`server/lib/buildId.js`): only a confirmed different build
+// justifies dropping the caches. Returns the server's build id, or null when
+// offline/unreachable/unstamped (all "do not purge" signals). `cache:
+// 'no-store'` bypasses the HTTP cache, and the service worker routes this
+// non-navigation GET network-first, so a cached shell can't spoof the probe.
+export const fetchServerBuildId = async () => {
+ if (typeof navigator !== 'undefined' && navigator.onLine === false) return null;
+ const res = await fetch('/', { cache: 'no-store' }).catch(() => null);
+ if (!res || !res.ok) return null;
+ const html = await res.text().catch(() => '');
+ const doc = new DOMParser().parseFromString(html, 'text/html');
+ const el = doc.querySelector('meta[name="portos-build-id"]');
+ return (el && el.getAttribute('content')) || null;
};
export const reloadOnceForStaleChunk = () => {
@@ -87,14 +95,17 @@ export const reloadOnceForStaleChunk = () => {
const flag = buildId ? `${buildId}` : '1';
if (sessionStorage.getItem(RELOAD_FLAG) === flag) return false;
sessionStorage.setItem(RELOAD_FLAG, flag);
- console.warn(`🔄 Stale chunk detected (build ${buildId || 'unknown'}) — clearing offline cache + reloading to pick up new bundle`);
+ 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 is reachable (see
- // isServerReachable). Bounded by PURGE_TIMEOUT_MS so a hung probe or Cache
- // Storage still reloads. `reload()` fires exactly once — `Promise.race`
- // settles once.
+ // 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(
- isServerReachable().then((reachable) => (reachable ? purgeOfflineCaches() : undefined)),
+ fetchServerBuildId().then((serverBuildId) =>
+ serverBuildId && serverBuildId !== buildId ? purgeOfflineCaches() : undefined
+ ),
PURGE_TIMEOUT_MS
).finally(() => {
window.location.reload();
diff --git a/client/src/utils/staleChunkReload.test.js b/client/src/utils/staleChunkReload.test.js
index 4262ed4f8d..8f88390c76 100644
--- a/client/src/utils/staleChunkReload.test.js
+++ b/client/src/utils/staleChunkReload.test.js
@@ -1,7 +1,7 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import {
isStaleChunkError,
- isServerReachable,
+ fetchServerBuildId,
reloadOnceForStaleChunk,
purgeOfflineCaches,
} from './staleChunkReload';
@@ -31,9 +31,15 @@ const setBuildId = (id) => {
: '';
};
-// Reachability probe: HEAD / — resolve as reachable unless a test overrides.
+// Build-id probe: GET / returns the server's stamped shell. Default to serving
+// a DIFFERENT build than the page's `build-abc`, i.e. "a new build exists".
+const shellHtml = (id) =>
+ `<html><head><meta name="portos-build-id" content="${id}"></head><body></body></html>`;
+
const stubFetch = (impl) => {
- const fetch = vi.fn(impl ?? (() => Promise.resolve({ ok: true })));
+ const fetch = vi.fn(
+ impl ?? (() => Promise.resolve({ ok: true, text: () => Promise.resolve(shellHtml('build-new')) }))
+ );
vi.stubGlobal('fetch', fetch);
return fetch;
};
@@ -99,27 +105,34 @@ describe('purgeOfflineCaches', () => {
});
});
-describe('isServerReachable', () => {
- it('is true when the HEAD probe succeeds', async () => {
+describe('fetchServerBuildId', () => {
+ it('reads the build id stamped into the served shell', async () => {
const fetch = stubFetch();
- await expect(isServerReachable()).resolves.toBe(true);
- expect(fetch).toHaveBeenCalledWith('/', { method: 'HEAD', cache: 'no-store' });
+ await expect(fetchServerBuildId()).resolves.toBe('build-new');
+ expect(fetch).toHaveBeenCalledWith('/', { cache: 'no-store' });
});
- it('is false when the probe rejects (offline)', async () => {
+ it('is null when the probe rejects (offline)', async () => {
stubFetch(() => Promise.reject(new TypeError('Failed to fetch')));
- await expect(isServerReachable()).resolves.toBe(false);
+ await expect(fetchServerBuildId()).resolves.toBeNull();
});
- it('is false on a non-ok response', async () => {
+ it('is null on a non-ok response', async () => {
stubFetch(() => Promise.resolve({ ok: false }));
- await expect(isServerReachable()).resolves.toBe(false);
+ await expect(fetchServerBuildId()).resolves.toBeNull();
+ });
+
+ it('is null when the shell has no build-id meta tag', async () => {
+ stubFetch(() =>
+ Promise.resolve({ ok: true, text: () => Promise.resolve('<html><head></head></html>') })
+ );
+ await expect(fetchServerBuildId()).resolves.toBeNull();
});
- it('short-circuits false when navigator reports offline', async () => {
+ it('short-circuits null when navigator reports offline', async () => {
const fetch = stubFetch();
vi.stubGlobal('navigator', { onLine: false });
- await expect(isServerReachable()).resolves.toBe(false);
+ await expect(fetchServerBuildId()).resolves.toBeNull();
expect(fetch).not.toHaveBeenCalled();
});
});
@@ -161,6 +174,25 @@ describe('reloadOnceForStaleChunk', () => {
expect(cacheDelete).not.toHaveBeenCalled();
});
+ it('skips the purge when the server still serves the SAME build (transient failure)', async () => {
+ stubSessionStorage();
+ // Server reachable, but serving the build the page already runs — the
+ // import error was a network blip, not a stale deployment.
+ stubFetch(() =>
+ Promise.resolve({ ok: true, text: () => Promise.resolve(shellHtml('build-abc')) })
+ );
+ const reload = stubReload();
+ const cacheDelete = vi.fn();
+ vi.stubGlobal('caches', {
+ keys: vi.fn().mockResolvedValue(['portos-shell-v1']),
+ delete: cacheDelete,
+ });
+
+ expect(reloadOnceForStaleChunk()).toBe(true);
+ await vi.waitFor(() => expect(reload).toHaveBeenCalledTimes(1));
+ expect(cacheDelete).not.toHaveBeenCalled();
+ });
+
it('does not reload twice for the same build id', async () => {
stubSessionStorage();
stubFetch();