Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(swr): keep the hydration gate up until the cache is ready (cold-open skeleton) (#17392)

Arvin Xud0952cd65087
diff --git a/src/layout/GlobalProvider/CacheHydrationGate.test.tsx b/src/layout/GlobalProvider/CacheHydrationGate.test.tsx
index acfc5cb4327..556f07307d3 100644
--- a/src/layout/GlobalProvider/CacheHydrationGate.test.tsx
+++ b/src/layout/GlobalProvider/CacheHydrationGate.test.tsx
@@ -97,13 +97,31 @@ describe('CacheHydrationGate', () => {
expect(screen.queryByTestId('app')).not.toBeNull();
});
- it('timeout backstop releases the app even if hydration never becomes ready', () => {
+ it('does NOT paint early while hydration is still in flight (no empty-chat + CLS)', () => {
+ // A heavy account's hydration outruns the former 1500ms window; painting then
+ // orphans any consumer that subscribes against the still-empty Map.
vi.useFakeTimers();
renderGate();
expect(screen.queryByTestId('app')).toBeNull();
act(() => {
- vi.advanceTimersByTime(1500);
+ vi.advanceTimersByTime(2500); // well past 1500ms, still not ready
+ });
+ expect(screen.queryByTestId('app')).toBeNull();
+
+ act(() => {
+ cacheHydration.markReady('anon:personal');
+ });
+ expect(screen.queryByTestId('app')).not.toBeNull();
+ });
+
+ it('hung-hydration backstop still releases if ready never fires', () => {
+ vi.useFakeTimers();
+ renderGate();
+ expect(screen.queryByTestId('app')).toBeNull();
+
+ act(() => {
+ vi.advanceTimersByTime(8000);
});
expect(screen.queryByTestId('app')).not.toBeNull();
});
diff --git a/src/layout/GlobalProvider/CacheHydrationGate.tsx b/src/layout/GlobalProvider/CacheHydrationGate.tsx
index fb4adc3b2a0..3d0184dccb8 100644
--- a/src/layout/GlobalProvider/CacheHydrationGate.tsx
+++ b/src/layout/GlobalProvider/CacheHydrationGate.tsx
@@ -10,7 +10,18 @@ import { useCacheScope } from '@/libs/swr/useCacheScope';
// first-write-wins: only the very first paint records the boot timing mark.
let firstPaintMarked = false;
-const HYDRATION_TIMEOUT = 1500;
+// Pure hung-hydration backstop — NOT a "boot is slow, paint anyway" timer.
+// `loadIdb` always signals `ready` from its `finally` (even on an IndexedDB
+// error), so legitimate hydration — however large the cached partition —
+// resolves `ready` on its own and releases the gate before this fires; the only
+// thing it catches is IndexedDB never responding, where there is no cache to
+// wait for. A short window (the former 1500ms) misfires on a heavy account whose
+// hydration outruns it: the gate paints an EMPTY app before the cache is in the
+// Map, and a consumer that subscribes to its key then is orphaned forever (SWR
+// does not observe the later direct Map insert), so it waits for the network —
+// the sustained cold-open skeleton. See `coldHydrationGate.integration.test.tsx`
+// (BUG→FIX) and `libs/swr/coldHydrationRace.test.tsx`.
+const HYDRATION_TIMEOUT = 8000;
/**
* Blocks the first paint until the active scope's IndexedDB cache has hydrated,
@@ -29,7 +40,11 @@ const HYDRATION_TIMEOUT = 1500;
* round-trip. That parallelism is what restores instant-from-cache first paint.
* Writes made before the session confirms the scope are quarantined by the
* cache provider (`isEphemeralScope`), so the optimistic window can't orphan or
- * pollute a partition. The 1500ms timeout is a pure hung-hydration backstop.
+ * pollute a partition. The timeout is a pure hung-hydration backstop (see
+ * `HYDRATION_TIMEOUT`): the gate otherwise waits for real `ready`, so a heavy
+ * account pays a slightly longer loading-screen ONCE at boot and then every
+ * agent/topic it opens is served straight from the fully-hydrated in-memory
+ * cache — no per-topic skeleton, no layout shift.
*/
const CacheHydrationGate = ({ children }: PropsWithChildren) => {
const scope = useCacheScope();
diff --git a/src/layout/GlobalProvider/coldHydrationGate.integration.test.tsx b/src/layout/GlobalProvider/coldHydrationGate.integration.test.tsx
new file mode 100644
index 00000000000..b0c19121763
--- /dev/null
+++ b/src/layout/GlobalProvider/coldHydrationGate.integration.test.tsx
@@ -0,0 +1,166 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * Integration: CacheHydrationGate + the real tiered provider + a consumer.
+ *
+ * The gate's whole job is to guarantee mount-after-hydrate: block first paint
+ * until the active scope's IndexedDB cache has hydrated, so every consumer
+ * mounted under it reads a populated Map. The pure-unit repro
+ * (`libs/swr/coldHydrationRace.test.tsx`) shows a consumer that subscribes
+ * before hydration is permanently orphaned — so if the gate paints early, the
+ * cold-open skeleton returns. This exercises that end to end.
+ */
+import { act, render, renderHook, waitFor } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { createElement } from 'react';
+import useSWR, { type Cache, SWRConfig, unstable_serialize } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheHydration } from '@/libs/swr/cacheHydration';
+import { localDataCache } from '@/libs/swr/localDataCache';
+import { createCacheProvider, type ScopedSWRProvider } from '@/libs/swr/localStorageProvider';
+
+import CacheHydrationGate from './CacheHydrationGate';
+
+let mockScope = 'anon:personal';
+vi.mock('@/libs/swr/useCacheScope', () => ({ useCacheScope: () => mockScope }));
+vi.mock('@/libs/bootTiming', () => ({ bootTiming: { mark: vi.fn(), recordSpan: vi.fn() } }));
+
+const SCOPE = 'u1:personal';
+const KEY = ['MSGS', 'topic-cold'];
+const CACHED = [{ id: 'm1', text: 'cached on disk' }];
+const never = () => new Promise<never>(() => {}); // never resolves — only cache can serve
+
+// A top-level probe so we can observe what an under-gate consumer reads.
+let probed: unknown;
+const Probe = () => {
+ const { data } = useSWR(KEY, never);
+ probed = data;
+ return null;
+};
+
+const asProvider = (p: unknown) => p as unknown as (c: Readonly<Cache>) => Cache;
+const wrap =
+ (provider: unknown) =>
+ ({ children }: { children: ReactNode }) =>
+ createElement(SWRConfig, { value: { provider: asProvider(provider) } }, children);
+
+const makeProvider = (): ScopedSWRProvider =>
+ createCacheProvider({
+ debounceMs: 5,
+ getScope: () => SCOPE,
+ idbPatterns: ['MSGS'],
+ localPatterns: [],
+ onScopeHydrated: cacheHydration.markReady,
+ });
+
+const seedDisk = async () => {
+ const p = makeProvider();
+ const r = renderHook(() => useSWR(KEY, () => Promise.resolve(CACHED)), { wrapper: wrap(p) });
+ await waitFor(() => expect(r.result.current.data).toEqual(CACHED));
+ await waitFor(async () =>
+ expect((await localDataCache.entriesByScope(SCOPE)).length).toBeGreaterThan(0),
+ );
+ r.unmount();
+ cacheHydration.markPending(SCOPE);
+};
+
+describe('CacheHydrationGate + provider + consumer', () => {
+ beforeEach(() => {
+ mockScope = SCOPE;
+ probed = undefined;
+ cacheHydration.markPending(SCOPE);
+ const el = document.createElement('div');
+ el.id = 'loading-screen';
+ document.body.appendChild(el);
+ });
+ afterEach(async () => {
+ document.getElementById('loading-screen')?.remove();
+ cacheHydration.markPending(SCOPE);
+ await localDataCache.clearScope(SCOPE);
+ });
+
+ it('a consumer under the gate reads the cache on first paint (no network)', async () => {
+ await seedDisk();
+ const provider = makeProvider();
+
+ render(
+ createElement(
+ SWRConfig,
+ { value: { provider: asProvider(provider) } },
+ createElement(CacheHydrationGate, null, createElement(Probe)),
+ ),
+ );
+
+ // The gate blocks the consumer until hydration completes; once it releases,
+ // the consumer must already see the cached data — never undefined-then-network.
+ await waitFor(() => expect(probed).toEqual(CACHED));
+ });
+
+ it('DECISIVE: an early orphaned subscriber does NOT poison the key for a later one', async () => {
+ await seedDisk();
+ const provider = makeProvider();
+
+ // an EARLY consumer subscribes before hydration → miss (orphaned)
+ const early = renderHook(() => useSWR(KEY, never), { wrapper: wrap(provider) });
+ expect(early.result.current.data).toBeUndefined();
+
+ await act(async () => {
+ await provider.hydrateScope?.();
+ });
+ expect(early.result.current.data).toBeUndefined(); // early one stays orphaned
+
+ // a LATER consumer subscribes AFTER hydration and reads the populated Map — it
+ // HITS. So the gate (which makes the real consumer a "late" subscriber by
+ // blocking it until `ready`) is sufficient on its own; the fix is to guarantee
+ // the gate releases strictly AFTER hydration.
+ const late = renderHook(() => useSWR(KEY, never), { wrapper: wrap(provider) });
+ expect(late.result.current.data).toEqual(CACHED);
+ });
+
+ it('BUG→FIX: slow hydration must NOT early-release the gate (else the consumer is orphaned)', () => {
+ vi.useFakeTimers();
+ try {
+ // A plain Map provider whose hydration timing we drive by hand, to model a
+ // heavy account whose IndexedDB hydration outruns the gate's timeout.
+ const map = new Map<string, unknown>();
+
+ render(
+ createElement(
+ SWRConfig,
+ { value: { provider: asProvider(() => map) } },
+ createElement(CacheHydrationGate, null, createElement(Probe)),
+ ),
+ );
+
+ // Hydration is still in flight well past the old 1500ms window. The gate
+ // must keep blocking — the consumer must not have subscribed yet (subscribing
+ // now, against an empty Map, orphans it forever).
+ act(() => {
+ vi.advanceTimersByTime(3000);
+ });
+ expect(probed).toBeUndefined();
+
+ // Hydration finishes: the row lands in the Map AND the scope is marked ready.
+ act(() => {
+ map.set(unstable_serialize(KEY), { data: CACHED });
+ cacheHydration.markReady(SCOPE);
+ });
+
+ // Gate releases → the consumer mounts AFTER hydration → reads the populated
+ // Map. On the buggy 1500ms gate it mounted empty at 1500ms and is orphaned,
+ // so this stays undefined.
+ expect(probed).toEqual(CACHED);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ // The local→remote handoff that cache-first relies on — the consumer shows the
+ // cached list, then SWR's revalidation replaces it with the fresh server data —
+ // is standard stale-while-revalidate and is already proven end to end by
+ // `libs/swr/cacheProvider.integration.test.tsx` ("persists fetched data … and
+ // serves it locally on reload", then the fresh server value flows through). The
+ // gate fix only changes release *timing*, not the revalidation/onData path, so
+ // that reconciliation is unchanged from a warm navigation.
+});
diff --git a/src/libs/swr/coldHydrationRace.test.tsx b/src/libs/swr/coldHydrationRace.test.tsx
new file mode 100644
index 00000000000..fcdc28a4309
--- /dev/null
+++ b/src/libs/swr/coldHydrationRace.test.tsx
@@ -0,0 +1,175 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * Deterministic reproduction + fix for the cold-open skeleton bug.
+ *
+ * On a cold boot the IndexedDB tier hydrates asynchronously. If a consumer
+ * registers its SWR key BEFORE that async hydration inserts the row into the
+ * provider Map, SWR records a cache miss — and because SWR does not observe a
+ * later *direct* Map mutation, the consumer stays empty until its own network
+ * revalidation resolves, ignoring the data already sitting on disk / in the Map.
+ * (Verified live: the message-list row is in the provider Map seconds before the
+ * conversation reads it, yet the conversation waits for the network.)
+ *
+ * Re-notifying after the fact does NOT work: once a consumer has subscribed to
+ * an empty key, the direct `map.set` during hydration replaces SWR's own state
+ * object and orphans the subscription — neither global nor bound `mutate` can
+ * revive it (see the third case). The only reliable fix is to guarantee the
+ * cache is hydrated BEFORE any consumer subscribes: the SPA bootstrap creates
+ * the provider and `await`s `hydrateScope()` before mounting the React root (the
+ * `FIX (bootstrap-await)` case).
+ */
+import { act, renderHook, waitFor } from '@testing-library/react';
+import type { PropsWithChildren } from 'react';
+import { createElement } from 'react';
+import useSWR, { type Cache, SWRConfig, unstable_serialize, useSWRConfig } from 'swr';
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { localDataCache } from './localDataCache';
+import { createCacheProvider, type ScopedSWRProvider } from './localStorageProvider';
+
+const SCOPE = 'race-user:personal';
+const KEY = ['MSGS', 'topic-cold'];
+const CACHED = [{ id: 'm1', text: 'cached on disk' }];
+const FRESH = [{ id: 'm1', text: 'from network' }];
+
+const makeProvider = () =>
+ createCacheProvider({
+ debounceMs: 5,
+ getScope: () => SCOPE,
+ idbPatterns: ['MSGS'],
+ localPatterns: [],
+ });
+
+const wrapper =
+ (provider: ScopedSWRProvider) =>
+ ({ children }: PropsWithChildren) =>
+ createElement(
+ SWRConfig,
+ { value: { provider: provider as unknown as (c: Readonly<Cache>) => Cache } },
+ children,
+ );
+
+/** Seed IndexedDB with a persisted SWR state row, as a prior session would leave it. */
+const seedDisk = async () => {
+ const p = makeProvider();
+ const r = renderHook(() => useSWR(KEY, () => Promise.resolve(CACHED)), { wrapper: wrapper(p) });
+ await waitFor(() => expect(r.result.current.data).toEqual(CACHED));
+ await waitFor(async () => {
+ const rows = await localDataCache.entriesByScope(SCOPE);
+ expect(rows.length).toBeGreaterThan(0);
+ });
+ r.unmount();
+};
+
+describe('cold-open hydration race (SWR + tiered provider + IndexedDB)', () => {
+ afterEach(async () => {
+ await localDataCache.clearScope(SCOPE);
+ });
+
+ it('control: hydration completes BEFORE mount → cached row is served locally', async () => {
+ await seedDisk();
+ const p = makeProvider();
+ await p.hydrateScope?.();
+
+ let resolveNet!: (v: unknown) => void;
+ const slow = new Promise((r) => {
+ resolveNet = r;
+ });
+ const r = renderHook(() => useSWR(KEY, () => slow), { wrapper: wrapper(p) });
+ expect(r.result.current.data).toEqual(CACHED);
+ resolveNet(FRESH);
+ });
+
+ it('BUG: consumer mounts BEFORE hydration → never sees the cached row until the network resolves', async () => {
+ await seedDisk();
+ const p = makeProvider();
+
+ let resolveNet!: (v: unknown) => void;
+ const slow = new Promise((r) => {
+ resolveNet = r;
+ });
+ const r = renderHook(() => useSWR(KEY, () => slow), { wrapper: wrapper(p) });
+ expect(r.result.current.data).toBeUndefined();
+
+ await act(async () => {
+ await p.hydrateScope?.();
+ });
+ const mapEntry = [...(p() as Map<string, { data?: unknown }>).values()].find(
+ (v) => JSON.stringify((v as { data?: unknown })?.data) === JSON.stringify(CACHED),
+ );
+ expect(mapEntry).toBeDefined(); // cached row IS in the Map now
+ expect(r.result.current.data).toBeUndefined(); // …yet the consumer is still empty
+
+ resolveNet(FRESH);
+ await waitFor(() => expect(r.result.current.data).toEqual(FRESH));
+ });
+
+ it('FINDING: mutate CANNOT recover an orphaned consumer — so the fix must be mount-after-hydrate', async () => {
+ // Why the naive "re-notify after hydration" fix (mutate) does not work, and
+ // why the only reliable fix is to guarantee consumers mount after hydration.
+ await seedDisk();
+ const p = makeProvider();
+
+ const r = renderHook(
+ () => {
+ const cfg = useSWRConfig();
+ const swr = useSWR(KEY, null); // no fetcher — pure cache read, no pending-fetch confound
+ return {
+ data: swr.data,
+ boundMutate: swr.mutate,
+ globalMutate: cfg.mutate,
+ cache: cfg.cache,
+ };
+ },
+ { wrapper: wrapper(p) },
+ );
+ expect(r.result.current.data).toBeUndefined(); // subscribed while Map empty → miss
+
+ await act(async () => {
+ await p.hydrateScope?.();
+ });
+
+ // SWR's cache Map now holds the row WITH its data — hydration worked…
+ const cached = r.result.current.cache.get(unstable_serialize(KEY)) as { data?: unknown };
+ expect(cached?.data).toEqual(CACHED);
+
+ // …but neither global nor key-bound mutate re-links the orphaned hook: the
+ // direct `map.set` during hydration replaced SWR's own state object, and the
+ // subscription can't be revived from outside. The consumer stays empty.
+ await act(async () => {
+ await r.result.current.globalMutate(KEY, CACHED, { revalidate: false });
+ });
+ expect(r.result.current.data).toBeUndefined();
+
+ await act(async () => {
+ await r.result.current.boundMutate(CACHED, { revalidate: false });
+ });
+ expect(r.result.current.data).toBeUndefined();
+ });
+
+ it('FIX (bootstrap-await): hydrate before mounting consumers → every consumer hits cache, no network', async () => {
+ await seedDisk();
+ const p = makeProvider();
+
+ // The architectural fix: the SPA bootstrap creates the provider and AWAITS
+ // hydrateScope() before mounting the React root, so the Map is populated
+ // before ANY consumer subscribes. (Contrast the BUG case, where a consumer
+ // subscribes during the async hydration window and is orphaned.)
+ await p.hydrateScope?.();
+
+ const never = () => new Promise<never>(() => {}); // never resolves — only cache can serve
+ const r = renderHook(
+ () => {
+ const first = useSWR(KEY, never);
+ const second = useSWR(KEY, never); // a second consumer of the same key
+ return { first: first.data, second: second.data };
+ },
+ { wrapper: wrapper(p) },
+ );
+
+ // both read the populated Map synchronously on first render — no network
+ expect(r.result.current.first).toEqual(CACHED);
+ expect(r.result.current.second).toEqual(CACHED);
+ });
+});