🤯 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: restore cached home identity and session recovery (#19219)
YuTengjinga8ef352bf50f
diff --git a/.agents/skills/data-fetching-architecture/SKILL.md b/.agents/skills/data-fetching-architecture/SKILL.mdindex 22c410ae535..81a16821456 100644--- a/.agents/skills/data-fetching-architecture/SKILL.md+++ b/.agents/skills/data-fetching-architecture/SKILL.md@@ -1,6 +1,6 @@---name: data-fetching-architecture-description: 'LobeHub data-fetching pipeline guide. Use for service layer, Zustand store, SWR, lambdaClient, useClientDataSWR, useFetchXxx hooks, or migrating useEffect fetches.'+description: 'LobeHub data-fetching pipeline guide. Use for service layer, Zustand store, SWR, lambdaClient, useClientDataSWR, useFetchXxx hooks, home first-paint flicker, persistent display caches, or migrating useEffect fetches.'user-invocable: false---@@ -54,6 +54,12 @@ user-invocable: false---+## Home First Paint and Persistent Caches++When changing home/sidebar first paint or persisted display data, read+[`references/home-first-paint.md`](./references/home-first-paint.md). It covers+avoiding flicker, reusing persistence, and the user `displaySnapshot.ts` boundary.+## Layer 1: Service Layer### Purpose@@ -652,6 +658,7 @@ See `store-data-structures` for details.- [ ] Detail pages: access `xxxDetailMap[id]`- [ ] Use loading states for UI feedback- [ ] Infinite-scroll failures persist as a visible tail Retry row, not a silent `catch`+- [ ] Changes affecting home first paint or persisted display data follow the guidance above**Mental model:** Types → Service → Reducer → Slice → Component 🎯diff --git a/.agents/skills/data-fetching-architecture/references/home-first-paint.md b/.agents/skills/data-fetching-architecture/references/home-first-paint.mdnew file mode 100644index 00000000000..3c56c3d8d91--- /dev/null+++ b/.agents/skills/data-fetching-architecture/references/home-first-paint.md@@ -0,0 +1,64 @@+# Home First Paint and Persistent Caches++Home and its sidebar must prioritize a stable first paint. Avoid showing a default+portrait, initials avatar, or hidden project section and then replacing it when user+data arrives. For repeat visits, consider persisting the data that determines those+elements: image URLs and selected configuration, not just the image bytes cached by+the browser.++## Choose the Existing Persistence Path++- Inspect the existing store, SWR key, persistence tier, and hydration consumer before+ adding storage. An in-memory SWR hit does not survive a full reload; a persisted+ entry does not help if the UI's Zustand state only receives network success events.+- Reuse `src/libs/swr/localStorageProvider.ts` and its `CACHE_TIERS` for suitable+ query results. Builtin agent identity/configuration and project lists use its+ asynchronous IndexedDB tier; the localStorage tier restores synchronously.+ Restore cached results into the state consumed by the UI, then revalidate through+ the existing SWR hook.+- For a small subset needed before a larger response arrives, reuse+ `LocalStorageQueryProjectionStorage` from `src/libs/queryProjectionStorage`.+ Keep field selection and lifecycle rules in the owning domain; do not create+ another storage framework or duplicate the same data across caches without a+ demonstrated need.+- Synchronous local restoration may run during pre-paint initialization, as in+ the `useLayoutEffect` hydration path in `src/store/project/store.ts`. This is not+ permission to fetch APIs in effects. IndexedDB hydration is asynchronous: account for its readiness instead+ of assuming persisted data is immediately available. With no usable cache, reserve+ stable space or show a bounded loading state until the relevant data resolves.+ Do not block the entire home on unrelated queries or add arbitrary delays.++## User Display Snapshot Reference++`src/store/user/displaySnapshot.ts` is the domain adapter for the user's avatar URL+and preference. It reuses `LocalStorageQueryProjectionStorage`; it is not a second+cache engine. `src/layout/AuthProvider/BetterAuth/UserUpdater.tsx` reads it after the+session identifies the exact user, before painting that user's initialized shell.+The authoritative user-state response still refreshes the values afterward.++- Keep the snapshot limited to validated display fields. Do not persist the whole+ `user:initState` response to fix flicker: it also contains entitlement and onboarding+ state. Cached preferences may shape presentation, but must not establish permission+ or authentication.+- Merge partial avatar/preference updates so updating one does not erase the other.+ On successful sign-out, clear that user's snapshot. Never restore a last-used+ user's private display data before confirming the current identity.+- Use this adapter for user display data; builtin agent artwork and project data+ belong to their existing domain caches. A new domain does not automatically need+ its own `displaySnapshot.ts`.++## Lifecycle and Verification++Reuse the SWR provider's existing user/workspace partitioning and identity trust+checks; do not implement another partition manager. Domain projections must supply+their explicit scope. Ensure in-memory keys and hydration consumers also respect+scope, since persistence partitioning alone cannot guard late callbacks.+Capture mutation scope and reject stale responses after a scope switch before they+update visible state or caches. Keep accepted writes reflected in the cache used on+the next reload, and preserve usable content during background refresh failures.++For changes affecting home first paint or persisted display data, select relevant+checks: a full reload with persisted data and delayed APIs, a missing/corrupt cache,+delayed asynchronous hydration, save-then-reload, sign-out, and account/workspace+switches. For visible transitions, inspect frames or video, not only the final+screenshot. Assert no default-to-custom flash, collapsing sections, cross-scope data, or indefinite loading on failure.diff --git a/locales/en-US/auth.json b/locales/en-US/auth.jsonindex f817d536331..69bbb57eaec 100644--- a/locales/en-US/auth.json+++ b/locales/en-US/auth.json@@ -294,6 +294,8 @@"profile.usernameRule": "Username can only contain letters, numbers, or underscores","profile.usernameTooLong": "Username cannot exceed 64 characters","profile.usernameUpdateFailed": "Failed to update username, please try again later",+ "session.checkFailed.description": "We could not verify your sign-in session. Please try again.",+ "session.checkFailed.title": "Unable to check your session","signin.subtitle": "Sign up or sign in to your {{appName}} account","signin.title": "Agent teammates that grow with you","signout": "Sign Out",diff --git a/locales/zh-CN/auth.json b/locales/zh-CN/auth.jsonindex 1d8d4c8bfa3..13dea0f023c 100644--- a/locales/zh-CN/auth.json+++ b/locales/zh-CN/auth.json@@ -294,6 +294,8 @@"profile.usernameRule": "仅支持字母、数字或下划线","profile.usernameTooLong": "用户名不能超过 64 个字符","profile.usernameUpdateFailed": "更新失败,请稍后重试",+ "session.checkFailed.description": "暂时无法确认你的登录状态,请重试。",+ "session.checkFailed.title": "登录状态检查失败","signin.subtitle": "登录或注册你的 {{appName}} 账号","signin.title": "同 Agent 团队一起无限进步","signout": "退出登录",diff --git a/packages/locales/src/default/auth.ts b/packages/locales/src/default/auth.tsindex 9a48acc3f7d..77efb3add53 100644--- a/packages/locales/src/default/auth.ts+++ b/packages/locales/src/default/auth.ts@@ -316,6 +316,8 @@ export default {'profile.usernameRule': 'Username can only contain letters, numbers, or underscores','profile.usernameTooLong': 'Username cannot exceed 64 characters','profile.usernameUpdateFailed': 'Failed to update username, please try again later',+ 'session.checkFailed.description': 'We could not verify your sign-in session. Please try again.',+ 'session.checkFailed.title': 'Unable to check your session','signin.subtitle': 'Sign up or sign in to your {{appName}} account','signin.title': 'Agent teammates that grow with you','signout': 'Sign Out',diff --git a/src/layout/AuthProvider/BetterAuth/UserUpdater.test.tsx b/src/layout/AuthProvider/BetterAuth/UserUpdater.test.tsxindex 8172cf88877..ab5d818bff8 100644--- a/src/layout/AuthProvider/BetterAuth/UserUpdater.test.tsx+++ b/src/layout/AuthProvider/BetterAuth/UserUpdater.test.tsx@@ -1,7 +1,9 @@-import { render } from '@testing-library/react';+import { act, fireEvent, render, screen } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { getAppPainted, setAppPainted } from '@/spa/atoms/app';import { useUserStore } from '@/store/user';+import { writeUserDisplaySnapshot } from '@/store/user/displaySnapshot';import UserUpdater from './UserUpdater';@@ -27,14 +29,254 @@ const sampleSession = (overrides?: Record<string, unknown>) => ({describe('UserUpdater', () => {beforeEach(() => {+ setAppPainted(true);+ localStorage.clear();useSessionMock.mockReset();useUserStore.setState({ user: undefined, isSignedIn: false, isLoaded: false });});afterEach(() => {+ localStorage.clear();+ vi.useRealTimers();useUserStore.setState({ user: undefined, isSignedIn: false, isLoaded: false });});+ it.each([400, 403, 404])(+ 'shows a recoverable error for terminal session status %s',+ async (status) => {+ vi.useFakeTimers();+ const refetch = vi.fn();+ useSessionMock.mockReturnValue({ data: null, error: { status }, isPending: false, refetch });+ const { unmount } = render(<UserUpdater />);+ expect(screen.getByRole('alert')).toBeTruthy();+ await act(async () => {+ await vi.advanceTimersByTimeAsync(60_000);+ });+ expect(refetch).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button'));+ expect(refetch).toHaveBeenCalledTimes(1);+ expect(useUserStore.getState().isSignedIn).toBe(false);+ unmount();+ },+ );++ it('stops automatic retries after three attempts and offers manual recovery', async () => {+ vi.useFakeTimers();+ const refetch = vi.fn().mockResolvedValue(undefined);+ useSessionMock.mockReturnValue({+ data: null,+ error: { status: 503 },+ isPending: false,+ refetch,+ });+ const { unmount } = render(<UserUpdater />);+ for (const delay of [1000, 2000, 4000]) {+ await act(async () => {+ await vi.advanceTimersByTimeAsync(delay);+ });+ }+ expect(refetch).toHaveBeenCalledTimes(3);+ expect(screen.getByRole('alert')).toBeTruthy();+ await act(async () => {+ await vi.advanceTimersByTimeAsync(60_000);+ });+ expect(refetch).toHaveBeenCalledTimes(3);+ fireEvent.click(screen.getByRole('button'));+ expect(refetch).toHaveBeenCalledTimes(4);+ unmount();+ });++ it('restores the authenticated user avatar and project preference before user-state returns', () => {+ writeUserDisplaySnapshot('u1', {+ avatar: '/cached-avatar.webp',+ preference: { lab: { enableProjects: true } },+ });+ useSessionMock.mockReturnValue(sampleSession());+ render(<UserUpdater />);++ expect(useUserStore.getState().user?.avatar).toBe('/cached-avatar.webp');+ expect(useUserStore.getState().preference.lab?.enableProjects).toBe(true);+ expect(useUserStore.getState().isSignedIn).toBe(true);+ });++ it('does not restore another user display snapshot or authenticate from a cache entry', () => {+ writeUserDisplaySnapshot('u1', {+ avatar: '/private-avatar.webp',+ preference: { lab: { enableProjects: true } },+ });+ useSessionMock.mockReturnValue({ data: null, error: null, isPending: true });+ const { unmount } = render(<UserUpdater />);+ expect(useUserStore.getState().isSignedIn).toBe(false);+ expect(useUserStore.getState().user).toBeUndefined();+ unmount();++ useSessionMock.mockReturnValue(sampleSession({ id: 'u2' }));+ render(<UserUpdater />);+ expect(useUserStore.getState().user?.avatar).toBe('');+ expect(useUserStore.getState().preference.lab?.enableProjects).not.toBe(true);+ });++ it('retries a transient cold-start session failure without confirming sign-out', async () => {+ vi.useFakeTimers();+ const refetch = vi.fn().mockResolvedValue(undefined);+ useSessionMock.mockReturnValue({+ data: null,+ error: { status: 503 },+ isPending: false,+ refetch,+ });+ const { unmount } = render(<UserUpdater />);++ expect(useUserStore.getState().isLoaded).toBe(false);+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1000);+ });+ expect(refetch).toHaveBeenCalledTimes(1);+ unmount();+ });++ it('preserves the verified user while a session refresh fails temporarily', () => {+ vi.useFakeTimers();+ useUserStore.setState({+ user: { id: 'u1', avatar: '/custom.webp' },+ isSignedIn: true,+ isLoaded: true,+ });+ useSessionMock.mockReturnValue({+ data: null,+ error: { status: 503 },+ isPending: false,+ refetch: vi.fn(),+ });+ const { unmount } = render(<UserUpdater />);++ expect(useUserStore.getState().isSignedIn).toBe(true);+ expect(useUserStore.getState().user?.avatar).toBe('/custom.webp');+ unmount();+ });++ it('keeps the rendered application usable when background session retries are exhausted', async () => {+ vi.useFakeTimers();+ const refetch = vi.fn().mockResolvedValue(undefined);+ useUserStore.setState({ user: { id: 'u1' }, isSignedIn: true, isLoaded: true });+ useSessionMock.mockReturnValue({+ data: null,+ error: { status: 503 },+ isPending: false,+ refetch,+ });+ const { unmount } = render(+ <UserUpdater>+ <span>Application</span>+ </UserUpdater>,+ );++ for (const delay of [1000, 2000, 4000]) {+ await act(async () => {+ await vi.advanceTimersByTimeAsync(delay);+ });+ }++ expect(refetch).toHaveBeenCalledTimes(3);+ expect(screen.queryByRole('alert')).toBeNull();+ expect(screen.getByText('Application').closest('[inert]')).toBeNull();+ unmount();+ });++ it('restores the application after a manual retry succeeds', () => {+ useSessionMock.mockReturnValue({+ data: null,+ error: { status: 403 },+ isPending: false,+ refetch: vi.fn(),+ });+ const { rerender, unmount } = render(+ <UserUpdater>+ <span>Application</span>+ </UserUpdater>,+ );+ expect(screen.getByText('Application').closest('[inert]')).toBeTruthy();+ fireEvent.click(screen.getByRole('button'));+ useSessionMock.mockReturnValue(sampleSession());+ rerender(+ <UserUpdater>+ <span>Application</span>+ </UserUpdater>,+ );+ expect(screen.queryByRole('alert')).toBeNull();+ expect(screen.getByText('Application')).toBeTruthy();+ expect(useUserStore.getState().isSignedIn).toBe(true);+ unmount();+ });++ it('reveals recovery without falsely declaring the underlying application painted', () => {+ setAppPainted(false);+ const overlay = document.createElement('div');+ overlay.id = 'loading-screen';+ document.body.append(overlay);+ useSessionMock.mockReturnValue({+ data: null,+ error: { status: 403 },+ isPending: false,+ refetch: vi.fn(),+ });+ const { unmount } = render(<UserUpdater />);+ expect(document.getElementById('loading-screen')).toBeNull();+ expect(getAppPainted()).toBe(false);+ expect(screen.getByRole('button')).toBeTruthy();+ unmount();+ setAppPainted(false);+ });++ it.each(['authenticated', 'unauthorized'])(+ 'keeps recovery visible after an %s retry until the underlying application paints',+ (outcome) => {+ setAppPainted(false);+ useSessionMock.mockReturnValue({+ data: null,+ error: { status: 403 },+ isPending: false,+ refetch: vi.fn(),+ });+ const { rerender, unmount } = render(+ <UserUpdater>+ <span>Application</span>+ </UserUpdater>,+ );+ fireEvent.click(screen.getByRole('button'));+ useSessionMock.mockReturnValue(+ outcome === 'authenticated'+ ? sampleSession()+ : { data: null, error: { status: 401 }, isPending: false, refetch: vi.fn() },+ );+ rerender(+ <UserUpdater>+ <span>Application</span>+ </UserUpdater>,+ );+ expect(screen.getByRole('alert')).toBeTruthy();+ expect(screen.getByText('Application').closest('[inert]')).toBeTruthy();+ act(() => setAppPainted(true));+ expect(screen.queryByRole('alert')).toBeNull();+ expect(screen.getByText('Application').closest('[inert]')).toBeNull();+ unmount();+ },+ );++ it('does not clear a verified user while a retry is in flight without session data', () => {+ useUserStore.setState({ user: { id: 'u1' }, isSignedIn: true, isLoaded: true });+ useSessionMock.mockReturnValue({+ data: null,+ error: null,+ isPending: false,+ isRefetching: true,+ });+ const { unmount } = render(<UserUpdater />);+ expect(useUserStore.getState().user?.id).toBe('u1');+ expect(useUserStore.getState().isSignedIn).toBe(true);+ unmount();+ });+it('preserves user fields populated by useInitUserState (e.g. interests) when better-auth re-emits the session on tab focus', () => {// Simulate the post-init state: useInitUserState has loaded interests etc.useUserStore.setState({@@ -110,5 +352,28 @@ describe('UserUpdater', () => {render(<UserUpdater />);expect(useUserStore.getState().user).toBeUndefined();+ expect(useUserStore.getState().isSignedIn).toBe(false);+ expect(useUserStore.getState().isLoaded).toBe(true);+ });++ it('clears a rejected session without retrying an unauthorized response', async () => {+ vi.useFakeTimers();+ const refetch = vi.fn();+ useUserStore.setState({ user: { id: 'u1' }, isSignedIn: true, isLoaded: true });+ useSessionMock.mockReturnValue({+ data: null,+ error: { status: 401 },+ isPending: false,+ refetch,+ });+ const { unmount } = render(<UserUpdater />);++ expect(useUserStore.getState().user).toBeUndefined();+ expect(useUserStore.getState().isSignedIn).toBe(false);+ await act(async () => {+ await vi.advanceTimersByTimeAsync(30_000);+ });+ expect(refetch).not.toHaveBeenCalled();+ unmount();});});diff --git a/src/layout/AuthProvider/BetterAuth/UserUpdater.tsx b/src/layout/AuthProvider/BetterAuth/UserUpdater.tsxindex c02d33b4d78..63cda52ad6c 100644--- a/src/layout/AuthProvider/BetterAuth/UserUpdater.tsx+++ b/src/layout/AuthProvider/BetterAuth/UserUpdater.tsx@@ -1,26 +1,67 @@'use client';-import { memo, useEffect } from 'react';-import { createStoreUpdater } from 'zustand-utils';+import { Flexbox } from '@lobehub/ui';+import { Alert, Button } from '@lobehub/ui/base-ui';+import { cssVar } from 'antd-style';+import { memo, type PropsWithChildren, useEffect, useLayoutEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { DEFAULT_PREFERENCE } from '@/const/user';import { useSession } from '@/libs/better-auth/auth-client';+import { useAppPainted } from '@/spa/atoms/app';+import { removeStaticLoadingScreen } from '@/spa/loadingScreen';import { useUserStore } from '@/store/user';+import { readUserDisplaySnapshot } from '@/store/user/displaySnapshot';import { type LobeUser } from '@/types/user';/*** Sync Better-Auth session state to Zustand store*/-const UserUpdater = memo(() => {- const { data: session, isPending, error } = useSession();+const UserUpdater = memo(({ children }: PropsWithChildren) => {+ const { data: session, isPending, isRefetching, error, refetch } = useSession();+ const { t } = useTranslation(['auth', 'common']);+ const [retryAttempt, setRetryAttempt] = useState(0);+ const [recoveryVisible, setRecoveryVisible] = useState(false);+ const appPainted = useAppPainted();+ /** Background session failures must not block an identity that already resolved. */+ const isInitialIdentityUnresolved = !useUserStore((state) => state.isLoaded);+ const status = error?.status;+ const retryable = !!error && (!status || status >= 500 || status === 408 || status === 429);+ const failed =+ isInitialIdentityUnresolved && !!error && status !== 401 && (!retryable || retryAttempt >= 3);+ /** A confirmed sign-out still needs a painted destination after recovery removed the splash. */+ const showRecovery =+ failed ||+ (recoveryVisible && ((!!error && status !== 401) || isPending || isRefetching || !appPainted));- const isLoaded = !isPending;- const isSignedIn = !!session?.user && !error;+ useLayoutEffect(() => {+ if (showRecovery) {+ setRecoveryVisible(true);+ /** Reveal recovery without claiming the application underneath has painted. */+ removeStaticLoadingScreen();+ } else {+ setRecoveryVisible(false);+ }+ }, [showRecovery]);const betterAuthUser = session?.user;- const useStoreUpdater = createStoreUpdater(useUserStore);- useStoreUpdater('isLoaded', isLoaded);- useStoreUpdater('isSignedIn', isSignedIn);+ /** A failed session check is not evidence of sign-out. Retry transient failures. */+ useEffect(() => {+ if (isPending || isRefetching) return;+ if (!error) {+ setRetryAttempt(0);+ return;+ }+ if (!retryable || retryAttempt >= 3) return;++ const delay = 1000 * 2 ** retryAttempt;+ const timer = setTimeout(() => {+ setRetryAttempt((attempt) => attempt + 1);+ void refetch();+ }, delay);+ return () => clearTimeout(timer);+ }, [error, isPending, isRefetching, refetch, retryable, retryAttempt]);// Sync user data from Better-Auth session to Zustand store.// Better-Auth refetches the session on tab focus (visibilitychange), which@@ -37,15 +78,22 @@ const UserUpdater = memo(() => {// drop the previous user's profile fields so they don't leak across// accounts. `useInitUserState` is `useOnlyFetchOnceSWR` with a constant// key, so it won't re-fetch profile data for the new user on its own.- useEffect(() => {- if (betterAuthUser) {+ useLayoutEffect(() => {+ if (isPending || isRefetching || (error && error.status !== 401)) return;++ if (betterAuthUser && !error) {useUserStore.setState((state) => {const baseUser = state.user?.id === betterAuthUser.id ? state.user : undefined;+ /** Restore display-only data after the session has identified its owner. */+ const snapshot = baseUser ? undefined : readUserDisplaySnapshot(betterAuthUser.id);return {+ isLoaded: true,+ isSignedIn: true,+ preference: baseUser ? state.preference : (snapshot?.preference ?? DEFAULT_PREFERENCE),user: {...baseUser,// Preserve avatar from settings, don't override with auth provider value- avatar: baseUser?.avatar || '',+ avatar: baseUser?.avatar ?? snapshot?.avatar ?? '',email: betterAuthUser.email,fullName: betterAuthUser.name,id: betterAuthUser.id,@@ -57,10 +105,52 @@ const UserUpdater = memo(() => {}// Clear user data when session becomes unavailable- useUserStore.setState({ user: undefined });- }, [betterAuthUser]);+ useUserStore.setState({+ isLoaded: true,+ isSignedIn: false,+ preference: DEFAULT_PREFERENCE,+ user: undefined,+ });+ }, [betterAuthUser, error, isPending, isRefetching]);- return null;+ /** Keep auth unresolved on transport failures; show recovery instead of a guest page. */+ return (+ <>+ <div inert={showRecovery} style={{ display: 'contents' }}>+ {children}+ </div>+ {showRecovery && (+ <Flexbox+ align="center"+ gap={16}+ justify="center"+ style={{+ background: cssVar.colorBgLayout,+ inset: 0,+ padding: 24,+ position: 'fixed',+ zIndex: 100000,+ }}+ >+ <Alert+ showIcon+ description={t('auth:session.checkFailed.description')}+ title={t('auth:session.checkFailed.title')}+ type="error"+ />+ <Button+ loading={isPending || isRefetching || (!failed && recoveryVisible)}+ onClick={() => {+ setRetryAttempt(0);+ void refetch();+ }}+ >+ {t('common:retry')}+ </Button>+ </Flexbox>+ )}+ </>+ );});export default UserUpdater;diff --git a/src/layout/AuthProvider/BetterAuth/index.tsx b/src/layout/AuthProvider/BetterAuth/index.tsxindex 483dddf30dd..15a03b7354c 100644--- a/src/layout/AuthProvider/BetterAuth/index.tsx+++ b/src/layout/AuthProvider/BetterAuth/index.tsx@@ -3,12 +3,7 @@ import { type PropsWithChildren } from 'react';import UserUpdater from './UserUpdater';const BetterAuth = ({ children }: PropsWithChildren) => {- return (- <>- {children}- <UserUpdater />- </>- );+ return <UserUpdater>{children}</UserUpdater>;};export default BetterAuth;diff --git a/src/layout/GlobalProvider/StoreInitialization.tsx b/src/layout/GlobalProvider/StoreInitialization.tsxindex b67f50c5082..35321bdcaab 100644--- a/src/layout/GlobalProvider/StoreInitialization.tsx+++ b/src/layout/GlobalProvider/StoreInitialization.tsx@@ -18,6 +18,14 @@ import { useUserStateRedirect } from './useUserStateRedirect';const DeferredStoreInitialization = lazy(() => import('./DeferredStoreInitialization'));+/** Subscribe only after the durable cache is hydrated by CacheHydrationGate. */+export const BuiltinAgentInitialization = () => {+ const isLogin = useUserStore(authSelectors.isLogin);+ const useInitBuiltinAgent = useAgentStore((s) => s.useInitBuiltinAgent);+ useInitBuiltinAgent(INBOX_SESSION_ID, { isLogin: Boolean(isLogin) });+ return null;+};+const StoreInitialization = memo(() => {// prefetch error ns to avoid don't show error content correctlyuseTranslation('error');@@ -34,8 +42,6 @@ const StoreInitialization = memo(() => {s.useCheckServerVersion,]);- const useInitBuiltinAgent = useAgentStore((s) => s.useInitBuiltinAgent);-// init the system preferenceuseInitSystemStatus();@@ -61,9 +67,6 @@ const StoreInitialization = memo(() => {*/const isLoginOnInit = Boolean(isLogin);- // init inbox agent via builtin agent mechanism- useInitBuiltinAgent(INBOX_SESSION_ID, { isLogin: isLoginOnInit });-const onUserStateSuccess = useUserStateRedirect();// init user statediff --git a/src/layout/SPAGlobalProvider/index.test.tsx b/src/layout/SPAGlobalProvider/index.test.tsxindex 5d7045c74f6..5d6831da1a9 100644--- a/src/layout/SPAGlobalProvider/index.test.tsx+++ b/src/layout/SPAGlobalProvider/index.test.tsx@@ -13,11 +13,14 @@ import { type DevDockLayout as DevDockLayoutComponent } from './index';let SPAGlobalProvider: typeof SPAGlobalProviderComponent;let DevDockLayout: typeof DevDockLayoutComponent;-const { cacheGateReleased, canAccessDevDock, devDockRenderError } = vi.hoisted(() => ({- cacheGateReleased: { current: true },- canAccessDevDock: vi.fn(() => false),- devDockRenderError: { current: null as Error | null },-}));+const { cacheGateReleased, canAccessDevDock, devDockRenderError, initializeBuiltin } = vi.hoisted(+ () => ({+ cacheGateReleased: { current: true },+ canAccessDevDock: vi.fn(() => false),+ devDockRenderError: { current: null as Error | null },+ initializeBuiltin: vi.fn(() => null),+ }),+);vi.mock('@lobehub/ui', async (importOriginal) => {const React = await import('react');@@ -145,6 +148,7 @@ vi.mock('@/layout/GlobalProvider/ServerVersionOutdatedAlert', () => ({}));vi.mock('@/layout/GlobalProvider/StoreInitialization', () => ({+ BuiltinAgentInitialization: initializeBuiltin,default: () => null,}));@@ -179,6 +183,7 @@ describe('SPAGlobalProvider', () => {}, 30_000);beforeEach(() => {+ initializeBuiltin.mockClear();cacheGateReleased.current = true;canAccessDevDock.mockReturnValue(false);devDockRenderError.current = null;@@ -187,6 +192,25 @@ describe('SPAGlobalProvider', () => {setPostRenderReady(false);});+ it('defers builtin subscriptions until persistent cache hydration has completed', () => {+ cacheGateReleased.current = false;+ const { unmount } = render(+ <SPAGlobalProvider>+ <div />+ </SPAGlobalProvider>,+ );+ expect(initializeBuiltin).not.toHaveBeenCalled();+ unmount();++ cacheGateReleased.current = true;+ render(+ <SPAGlobalProvider>+ <div />+ </SPAGlobalProvider>,+ );+ expect(initializeBuiltin).toHaveBeenCalled();+ });+afterEach(() => {vi.unstubAllEnvs();});diff --git a/src/layout/SPAGlobalProvider/index.tsx b/src/layout/SPAGlobalProvider/index.tsxindex f21f2e8b061..7b4a5b2c202 100644--- a/src/layout/SPAGlobalProvider/index.tsx+++ b/src/layout/SPAGlobalProvider/index.tsx@@ -18,7 +18,9 @@ import { FaviconProvider } from '@/layout/GlobalProvider/FaviconProvider';import { GroupWizardProvider } from '@/layout/GlobalProvider/GroupWizardProvider';import QueryProvider from '@/layout/GlobalProvider/Query';import ServerVersionOutdatedAlert from '@/layout/GlobalProvider/ServerVersionOutdatedAlert';-import StoreInitialization from '@/layout/GlobalProvider/StoreInitialization';+import StoreInitialization, {+ BuiltinAgentInitialization,+} from '@/layout/GlobalProvider/StoreInitialization';import { registerNativeContextMenuInterceptor } from '@/libs/contextMenu';import { usePostRenderReady } from '@/spa/atoms/app';import { ServerConfigStoreProvider } from '@/store/serverConfig/Provider';@@ -99,6 +101,7 @@ const SPAGlobalProvider = memo<PropsWithChildren>(({ children }) => {<StyleProvider speedy={import.meta.env.PROD}><LobeAnalyticsProviderWrapper><CacheHydrationGate>+ <BuiltinAgentInitialization /><DevDockLayout>{children}</DevDockLayout></CacheHydrationGate></LobeAnalyticsProviderWrapper>diff --git a/src/libs/queryProjectionStorage/localStorage.test.ts b/src/libs/queryProjectionStorage/localStorage.test.tsindex d8797e55352..d1d48142653 100644--- a/src/libs/queryProjectionStorage/localStorage.test.ts+++ b/src/libs/queryProjectionStorage/localStorage.test.ts@@ -7,6 +7,16 @@ afterEach(() => {});describe('LocalStorageQueryProjectionStorage', () => {+ it('restores a scoped projection synchronously before the next paint', () => {+ const storage = new LocalStorageQueryProjectionStorage<string[]>({ namespace: 'test' });+ const key = { queryKey: 'display', scope: 'user-a' };++ void storage.set(key, { data: ['cached'], updatedAt: 1 });++ expect(storage.getSync(key)).toEqual({ data: ['cached'], updatedAt: 1 });+ expect(storage.getSync({ ...key, scope: 'user-b' })).toBeUndefined();+ });+it('reads and writes one scoped query through the async interface', async () => {const storage = new LocalStorageQueryProjectionStorage<string[]>({ namespace: 'test' });const key = { queryKey: 'limit:10', scope: 'user:workspace' };diff --git a/src/libs/queryProjectionStorage/localStorage.ts b/src/libs/queryProjectionStorage/localStorage.tsindex be268b83522..a08dac1659a 100644--- a/src/libs/queryProjectionStorage/localStorage.ts+++ b/src/libs/queryProjectionStorage/localStorage.ts@@ -27,7 +27,11 @@ export class LocalStorageQueryProjectionStorage<T> implements QueryProjectionSto#key = ({ queryKey, scope }: QueryProjectionKey) =>`${this.#namespace}:${encodeURIComponent(scope)}:${encodeURIComponent(queryKey)}`;- get = async (key: QueryProjectionKey): Promise<QueryProjection<T> | undefined> => {+ get = async (key: QueryProjectionKey): Promise<QueryProjection<T> | undefined> =>+ this.getSync(key);++ /** Restore a local projection inside pre-paint initialization without yielding a frame. */+ getSync = (key: QueryProjectionKey): QueryProjection<T> | undefined => {if (typeof window === 'undefined') return undefined;try {diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex f7e18d56def..1ba0f874f98 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -1386,7 +1386,11 @@ export const userKeys = {initState: def('user:initState', () => ['user:initState']),};export const builtinAgentKeys = {- init: def('builtinAgent:init', (slug: string) => ['builtinAgent:init', slug]),+ init: def('builtinAgent:init', (slug: string, scope: string) => [+ 'builtinAgent:init',+ slug,+ scope,+ ]),};export const imessageKeys = {bridgeStatus: def('imessage:bridgeStatus', () => ['imessage:bridgeStatus']),diff --git a/src/libs/swr/localStorageProvider.test.ts b/src/libs/swr/localStorageProvider.test.tsindex db026aad47a..3d06e30388e 100644--- a/src/libs/swr/localStorageProvider.test.ts+++ b/src/libs/swr/localStorageProvider.test.ts@@ -5,7 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { bootTiming } from '@/libs/bootTiming';-import { taskTemplateKeys } from './keys';+import { builtinAgentKeys, taskTemplateKeys } from './keys';import { buildLocalDataKey, localDataCache } from './localDataCache';import {CACHE_TIERS,@@ -60,6 +60,25 @@ describe('createCacheProvider — tiering', () => {expect(getScopedCacheKey('anon:personal')).not.toBe(getScopedCacheKey('u1:personal'));});+ it('restores the builtin agent configuration from durable storage after a reload', async () => {+ const scope = { value: 's1' };+ const options = { idbPatterns: [...CACHE_TIERS.idb], localPatterns: [...CACHE_TIERS.local] };+ const { provider } = buildProvider(scope, options);+ await provider.hydrateScope?.();+ const key = JSON.stringify(builtinAgentKeys.init('inbox', 's1'));+ const data = { data: { id: 'inbox-1', profile: { fullBodyArtwork: '/custom.webp' } } };+ provider().set(key, data);+ await until(async () => (await localDataCache.entriesByScope('s1')).length > 0);++ const { provider: restored } = buildProvider(scope, options);+ await restored.hydrateScope?.();+ expect(restored().get(key)).toEqual(data);++ const { provider: otherUser } = buildProvider({ value: 's2' }, options);+ await otherUser.hydrateScope?.();+ expect(otherUser().get(key)).toBeUndefined();+ });+it('routes local-tier keys to scoped localStorage only', async () => {const scope = { value: 's1' };const { provider } = buildProvider(scope);diff --git a/src/libs/swr/localStorageProvider.ts b/src/libs/swr/localStorageProvider.tsindex d849788e037..4cf77d08a5a 100644--- a/src/libs/swr/localStorageProvider.ts+++ b/src/libs/swr/localStorageProvider.ts@@ -483,6 +483,8 @@ export const CACHE_TIERS = {'message:', // chat messages (conversation + legacy stores)'topic:', // topic lists / agent view / search'agent:', // sidebar agent list + agent documents+ 'builtinAgent:', // builtin identity and configuration used by the first paint+ 'project/list', // project sidebar lists restored before their background refresh'group:detail', // group detail (group list stays in localStorage)'task:', // task lists + detail'document:', // editor document contentdiff --git a/src/store/agent/slices/agent/action.test.ts b/src/store/agent/slices/agent/action.test.tsindex c0d8af99177..68f831d18cd 100644--- a/src/store/agent/slices/agent/action.test.ts+++ b/src/store/agent/slices/agent/action.test.ts@@ -1,11 +1,14 @@import { CHAT_GROUP_SESSION_ID_PREFIX } from '@lobechat/types';import { toast } from '@lobehub/ui/base-ui';import { act, renderHook, waitFor } from '@testing-library/react';+import { createElement, type PropsWithChildren } from 'react';+import { SWRConfig, unstable_serialize } from 'swr';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import * as activeWorkspaceModule from '@/business/client/hooks/useActiveWorkspaceId';import { setScopedMutate } from '@/libs/swr';-import { agentConfigKeys } from '@/libs/swr/keys';+import { agentConfigKeys, builtinAgentKeys } from '@/libs/swr/keys';+import * as cacheScopeModule from '@/libs/swr/useCacheScope';import { agentService } from '@/services/agent';import { agentDocumentService } from '@/services/agentDocument';import { useGlobalStore } from '@/store/global';@@ -21,6 +24,7 @@ vi.mock('@/services/agent', () => ({agentService: {createAgent: vi.fn(),getAgentConfigById: vi.fn(),+ getBuiltinAgent: vi.fn(),getSessionConfig: vi.fn(),queryAgents: vi.fn(),updateAgentConfig: vi.fn(),@@ -64,6 +68,9 @@ vi.mock('swr', async (importOriginal) => {beforeEach(() => {vi.clearAllMocks();+ vi.spyOn(cacheScopeModule, 'useCacheScope').mockImplementation(() =>+ cacheScopeModule.getCacheScope(),+ );setScopedMutate(vi.fn() as any);useAgentStore.setState({activeAgentId: undefined,@@ -85,6 +92,188 @@ afterEach(() => {});describe('AgentSlice Actions', () => {+ describe('builtin agent cache hydration', () => {+ it('does not apply an old user response after switching personal accounts', async () => {+ let scope = 'user-a:personal';+ vi.spyOn(cacheScopeModule, 'getCacheScope').mockImplementation(() => scope);+ let resolveOld!: (value: Awaited<ReturnType<typeof agentService.getBuiltinAgent>>) => void;+ vi.mocked(agentService.getBuiltinAgent).mockImplementation(+ () =>+ new Promise((resolve) => {+ if (scope === 'user-a:personal') resolveOld = resolve;+ }),+ );+ const cachedUserB = { id: 'inbox-b', name: 'Chief B' };+ const cache = new Map([+ [+ unstable_serialize(builtinAgentKeys.init('inbox', 'user-b:personal')),+ { data: cachedUserB },+ ],+ ]);+ const wrapper = ({ children }: PropsWithChildren) =>+ createElement(SWRConfig, { value: { provider: () => cache } }, children);+ const hook = renderHook(+ () => useAgentStore.getState().useInitBuiltinAgent('inbox', { isLogin: true }),+ { wrapper },+ );+ await waitFor(() => expect(resolveOld).toBeDefined());+ scope = 'user-b:personal';+ hook.rerender();+ expect(useAgentStore.getState().builtinAgentIdMap.inbox).toBe('inbox-b');++ await act(async () => {+ resolveOld({ id: 'inbox-a', name: 'Chief A' } as Awaited<+ ReturnType<typeof agentService.getBuiltinAgent>+ >);+ });+ expect(useAgentStore.getState().builtinAgentIdMap.inbox).toBe('inbox-b');+ expect(useAgentStore.getState().agentMap['inbox-a']).toBeUndefined();+ hook.unmount();+ });++ it('seeds the startup snapshot without refetching after changing the builtin agent name', async () => {+ const scopedMutate = vi.fn().mockResolvedValue(undefined);+ setScopedMutate(scopedMutate);+ useAgentStore.setState({ builtinAgentIdMap: { inbox: 'inbox-1' } });+ const updatedAgent = {+ id: 'inbox-1',+ name: 'Renamed chief',+ profile: { fullBodyArtwork: '/custom-chief.webp' },+ } as LobeAgentConfig;+ vi.mocked(agentService.updateAgentMeta).mockResolvedValue({+ agent: updatedAgent,+ success: true,+ });++ await useAgentStore+ .getState()+ .optimisticUpdateAgentMeta('inbox-1', { name: 'Renamed chief' });++ expect(agentService.getBuiltinAgent).not.toHaveBeenCalled();+ expect(scopedMutate).toHaveBeenCalledWith(agentConfigKeys.config('inbox-1'), updatedAgent, {+ revalidate: false,+ });+ expect(scopedMutate).toHaveBeenCalledWith(+ builtinAgentKeys.init('inbox', cacheScopeModule.getCacheScope()),+ updatedAgent,+ { revalidate: false },+ );+ });++ it('does not seed a metadata response into a changed cache scope', async () => {+ let scope = 'user-a:personal';+ vi.spyOn(cacheScopeModule, 'getCacheScope').mockImplementation(() => scope);+ const scopedMutate = vi.fn().mockResolvedValue(undefined);+ setScopedMutate(scopedMutate);+ useAgentStore.setState({ builtinAgentIdMap: { inbox: 'inbox-1' } });++ let resolveUpdate!: (value: any) => void;+ vi.mocked(agentService.updateAgentMeta).mockImplementation(+ () =>+ new Promise((resolve) => {+ resolveUpdate = resolve;+ }),+ );++ let save!: Promise<void>;+ act(() => {+ save = useAgentStore+ .getState()+ .optimisticUpdateAgentMeta('inbox-1', { name: 'Renamed chief' });+ });+ await waitFor(() => expect(resolveUpdate).toBeDefined());++ scope = 'user-b:personal';+ useAgentStore.setState({ agentMap: {}, builtinAgentIdMap: {} });+ await act(async () => {+ resolveUpdate({+ agent: { id: 'inbox-1', name: 'Renamed chief' } as LobeAgentConfig,+ success: true,+ });+ await save;+ });++ expect(useAgentStore.getState().agentMap['inbox-1']).toBeUndefined();+ expect(+ scopedMutate.mock.calls.some(+ ([key]) =>+ JSON.stringify(key) === JSON.stringify(agentConfigKeys.config('inbox-1')) ||+ JSON.stringify(key) ===+ JSON.stringify(builtinAgentKeys.init('inbox', 'user-b:personal')),+ ),+ ).toBe(false);+ });++ it('keeps the network refresh for an explicit builtin config refresh', async () => {+ const scopedMutate = vi.fn().mockResolvedValue(undefined);+ setScopedMutate(scopedMutate);+ useAgentStore.setState({ builtinAgentIdMap: { inbox: 'inbox-1' } });+ vi.mocked(agentService.getBuiltinAgent).mockResolvedValue({+ id: 'inbox-1',+ } as Awaited<ReturnType<typeof agentService.getBuiltinAgent>>);++ await act(async () => {+ await useAgentStore.getState().internal_refreshAgentConfig('inbox-1');+ });++ expect(agentService.getBuiltinAgent).toHaveBeenCalledWith('inbox');+ });++ it('restores the inbox identity and custom artwork while revalidation is pending', () => {+ const data = {+ id: 'cached-inbox',+ name: 'Custom chief',+ profile: { fullBodyArtwork: 'https://example.com/custom-chief.webp' },+ };+ vi.mocked(agentService.getBuiltinAgent).mockImplementation(() => new Promise(() => {}));+ const cache = new Map([+ [+ unstable_serialize(builtinAgentKeys.init('inbox', cacheScopeModule.getCacheScope())),+ { data },+ ],+ ]);+ const wrapper = ({ children }: PropsWithChildren) =>+ createElement(SWRConfig, { value: { provider: () => cache } }, children);++ const hook = renderHook(+ () => useAgentStore.getState().useInitBuiltinAgent('inbox', { isLogin: true }),+ { wrapper },+ );++ expect(useAgentStore.getState().builtinAgentIdMap.inbox).toBe('cached-inbox');+ expect(useAgentStore.getState().agentMap['cached-inbox']).toMatchObject(data);+ hook.unmount();+ });++ it('reads the workspace inbox cache instead of the personal inbox cache', () => {+ vi.spyOn(activeWorkspaceModule, 'useActiveWorkspaceId').mockReturnValue('workspace-1');+ vi.mocked(agentService.getBuiltinAgent).mockImplementation(() => new Promise(() => {}));+ const cache = new Map([+ [+ unstable_serialize(builtinAgentKeys.init('inbox', cacheScopeModule.getCacheScope())),+ { data: { id: 'personal-inbox' } },+ ],+ [+ unstable_serialize([+ ...builtinAgentKeys.init('inbox', cacheScopeModule.getCacheScope()),+ 'workspace-1',+ ]),+ { data: { id: 'workspace-inbox' } },+ ],+ ]);+ const wrapper = ({ children }: PropsWithChildren) =>+ createElement(SWRConfig, { value: { provider: () => cache } }, children);+ const hook = renderHook(+ () => useAgentStore.getState().useInitBuiltinAgent('inbox', { isLogin: true }),+ { wrapper },+ );++ expect(useAgentStore.getState().builtinAgentIdMap.inbox).toBe('workspace-inbox');+ expect(useAgentStore.getState().agentMap['personal-inbox']).toBeUndefined();+ hook.unmount();+ });+ });+describe('system role streaming', () => {it('accepts chunks and lets only the stream owner clear the visual buffer', async () => {const { result } = renderHook(() => useAgentStore());diff --git a/src/store/agent/slices/agent/action.ts b/src/store/agent/slices/agent/action.tsindex 0d576aca6a7..6c85fcf589c 100644--- a/src/store/agent/slices/agent/action.ts+++ b/src/store/agent/slices/agent/action.ts@@ -17,7 +17,8 @@ import type { PartialDeep } from 'type-fest';import { getActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import { MESSAGE_CANCEL_FLAT } from '@/const/message';import { mutate, useClientDataSWR, useClientDataSWRWithSync } from '@/libs/swr';-import { agentConfigKeys } from '@/libs/swr/keys';+import { agentConfigKeys, builtinAgentKeys } from '@/libs/swr/keys';+import { getCacheScope } from '@/libs/swr/useCacheScope';import type { AvailableAgentItem, CreateAgentParams, CreateAgentResult } from '@/services/agent';import { agentService, AVAILABLE_AGENTS_CONTEXT_QUERY_LIMIT } from '@/services/agent';import {@@ -726,6 +727,7 @@ export class AgentSliceActionImpl {signal?: AbortSignal,): Promise<void> => {const { internal_dispatchAgentMap, updateSaveStatus } = this.#get();+ const scope = getCacheScope();// 1. Optimistic update - meta fields are at the top level of agent configinternal_dispatchAgentMap(id, meta as PartialDeep<LobeAgentConfig>);@@ -734,10 +736,12 @@ export class AgentSliceActionImpl {try {// 2. API call returns updated agent dataconst result = await agentService.updateAgentMeta(id, meta, signal);+ if (scope !== getCacheScope()) return;- // 3. Use returned data directly (no refetch needed!)+ // 3. Apply returned data, then seed related caches for later subscribers.if (result?.success && result.agent) {internal_dispatchAgentMap(id, result.agent);+ await this.#get().internal_refreshAgentConfig(id, result.agent);this.#get().invalidateAvailableAgents();}updateSaveStatus('saved');@@ -751,8 +755,33 @@ export class AgentSliceActionImpl {}};- internal_refreshAgentConfig = async (id: string): Promise<void> => {- await mutate(agentConfigKeys.config(id));+ internal_refreshAgentConfig = async (+ id: string,+ updatedAgent?: LobeAgentConfig,+ ): Promise<void> => {+ /** Keep related agent and builtin-agent snapshots current after a successful edit. */+ const slugs = Object.entries(this.#get().builtinAgentIdMap)+ .filter(([, agentId]) => agentId === id)+ .map(([slug]) => slug);++ /** Reuse the authoritative update response; other mutations still need a network refresh. */+ if (updatedAgent) {+ const scope = getCacheScope();+ await Promise.all([+ mutate(agentConfigKeys.config(id), updatedAgent, { revalidate: false }),+ ...slugs.map((slug) =>+ mutate(builtinAgentKeys.init(slug, scope), updatedAgent as AgentItem, {+ revalidate: false,+ }),+ ),+ ]);+ return;+ }++ await Promise.all([+ mutate(agentConfigKeys.config(id)),+ ...slugs.map((slug) => this.#get().refreshBuiltinAgent(slug)),+ ]);};internal_createAbortController = (key: keyof AgentSliceState): AbortController => {diff --git a/src/store/agent/slices/builtin/action.ts b/src/store/agent/slices/builtin/action.tsindex ac4965c90da..17d203c794a 100644--- a/src/store/agent/slices/builtin/action.ts+++ b/src/store/agent/slices/builtin/action.ts@@ -1,9 +1,11 @@import { type AgentItem, type LobeAgentConfig } from '@lobechat/types';+import { useLayoutEffect } from 'react';import { type SWRResponse } from 'swr';import { type PartialDeep } from 'type-fest';-import { useOnlyFetchOnceSWR } from '@/libs/swr';+import { mutate, useClientDataSWR } from '@/libs/swr';import { builtinAgentKeys } from '@/libs/swr/keys';+import { getCacheScope, useCacheScope } from '@/libs/swr/useCacheScope';import { agentService } from '@/services/agent';import { type StoreSetter } from '@/store/types';@@ -37,10 +39,11 @@ export class BuiltinAgentSliceActionImpl {}refreshBuiltinAgent = async (slug: string): Promise<void> => {+ const scope = getCacheScope();const data = await agentService.getBuiltinAgent(slug);- if (data?.id) {+ if (data?.id && scope === getCacheScope()) {this.#get().internal_dispatchAgentMap(data.id, data as PartialDeep<LobeAgentConfig>);- // Mirror useInitBuiltinAgent's onSuccess: keep builtinAgentIdMap in sync+ // Mirror useInitBuiltinAgent's hydration: keep builtinAgentIdMap in sync// so callers can rely on this as a real "ensure" path instead of just a// post-init refresh.this.#set(@@ -48,6 +51,7 @@ export class BuiltinAgentSliceActionImpl {false,`refreshBuiltinAgent/${slug}`,);+ await mutate(builtinAgentKeys.init(slug, scope), data, { revalidate: false });}};@@ -55,30 +59,39 @@ export class BuiltinAgentSliceActionImpl {slug: string,context?: UseInitBuiltinAgentContext,): SWRResponse<AgentItem | null> => {- return useOnlyFetchOnceSWR(- context?.isLogin === false ? null : builtinAgentKeys.init(slug),+ const scope = useCacheScope();+ const response = useClientDataSWR<AgentItem | null>(+ context?.isLogin === false ? null : builtinAgentKeys.init(slug, scope),async () => {const data = await agentService.getBuiltinAgent(slug);- return data as AgentItem | null;+ return scope === getCacheScope() ? (data as AgentItem | null) : null;},{- onSuccess: (data: AgentItem | null) => {- if (data?.id) {- // Update builtinAgentIdMap with the agent id- // Update agentMap with the agent config- // AgentItem contains all fields needed for LobeAgentConfig- this.#get().internal_dispatchAgentMap(data.id, data as PartialDeep<LobeAgentConfig>);-- this.#set(- { builtinAgentIdMap: { ...this.#get().builtinAgentIdMap, [slug]: data.id } },- false,- `useInitBuiltinAgent/${slug}`,- );- }- },+ dedupingInterval: 2000,+ revalidateOnFocus: false,+ revalidateOnReconnect: false,},);++ const { data } = response;+ /**+ * Cache hits do not invoke SWR's onSuccess. Restore the identity and artwork+ * before paint as well as after revalidation, so a reload does not briefly+ * display the default chief. Ignore responses from an obsolete identity scope.+ */+ useLayoutEffect(() => {+ if (context?.isLogin === false || !data?.id || scope !== getCacheScope()) return;++ this.#get().internal_dispatchAgentMap(data.id, data as PartialDeep<LobeAgentConfig>);+ this.#set(+ { builtinAgentIdMap: { ...this.#get().builtinAgentIdMap, [slug]: data.id } },+ false,+ `useInitBuiltinAgent/${slug}`,+ );+ }, [data, slug, scope, context?.isLogin]);++ return response;};}diff --git a/src/store/project/store.test.ts b/src/store/project/store.test.tsindex 2893d2c2fa7..abc629c88e0 100644--- a/src/store/project/store.test.ts+++ b/src/store/project/store.test.ts@@ -1,6 +1,7 @@import { act, renderHook } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';+import { mutate } from '@/libs/swr';import { projectService } from '@/services/project';import type { ProjectDetail, ProjectListItem } from './store';@@ -8,7 +9,12 @@ import { useCurrentProjectDetail, useCurrentProjectList, useProjectStore } fromconst mocks = vi.hoisted(() => ({activeWorkspaceId: null as string | null,- swrConfigs: [] as Array<{ onSuccess: (response: unknown) => void }>,+ cacheScope: 'user-1:personal',+ currentCacheScope: 'user-1:personal',+ swrData: undefined as unknown,+ swrDataByKey: {} as Record<string, unknown>,+ swrConfigs: [] as Array<{ onSuccess?: (response: unknown) => void }>,+ swrKeys: [] as unknown[],}));vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({@@ -16,36 +22,113 @@ vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({useActiveWorkspaceId: () => mocks.activeWorkspaceId,}));+vi.mock('@/libs/swr/useCacheScope', () => ({+ getCacheScope: () => mocks.currentCacheScope,+ useCacheScope: () => mocks.cacheScope,+}));+vi.mock('@/libs/swr', () => ({mutate: vi.fn(),useClientDataSWR: vi.fn(- (_key: unknown, _fetcher: unknown, config: { onSuccess: (response: unknown) => void }) => {+ (key: unknown, _fetcher: unknown, config: { onSuccess?: (response: unknown) => void } = {}) => {mocks.swrConfigs.push(config);- return {};+ mocks.swrKeys.push(key);+ const serializedKey = JSON.stringify(key);+ return {+ data:+ serializedKey in mocks.swrDataByKey ? mocks.swrDataByKey[serializedKey] : mocks.swrData,+ };},),}));-describe('project store workspace scope', () => {+describe('project store cache scope', () => {beforeEach(() => {mocks.activeWorkspaceId = null;+ mocks.cacheScope = 'user-1:personal';+ mocks.currentCacheScope = 'user-1:personal';+ mocks.swrData = undefined;+ mocks.swrDataByKey = {};mocks.swrConfigs = [];+ mocks.swrKeys = [];useProjectStore.setState({ projectDetails: {}, projectLists: {} });});+ it('restores a persisted project list into the store before the first paint', () => {+ const cachedProject = { id: 'cached-project', name: 'Cached project' } as ProjectListItem;+ mocks.swrData = { data: [cachedProject], message: 'cached', success: true };++ renderHook(() => useProjectStore.getState().useFetchProjectList());++ expect(useProjectStore.getState().projectLists['user-1:personal']).toEqual([cachedProject]);+ });++ it('ignores a project response from a workspace that is no longer active', () => {+ const staleProject = { id: 'stale-project' } as ProjectListItem;+ mocks.swrData = { data: [staleProject], message: 'stale', success: true };+ mocks.cacheScope = 'user-1:personal';+ mocks.currentCacheScope = 'user-1:workspace-1';++ renderHook(() => useProjectStore.getState().useFetchProjectList());++ expect(useProjectStore.getState().projectLists['user-1:personal']).toBeUndefined();+ expect(useProjectStore.getState().projectLists['user-1:workspace-1']).toBeUndefined();+ });++ it('hides the previous account project list while old SWR data is still present', () => {+ const previousProject = { id: 'previous-project', name: 'Previous account' } as ProjectListItem;+ const previousResponse = { data: [previousProject], success: true };+ // Simulate the old shared key remaining populated until Query reloads the new scope.+ mocks.swrDataByKey = {+ [JSON.stringify('project/list')]: previousResponse,+ [JSON.stringify(['project/list', 'user-1:personal'])]: previousResponse,+ };+ const { rerender } = renderHook(() => useProjectStore.getState().useFetchProjectList());++ mocks.cacheScope = 'user-2:personal';+ mocks.currentCacheScope = 'user-2:personal';+ rerender();++ expect(mocks.swrKeys).toEqual([+ ['project/list', 'user-1:personal'],+ ['project/list', 'user-2:personal'],+ ]);+ expect(renderHook(() => useCurrentProjectList()).result.current).toEqual([]);+ });++ it('hides the previous account project detail after switching accounts', () => {+ const previousDetail = {+ project: { id: 'shared-id', name: 'Previous account' },+ } as ProjectDetail;+ const { rerender } = renderHook(() =>+ useProjectStore.getState().useFetchProjectDetail('shared-id'),+ );++ act(() => mocks.swrConfigs.at(-1)?.onSuccess?.({ data: previousDetail, success: true }));+ mocks.cacheScope = 'user-2:personal';+ mocks.currentCacheScope = 'user-2:personal';+ rerender();++ expect(renderHook(() => useCurrentProjectDetail('shared-id')).result.current).toBeUndefined();+ });+it('keeps project lists isolated between personal and workspace contexts', () => {const personalProject = { id: 'personal-project' } as ProjectListItem;const workspaceProject = { id: 'workspace-project' } as ProjectListItem;+ mocks.swrData = { data: [personalProject], success: true };const { rerender } = renderHook(() => useProjectStore.getState().useFetchProjectList());- act(() => mocks.swrConfigs.at(-1)?.onSuccess({ data: [personalProject], success: true }));mocks.activeWorkspaceId = 'workspace-1';+ mocks.cacheScope = 'user-1:workspace-1';+ mocks.currentCacheScope = 'user-1:workspace-1';+ mocks.swrData = { data: [workspaceProject], success: true };rerender();- act(() => mocks.swrConfigs.at(-1)?.onSuccess({ data: [workspaceProject], success: true }));expect(renderHook(() => useCurrentProjectList()).result.current).toEqual([workspaceProject]);mocks.activeWorkspaceId = null;+ mocks.cacheScope = 'user-1:personal';+ mocks.currentCacheScope = 'user-1:personal';expect(renderHook(() => useCurrentProjectList()).result.current).toEqual([personalProject]);});@@ -56,15 +139,23 @@ describe('project store workspace scope', () => {useProjectStore.getState().useFetchProjectDetail('shared-id'),);- act(() => mocks.swrConfigs.at(-1)?.onSuccess({ data: personalDetail, success: true }));+ act(() => mocks.swrConfigs.at(-1)?.onSuccess?.({ data: personalDetail, success: true }));mocks.activeWorkspaceId = 'workspace-1';+ mocks.cacheScope = 'user-1:workspace-1';+ mocks.currentCacheScope = 'user-1:workspace-1';rerender();- act(() => mocks.swrConfigs.at(-1)?.onSuccess({ data: workspaceDetail, success: true }));+ act(() => mocks.swrConfigs.at(-1)?.onSuccess?.({ data: workspaceDetail, success: true }));+ expect(mocks.swrKeys).toEqual([+ ['project/detail', 'user-1:personal', 'shared-id'],+ ['project/detail', 'user-1:workspace-1', 'shared-id'],+ ]);expect(renderHook(() => useCurrentProjectDetail('shared-id')).result.current).toBe(workspaceDetail,);mocks.activeWorkspaceId = null;+ mocks.cacheScope = 'user-1:personal';+ mocks.currentCacheScope = 'user-1:personal';expect(renderHook(() => useCurrentProjectDetail('shared-id')).result.current).toBe(personalDetail,);@@ -92,18 +183,17 @@ describe('project store workspace scope', () => {});it('refreshes the project list after deletion', async () => {- const refreshProjectList = vi.fn().mockResolvedValue(undefined);+ vi.mocked(mutate).mockClear();vi.spyOn(projectService, 'delete').mockResolvedValue({data: { id: 'project-1' } as ProjectListItem,message: 'Project deleted',success: true,});- useProjectStore.setState({ refreshProjectList });await useProjectStore.getState().deleteProject('project-1');expect(projectService.delete).toHaveBeenCalledWith('project-1');- expect(refreshProjectList).toHaveBeenCalledOnce();+ expect(mutate).toHaveBeenCalledWith(['project/list', 'user-1:personal']);});it('updates project list and detail caches after renaming', async () => {@@ -117,15 +207,17 @@ describe('project store workspace scope', () => {success: true,});useProjectStore.setState({- projectDetails: { personal: { launch: detail } },- projectLists: { personal: [project] },+ projectDetails: { 'user-1:personal': { launch: detail } },+ projectLists: { 'user-1:personal': [project] },refreshProjectList,});await useProjectStore.getState().updateProject('project-1', { name: 'Renamed' });- expect(useProjectStore.getState().projectLists.personal[0].name).toBe('Renamed');- expect(useProjectStore.getState().projectDetails.personal.launch.project.name).toBe('Renamed');+ expect(useProjectStore.getState().projectLists['user-1:personal'][0].name).toBe('Renamed');+ expect(useProjectStore.getState().projectDetails['user-1:personal'].launch.project.name).toBe(+ 'Renamed',+ );expect(refreshProjectList).toHaveBeenCalledOnce();});});diff --git a/src/store/project/store.ts b/src/store/project/store.tsindex 9b51d8a9ae4..51efae8348d 100644--- a/src/store/project/store.ts+++ b/src/store/project/store.ts@@ -1,12 +1,11 @@+import { useLayoutEffect } from 'react';import type { SWRResponse } from 'swr';import { shallow } from 'zustand/shallow';import { createWithEqualityFn } from 'zustand/traditional';-import {- getActiveWorkspaceId,- useActiveWorkspaceId,-} from '@/business/client/hooks/useActiveWorkspaceId';+import { getActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import { mutate, useClientDataSWR } from '@/libs/swr';+import { getCacheScope, useCacheScope } from '@/libs/swr/useCacheScope';import { projectService } from '@/services/project';import { createDevtools } from '@/store/middleware/createDevtools';import { expose } from '@/store/middleware/expose';@@ -17,9 +16,8 @@ export type ProjectListItem = ProjectListResponse['data'][number];export type ProjectDetail = ProjectDetailResponse['data'];const LIST_KEY = 'project/list';-const detailKey = (id: string) => ['project/detail', id] as const;-const PERSONAL_SCOPE = 'personal';-const projectScopeKey = (workspaceId: string | null) => workspaceId ?? PERSONAL_SCOPE;+const listKey = (scope: string) => [LIST_KEY, scope] as const;+const detailKey = (scope: string, id: string) => ['project/detail', scope, id] as const;interface ProjectStore {createProject: (input: {@@ -51,7 +49,7 @@ export const useProjectStore = createWithEqualityFn<ProjectStore>()(},projectDetails: {},projectLists: {},- refreshProjectList: async () => mutate(LIST_KEY),+ refreshProjectList: async () => mutate(listKey(getCacheScope())),updateProject: async (id, input) => {const response = await projectService.update(id, input);const project = response.data;@@ -83,11 +81,12 @@ export const useProjectStore = createWithEqualityFn<ProjectStore>()(return project;},useFetchProjectDetail: (id) => {- const workspaceId = useActiveWorkspaceId();- const scope = projectScopeKey(workspaceId);+ const scope = useCacheScope();++ return useClientDataSWR(id ? detailKey(scope, id) : null, () => projectService.detail(id!), {+ onSuccess: (response: ProjectDetailResponse) => {+ if (scope !== getCacheScope()) return;- return useClientDataSWR(id ? detailKey(id) : null, () => projectService.detail(id!), {- onSuccess: (response: ProjectDetailResponse) =>set((state) => ({projectDetails: {@@ -97,21 +96,33 @@ export const useProjectStore = createWithEqualityFn<ProjectStore>()(}),false,'useFetchProjectDetail/success',- ),+ );+ },});},useFetchProjectList: (enabled = true) => {- const workspaceId = useActiveWorkspaceId();- const scope = projectScopeKey(workspaceId);+ const scope = useCacheScope();+ const response = useClientDataSWR(enabled ? listKey(scope) : null, () =>+ projectService.listAll(),+ );+ const { data } = response;- return useClientDataSWR(enabled ? LIST_KEY : null, () => projectService.listAll(), {- onSuccess: (response: ProjectListResponse) =>- set(- (state) => ({ projectLists: { ...state.projectLists, [scope]: response.data } }),- false,- 'useFetchProjectList/success',- ),- });+ useLayoutEffect(() => {+ /**+ * SWR cache hits do not invoke onSuccess. Hydrate Zustand before paint+ * so the sidebar can render the cached list during a cold refresh.+ * Ignore data captured for an obsolete user or workspace scope.+ */+ if (!enabled || !data || scope !== getCacheScope()) return;++ set(+ (state) => ({ projectLists: { ...state.projectLists, [scope]: data.data } }),+ false,+ 'useFetchProjectList/hydrate',+ );+ }, [data, enabled, scope]);++ return response;},})),shallow,@@ -120,11 +131,11 @@ export const useProjectStore = createWithEqualityFn<ProjectStore>()(expose('project', useProjectStore);export const useCurrentProjectList = () => {- const scope = projectScopeKey(useActiveWorkspaceId());+ const scope = useCacheScope();return useProjectStore((state) => state.projectLists[scope] ?? []);};export const useCurrentProjectDetail = (id?: string) => {- const scope = projectScopeKey(useActiveWorkspaceId());+ const scope = useCacheScope();return useProjectStore((state) => (id ? state.projectDetails[scope]?.[id] : undefined));};diff --git a/src/store/user/displaySnapshot.test.ts b/src/store/user/displaySnapshot.test.tsnew file mode 100644index 00000000000..28cb1c06a52--- /dev/null+++ b/src/store/user/displaySnapshot.test.ts@@ -0,0 +1,72 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ clearUserDisplaySnapshot,+ readUserDisplaySnapshot,+ writeUserDisplaySnapshot,+} from './displaySnapshot';++beforeEach(() => {+ localStorage.clear();+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe('user display snapshot', () => {+ it('keeps the avatar and preference isolated by exact user id', () => {+ writeUserDisplaySnapshot('user-a', {+ avatar: '',+ preference: { lab: { enableProjects: true } },+ });++ expect(readUserDisplaySnapshot('user-a')).toEqual({+ avatar: '',+ preference: { lab: { enableProjects: true } },+ });+ expect(readUserDisplaySnapshot('user-b')).toBeUndefined();+ });++ it('merges partial writes without dropping the other display field', () => {+ writeUserDisplaySnapshot('user-a', {+ avatar: 'avatar-a',+ });+ writeUserDisplaySnapshot('user-a', {+ preference: { lab: { enableProjects: true } },+ });++ expect(readUserDisplaySnapshot('user-a')).toEqual({+ avatar: 'avatar-a',+ preference: { lab: { enableProjects: true } },+ });+ });++ it('clears only the requested user snapshot', () => {+ writeUserDisplaySnapshot('user-a', { avatar: 'avatar-a' });+ writeUserDisplaySnapshot('user-b', { avatar: 'avatar-b' });++ clearUserDisplaySnapshot('user-a');++ expect(readUserDisplaySnapshot('user-a')).toBeUndefined();+ expect(readUserDisplaySnapshot('user-b')).toEqual({ avatar: 'avatar-b' });+ });++ it('ignores malformed persisted data', () => {+ vi.spyOn(localStorage, 'getItem').mockReturnValue('{malformed');++ expect(readUserDisplaySnapshot('user-a')).toBeUndefined();+ });++ it('does not throw when localStorage is unavailable', () => {+ vi.spyOn(localStorage, 'setItem').mockImplementation(() => {+ throw new Error('storage unavailable');+ });++ expect(() =>+ writeUserDisplaySnapshot('user-a', {+ avatar: 'avatar-a',+ }),+ ).not.toThrow();+ });+});diff --git a/src/store/user/displaySnapshot.ts b/src/store/user/displaySnapshot.tsnew file mode 100644index 00000000000..1d8751fcbad--- /dev/null+++ b/src/store/user/displaySnapshot.ts@@ -0,0 +1,75 @@+import { UserPreferenceSchema } from '@lobechat/types';+import { isRecord } from '@lobechat/utils/object';++import { LocalStorageQueryProjectionStorage } from '@/libs/queryProjectionStorage';+import type { UserPreference } from '@/types/user';++export interface UserDisplaySnapshot {+ avatar?: string;+ preference?: UserPreference;+}++/**+ * Only display fields may be restored before the authoritative user-state response.+ * Persisting that whole response would also restore stale entitlement and onboarding state.+ */+const storage = new LocalStorageQueryProjectionStorage<UserDisplaySnapshot>({+ namespace: 'lobehub:user-display-snapshot:v1',+});+const snapshotKey = (userId: string) => ({ queryKey: 'display', scope: userId });++const sanitizeSnapshot = (value: unknown): UserDisplaySnapshot | undefined => {+ if (!isRecord(value)) return undefined;++ const snapshot: UserDisplaySnapshot = {};++ if (typeof value.avatar === 'string') snapshot.avatar = value.avatar;++ if (value.preference !== undefined) {+ const result = UserPreferenceSchema.safeParse(value.preference);+ if (result.success) snapshot.preference = result.data;+ }++ return Object.keys(snapshot).length > 0 ? snapshot : undefined;+};++/**+ * Read the small, user-scoped display snapshot used to bridge the auth and+ * user-state requests during a cold boot.+ *+ * The caller must provide the exact authenticated user id. No last-used user+ * fallback is allowed because this data can contain private profile settings.+ */+export const readUserDisplaySnapshot = (userId: string): UserDisplaySnapshot | undefined => {+ if (!userId) return undefined;+ return sanitizeSnapshot(storage.getSync(snapshotKey(userId))?.data);+};++/**+ * Persist only the display fields needed before the authoritative user state+ * request resolves. The value is merged with the existing user entry so a+ * partial update cannot discard the other display field.+ */+export const writeUserDisplaySnapshot = (+ userId: string | undefined,+ snapshot: UserDisplaySnapshot,+): void => {+ if (!userId) return;++ const sanitized = sanitizeSnapshot(snapshot);+ if (!sanitized) return;++ void storage.set(snapshotKey(userId), {+ data: { ...readUserDisplaySnapshot(userId), ...sanitized },+ updatedAt: Date.now(),+ });+};++/**+ * Remove the persisted display snapshot for one user after that user's session+ * has been successfully signed out.+ */+export const clearUserDisplaySnapshot = (userId: string | undefined): void => {+ if (!userId) return;+ void storage.remove(snapshotKey(userId));+};diff --git a/src/store/user/slices/auth/action.test.ts b/src/store/user/slices/auth/action.test.tsindex 072d508204b..ae6a9e6aba2 100644--- a/src/store/user/slices/auth/action.test.ts+++ b/src/store/user/slices/auth/action.test.ts@@ -1,9 +1,10 @@import { act, renderHook } from '@testing-library/react';-import { afterEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { mutate } from '@/libs/swr';import { userKeys } from '@/libs/swr/keys';import { useUserStore } from '@/store/user';+import { readUserDisplaySnapshot, writeUserDisplaySnapshot } from '@/store/user/displaySnapshot';// Mock @/libs/swr mutatevi.mock('@/libs/swr', async () => {@@ -22,6 +23,10 @@ const mockBetterAuthClient = vi.hoisted(() => ({vi.mock('@/libs/better-auth/auth-client', () => mockBetterAuthClient);+beforeEach(() => {+ localStorage.clear();+});+afterEach(() => {vi.restoreAllMocks();vi.clearAllMocks();@@ -48,7 +53,19 @@ describe('createAuthSlice', () => {});describe('logout', () => {- it('should call better-auth signOut', async () => {+ it('clears the captured user snapshot after successful sign-out', async () => {+ writeUserDisplaySnapshot('user-a', { avatar: 'avatar-a' });+ writeUserDisplaySnapshot('user-b', { avatar: 'avatar-b' });+ localStorage.setItem('lobehub:active-scope', 'user-a:personal');+ useUserStore.setState({ user: { id: 'user-a' } });++ mockBetterAuthClient.signOut.mockImplementationOnce(async ({ fetchOptions }) => {+ // A concurrent session update must not change which snapshot this+ // sign-out is allowed to clear.+ useUserStore.setState({ user: { id: 'user-b' } });+ fetchOptions?.onSuccess?.();+ });+const { result } = renderHook(() => useUserStore());await act(async () => {@@ -56,6 +73,24 @@ describe('createAuthSlice', () => {});expect(mockBetterAuthClient.signOut).toHaveBeenCalled();+ expect(readUserDisplaySnapshot('user-a')).toBeUndefined();+ expect(readUserDisplaySnapshot('user-b')).toEqual({ avatar: 'avatar-b' });+ expect(localStorage.getItem('lobehub:active-scope')).toBeNull();+ });++ it('preserves the signing-out user snapshot when sign-out fails', async () => {+ writeUserDisplaySnapshot('user-a', { avatar: 'avatar-a' });+ localStorage.setItem('lobehub:active-scope', 'user-a:personal');+ useUserStore.setState({ user: { id: 'user-a' } });+ mockBetterAuthClient.signOut.mockRejectedValueOnce(new Error('sign-out failed'));++ const { result } = renderHook(() => useUserStore());+ const logoutPromise = result.current.logout();++ await expect(logoutPromise).rejects.toThrow('sign-out failed');++ expect(readUserDisplaySnapshot('user-a')).toEqual({ avatar: 'avatar-a' });+ expect(localStorage.getItem('lobehub:active-scope')).toBe('user-a:personal');});});diff --git a/src/store/user/slices/auth/action.ts b/src/store/user/slices/auth/action.tsindex 60263cf7dbd..36c2aeef3fa 100644--- a/src/store/user/slices/auth/action.ts+++ b/src/store/user/slices/auth/action.ts@@ -3,6 +3,7 @@ import { type SSOProvider } from '@lobechat/types';import { clearActiveScopeKey } from '@/libs/swr/useCacheScope';import { type StoreSetter } from '@/store/types';+import { clearUserDisplaySnapshot } from '../../displaySnapshot';import { type UserStore } from '../../store';interface AuthProvidersData {@@ -61,6 +62,10 @@ export class UserAuthActionImpl {};logout = async (options?: { redirectTo?: string }): Promise<void> => {+ // Capture the owner before any async work. The store may be updated by a+ // concurrent session event before Better Auth confirms this sign-out.+ const signingOutUserId = this.#get().user?.id;+// Clear the OIDC Provider session for the current browser *before*// destroying the better-auth session. This prevents a stale OIDC session// from silently issuing tokens for the old account after the user signs@@ -78,6 +83,7 @@ export class UserAuthActionImpl {// Drop the persisted active scope so the next boot doesn't hydrate the// signed-out user's cache (localStorage survives the reload below).clearActiveScopeKey();+ clearUserDisplaySnapshot(signingOutUserId);// Use window.location.href to trigger a full page reload// This ensures all client-side state (React, Zustand, cache) is clearedwindow.location.href = options?.redirectTo || '/signin';diff --git a/src/store/user/slices/common/action.test.ts b/src/store/user/slices/common/action.test.tsindex 7adcd01baf9..7d59d640b27 100644--- a/src/store/user/slices/common/action.test.ts+++ b/src/store/user/slices/common/action.test.ts@@ -6,6 +6,7 @@ import type * as SWRLib from '@/libs/swr';import { taskTemplateKeys, userKeys } from '@/libs/swr/keys';import { userService } from '@/services/user';import { useUserStore } from '@/store/user';+import { readUserDisplaySnapshot, writeUserDisplaySnapshot } from '@/store/user/displaySnapshot';import { userGeneralSettingsSelectors } from '@/store/user/selectors';import { type GlobalServerConfig } from '@/types/serverConfig';import { type UserInitializationState, type UserPreference } from '@/types/user';@@ -35,6 +36,7 @@ vi.mock('swr', async (importOriginal) => {});beforeEach(() => {+ localStorage.clear();swrMocks.mutate.mockReset();swrMocks.mutate.mockResolvedValue(undefined);});@@ -266,6 +268,50 @@ describe('createCommonSlice', () => {});});+ it('should persist the authoritative avatar and preference for the returned user', async () => {+ const { result } = renderHook(() => useUserStore());+ const mockUserState: UserInitializationState = {+ avatar: 'avatar-a',+ preference: { lab: { enableProjects: true } },+ settings: {},+ userId: 'user-a',+ };++ vi.spyOn(userService, 'getUserState').mockResolvedValueOnce(mockUserState);++ renderHook(() => result.current.useInitUserState(true, mockServerConfig), {+ wrapper: withSWR,+ });++ await waitFor(() => {+ expect(readUserDisplaySnapshot('user-a')).toEqual({+ avatar: 'avatar-a',+ preference: { lab: { enableProjects: true } },+ });+ });+ expect(readUserDisplaySnapshot('user-b')).toBeUndefined();+ });++ it('should clear a previously cached avatar when the authoritative state has none', async () => {+ const { result } = renderHook(() => useUserStore());+ const mockUserState: UserInitializationState = {+ preference: { lab: { enableProjects: true } },+ settings: {},+ userId: 'user-a',+ };++ vi.spyOn(userService, 'getUserState').mockResolvedValueOnce(mockUserState);++ writeUserDisplaySnapshot('user-a', { avatar: 'stale-avatar' });+ renderHook(() => result.current.useInitUserState(true, mockServerConfig), {+ wrapper: withSWR,+ });++ await waitFor(() => {+ expect(readUserDisplaySnapshot('user-a')?.avatar).toBe('');+ });+ });+it('should handle the case when user state have avatar', async () => {const { result } = renderHook(() => useUserStore());const mockUserState: UserInitializationState = {diff --git a/src/store/user/slices/common/action.ts b/src/store/user/slices/common/action.tsindex f5c122695e5..9d9abf62e2a 100644--- a/src/store/user/slices/common/action.ts+++ b/src/store/user/slices/common/action.ts@@ -17,6 +17,7 @@ import { type UserSettings } from '@/types/user/settings';import { merge } from '@/utils/merge';import { setNamespace } from '@/utils/storeDebug';+import { writeUserDisplaySnapshot } from '../../displaySnapshot';import { userGeneralSettingsSelectors } from '../settings/selectors';const n = setNamespace('common');@@ -129,6 +130,11 @@ export class CommonActionImpl {const isEmpty = Object.keys(data.preference || {}).length === 0;const preference = isEmpty ? DEFAULT_PREFERENCE : data.preference;+ writeUserDisplaySnapshot(data.userId, {+ avatar: data.avatar ?? '',+ preference,+ });+// if there is avatar or userId (from client DB), update it into userconst user =data.avatar || data.userIddiff --git a/src/store/user/slices/onboarding/action.ts b/src/store/user/slices/onboarding/action.tsindex e2165e8c3dc..3dae6d78e9f 100644--- a/src/store/user/slices/onboarding/action.ts+++ b/src/store/user/slices/onboarding/action.ts@@ -2,7 +2,6 @@ import { CURRENT_ONBOARDING_VERSION, INBOX_SESSION_ID } from '@lobechat/const';import { CLASSIC_ONBOARDING_MAX_STEP, getPluginMode, upsertPluginMode } from '@lobechat/types';import { userService } from '@/services/user';-import { getAgentStoreState } from '@/store/agent';import { type StoreSetter } from '@/store/types';import { type UserStore } from '@/store/user';@@ -97,6 +96,8 @@ export class OnboardingActionImpl {};toggleInboxAgentDefaultPlugin = async (id: string, open?: boolean): Promise<void> => {+ /** Break the user → agent → cache-scope → user initialization cycle. */+ const { getAgentStoreState } = await import('@/store/agent');const currentSettings = settingsSelectors.currentSettings(this.#get());const isDefaultPinned =getPluginMode(currentSettings.defaultAgent?.config?.plugins, id) === 'pinned';diff --git a/src/store/user/slices/preference/action.test.ts b/src/store/user/slices/preference/action.test.tsindex de2f730c7d2..5f78c70329b 100644--- a/src/store/user/slices/preference/action.test.ts+++ b/src/store/user/slices/preference/action.test.ts@@ -1,10 +1,13 @@import { act, renderHook } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { userService } from '@/services/user';import { useUserStore } from '@/store/user';+import { readUserDisplaySnapshot, writeUserDisplaySnapshot } from '@/store/user/displaySnapshot';import { type UserGuide } from '@/types/user';beforeEach(() => {+ localStorage.clear();vi.clearAllMocks();});@@ -36,5 +39,80 @@ describe('createPreferenceSlice', () => {expect(result.current.preference.hideSyncAlert).toEqual(true);});++ it('persists the preference after the server update succeeds', async () => {+ const updatePreferenceSpy = vi+ .spyOn(userService, 'updatePreference')+ .mockResolvedValue(undefined as any);++ act(() => {+ useUserStore.setState({ user: { avatar: 'avatar-a', id: 'user-a' } as any });+ });++ await act(async () => {+ await useUserStore.getState().updatePreference({+ lab: { enableProjects: true },+ });+ });++ expect(updatePreferenceSpy).toHaveBeenCalled();+ expect(readUserDisplaySnapshot('user-a')).toEqual({+ preference: expect.objectContaining({+ lab: expect.objectContaining({ enableProjects: true }),+ }),+ });+ });++ it('does not persist a failed preference update', async () => {+ vi.spyOn(userService, 'updatePreference').mockRejectedValue(new Error('update failed'));++ act(() => {+ useUserStore.setState({ user: { avatar: 'avatar-a', id: 'user-a' } as any });+ });++ await expect(+ useUserStore.getState().updatePreference({ lab: { enableProjects: true } }),+ ).rejects.toThrow('update failed');+ expect(readUserDisplaySnapshot('user-a')).toBeUndefined();+ });++ it('persists under the user id captured before an update can switch accounts', async () => {+ let resolveUpdate: (() => void) | undefined;+ const updatePreferenceSpy = vi.spyOn(userService, 'updatePreference').mockImplementation(+ () =>+ new Promise<Awaited<ReturnType<typeof userService.updatePreference>>>((resolve) => {+ resolveUpdate = () => resolve(undefined);+ }),+ );++ act(() => {+ useUserStore.setState({ user: { avatar: 'avatar-a', id: 'user-a' } });+ });++ let updatePromise: Promise<void> | undefined;+ act(() => {+ updatePromise = useUserStore.getState().updatePreference({ lab: { enableProjects: true } });+ });+ writeUserDisplaySnapshot('user-a', { avatar: 'updated-avatar' });++ act(() => {+ useUserStore.setState({ user: { avatar: 'avatar-b', id: 'user-b' } });+ });++ expect(resolveUpdate).toBeDefined();+ await act(async () => {+ resolveUpdate?.();+ await updatePromise;+ });++ expect(updatePreferenceSpy).toHaveBeenCalled();+ expect(readUserDisplaySnapshot('user-a')).toEqual({+ avatar: 'updated-avatar',+ preference: expect.objectContaining({+ lab: expect.objectContaining({ enableProjects: true }),+ }),+ });+ expect(readUserDisplaySnapshot('user-b')).toBeUndefined();+ });});});diff --git a/src/store/user/slices/preference/action.ts b/src/store/user/slices/preference/action.tsindex e9690986cbf..6206c9b653d 100644--- a/src/store/user/slices/preference/action.ts+++ b/src/store/user/slices/preference/action.ts@@ -5,6 +5,8 @@ import { type UserGuide, type UserLab, type UserPreference } from '@/types/user'import { merge } from '@/utils/merge';import { setNamespace } from '@/utils/storeDebug';+import { writeUserDisplaySnapshot } from '../../displaySnapshot';+const n = setNamespace('preference');type Setter = StoreSetter<UserStore>;@@ -35,10 +37,15 @@ export class PreferenceActionImpl {updatePreference = async (preference: Partial<UserPreference>, action?: any): Promise<void> => {const nextPreference = merge(this.#get().preference, preference);+ const userId = this.#get().user?.id;this.#set({ preference: nextPreference }, false, action || n('updatePreference'));await userService.updatePreference(nextPreference);++ writeUserDisplaySnapshot(userId, {+ preference: nextPreference,+ });};}