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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: purge service-worker cache before stale-chunk recovery reload
[._.]/ Adam Eivy9766c0f12c74
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex a7795d3019..23dff25f59 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -41,6 +41,8 @@- **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`).+- **[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.- **[issue-2633] Direct `task:ready` emits now claim against the right task file.** The Creative Director bridge, the on-demand `dequeueNextTask`, and `spawnPriority0OnDemand` publish task records with no `taskType`, so an internal (`sys-*`/`cd-*`/`app-improve-*`) task's claim/in_progress `updateTask` fell back to `'user'`, targeted TASKS.md instead of COS-TASKS.md, missed the record, and returned a truthy `{ error }` object the `if (!updateResult)` check silently swallowed — leaving the task un-claimed while the agent spawned anyway. `runAgentSpawn` now normalizes `taskType` from the id via `isInternalTaskId` up front (mirroring the completion path), so a correctly-routed internal task's claim lands in COS-TASKS.md. The in_progress-claim miss is now warn-logged so it's no longer silent — but it stays non-fatal: legitimately-unpersisted autonomous emits (Priority 3 mission and Priority 4 idle-review tasks carry `taskType:'internal'` but are never written to COS-TASKS.md) must still spawn as they did before, so only a `null` result (updateTask threw) aborts the spawn.diff --git a/client/src/utils/README.md b/client/src/utils/README.mdindex 63b7e3b84a..f90aaaa023 100644--- a/client/src/utils/README.md+++ b/client/src/utils/README.md@@ -44,7 +44,7 @@ grep -i "what you want to do" client/src/utils/README.md| 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. |+| `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. |## File handlingdiff --git a/client/src/utils/staleChunkReload.js b/client/src/utils/staleChunkReload.jsindex fea5527880..85de17a143 100644--- a/client/src/utils/staleChunkReload.js+++ b/client/src/utils/staleChunkReload.js@@ -15,6 +15,17 @@ const STALE_CHUNK_PATTERNS = [const RELOAD_FLAG = 'portos.staleChunkReloadAttempted';+// The service worker names every cache it owns with this prefix+// (`portos-shell-v1`, `portos-assets-v1`, …). Mirrored from public/sw.js so the+// page can drop them without the SW's cooperation — Cache Storage is shared+// 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.+const PURGE_TIMEOUT_MS = 1500;+export const isStaleChunkError = (err) => {const msg = (err?.message || String(err || '')).toLowerCase();return STALE_CHUNK_PATTERNS.some(p => msg.includes(p));@@ -30,12 +41,44 @@ const getCurrentBuildId = () => {return el ? el.getAttribute('content') : null;};+// Drop the service worker's offline caches (app shell + hashed asset chunks) so+// the recovery reload is GUARANTEED to boot the fresh bundle. Without this, the+// SW's cache-first `/assets/` strategy — and, on a flaky mobile link, its+// network-first navigation falling back to the cached shell — can re-serve the+// exact stale code that just 404'd. That would waste the one-shot reload guard+// and strand the user on the error screen ("still Importing a module script+// failed even after a reload"). Content-hashed assets that are still valid just+// get re-fetched once; the cost is a single cold load. Best-effort and guarded+// so a missing/disabled Cache Storage is a no-op, not a throw.+export const purgeOfflineCaches = async () => {+ if (typeof caches === 'undefined' || typeof caches.keys !== 'function') return;+ const keys = await caches.keys().catch(() => []);+ await Promise.all(+ keys+ .filter((name) => name.startsWith(CACHE_PREFIX))+ .map((name) => caches.delete(name).catch(() => {}))+ );+};++// Resolve when `promise` settles or after `ms`, whichever comes first — so a+// slow/hung purge can't block the recovery reload indefinitely.+const withTimeout = (promise, ms) =>+ Promise.race([+ Promise.resolve(promise).catch(() => {}),+ new Promise((resolve) => setTimeout(resolve, ms)),+ ]);+export const reloadOnceForStaleChunk = () => {const buildId = getCurrentBuildId();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'}) — reloading to pick up new bundle`);- window.location.reload();+ 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(() => {+ window.location.reload();+ });return true;};diff --git a/client/src/utils/staleChunkReload.test.js b/client/src/utils/staleChunkReload.test.jsnew file mode 100644index 0000000000..2910ddbac0--- /dev/null+++ b/client/src/utils/staleChunkReload.test.js@@ -0,0 +1,154 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import {+ isStaleChunkError,+ reloadOnceForStaleChunk,+ purgeOfflineCaches,+} from './staleChunkReload';++// jsdom lacks Cache Storage and a settable location.reload; stub both.+const stubSessionStorage = () => {+ const store = new Map();+ vi.stubGlobal('sessionStorage', {+ getItem: (k) => (store.has(k) ? store.get(k) : null),+ setItem: (k, v) => store.set(k, String(v)),+ removeItem: (k) => store.delete(k),+ clear: () => store.clear(),+ });+ return store;+};++const stubReload = () => {+ const reload = vi.fn();+ // location is non-configurable in jsdom; replace the whole object.+ vi.stubGlobal('location', { reload });+ return reload;+};++const setBuildId = (id) => {+ document.head.innerHTML = id+ ? `<meta name="portos-build-id" content="${id}">`+ : '';+};++beforeEach(() => {+ setBuildId('build-abc');+});++afterEach(() => {+ vi.unstubAllGlobals();+ document.head.innerHTML = '';+});++describe('isStaleChunkError', () => {+ it.each([+ 'Importing a module script failed',+ 'Failed to fetch dynamically imported module',+ 'error loading dynamically imported module',+ 'Expected a JavaScript module but got MIME type text/html',+ ])('matches %s', (msg) => {+ expect(isStaleChunkError(new Error(msg))).toBe(true);+ });++ it('is case-insensitive and accepts non-Error values', () => {+ expect(isStaleChunkError('IMPORTING A MODULE SCRIPT FAILED')).toBe(true);+ });++ it('ignores unrelated errors', () => {+ expect(isStaleChunkError(new Error('network down'))).toBe(false);+ expect(isStaleChunkError(null)).toBe(false);+ });+});++describe('purgeOfflineCaches', () => {+ it('deletes only portos-* caches and swallows failures', async () => {+ const deleted = [];+ vi.stubGlobal('caches', {+ keys: vi.fn().mockResolvedValue([+ 'portos-shell-v1',+ 'portos-assets-v1',+ 'some-other-cache',+ ]),+ delete: vi.fn((name) => {+ deleted.push(name);+ return Promise.resolve(true);+ }),+ });+ await purgeOfflineCaches();+ expect(deleted).toEqual(['portos-shell-v1', 'portos-assets-v1']);+ });++ it('no-ops when Cache Storage is unavailable', async () => {+ vi.stubGlobal('caches', undefined);+ await expect(purgeOfflineCaches()).resolves.toBeUndefined();+ });++ it('does not throw when caches.keys rejects', async () => {+ vi.stubGlobal('caches', {+ keys: vi.fn().mockRejectedValue(new Error('storage disabled')),+ delete: vi.fn(),+ });+ await expect(purgeOfflineCaches()).resolves.toBeUndefined();+ });+});++describe('reloadOnceForStaleChunk', () => {+ it('purges caches then reloads once for a given build', async () => {+ stubSessionStorage();+ const reload = stubReload();+ const deleted = [];+ vi.stubGlobal('caches', {+ keys: vi.fn().mockResolvedValue(['portos-shell-v1']),+ delete: vi.fn((name) => {+ deleted.push(name);+ return Promise.resolve(true);+ }),+ });++ expect(reloadOnceForStaleChunk()).toBe(true);+ // Reload is deferred until the purge settles.+ await vi.waitFor(() => expect(reload).toHaveBeenCalledTimes(1));+ expect(deleted).toEqual(['portos-shell-v1']);+ });++ it('does not reload twice for the same build id', async () => {+ stubSessionStorage();+ const reload = stubReload();+ vi.stubGlobal('caches', undefined);++ expect(reloadOnceForStaleChunk()).toBe(true);+ await vi.waitFor(() => expect(reload).toHaveBeenCalledTimes(1));+ // Second stale error in the SAME build → guard blocks it.+ expect(reloadOnceForStaleChunk()).toBe(false);+ expect(reload).toHaveBeenCalledTimes(1);+ });++ it('reloads again after a new build ships (guard is build-scoped)', async () => {+ stubSessionStorage();+ const reload = stubReload();+ vi.stubGlobal('caches', undefined);++ expect(reloadOnceForStaleChunk()).toBe(true);+ await vi.waitFor(() => expect(reload).toHaveBeenCalledTimes(1));++ setBuildId('build-def');+ expect(reloadOnceForStaleChunk()).toBe(true);+ await vi.waitFor(() => expect(reload).toHaveBeenCalledTimes(2));+ });++ it('still reloads when the cache purge hangs (timeout backstop)', async () => {+ vi.useFakeTimers();+ stubSessionStorage();+ const reload = stubReload();+ // keys() never resolves → purge would hang without the timeout.+ vi.stubGlobal('caches', {+ keys: vi.fn(() => new Promise(() => {})),+ delete: vi.fn(),+ });++ expect(reloadOnceForStaleChunk()).toBe(true);+ expect(reload).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(1500);+ expect(reload).toHaveBeenCalledTimes(1);+ vi.useRealTimers();+ });+});