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(desktop): prevent full-screen blank on login by latching CacheHydrationGate (#16753)

Arvin Xuc92d752aa3c7
diff --git a/.agents/skills/agent-testing/references/probe-mock-patterns.md b/.agents/skills/agent-testing/references/probe-mock-patterns.md
index 8f3172876d6..fdaccc87c07 100644
--- a/.agents/skills/agent-testing/references/probe-mock-patterns.md
+++ b/.agents/skills/agent-testing/references/probe-mock-patterns.md
@@ -245,6 +245,31 @@
- **Doesn't work**: `window.__LOBE_STORES.page.getState()` β€” the value is a bound
hook function exposing only `length`/`name`; state isn't readable from it.
+### C1b. βœ… WORKS β€” expose `setState` via HMR to drive a REAL identity/scope change (login repro)
+
+- **Situation**: verifying behavior on an identity/cache-scope change (e.g. login,
+ `useCacheScope` = `${userId}:${workspaceId}`) on the ALREADY-LOADED app, without a
+ real OAuth flow. Cold-boot repro is timing-flaky under machine load; the faithful,
+ deterministic path is to flip `userId` on the live app.
+- **Doesn't work**: `window.__LOBE_STORES.user()` returns `getState()` (actions but no
+ `setState`); there is no public `setUserId` action to call.
+- **Works**: patch the dev-only exposer `src/store/middleware/expose.ts` (HMR) to also
+ attach `setState`, then drive the store from `eval`:
+ ```ts
+ // expose.ts, temporary β€” REMOVE after: git checkout -- src/store/middleware/expose.ts
+ const handle = () => store.getState();
+ (handle as any).setState = (store as any).setState;
+ window.__LOBE_STORES[name] = handle as any;
+ ```
+ `expose()` only runs at store creation, so reload the renderer once after the edit so
+ stores re-expose with the handle. Then:
+ ```js
+ var u = window.__LOBE_STORES.user;
+ var c = u().user || {};
+ u.setState({ user: Object.assign({}, c, { id: 'probe_scope_0705' }) }); // β†’ scope flips
+ ```
+ In-memory only (no DB write); a reload restores the real id. Revert the file after.
+
### C2. βœ… WORKS β€” temporary debug global inside the component
- The decisive way to read a component's live props / store / SWR values: add a
@@ -393,15 +418,40 @@
redirects to `/signin?callbackUrl=...` β€” the deep-route hard-load runs an
SSR/middleware auth check the seeded cookie doesn't satisfy, even though `/`
is authed and the agent is owned by the seeded user.
+
- **Doesn't work**: hard-loading the deep route directly; repeated deep hard-loads
can also drop the seeded cookie so even `/` starts bouncing (re-run `web-seed`).
+
- **Works**: hard-load `/` (authed), confirm by screenshot (not the app-probe auth
JSON β€” it false-negatives here, returns `isSignedIn:false` on an authed page),
then **client-side soft-nav** with no server round-trip:
+
```bash
agent-browser eval "history.pushState({},'','/agent/<id>/docs'); window.dispatchEvent(new PopStateEvent('popstate')); 'nav'" --session lobehub-dev
```
+
react-router picks up the popstate and renders the route in-context with the
already-hydrated auth. Right-panels that render at a _layout_ level do NOT see a
child route's `:param` via `useParams()` β€” read it from `location.pathname` if
you need it.
+
+- **D11. βœ… WORKS β€” catch a BRIEF blank/transient frame (sub-second) that screencast misses.**
+ Verifying a momentary full-screen blank (e.g. a React subtree unmounting to `null` for
+ \~150–350ms during a scope change): `Page.startScreencast` only emits frames on a VISUAL
+ CHANGE, so a _static_ blank produces NO frame β€” you see a time GAP in the manifest, not a
+ blank image. Single timed `cdp-screenshot` also loses the race (its own \~200ms latency
+ overshoots) and `captureScreenshot` can return the prior surface.
+ - **Works β€” two complementary probes**:
+ 1. **DOM proof (deterministic)**: sample `document.getElementById('root').innerText.trim().length`
+ at 150/350/600ms after the trigger via one `eval` returning a Promise. A full unmount
+ drops it to `0`, then it recovers β€” unambiguous, load-independent. (Fixed vs broken:
+ `6064 β†’ 0 β†’ 5646` vs `6089 β†’ 6002 β†’ 6042` never-0.)
+ 2. **Freeze the pixels**: to actually capture the blank image, keep the blank ON SCREEN
+ longer by re-triggering every \~80ms (e.g. flip `userId` to a fresh value each tick so a
+ `key={scope}` gate stays remounted), while firing raw CDP `Page.captureScreenshot` every
+ 80ms over the same window. Blank frames come back tiny (\~34KB jpeg) vs content (\~294KB);
+ convert + Read one to confirm. (A raw-CDP forced capture DOES render a static frame; the
+ trick is holding the state, not the capture.)
+ - Byte-size is a reliable auto-flag for near-uniform frames (blank/loading), but two
+ different near-uniform states (dark loading-screen vs blank) can both be small β€” always
+ Read the frame to tell them apart (Case 1 rule).
diff --git a/src/layout/GlobalProvider/CacheHydrationGate.test.tsx b/src/layout/GlobalProvider/CacheHydrationGate.test.tsx
new file mode 100644
index 00000000000..a8711ed8651
--- /dev/null
+++ b/src/layout/GlobalProvider/CacheHydrationGate.test.tsx
@@ -0,0 +1,150 @@
+import { act, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheHydration } from '@/libs/swr/cacheHydration';
+
+// Import after mocks are registered.
+import CacheHydrationGate from './CacheHydrationGate';
+
+// --- controllable inputs -----------------------------------------------------
+let mockScope = 'anon:personal';
+let mockIsAuthLoaded = true;
+let mockIsUserStateInit = true;
+let mockIsDesktop = false;
+
+vi.mock('@/libs/swr/useCacheScope', () => ({
+ useCacheScope: () => mockScope,
+}));
+
+vi.mock('@/store/user', () => ({
+ useUserStore: (selector: (s: any) => unknown) =>
+ selector({ isLoaded: mockIsAuthLoaded, isUserStateInit: mockIsUserStateInit }),
+}));
+
+vi.mock('@/store/user/selectors', () => ({
+ authSelectors: { isLoaded: (s: any) => s.isLoaded },
+}));
+
+vi.mock('@/libs/bootTiming', () => ({
+ bootTiming: { mark: vi.fn() },
+}));
+
+vi.mock('@lobechat/const', () => ({
+ get isDesktop() {
+ return mockIsDesktop;
+ },
+}));
+
+const ALL_SCOPES = ['anon:personal', 'u1:personal', 'u2:personal'];
+const resetHydration = () => ALL_SCOPES.forEach((s) => cacheHydration.markPending(s));
+
+const Child = () => <div data-testid="app">app content</div>;
+
+const renderGate = () =>
+ render(
+ <CacheHydrationGate>
+ <Child />
+ </CacheHydrationGate>,
+ );
+
+beforeEach(() => {
+ mockScope = 'anon:personal';
+ mockIsAuthLoaded = true;
+ mockIsUserStateInit = true;
+ mockIsDesktop = false;
+ resetHydration();
+ // A loading-screen node so the gate's removal side-effect has a target.
+ const el = document.createElement('div');
+ el.id = 'loading-screen';
+ document.body.appendChild(el);
+});
+
+afterEach(() => {
+ resetHydration();
+ document.getElementById('loading-screen')?.remove();
+ vi.useRealTimers();
+});
+
+describe('CacheHydrationGate', () => {
+ it('blocks first paint (renders nothing) until the initial scope is ready', () => {
+ // web path (isDesktop=false): released needs isAuthLoaded && ready
+ renderGate();
+ // not ready yet β†’ blocked
+ expect(screen.queryByTestId('app')).toBeNull();
+ expect(document.getElementById('loading-screen')).not.toBeNull();
+
+ act(() => {
+ cacheHydration.markReady('anon:personal');
+ });
+
+ expect(screen.queryByTestId('app')).not.toBeNull();
+ // loading-screen removed once released
+ expect(document.getElementById('loading-screen')).toBeNull();
+ });
+
+ it('CORE: after first release, a scope change does NOT unmount the app (no white-screen)', () => {
+ renderGate();
+ act(() => {
+ cacheHydration.markReady('anon:personal');
+ });
+ expect(screen.queryByTestId('app')).not.toBeNull();
+
+ // Simulate login: scope flips to the signed-in user, whose cache is NOT yet
+ // hydrated (markPending / never marked ready). The old key={scope} remount
+ // would blank the whole tree here.
+ act(() => {
+ mockScope = 'u1:personal';
+ cacheHydration.markPending('u1:personal'); // new scope not ready
+ // force a re-render through the hydration store subscription
+ cacheHydration.markReady('anon:personal');
+ });
+
+ // App stays mounted throughout the scope change β€” this is the invariant that
+ // prevents the reported full-screen white flash on login.
+ expect(screen.queryByTestId('app')).not.toBeNull();
+
+ // Even after the new scope finishes hydrating, still mounted (never blanked).
+ act(() => {
+ cacheHydration.markReady('u1:personal');
+ });
+ expect(screen.queryByTestId('app')).not.toBeNull();
+ });
+
+ it('desktop first paint waits for isUserStateInit even when cache is ready', () => {
+ mockIsDesktop = true;
+ mockIsUserStateInit = false;
+ renderGate();
+
+ act(() => {
+ cacheHydration.markReady('anon:personal');
+ });
+ // cache ready + auth loaded, but identity round-trip not done β†’ still blocked
+ expect(screen.queryByTestId('app')).toBeNull();
+
+ // Flip identity to resolved and drive a genuine hydration snapshot change so
+ // the gate re-renders and re-evaluates the release condition.
+ act(() => {
+ mockIsUserStateInit = true;
+ cacheHydration.markPending('anon:personal'); // ready: true β†’ false (re-render, still !ready)
+ });
+ expect(screen.queryByTestId('app')).toBeNull();
+
+ act(() => {
+ cacheHydration.markReady('anon:personal'); // ready: false β†’ true β†’ release
+ });
+ expect(screen.queryByTestId('app')).not.toBeNull();
+ });
+
+ it('timeout backstop releases the app even if hydration never becomes ready', () => {
+ vi.useFakeTimers();
+ mockIsDesktop = true;
+ mockIsUserStateInit = false; // would otherwise block forever on desktop
+ renderGate();
+ expect(screen.queryByTestId('app')).toBeNull();
+
+ act(() => {
+ vi.advanceTimersByTime(1500);
+ });
+ expect(screen.queryByTestId('app')).not.toBeNull();
+ });
+});
diff --git a/src/layout/GlobalProvider/CacheHydrationGate.tsx b/src/layout/GlobalProvider/CacheHydrationGate.tsx
index 64720b733a6..9cda697c443 100644
--- a/src/layout/GlobalProvider/CacheHydrationGate.tsx
+++ b/src/layout/GlobalProvider/CacheHydrationGate.tsx
@@ -1,35 +1,43 @@
'use client';
+import { isDesktop } from '@lobechat/const';
import type { PropsWithChildren } from 'react';
import { useEffect, useLayoutEffect, useState, useSyncExternalStore } from 'react';
import { bootTiming } from '@/libs/bootTiming';
-import { cacheHydration, isCacheHydrationBlocked } from '@/libs/swr/cacheHydration';
+import { cacheHydration } from '@/libs/swr/cacheHydration';
import { useCacheScope } from '@/libs/swr/useCacheScope';
import { useUserStore } from '@/store/user';
import { authSelectors } from '@/store/user/selectors';
-// first-write-wins: keyed by scope remounts must not overwrite the initial mark
+// first-write-wins: only the very first paint records the boot timing mark.
let firstPaintMarked = false;
const HYDRATION_TIMEOUT = 1500;
+/**
+ * Blocks the first paint until the initial identity scope's IndexedDB cache has
+ * hydrated, so the app never flashes empty on cold boot β€” the static
+ * `loading-screen` overlay covers exactly this window.
+ *
+ * This is a one-way latch: once released it never blanks again. A later scope
+ * change (anonymous β†’ signed-in, or workspace switch) re-hydrates the SWR cache
+ * *in place* via `Query.tsx`'s `reloadScope()`, keeping the current tree mounted
+ * while the new scope's data swaps in underneath. Re-blocking here (as the old
+ * `key={scope}` remount did) would unmount the whole app and expose a
+ * full-screen white flash on login.
+ *
+ * On desktop the first paint additionally waits for `isUserStateInit` β€” the
+ * `getUserState()` identity round-trip that populates `userId`. Without it the
+ * cold boot would paint the anonymous scope first and then flip to the signed-in
+ * scope, briefly flashing the logged-out shell. Anonymous desktop still resolves
+ * (the round-trip completes with a null cloud `userId`), and the 1500ms timeout
+ * is a hard backstop so a hung round-trip never keeps the app blank.
+ */
const CacheHydrationGate = ({ children }: PropsWithChildren) => {
const scope = useCacheScope();
-
- return (
- <CacheHydrationGateInner key={scope} scope={scope}>
- {children}
- </CacheHydrationGateInner>
- );
-};
-
-interface CacheHydrationGateInnerProps extends PropsWithChildren {
- scope: string;
-}
-
-const CacheHydrationGateInner = ({ children, scope }: CacheHydrationGateInnerProps) => {
const isAuthLoaded = Boolean(useUserStore(authSelectors.isLoaded));
+ const isUserStateInit = useUserStore((s) => s.isUserStateInit);
const ready = useSyncExternalStore(
cacheHydration.subscribe,
@@ -38,39 +46,41 @@ const CacheHydrationGateInner = ({ children, scope }: CacheHydrationGateInnerPro
);
const [released, setReleased] = useState(false);
- const [timedOutScope, setTimedOutScope] = useState<string | null>(null);
+ const [timedOut, setTimedOut] = useState(false);
+ // Only the first hydration is time-boxed; after release the latch holds.
useEffect(() => {
- const timer = setTimeout(() => setTimedOutScope(scope), HYDRATION_TIMEOUT);
+ if (released) return;
+ const timer = setTimeout(() => setTimedOut(true), HYDRATION_TIMEOUT);
return () => clearTimeout(timer);
- }, [scope]);
+ }, [released]);
useEffect(() => {
+ if (released) return;
+ // Hard backstop: never stay blank past the timeout, whatever is pending.
+ if (timedOut) {
+ setReleased(true);
+ return;
+ }
if (!isAuthLoaded) return;
- if (!cacheHydration.isReady(scope) && timedOutScope !== scope) return;
+ // Desktop paints against the final identity scope, not the anonymous one.
+ if (isDesktop && !isUserStateInit) return;
+ if (!ready) return;
setReleased(true);
- }, [isAuthLoaded, ready, scope, timedOutScope]);
-
- const booting = isCacheHydrationBlocked({
- isAuthLoaded,
- ready,
- released,
- scope,
- timedOutScope,
- });
+ }, [isAuthLoaded, isUserStateInit, ready, released, timedOut]);
useLayoutEffect(() => {
- if (booting) return;
+ if (!released) return;
if (!firstPaintMarked) {
firstPaintMarked = true;
bootTiming.mark('first-paint');
}
document.getElementById('loading-screen')?.remove();
- }, [booting]);
+ }, [released]);
- if (booting) return null;
+ if (!released) return null;
return <>{children}</>;
};
diff --git a/src/layout/GlobalProvider/Query.tsx b/src/layout/GlobalProvider/Query.tsx
index 0ac033d4539..1f1fad92ce7 100644
--- a/src/layout/GlobalProvider/Query.tsx
+++ b/src/layout/GlobalProvider/Query.tsx
@@ -5,6 +5,7 @@ import type { PropsWithChildren } from 'react';
import React, { useLayoutEffect, useRef, useState } from 'react';
import { type Cache, SWRConfig } from 'swr';
+import { mutate } from '@/libs/swr';
import { cacheHydration } from '@/libs/swr/cacheHydration';
import { swrCacheProvider } from '@/libs/swr/localStorageProvider';
import { getCacheScope, useCacheScope } from '@/libs/swr/useCacheScope';
@@ -35,9 +36,20 @@ const QueryProvider = ({ children }: PropsWithChildren) => {
const reloadScope = provider.reloadScope;
if (!reloadScope) return;
- void reloadScope().catch((error) => {
- console.error('[SWR Cache] failed to reload scope', error);
- });
+ // `reloadScope()` swaps the provider Map's persisted entries to the new
+ // scope in place, but SWR does not observe direct Map mutation. Mounted
+ // consumers whose key does not change across the swap (e.g. keys embedding
+ // only a scope-stable agent/topic id, since `augmentKey` adds workspaceId
+ // but never userId) would otherwise keep rendering the previous scope's
+ // data until an incidental revalidation. Broadcast a global revalidation
+ // once the swap resolves so every consumer re-reads under the new scope β€”
+ // the CacheHydrationGate latch keeps the tree mounted, so this replaces the
+ // correctness role the old `key={scope}` remount used to play.
+ void reloadScope()
+ .then(() => mutate(() => true, undefined, { revalidate: true }))
+ .catch((error) => {
+ console.error('[SWR Cache] failed to reload scope', error);
+ });
}, [scope, provider]);
return (