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

retry lazy route chunks before failing on flaky mobile networks

[._.]/ Adam Eivy9bfc152de1bf
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index dcae153789..4624898cff 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -36,6 +36,8 @@
## Fixed
+- **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.
+
- **[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-2540] Stop full-JSONB table loads for pipeline issue id sweeps and bound the multi-account message inbox aggregate.** `listIssueIds` (the conflict-journal orphan-base-hash sweep + tombstone GC) went through `readState()` → `loadAll()`, pulling every issue's full `data` JSONB — up to ~12MB of stage `runHistory` each — into memory only to read the ids; it now sources the store's `SELECT id` projection, with the PG backend filtering tombstones via the mirrored `deleted` column (`listIds({ includeDeleted })`) so the whole-record load is skipped entirely for the default live sweep. Separately, `messageSync.getMessages`'s multi-account inbox spread every message from every account into one array and globally sorted it before slicing a page; it now bounds each account's contribution to the top `offset+limit` by date and merges those heads, so a paged inbox reads `accounts × (offset+limit)` messages into the merge instead of the full cross-account total (the exact `total` count is preserved).
- **[issue-2538] Bound Spotify auth and privacy-broker fetches, and single-flight token refresh.** The Spotify token endpoint (`spotifyAuth.js`) and the BADBOOL / CA-registry broker fetchers (`privacyBrokers.js`) used bare `fetch` with no timeout, so a hung `accounts.spotify.com` could stall an OAuth callback or a history-sync refresh — and a broker source that never responded could hang a user-triggered refresh — indefinitely. All three now go through the shared `fetchWithTimeout` helper with a 15s cap. Separately, concurrent `getAccessToken()` callers that all found the token expired each POSTed their own refresh, and since Spotify rotates the grant the losers persisted a stale token (last-write-wins); refreshes now share one in-flight `refreshPromise` (single-flight), so the grant is rotated exactly once and the guard is released on settle so a failed refresh can retry.
diff --git a/client/src/utils/lazyWithReload.js b/client/src/utils/lazyWithReload.js
index 48cb53553f..a6776544f0 100644
--- a/client/src/utils/lazyWithReload.js
+++ b/client/src/utils/lazyWithReload.js
@@ -1,12 +1,37 @@
import { lazy } from 'react';
import { isStaleChunkError, reloadOnceForStaleChunk } from './staleChunkReload';
+// How many times to re-attempt a failed dynamic import before giving up, and
+// the base backoff between attempts (multiplied by the attempt number).
+const MAX_RETRIES = 2;
+const RETRY_BASE_DELAY_MS = 350;
+
+const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
+
+// Retry a dynamic import a few times before treating the failure as terminal.
+// On flaky mobile/cellular links a chunk 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 wouldn't fix a network hiccup, so a short retry recovers silently
+// without the jarring full-page reload. A genuinely stale chunk (renamed by a
+// rebuild) just 404s on each quick retry and falls through to the reload path.
+export const importWithRetry = (importFn, retriesLeft = MAX_RETRIES) =>
+ importFn().catch(async (err) => {
+ if (retriesLeft > 0) {
+ await delay(RETRY_BASE_DELAY_MS * (MAX_RETRIES - retriesLeft + 1));
+ return importWithRetry(importFn, retriesLeft - 1);
+ }
+ throw err;
+ });
+
// React.lazy() wrapper that recovers from stale-chunk errors after a rebuild
-// changes Vite chunk hashes while a tab is still open. When such an error
-// fires, reload the page once to pick up the new bundle; everything else
-// re-throws so error boundaries can see it.
+// changes Vite chunk hashes while a tab is still open. The import is retried a
+// couple of times first (see importWithRetry) to ride out transient mobile
+// network failures; if it still fails with a stale-chunk error, reload the page
+// once to pick up the new bundle. Everything else re-throws so error boundaries
+// can see it.
export const lazyWithReload = (importFn) => lazy(() =>
- importFn().catch(err => {
+ importWithRetry(importFn).catch(err => {
if (isStaleChunkError(err) && reloadOnceForStaleChunk()) {
return new Promise(() => {});
}
diff --git a/client/src/utils/lazyWithReload.test.js b/client/src/utils/lazyWithReload.test.js
new file mode 100644
index 0000000000..ea0c47bdfc
--- /dev/null
+++ b/client/src/utils/lazyWithReload.test.js
@@ -0,0 +1,40 @@
+import { describe, it, expect, vi } from 'vitest';
+import { importWithRetry } from './lazyWithReload';
+
+describe('importWithRetry', () => {
+ it('resolves on the first attempt without retrying', async () => {
+ const mod = { default: () => null };
+ const importFn = vi.fn().mockResolvedValue(mod);
+ await expect(importWithRetry(importFn)).resolves.toBe(mod);
+ expect(importFn).toHaveBeenCalledTimes(1);
+ });
+
+ it('recovers from a transient failure by retrying (flaky mobile network)', async () => {
+ vi.useFakeTimers();
+ const mod = { default: () => null };
+ const importFn = vi
+ .fn()
+ .mockRejectedValueOnce(new Error('Importing a module script failed'))
+ .mockResolvedValueOnce(mod);
+ const promise = importWithRetry(importFn);
+ await vi.runAllTimersAsync();
+ await expect(promise).resolves.toBe(mod);
+ expect(importFn).toHaveBeenCalledTimes(2);
+ vi.useRealTimers();
+ });
+
+ it('re-throws after exhausting all attempts', async () => {
+ vi.useFakeTimers();
+ const err = new Error('Importing a module script failed');
+ const importFn = vi.fn().mockRejectedValue(err);
+ const promise = importWithRetry(importFn);
+ // Attach a rejection handler up front so the eventual rejection is never
+ // an unhandled promise while fake timers advance.
+ const settled = expect(promise).rejects.toBe(err);
+ await vi.runAllTimersAsync();
+ await settled;
+ // 1 initial attempt + MAX_RETRIES (2) = 3 total
+ expect(importFn).toHaveBeenCalledTimes(3);
+ vi.useRealTimers();
+ });
+});