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 (claude): gate cache purge on server reachability so an offline device keeps its offline shell

[._.]/ Adam Eivyc93edafeb52f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 23dff25f59..bae5624be7 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. New `purgeOfflineCaches` helper 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 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`).
- **[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 85de17a143..903ad9a37b 100644
--- a/client/src/utils/staleChunkReload.js
+++ b/client/src/utils/staleChunkReload.js
@@ -68,6 +68,20 @@ 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);
+};
+
export const reloadOnceForStaleChunk = () => {
const buildId = getCurrentBuildId();
const flag = buildId ? `${buildId}` : '1';
@@ -75,9 +89,14 @@ export const reloadOnceForStaleChunk = () => {
sessionStorage.setItem(RELOAD_FLAG, flag);
console.warn(`🔄 Stale chunk detected (build ${buildId || 'unknown'}) — clearing offline cache + reloading to pick up new bundle`);
// Purge the offline caches BEFORE reloading so the reload can't be handed the
- // stale shell/chunks back. Bounded by PURGE_TIMEOUT_MS so a hung Cache Storage
- // still reloads. `reload()` fires exactly once — `Promise.race` settles once.
- withTimeout(purgeOfflineCaches(), PURGE_TIMEOUT_MS).finally(() => {
+ // 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.
+ withTimeout(
+ isServerReachable().then((reachable) => (reachable ? purgeOfflineCaches() : undefined)),
+ PURGE_TIMEOUT_MS
+ ).finally(() => {
window.location.reload();
});
return true;
diff --git a/client/src/utils/staleChunkReload.test.js b/client/src/utils/staleChunkReload.test.js
index 2910ddbac0..4262ed4f8d 100644
--- a/client/src/utils/staleChunkReload.test.js
+++ b/client/src/utils/staleChunkReload.test.js
@@ -1,6 +1,7 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import {
isStaleChunkError,
+ isServerReachable,
reloadOnceForStaleChunk,
purgeOfflineCaches,
} from './staleChunkReload';
@@ -30,6 +31,13 @@ const setBuildId = (id) => {
: '';
};
+// Reachability probe: HEAD / — resolve as reachable unless a test overrides.
+const stubFetch = (impl) => {
+ const fetch = vi.fn(impl ?? (() => Promise.resolve({ ok: true })));
+ vi.stubGlobal('fetch', fetch);
+ return fetch;
+};
+
beforeEach(() => {
setBuildId('build-abc');
});
@@ -91,9 +99,35 @@ describe('purgeOfflineCaches', () => {
});
});
+describe('isServerReachable', () => {
+ it('is true when the HEAD probe succeeds', async () => {
+ const fetch = stubFetch();
+ await expect(isServerReachable()).resolves.toBe(true);
+ expect(fetch).toHaveBeenCalledWith('/', { method: 'HEAD', cache: 'no-store' });
+ });
+
+ it('is false when the probe rejects (offline)', async () => {
+ stubFetch(() => Promise.reject(new TypeError('Failed to fetch')));
+ await expect(isServerReachable()).resolves.toBe(false);
+ });
+
+ it('is false on a non-ok response', async () => {
+ stubFetch(() => Promise.resolve({ ok: false }));
+ await expect(isServerReachable()).resolves.toBe(false);
+ });
+
+ it('short-circuits false when navigator reports offline', async () => {
+ const fetch = stubFetch();
+ vi.stubGlobal('navigator', { onLine: false });
+ await expect(isServerReachable()).resolves.toBe(false);
+ expect(fetch).not.toHaveBeenCalled();
+ });
+});
+
describe('reloadOnceForStaleChunk', () => {
it('purges caches then reloads once for a given build', async () => {
stubSessionStorage();
+ stubFetch();
const reload = stubReload();
const deleted = [];
vi.stubGlobal('caches', {
@@ -110,8 +144,26 @@ describe('reloadOnceForStaleChunk', () => {
expect(deleted).toEqual(['portos-shell-v1']);
});
+ it('skips the purge but still reloads when the server is unreachable', async () => {
+ stubSessionStorage();
+ stubFetch(() => Promise.reject(new TypeError('Failed to fetch')));
+ 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));
+ // 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.
+ expect(cacheDelete).not.toHaveBeenCalled();
+ });
+
it('does not reload twice for the same build id', async () => {
stubSessionStorage();
+ stubFetch();
const reload = stubReload();
vi.stubGlobal('caches', undefined);
@@ -124,6 +176,7 @@ describe('reloadOnceForStaleChunk', () => {
it('reloads again after a new build ships (guard is build-scoped)', async () => {
stubSessionStorage();
+ stubFetch();
const reload = stubReload();
vi.stubGlobal('caches', undefined);
@@ -135,9 +188,28 @@ describe('reloadOnceForStaleChunk', () => {
await vi.waitFor(() => expect(reload).toHaveBeenCalledTimes(2));
});
+ it('still reloads when the reachability probe hangs (timeout backstop)', async () => {
+ vi.useFakeTimers();
+ stubSessionStorage();
+ // Probe never resolves → the whole purge chain would hang without the timeout.
+ stubFetch(() => new Promise(() => {}));
+ const reload = stubReload();
+ vi.stubGlobal('caches', {
+ keys: vi.fn().mockResolvedValue([]),
+ delete: vi.fn(),
+ });
+
+ expect(reloadOnceForStaleChunk()).toBe(true);
+ expect(reload).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(1500);
+ expect(reload).toHaveBeenCalledTimes(1);
+ vi.useRealTimers();
+ });
+
it('still reloads when the cache purge hangs (timeout backstop)', async () => {
vi.useFakeTimers();
stubSessionStorage();
+ stubFetch();
const reload = stubReload();
// keys() never resolves → purge would hang without the timeout.
vi.stubGlobal('caches', {