π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix: block first paint until userId resolves (stop anon-scope cache orphans) (#16850)
Arvin Xu72a19af4bc38
diff --git a/src/layout/GlobalProvider/CacheHydrationGate.test.tsx b/src/layout/GlobalProvider/CacheHydrationGate.test.tsxindex a8711ed8651..de29005c59d 100644--- a/src/layout/GlobalProvider/CacheHydrationGate.test.tsx+++ b/src/layout/GlobalProvider/CacheHydrationGate.test.tsx@@ -9,7 +9,8 @@ import CacheHydrationGate from './CacheHydrationGate';// --- controllable inputs -----------------------------------------------------let mockScope = 'anon:personal';let mockIsAuthLoaded = true;-let mockIsUserStateInit = true;+let mockIsSignedIn = true;+let mockUserId: string | undefined = 'u1';let mockIsDesktop = false;vi.mock('@/libs/swr/useCacheScope', () => ({@@ -18,11 +19,16 @@ vi.mock('@/libs/swr/useCacheScope', () => ({vi.mock('@/store/user', () => ({useUserStore: (selector: (s: any) => unknown) =>- selector({ isLoaded: mockIsAuthLoaded, isUserStateInit: mockIsUserStateInit }),+ selector({+ isLoaded: mockIsAuthLoaded,+ isSignedIn: mockIsSignedIn,+ user: { id: mockUserId },+ }),}));vi.mock('@/store/user/selectors', () => ({- authSelectors: { isLoaded: (s: any) => s.isLoaded },+ authSelectors: { isLoaded: (s: any) => s.isLoaded, isLogin: (s: any) => s.isSignedIn },+ userProfileSelectors: { userId: (s: any) => s.user?.id },}));vi.mock('@/libs/bootTiming', () => ({@@ -50,7 +56,8 @@ const renderGate = () =>beforeEach(() => {mockScope = 'anon:personal';mockIsAuthLoaded = true;- mockIsUserStateInit = true;+ mockIsSignedIn = true;+ mockUserId = 'u1';mockIsDesktop = false;resetHydration();// A loading-screen node so the gate's removal side-effect has a target.@@ -67,7 +74,6 @@ afterEach(() => {describe('CacheHydrationGate', () => {it('blocks first paint (renders nothing) until the initial scope is ready', () => {- // web path (isDesktop=false): released needs isAuthLoaded && readyrenderGate();// not ready yet β blockedexpect(screen.queryByTestId('app')).toBeNull();@@ -110,21 +116,20 @@ describe('CacheHydrationGate', () => {expect(screen.queryByTestId('app')).not.toBeNull();});- it('desktop first paint waits for isUserStateInit even when cache is ready', () => {- mockIsDesktop = true;- mockIsUserStateInit = false;+ 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, but identity round-trip not done β still blocked+ // cache ready + auth loaded + signed in, but identity round-trip not done β blockedexpect(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.+ // Resolve identity and drive a genuine hydration snapshot change so the gate+ // re-renders and re-evaluates the release condition.act(() => {- mockIsUserStateInit = true;+ mockUserId = 'u1';cacheHydration.markPending('anon:personal'); // ready: true β false (re-render, still !ready)});expect(screen.queryByTestId('app')).toBeNull();@@ -135,10 +140,76 @@ describe('CacheHydrationGate', () => {expect(screen.queryByTestId('app')).not.toBeNull();});- it('timeout backstop releases the app even if hydration never becomes ready', () => {+ 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;- mockIsUserStateInit = false; // would otherwise block forever on desktop+ 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('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', () => {+ vi.useFakeTimers();+ mockIsSignedIn = false;+ mockUserId = undefined;renderGate();expect(screen.queryByTestId('app')).toBeNull();@@ -147,4 +218,35 @@ 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.tsxindex 9cda697c443..bac500c0ac9 100644--- a/src/layout/GlobalProvider/CacheHydrationGate.tsx+++ b/src/layout/GlobalProvider/CacheHydrationGate.tsx@@ -8,7 +8,7 @@ import { bootTiming } from '@/libs/bootTiming';import { cacheHydration } from '@/libs/swr/cacheHydration';import { useCacheScope } from '@/libs/swr/useCacheScope';import { useUserStore } from '@/store/user';-import { authSelectors } from '@/store/user/selectors';+import { authSelectors, userProfileSelectors } from '@/store/user/selectors';// first-write-wins: only the very first paint records the boot timing mark.let firstPaintMarked = false;@@ -27,17 +27,23 @@ const HYDRATION_TIMEOUT = 1500;* `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.+ * The first paint additionally waits for a real `userId` β but only where one+ * is expected, i.e. where the identity round-trip actually runs: desktop+ * (always resolves 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.*/const CacheHydrationGate = ({ children }: PropsWithChildren) => {const scope = useCacheScope();const isAuthLoaded = Boolean(useUserStore(authSelectors.isLoaded));- const isUserStateInit = useUserStore((s) => s.isUserStateInit);+ const isSignedIn = useUserStore(authSelectors.isLogin);+ const userId = useUserStore(userProfileSelectors.userId);const ready = useSyncExternalStore(cacheHydration.subscribe,@@ -57,18 +63,28 @@ const CacheHydrationGate = ({ children }: PropsWithChildren) => {useEffect(() => {if (released) return;- // Hard backstop: never stay blank past the timeout, whatever is pending.++ // 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 || 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 (!isAuthLoaded) return;- // Desktop paints against the final identity scope, not the anonymous one.- if (isDesktop && !isUserStateInit) return;if (!ready) return;setReleased(true);- }, [isAuthLoaded, isUserStateInit, ready, released, timedOut]);+ }, [isAuthLoaded, isSignedIn, userId, ready, released, timedOut]);useLayoutEffect(() => {if (!released) return;diff --git a/src/libs/swr/localStorageProvider.test.ts b/src/libs/swr/localStorageProvider.test.tsindex f95f7acc2e3..37f2afe30fb 100644--- a/src/libs/swr/localStorageProvider.test.ts+++ b/src/libs/swr/localStorageProvider.test.ts@@ -282,6 +282,97 @@ describe('createCacheProvider β tiering', () => {});});+/**+ * Regression: data fetched while the scope is provisional (anonymous, before+ * `userId` resolves on a slow cold boot) must not be persisted. Without the+ * `isEphemeralScope` quarantine, an `anon:personal` write lands in IndexedDB+ * and is orphaned the moment the real user scope resolves β surfacing as a+ * stale-loading cache miss on the next boot.+ */+describe('createCacheProvider β ephemeral (anonymous) scope quarantine', () => {+ const isAnon = (scope: string) => scope.startsWith('anon:');++ beforeEach(() => localStorage.clear());+ afterEach(async () => {+ vi.restoreAllMocks();+ await localDataCache.clearScope('anon:personal');+ await localDataCache.clearScope('u1:ws');+ });++ it('reproduces the leak: without quarantine, an anon-scope write persists and is orphaned on the scope flip', async () => {+ const scope = { value: 'anon:personal' };+ const { provider } = buildProvider(scope); // no isEphemeralScope β current prod behavior for web+ const map = provider();++ // A message fetched during the anonymous boot window.+ map.set('MSGS:t1', { items: ['hi'] });+ map.set('recents', { items: [1] });++ // It leaks into the anon partitions (this is the bug).+ await until(async () => (await localDataCache.entriesByScope('anon:personal')).length > 0);+ expect(await localDataCache.entriesByScope('anon:personal')).toHaveLength(1);+ await until(() => localStorage.getItem(getScopedCacheKey('anon:personal')) !== null);++ // userId resolves β scope flips to the real user; the fresh provider hydrates+ // the user partition and never sees the orphaned anon row.+ scope.value = 'u1:ws';+ const { provider: userProvider } = buildProvider(scope);+ const userMap = userProvider();+ await new Promise((r) => setTimeout(r, 40));+ expect(userMap.has('MSGS:t1')).toBe(false);+ // The orphaned row is stranded in the anon partition forever.+ expect(await localDataCache.entriesByScope('anon:personal')).toHaveLength(1);+ });++ it('fix: with isEphemeralScope, anon-scope writes stay memory-only (no idb, no localStorage)', async () => {+ const scope = { value: 'anon:personal' };+ const { provider } = buildProvider(scope, { isEphemeralScope: isAnon });+ const map = provider();++ map.set('MSGS:t1', { items: ['hi'] });+ map.set('recents', { items: [1] });++ // In-memory cache still serves the boot fetchβ¦+ expect(map.get('MSGS:t1')).toEqual({ items: ['hi'] });++ // β¦but nothing is persisted to either tier.+ await new Promise((r) => setTimeout(r, 40));+ expect(await localDataCache.entriesByScope('anon:personal')).toHaveLength(0);+ expect(localStorage.getItem(getScopedCacheKey('anon:personal'))).toBeNull();+ });++ it('fix: writes under the resolved (non-anon) scope still persist normally', async () => {+ const scope = { value: 'u1:ws' };+ const { provider } = buildProvider(scope, { isEphemeralScope: isAnon });+ const map = provider();++ map.set('MSGS:t1', { items: ['hi'] });+ map.set('recents', { items: [1] });++ await until(async () => (await localDataCache.entriesByScope('u1:ws')).length > 0);+ expect(await localDataCache.entriesByScope('u1:ws')).toHaveLength(1);+ await until(() => localStorage.getItem(getScopedCacheKey('u1:ws')) !== null);+ });++ it('fix: the flushAll (visibility/pagehide) path also respects the quarantine', async () => {+ const scope = { value: 'anon:personal' };+ const { provider } = buildProvider(scope, { isEphemeralScope: isAnon, debounceMs: 100000 });+ const map = provider();+ map.set('MSGS:t1', { items: ['hi'] });+ map.set('recents', { items: [1] });++ // Force the synchronous teardown flush that bypasses the debounce.+ document.dispatchEvent(new Event('visibilitychange'));+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'hidden' });+ document.dispatchEvent(new Event('visibilitychange'));+ window.dispatchEvent(new Event('pagehide'));++ await new Promise((r) => setTimeout(r, 40));+ expect(await localDataCache.entriesByScope('anon:personal')).toHaveLength(0);+ expect(localStorage.getItem(getScopedCacheKey('anon:personal'))).toBeNull();+ });+});+describe('cache-hydration span', () => {beforeEach(() => {localStorage.clear();diff --git a/src/libs/swr/localStorageProvider.ts b/src/libs/swr/localStorageProvider.tsindex 6679c5e19a7..2a0f8edc476 100644--- a/src/libs/swr/localStorageProvider.ts+++ b/src/libs/swr/localStorageProvider.ts@@ -26,6 +26,7 @@import { bootTiming } from '@/libs/bootTiming';import { buildLocalDataKey, localDataCache } from './localDataCache';+import { isAnonymousScope } from './useCacheScope';interface CacheEntry<T = unknown> {/** Cached data */@@ -45,6 +46,17 @@ export interface CacheProviderOptions {getScope?: () => string;/** SWR key patterns persisted to the IndexedDB tier. */idbPatterns?: string[];+ /**+ * Predicate marking a scope as *provisional* β writes made while it is active+ * must never be persisted. On desktop the identity round-trip can complete (or+ * the CacheHydrationGate timeout backstop can fire) before `userId` resolves,+ * briefly making the scope anonymous. Data fetched + flushed during that+ * window lands in the `anon` partition and is orphaned the instant the real+ * user scope resolves (`reloadScope`), surfacing as a stale-loading cache miss+ * on the next boot. Keeping the in-memory cache but skipping persistence for+ * these scopes closes that leak.+ */+ isEphemeralScope?: (scope: string) => boolean;/** SWR key patterns persisted to the localStorage tier. */localPatterns?: string[];/** Max localStorage-tier entries, defaults to 50. */@@ -115,6 +127,7 @@ export function createCacheProvider(options: CacheProviderOptions = {}): ScopedSdebounceMs = 2000,getScope = () => 'default',idbPatterns = [],+ isEphemeralScope,localPatterns = [],ttl = 7 * 24 * 60 * 60 * 1000, // 7 daysmaxLocalEntries = 50,@@ -145,6 +158,13 @@ export function createCacheProvider(options: CacheProviderOptions = {}): ScopedSreturn null;};+ /**+ * Whether the *current* scope may be written to persistence. Provisional+ * scopes (see `isEphemeralScope`) stay memory-only so their transient boot+ * data never leaks into a partition that gets orphaned on the next scope flip.+ */+ const isPersistableScope = (): boolean => !isEphemeralScope?.(getScope());+let cacheMapInstance: TieredCacheMap | null = null;let hydratedScope: string | null = null;let hydrationEpoch = 0;@@ -173,6 +193,7 @@ export function createCacheProvider(options: CacheProviderOptions = {}): ScopedSconst saveLocal = () => {if (!cacheMapInstance) return;+ if (!isPersistableScope()) return;const key = getScopedCacheKey(getScope());try {const entries = Array.from(cacheMapInstance.entries())@@ -216,6 +237,7 @@ export function createCacheProvider(options: CacheProviderOptions = {}): ScopedSconst flushIdb = () => {if (!cacheMapInstance) return;const scope = getScope();+ if (isEphemeralScope?.(scope)) return;const writes = [...dirtyIdb];const dels = [...deletedIdb];dirtyIdb.clear();@@ -272,6 +294,10 @@ export function createCacheProvider(options: CacheProviderOptions = {}): ScopedS// --- write routing -------------------------------------------------------const onSet = (key: string) => {+ // Provisional scope β memory only; never schedule a persist (see+ // `isEphemeralScope`). The post-flip global revalidation re-writes keys+ // under the resolved scope, so nothing is lost.+ if (!isPersistableScope()) return;const tier = tierOf(key);if (tier === 'local') debouncedSaveLocal();else if (tier === 'idb') {@@ -282,6 +308,7 @@ export function createCacheProvider(options: CacheProviderOptions = {}): ScopedS};const onDelete = (key: string) => {+ if (!isPersistableScope()) return;const tier = tierOf(key);if (tier === 'local') debouncedSaveLocal();else if (tier === 'idb') {@@ -483,6 +510,16 @@ 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,localPatterns: [...CACHE_TIERS.local],onScopeHydrated,// Governs the localStorage tier only (recents-style shells); the IndexedDBdiff --git a/src/libs/swr/useCacheScope.ts b/src/libs/swr/useCacheScope.tsindex fe4049ed8ee..f3f7c87a531 100644--- a/src/libs/swr/useCacheScope.ts+++ b/src/libs/swr/useCacheScope.ts@@ -24,6 +24,16 @@ export const buildCacheScope = (workspaceId: string | null | undefined,): string => `${userId || ANON}:${workspaceId || PERSONAL}`;+/**+ * 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}:`);+/*** React hook returning the current cache scope. Recomputes when the signed-in* user or the active workspace changes.