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.

⚑️ perf(swr): persist activeScopeKey for parallel cache hydration (instant-open gate) (#16951)

Arvin Xu54f98c49d6cd
diff --git a/src/layout/GlobalProvider/CacheHydrationGate.test.tsx b/src/layout/GlobalProvider/CacheHydrationGate.test.tsx
index f6b7fa9b418..acfc5cb4327 100644
--- a/src/layout/GlobalProvider/CacheHydrationGate.test.tsx
+++ b/src/layout/GlobalProvider/CacheHydrationGate.test.tsx
@@ -8,39 +8,15 @@ import CacheHydrationGate from './CacheHydrationGate';
// --- controllable inputs -----------------------------------------------------
let mockScope = 'anon:personal';
-let mockIsAuthLoaded = true;
-let mockIsSignedIn = true;
-let mockUserId: string | undefined = 'u1';
-let mockIsDesktop = false;
vi.mock('@/libs/swr/useCacheScope', () => ({
useCacheScope: () => mockScope,
}));
-vi.mock('@/store/user', () => ({
- useUserStore: (selector: (s: any) => unknown) =>
- selector({
- isLoaded: mockIsAuthLoaded,
- isSignedIn: mockIsSignedIn,
- user: { id: mockUserId },
- }),
-}));
-
-vi.mock('@/store/user/selectors', () => ({
- authSelectors: { isLoaded: (s: any) => s.isLoaded, isLogin: (s: any) => s.isSignedIn },
- userProfileSelectors: { userId: (s: any) => s.user?.id },
-}));
-
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));
@@ -55,10 +31,6 @@ const renderGate = () =>
beforeEach(() => {
mockScope = 'anon:personal';
- mockIsAuthLoaded = true;
- mockIsSignedIn = true;
- mockUserId = 'u1';
- mockIsDesktop = false;
resetHydration();
// A loading-screen node so the gate's removal side-effect has a target.
const el = document.createElement('div');
@@ -74,7 +46,7 @@ afterEach(() => {
});
describe('CacheHydrationGate', () => {
- it('blocks first paint (renders nothing) until the initial scope is ready', () => {
+ it('blocks first paint (renders nothing) until the active scope is hydrated', () => {
renderGate();
// not ready yet β†’ blocked
expect(screen.queryByTestId('app')).toBeNull();
@@ -96,137 +68,37 @@ describe('CacheHydrationGate', () => {
});
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.
+ // Simulate the session resolving a different scope whose cache is NOT yet
+ // hydrated. 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');
+ cacheHydration.markReady('anon:personal'); // force a re-render via the store
});
- // App stays mounted throughout the scope change β€” this is the invariant that
- // prevents the reported full-screen white flash on login.
+ // App stays mounted throughout the scope change.
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('first paint waits for userId to resolve (signed-in) even when cache is ready', () => {
- mockUserId = undefined;
- renderGate();
-
- act(() => {
- cacheHydration.markReady('anon:personal');
- });
- // cache ready + auth loaded + signed in, but identity round-trip not done β†’ blocked
- expect(screen.queryByTestId('app')).toBeNull();
-
- // Resolve identity and drive a genuine hydration snapshot change so the gate
- // re-renders and re-evaluates the release condition.
- act(() => {
- mockUserId = 'u1';
- 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 once identity is resolved even if cache never hydrates', () => {
- vi.useFakeTimers();
- mockUserId = 'u1';
- // cache scope is never marked ready
- renderGate();
- expect(screen.queryByTestId('app')).toBeNull();
-
- act(() => {
- vi.advanceTimersByTime(1500);
- });
- expect(screen.queryByTestId('app')).not.toBeNull();
- });
-
- it('REGRESSION: signed-in desktop stays blocked past the timeout when userId is unresolved', () => {
- vi.useFakeTimers();
- mockIsDesktop = true;
- mockUserId = undefined;
- renderGate();
- expect(screen.queryByTestId('app')).toBeNull();
-
- // The old behavior released into the anonymous scope here β€” orphaning any
- // data fetched under it. The userId guard now precedes the timeout backstop.
- act(() => {
- vi.advanceTimersByTime(1500);
- });
- expect(screen.queryByTestId('app')).toBeNull();
- expect(document.getElementById('loading-screen')).not.toBeNull();
-
- // Identity resolves later (incl. via SWR focus/reconnect revalidation) β†’ release.
- act(() => {
- mockUserId = 'u1';
- cacheHydration.markReady('anon:personal');
- });
- expect(screen.queryByTestId('app')).not.toBeNull();
- });
-
- it('releases desktop onboarding without waiting for userId', () => {
- vi.useFakeTimers();
- window.history.replaceState(null, '', '/desktop-onboarding');
- mockIsDesktop = true;
- mockIsSignedIn = false;
- mockUserId = undefined;
+ it('releases the moment the active scope is ready β€” no identity round-trip wait', () => {
+ // The persisted activeScopeKey means the hydrated scope is already the real
+ // user partition, so the gate must not wait for auth/userId β€” only `ready`.
renderGate();
-
- act(() => {
- vi.advanceTimersByTime(1500);
- });
-
- expect(screen.queryByTestId('app')).not.toBeNull();
- expect(document.getElementById('loading-screen')).toBeNull();
- });
-
- it('REGRESSION: signed-in web stays blocked past the timeout when userId is unresolved', () => {
- vi.useFakeTimers();
- mockIsSignedIn = true;
- mockUserId = undefined;
- renderGate();
-
- act(() => {
- vi.advanceTimersByTime(1500);
- });
expect(screen.queryByTestId('app')).toBeNull();
act(() => {
- mockUserId = 'u1';
cacheHydration.markReady('anon:personal');
});
expect(screen.queryByTestId('app')).not.toBeNull();
});
- it('P1 FIX: no-auth / logged-out web is NOT blocked on userId β€” releases once ready', () => {
- mockIsSignedIn = false; // no session (no-auth deployment, or logged out)
- mockUserId = undefined; // and no userId will ever arrive
- renderGate();
-
- // No userId gate applies β†’ only the cache-ready condition remains.
- act(() => {
- cacheHydration.markReady('anon:personal');
- });
- expect(screen.queryByTestId('app')).not.toBeNull();
- });
-
- it('P1 FIX: no-auth / logged-out web releases via the timeout even if cache never hydrates', () => {
+ it('timeout backstop releases the app even if hydration never becomes ready', () => {
vi.useFakeTimers();
- mockIsSignedIn = false;
- mockUserId = undefined;
renderGate();
expect(screen.queryByTestId('app')).toBeNull();
@@ -235,35 +107,4 @@ describe('CacheHydrationGate', () => {
});
expect(screen.queryByTestId('app')).not.toBeNull();
});
-
- it('does not treat a stale isSignedIn as final while auth is still loading', () => {
- // Auth mid-load: isSignedIn is not yet trustworthy. Must not release into
- // anon via timeout before the session resolves.
- vi.useFakeTimers();
- mockIsAuthLoaded = false;
- mockIsSignedIn = false;
- mockUserId = undefined;
- renderGate();
-
- act(() => {
- vi.advanceTimersByTime(1500);
- });
- expect(screen.queryByTestId('app')).toBeNull();
-
- // Session resolves to signed-in β†’ now a userId is expected β†’ keep blocking until it lands.
- act(() => {
- mockIsAuthLoaded = true;
- mockIsSignedIn = true;
- cacheHydration.markReady('anon:personal'); // false→true snapshot change → re-render
- });
- expect(screen.queryByTestId('app')).toBeNull();
-
- // userId resolves β†’ release. (markPending forces a re-render that reads the
- // updated mockUserId; the mock store itself doesn't notify.)
- act(() => {
- mockUserId = 'u1';
- cacheHydration.markPending('anon:personal'); // true→false snapshot change → re-render
- });
- expect(screen.queryByTestId('app')).not.toBeNull();
- });
});
diff --git a/src/layout/GlobalProvider/CacheHydrationGate.tsx b/src/layout/GlobalProvider/CacheHydrationGate.tsx
index 9cdf4ef6c92..fb4adc3b2a0 100644
--- a/src/layout/GlobalProvider/CacheHydrationGate.tsx
+++ b/src/layout/GlobalProvider/CacheHydrationGate.tsx
@@ -1,14 +1,11 @@
'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 } from '@/libs/swr/cacheHydration';
import { useCacheScope } from '@/libs/swr/useCacheScope';
-import { useUserStore } from '@/store/user';
-import { authSelectors, userProfileSelectors } from '@/store/user/selectors';
// first-write-wins: only the very first paint records the boot timing mark.
let firstPaintMarked = false;
@@ -16,36 +13,26 @@ 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.
+ * Blocks the first paint until the active 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.
+ * while the new scope's data swaps in underneath.
*
- * The first paint additionally waits for a real `userId` β€” but only where one
- * is expected, i.e. where the identity round-trip actually runs: normal desktop
- * app paths (which resolve a `DESKTOP_USER` id) or a signed-in web session. The
- * anonymous scope is only ever a transient pre-identity boot state, so painting
- * under it would persist fetched data into the `anon` partition and orphan it
- * the moment the real scope resolves (the stale-loading cache-miss bug).
- * Blocking until `userId` lands closes that leak at the root: no data UI ever
- * mounts under the anonymous scope. A no-auth / logged-out web deployment has
- * no `userId` to wait for, so it is exempt and falls through to the
- * timeout/ready backstop. `initState` revalidates on focus/reconnect, so a
- * transient network failure self-heals into a release.
+ * The active scope is known synchronously at boot from the persisted
+ * `activeScopeKey` (the last-known `${userId}:${workspace}`), so the provider
+ * hydrates the *real* user partition in parallel with the session check β€” the
+ * gate only waits for that hydration (`ready`), not for the identity
+ * 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.
*/
const CacheHydrationGate = ({ children }: PropsWithChildren) => {
const scope = useCacheScope();
- const isAuthLoaded = Boolean(useUserStore(authSelectors.isLoaded));
- const isSignedIn = useUserStore(authSelectors.isLogin);
- const userId = useUserStore(userProfileSelectors.userId);
- const isDesktopOnboarding =
- typeof window !== 'undefined' && window.location.pathname.startsWith('/desktop-onboarding');
const ready = useSyncExternalStore(
cacheHydration.subscribe,
@@ -65,28 +52,11 @@ const CacheHydrationGate = ({ children }: PropsWithChildren) => {
useEffect(() => {
if (released) return;
-
- // A userId is expected only where the identity round-trip runs (desktop or a
- // signed-in web session β€” the same condition that triggers `useInitUserState`).
- // No-auth / logged-out web never produces one, so it must not be blocked here.
- // Guard on `isAuthLoaded` so we don't act on a stale `isSignedIn` mid-load.
- if (isAuthLoaded && ((isDesktop && !isDesktopOnboarding) || isSignedIn) && !userId) return;
-
- // Block until the session check resolves (it always does β€” success, failure,
- // or no-auth β€” so this isn't an infinite hang). Preceding the timeout means a
- // slow session can't release into the anonymous scope.
- if (!isAuthLoaded) return;
-
- // Backstop: identity resolved, but cache hydration is hung β€” release rather
- // than hang. Safe because a userId is either present or not expected here.
- if (timedOut) {
- setReleased(true);
- return;
- }
- if (!ready) return;
-
- setReleased(true);
- }, [isAuthLoaded, isDesktopOnboarding, isSignedIn, userId, ready, released, timedOut]);
+ // Release the moment the active scope's cache has hydrated β€” the persisted
+ // activeScopeKey means that's already the real user partition, so this paints
+ // straight from cache. The timeout backstop guards a hung hydration only.
+ if (ready || timedOut) setReleased(true);
+ }, [ready, timedOut, released]);
useLayoutEffect(() => {
if (!released) return;
diff --git a/src/libs/swr/localStorageProvider.ts b/src/libs/swr/localStorageProvider.ts
index 2a0f8edc476..b07ba106a7e 100644
--- a/src/libs/swr/localStorageProvider.ts
+++ b/src/libs/swr/localStorageProvider.ts
@@ -26,7 +26,7 @@
import { bootTiming } from '@/libs/bootTiming';
import { buildLocalDataKey, localDataCache } from './localDataCache';
-import { isAnonymousScope } from './useCacheScope';
+import { isScopeTrusted } from './useCacheScope';
interface CacheEntry<T = unknown> {
/** Cached data */
@@ -510,16 +510,15 @@ export const swrCacheProvider = (
return createCacheProvider({
getScope,
idbPatterns: [...CACHE_TIERS.idb],
- // Desktop's anonymous scope is a transient pre-identity boot state (a
- // successful `getUserState` always resolves a real `userId`), so quarantine
- // its writes from persistence β€” otherwise a slow identity round-trip lets
- // real data land in the `anon` partition and get orphaned on the scope flip.
- // The anonymous scope is only ever a transient pre-identity boot state β€”
- // quarantine its writes from persistence so a slow identity round-trip
- // can't land real data in the `anon` partition and orphan it on the scope
- // flip. (The CacheHydrationGate now blocks paint until `userId` resolves, so
- // this is defense-in-depth for any fetcher that mounts outside the gate.)
- isEphemeralScope: isAnonymousScope,
+ // Quarantine writes until the session check resolves (`isScopeTrusted`).
+ // The active scope is optimistic (persisted last-known user) before the
+ // session confirms it, so a write made then could land in the wrong
+ // partition on an account switch / first-ever boot and get orphaned. Once the
+ // session resolves the scope is definitive and writes persist β€” including
+ // no-auth, where the check completes to "not signed in" and the anonymous
+ // scope is a legitimate durable context. `reloadScope` clears the dirty set
+ // on a real scope flip, so quarantined writes never survive a switch.
+ isEphemeralScope: () => !isScopeTrusted(),
localPatterns: [...CACHE_TIERS.local],
onScopeHydrated,
// Governs the localStorage tier only (recents-style shells); the IndexedDB
diff --git a/src/libs/swr/useCacheScope.test.ts b/src/libs/swr/useCacheScope.test.ts
index cc1d6840895..d44e94ef277 100644
--- a/src/libs/swr/useCacheScope.test.ts
+++ b/src/libs/swr/useCacheScope.test.ts
@@ -1,6 +1,39 @@
-import { describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { buildCacheScope } from './useCacheScope';
+import {
+ buildCacheScope,
+ clearActiveScopeKey,
+ getCacheScope,
+ isAnonymousScope,
+ isScopeTrusted,
+} from './useCacheScope';
+
+let mockUserId: string | null | undefined = undefined;
+let mockIsAuthLoaded = false;
+let mockIsUserStateInit = false;
+let mockWorkspaceId: string | null = null;
+let mockIsDesktop = false;
+
+vi.mock('@lobechat/const', () => ({
+ get isDesktop() {
+ return mockIsDesktop;
+ },
+}));
+vi.mock('@/store/user', () => ({
+ getUserStoreState: () => ({
+ isLoaded: mockIsAuthLoaded,
+ isUserStateInit: mockIsUserStateInit,
+ user: { id: mockUserId },
+ }),
+}));
+vi.mock('@/store/user/selectors', () => ({
+ authSelectors: { isLoaded: (s: any) => s.isLoaded },
+ userProfileSelectors: { userId: (s: any) => s.user?.id },
+}));
+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
+ getActiveWorkspaceId: () => mockWorkspaceId,
+ useActiveWorkspaceId: () => mockWorkspaceId,
+}));
describe('buildCacheScope', () => {
it('falls back to anon/personal', () => {
@@ -18,3 +51,98 @@ describe('buildCacheScope', () => {
expect(buildCacheScope('u1', 'w1')).not.toBe(buildCacheScope('u1', 'w2'));
});
});
+
+describe('isAnonymousScope', () => {
+ it('matches the anon partition only', () => {
+ expect(isAnonymousScope('anon:personal')).toBe(true);
+ expect(isAnonymousScope('u1:personal')).toBe(false);
+ });
+});
+
+describe('activeScopeKey + optimistic scope', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ mockUserId = undefined;
+ mockIsAuthLoaded = false;
+ mockIsUserStateInit = false;
+ mockWorkspaceId = null;
+ mockIsDesktop = false;
+ });
+
+ afterEach(() => {
+ localStorage.clear();
+ });
+
+ it('getCacheScope falls back to anon when no userId and no persisted scope (first-ever boot)', () => {
+ expect(getCacheScope()).toBe('anon:personal');
+ });
+
+ it('getCacheScope returns the persisted activeScopeKey optimistically when userId is unresolved', () => {
+ localStorage.setItem('lobehub:active-scope', 'user_abc:w1');
+ // userId still unresolved β€” but we hydrate the last-known user partition
+ expect(getCacheScope()).toBe('user_abc:w1');
+ });
+
+ it('getCacheScope prefers the real resolved scope over the persisted one', () => {
+ localStorage.setItem('lobehub:active-scope', 'user_abc:w1');
+ mockUserId = 'user_real';
+ mockWorkspaceId = 'w2';
+ expect(getCacheScope()).toBe('user_real:w2');
+ });
+
+ it('getCacheScope ignores the persisted scope once the session resolves signed-out', () => {
+ // expired cookie / sign-out in another tab: session settled, but no user
+ localStorage.setItem('lobehub:active-scope', 'user_abc:w1');
+ mockIsAuthLoaded = true;
+ expect(getCacheScope()).toBe('anon:personal');
+ });
+
+ it('getCacheScope keeps the persisted scope on desktop until user state initializes', () => {
+ // desktop hardcodes isLoaded=true on mount; userId lands with useInitUserState
+ localStorage.setItem('lobehub:active-scope', 'user_abc:w1');
+ mockIsDesktop = true;
+ mockIsAuthLoaded = true;
+ mockIsUserStateInit = false;
+ expect(getCacheScope()).toBe('user_abc:w1');
+ });
+
+ it('clearActiveScopeKey removes the persisted scope (logout)', () => {
+ localStorage.setItem('lobehub:active-scope', 'user_abc:personal');
+ clearActiveScopeKey();
+ expect(localStorage.getItem('lobehub:active-scope')).toBeNull();
+ // β†’ next getCacheScope (userId unresolved) falls back to anon
+ expect(getCacheScope()).toBe('anon:personal');
+ });
+});
+
+describe('isScopeTrusted', () => {
+ beforeEach(() => {
+ mockIsAuthLoaded = false;
+ mockIsUserStateInit = false;
+ mockIsDesktop = false;
+ });
+
+ it('is untrusted while the session check is in flight', () => {
+ mockIsAuthLoaded = false;
+ expect(isScopeTrusted()).toBe(false);
+ });
+
+ it('is trusted once the session check resolves (covers both signed-in and no-auth)', () => {
+ mockIsAuthLoaded = true;
+ expect(isScopeTrusted()).toBe(true);
+ });
+
+ it('on desktop, is untrusted until user state initializes even though isLoaded is true', () => {
+ mockIsDesktop = true;
+ mockIsAuthLoaded = true;
+ mockIsUserStateInit = false;
+ expect(isScopeTrusted()).toBe(false);
+ });
+
+ it('on desktop, is trusted once user state initializes', () => {
+ mockIsDesktop = true;
+ mockIsAuthLoaded = true;
+ mockIsUserStateInit = true;
+ expect(isScopeTrusted()).toBe(true);
+ });
+});
diff --git a/src/libs/swr/useCacheScope.ts b/src/libs/swr/useCacheScope.ts
index f3f7c87a531..adb9ef22bb9 100644
--- a/src/libs/swr/useCacheScope.ts
+++ b/src/libs/swr/useCacheScope.ts
@@ -1,13 +1,61 @@
+import { isDesktop } from '@lobechat/const';
+import { useEffect, useState } from 'react';
+
import {
getActiveWorkspaceId,
useActiveWorkspaceId,
} from '@/business/client/hooks/useActiveWorkspaceId';
-import { getUserStoreState, useUserStore } from '@/store/user';
-import { userProfileSelectors } from '@/store/user/selectors';
+import { getUserStoreState, type UserStore, useUserStore } from '@/store/user';
+import { authSelectors, userProfileSelectors } from '@/store/user/selectors';
const ANON = 'anon';
const PERSONAL = 'personal';
+/**
+ * localStorage key holding the last-known resolved cache scope
+ * (`${userId}:${workspaceId}`). On a cold boot the identity round-trip hasn't
+ * resolved yet, so we can't know which user partition to hydrate β€” reading this
+ * synchronously lets us hydrate the *real* user's IndexedDB cache in parallel
+ * with the session check, instead of the empty anonymous partition and only
+ * re-hydrating after the session resolves. That parallelism is what restores
+ * instant-from-cache first paint (the #10884 synchronous-cache behavior the
+ * async IndexedDB tier in #15844 lost).
+ */
+const ACTIVE_SCOPE_STORAGE_KEY = 'lobehub:active-scope';
+
+const isBrowser = () => typeof localStorage !== 'undefined';
+
+const readActiveScope = (): string | null => {
+ if (!isBrowser()) return null;
+ try {
+ return localStorage.getItem(ACTIVE_SCOPE_STORAGE_KEY);
+ } catch {
+ return null;
+ }
+};
+
+const writeActiveScope = (scope: string): void => {
+ if (!isBrowser()) return;
+ try {
+ localStorage.setItem(ACTIVE_SCOPE_STORAGE_KEY, scope);
+ } catch {
+ // best-effort
+ }
+};
+
+/**
+ * Drop the persisted active scope. Call on logout / sign-out so the next boot
+ * doesn't hydrate a since-logged-out user's cache.
+ */
+export const clearActiveScopeKey = (): void => {
+ if (!isBrowser()) return;
+ try {
+ localStorage.removeItem(ACTIVE_SCOPE_STORAGE_KEY);
+ } catch {
+ // best-effort
+ }
+};
+
/**
* Build a cache scope string from the current identity.
*
@@ -17,7 +65,7 @@ const PERSONAL = 'personal';
* never collides or overwrites each other.
*
* Personal mode (no active workspace) collapses to `${userId}:personal`;
- * logged-out / SSR collapses to `anon:personal`.
+ * logged-out / SSR / first-ever boot collapses to `anon:personal`.
*/
export const buildCacheScope = (
userId: string | null | undefined,
@@ -26,27 +74,100 @@ export const buildCacheScope = (
/**
* Whether a scope belongs to the anonymous (identity-unresolved) partition.
- *
- * The anonymous scope is only ever a transient pre-identity boot state β€” once
- * auth resolves, every signed-in user has a real `userId` β€” so it is never a
- * durable identity and its writes must not be persisted (see the cache
- * provider's `isEphemeralScope`).
*/
export const isAnonymousScope = (scope: string): boolean => scope.startsWith(`${ANON}:`);
+/**
+ * Whether the identity round-trip has landed, i.e. `userId` is now known to be
+ * either a real id or genuinely absent.
+ *
+ * The signal differs per deployment, and `isLoaded` alone is *not* it:
+ *
+ * - Web (Better-Auth): `isLoaded` flips when the session request settles, at
+ * which point `user` is populated (or confirmed empty). It is the signal.
+ * - Desktop: `DesktopAuthProvider` hardcodes `isLoaded` to `true` on mount
+ * because the server trusts `DESKTOP_USER_ID`, but `userId` only lands when
+ * the async `useInitUserState` fetch resolves. `isUserStateInit` is the
+ * signal there; using `isLoaded` would declare the anonymous boot scope
+ * trustworthy and let that window's writes orphan into the `anon` partition.
+ * - No-auth self-host: `isLoaded` is `true` on mount and `useInitUserState`
+ * never runs, so `userId` stays undefined forever and `anon` is the real,
+ * durable scope. `isDesktop` is false there, so `isLoaded` applies.
+ */
+const isIdentityResolved = (s: UserStore): boolean =>
+ isDesktop ? s.isUserStateInit : Boolean(authSelectors.isLoaded(s));
+
+/**
+ * The effective cache scope for the *current* moment.
+ *
+ * - Identity resolved, `userId` known: the real scope `${userId}:${workspace}`.
+ * - Identity unresolved (cold boot, identity round-trip in flight): the
+ * persisted `activeScopeKey` (last-known user) so the cache provider hydrates
+ * the right partition up front β€” falling back to `anon:personal` only on a
+ * first-ever boot with no persisted scope.
+ * - Identity resolved, no `userId` (expired cookie, sign-out in another tab,
+ * no-auth): `anon:personal`. The persisted scope must be ignored here or a
+ * logged-out visitor keeps reading and writing the previous user's partition.
+ */
+const resolveScope = (
+ userId: string | null | undefined,
+ workspaceId: string | null | undefined,
+ persisted: string | null,
+ identityResolved: boolean,
+): string => {
+ if (userId) return buildCacheScope(userId, workspaceId);
+ if (identityResolved) return buildCacheScope(undefined, undefined);
+ return persisted ?? buildCacheScope(undefined, undefined);
+};
+
/**
* React hook returning the current cache scope. Recomputes when the signed-in
- * user or the active workspace changes.
+ * user or the active workspace changes. Persists every resolved real (non-anon)
+ * scope so the next cold boot can hydrate it in parallel with the session check.
*/
export const useCacheScope = (): string => {
const userId = useUserStore(userProfileSelectors.userId);
+ const identityResolved = useUserStore(isIdentityResolved);
const workspaceId = useActiveWorkspaceId();
- return buildCacheScope(userId, workspaceId);
+ // Read once on mount β€” the persisted key only matters before identity resolves.
+ const [persisted] = useState(readActiveScope);
+
+ const scope = resolveScope(userId, workspaceId, persisted, identityResolved);
+
+ useEffect(() => {
+ if (userId && !isAnonymousScope(scope)) writeActiveScope(scope);
+ // The identity round-trip landed on "nobody": the persisted scope belongs to
+ // a session that is no longer valid, so drop it rather than let the next
+ // boot optimistically hydrate it again.
+ else if (identityResolved && !userId) clearActiveScopeKey();
+ }, [scope, userId, identityResolved]);
+
+ return scope;
};
/**
* Non-React getter for the current cache scope (for use inside services /
- * imperative code paths).
+ * imperative code paths, and the SWR cache provider's `getScope`).
+ */
+export const getCacheScope = (): string => {
+ const state = getUserStoreState();
+
+ return resolveScope(
+ userProfileSelectors.userId(state),
+ getActiveWorkspaceId(),
+ readActiveScope(),
+ isIdentityResolved(state),
+ );
+};
+
+/**
+ * Whether the current scope has been confirmed by a resolved identity.
+ *
+ * Until the identity round-trip lands, the scope is the optimistic persisted
+ * one (or anon) β€” writes made then are quarantined (see the cache provider's
+ * `isEphemeralScope`) so an account switch / first-ever boot can't pollute or
+ * orphan a partition. Once identity resolves, writes persist normally (this
+ * also covers no-auth: the session check completes to "not signed in", and the
+ * anonymous scope is a legitimate durable context there).
*/
-export const getCacheScope = (): string =>
- buildCacheScope(userProfileSelectors.userId(getUserStoreState()), getActiveWorkspaceId());
+export const isScopeTrusted = (): boolean => isIdentityResolved(getUserStoreState());
diff --git a/src/store/user/slices/auth/action.ts b/src/store/user/slices/auth/action.ts
index 3543c5632dc..c58a1f5cfec 100644
--- a/src/store/user/slices/auth/action.ts
+++ b/src/store/user/slices/auth/action.ts
@@ -1,5 +1,6 @@
import { type SSOProvider } from '@lobechat/types';
+import { clearActiveScopeKey } from '@/libs/swr/useCacheScope';
import { type StoreSetter } from '@/store/types';
import { type UserStore } from '../../store';
@@ -74,6 +75,9 @@ export class UserAuthActionImpl {
await signOut({
fetchOptions: {
onSuccess: () => {
+ // Drop the persisted active scope so the next boot doesn't hydrate the
+ // signed-out user's cache (localStorage survives the reload below).
+ clearActiveScopeKey();
// Use window.location.href to trigger a full page reload
// This ensures all client-side state (React, Zustand, cache) is cleared
window.location.href = '/signin';