🤯 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
♻️ refactor: add local-first Agent and Project projections (#18913)
Arvin Xu2cb2d4111291
diff --git a/src/features/AgentIdentityModal/useAgentIdentityForm.test.ts b/src/features/AgentIdentityModal/useAgentIdentityForm.test.tsindex 2a399879706..2fb19d8e552 100644--- a/src/features/AgentIdentityModal/useAgentIdentityForm.test.ts+++ b/src/features/AgentIdentityModal/useAgentIdentityForm.test.ts@@ -6,14 +6,13 @@ import { useAgentIdentityForm } from './useAgentIdentityForm';const mocks = vi.hoisted(() => ({agentMap: {} as Record<string, { name?: string; slug?: string; title?: string }>,refreshAgentConfig: vi.fn(),- refreshAgentList: vi.fn(),- updateAgentMetaById: vi.fn(),+ updateAgentMeta: vi.fn(),updateAgentSlug: vi.fn(),}));vi.mock('@/store/home', () => ({useHomeStore: (selector: (state: unknown) => unknown) =>- selector({ refreshAgentList: mocks.refreshAgentList }),+ selector({ updateAgentMeta: mocks.updateAgentMeta }),}));vi.mock('@/services/agent', () => ({@@ -27,7 +26,6 @@ vi.mock('@/store/agent', () => ({selector({agentMap: mocks.agentMap,internal_refreshAgentConfig: mocks.refreshAgentConfig,- updateAgentMetaById: mocks.updateAgentMetaById,}),}));@@ -50,7 +48,7 @@ beforeEach(() => {vi.clearAllMocks();mocks.agentMap = { 'agent-a': { name: 'Alice', slug: 'old-slug', title: 'Health Assistant' } };mocks.updateAgentSlug.mockResolvedValue({ success: true });- mocks.updateAgentMetaById.mockResolvedValue(undefined);+ mocks.updateAgentMeta.mockResolvedValue(undefined);});describe('useAgentIdentityForm', () => {@@ -70,7 +68,7 @@ describe('useAgentIdentityForm', () => {await result.current.save();});- expect(mocks.updateAgentMetaById).toHaveBeenCalledExactlyOnceWith('agent-a', {+ expect(mocks.updateAgentMeta).toHaveBeenCalledExactlyOnceWith('agent-a', {name: '小艾',title: 'Health Assistant',});@@ -78,9 +76,7 @@ describe('useAgentIdentityForm', () => {expect(onSaved).toHaveBeenCalled();});- // The sidebar keeps its own copy of the label; without a refresh the list- // shows the old name while the profile shows the new one.- it('refreshes the sidebar list after a rename', async () => {+ it('routes identity changes through the optimistic sidebar projection', async () => {const { result } = setup();act(() => result.current.setName('小艾'));@@ -88,7 +84,7 @@ describe('useAgentIdentityForm', () => {await result.current.save();});- expect(mocks.refreshAgentList).toHaveBeenCalledOnce();+ expect(mocks.updateAgentMeta).toHaveBeenCalledOnce();});it('does not refresh the sidebar when the save was rejected', async () => {@@ -100,7 +96,7 @@ describe('useAgentIdentityForm', () => {await result.current.save();});- expect(mocks.refreshAgentList).not.toHaveBeenCalled();+ expect(mocks.updateAgentMeta).not.toHaveBeenCalled();});it('routes a slug change to its own endpoint, normalized to lowercase', async () => {@@ -127,7 +123,7 @@ describe('useAgentIdentityForm', () => {expect(result.current.error).toBe('settingAgent.slug.error.taken');// A rejected slug must not leave name/role persisted behind a closed form.- expect(mocks.updateAgentMetaById).not.toHaveBeenCalled();+ expect(mocks.updateAgentMeta).not.toHaveBeenCalled();expect(onSaved).not.toHaveBeenCalled();});@@ -162,7 +158,7 @@ describe('useAgentIdentityForm', () => {});expect(mocks.updateAgentSlug).not.toHaveBeenCalled();- expect(mocks.updateAgentMetaById).toHaveBeenCalledExactlyOnceWith('agent-a', {+ expect(mocks.updateAgentMeta).toHaveBeenCalledExactlyOnceWith('agent-a', {name: '',title: 'Lobe AI',});diff --git a/src/features/AgentIdentityModal/useAgentIdentityForm.ts b/src/features/AgentIdentityModal/useAgentIdentityForm.tsindex 824f6494915..ca2eb21012d 100644--- a/src/features/AgentIdentityModal/useAgentIdentityForm.ts+++ b/src/features/AgentIdentityModal/useAgentIdentityForm.ts@@ -27,9 +27,8 @@ export const useAgentIdentityForm = ({ agentId, onSaved }: UseAgentIdentityFormOconst meta = useAgentStore(agentSelectors.getAgentMetaById(agentId));const slug = useAgentStore(agentSelectors.getAgentSlugById(agentId));- const updateMetaById = useAgentStore((s) => s.updateAgentMetaById);const refreshAgentConfig = useAgentStore((s) => s.internal_refreshAgentConfig);- const refreshAgentList = useHomeStore((s) => s.refreshAgentList);+ const updateAgentMeta = useHomeStore((s) => s.updateAgentMeta);const [name, setName] = useState(meta.name || '');const [title, setTitle] = useState(meta.title || '');@@ -56,11 +55,7 @@ export const useAgentIdentityForm = ({ agentId, onSaved }: UseAgentIdentityFormOawait refreshAgentConfig(agentId);}- await updateMetaById(agentId, { name: name.trim(), title: title.trim() });- // The sidebar holds its own copy of the label — without this the list keeps- // showing the old name until something else revalidates. Same convention as- // the sidebar's own rename popover.- await refreshAgentList();+ await updateAgentMeta(agentId, { name: name.trim(), title: title.trim() });onSaved();} catch {setError(t('settingAgent.identity.saveFailed'));diff --git a/src/features/EditingPopover/AgentContent.tsx b/src/features/EditingPopover/AgentContent.tsxindex 3cb0ef811be..619a3313b99 100644--- a/src/features/EditingPopover/AgentContent.tsx+++ b/src/features/EditingPopover/AgentContent.tsx@@ -44,22 +44,28 @@ const AgentContent = memo<AgentContentProps>(({ id, title, avatar, onClose }) =>const backgroundColorChanged = newBackgroundColor !== meta.backgroundColor;if (titleChanged || avatarChanged || backgroundColorChanged) {- try {- useHomeStore.getState().setAgentUpdatingId(id);-- const updates: { avatar?: string; backgroundColor?: string; title?: string } = {};- if (titleChanged) updates.title = newTitle;- if (avatarChanged) updates.avatar = newAvatar || undefined;- if (backgroundColorChanged) updates.backgroundColor = newBackgroundColor;-- await useAgentStore.getState().optimisticUpdateAgentMeta(id, updates);- await useHomeStore.getState().refreshAgentList();- } finally {- useHomeStore.getState().setAgentUpdatingId(null);- }+ const updates: { avatar?: string; backgroundColor?: string; title?: string } = {};+ if (titleChanged) updates.title = newTitle;+ if (avatarChanged) updates.avatar = newAvatar || undefined;+ if (backgroundColorChanged) updates.backgroundColor = newBackgroundColor;++ void useHomeStore+ .getState()+ .updateAgentMeta(id, updates)+ .catch(() => toast.error(t('operationFailed', { ns: 'common' })));}onClose();- }, [newTitle, newAvatar, newBackgroundColor, title, avatar, meta.backgroundColor, id, onClose]);+ }, [+ newTitle,+ newAvatar,+ newBackgroundColor,+ title,+ avatar,+ meta.backgroundColor,+ id,+ onClose,+ t,+ ]);const handleAvatarUpload = useCallback(async (file: File) => {diff --git a/src/features/HomeSidebar/Body/Project/index.tsx b/src/features/HomeSidebar/Body/Project/index.tsxindex 73f153d1a45..f39f6bc7d6b 100644--- a/src/features/HomeSidebar/Body/Project/index.tsx+++ b/src/features/HomeSidebar/Body/Project/index.tsx@@ -64,7 +64,7 @@ const Project = memo<ProjectProps>(({ itemKey }) => {<AccordionPanel>{error ? (<AsyncError error={error} variant="inline" onRetry={() => mutate()} />- ) : isLoading ? (+ ) : isLoading && projects.length === 0 ? (<SkeletonList rows={3} />) : projects.length === 0 ? (<NavItemdiff --git a/src/features/Portal/AgentDetail/Body.tsx b/src/features/Portal/AgentDetail/Body.tsxindex bd04fd06809..be61eb66013 100644--- a/src/features/Portal/AgentDetail/Body.tsx+++ b/src/features/Portal/AgentDetail/Body.tsx@@ -10,6 +10,7 @@ import AsyncError from '@/components/AsyncError';import Avatar from '@/components/Avatar';import SurfaceSkeleton from '@/components/Skeleton/Surface';import { AgentNotFound } from '@/features/AgentNotFound';+import { useCacheScope } from '@/libs/swr/useCacheScope';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors, agentSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';@@ -24,6 +25,9 @@ const Body = memo(() => {const openingMessage = useAgentStore((s) => agentSelectors.getAgentConfigById(agentId)(s)?.openingMessage,);+ const scope = useCacheScope();+ // A config cached by the previous workspace must not render as this one's.+ const hasConfig = useAgentStore(agentByIdSelectors.hasAgentConfigInScope(agentId, scope));const isNotFound = useAgentStore(agentByIdSelectors.isAgentNotFoundById(agentId));const displayName = agentDisplayName(meta, t('defaultSession', { ns: 'common' }));@@ -47,7 +51,7 @@ const Body = memo(() => {);}- if (isLoading) return <SurfaceSkeleton header={false} variant={'form'} />;+ if (isLoading && !hasConfig) return <SurfaceSkeleton header={false} variant={'form'} />;return (<Flexbox align="center" flex={1} gap={16} padding={32} style={{ overflowY: 'auto' }}>diff --git a/src/features/Projects/Conversation/index.tsx b/src/features/Projects/Conversation/index.tsxindex 373eead347d..19294d8a4ec 100644--- a/src/features/Projects/Conversation/index.tsx+++ b/src/features/Projects/Conversation/index.tsx@@ -58,7 +58,7 @@ const ProjectConversation = memo(() => {if (detailSWR.error) {return <AsyncError error={detailSWR.error} variant="page" onRetry={detailSWR.mutate} />;}- if (detailSWR.isLoading || !coordinatorAgentId) {+ if (!detail || !coordinatorAgentId) {return (<Center height="100%" width="100%"><Spin size="small" />diff --git a/src/features/Projects/RenameProjectModal.tsx b/src/features/Projects/RenameProjectModal.tsxindex a689cf63523..cb13c567399 100644--- a/src/features/Projects/RenameProjectModal.tsx+++ b/src/features/Projects/RenameProjectModal.tsx@@ -24,23 +24,19 @@ const RenameProjectContent = ({ project }: RenameProjectContentProps) => {const { t } = useTranslation(['project', 'common']);const { close } = useModalContext();const updateProject = useProjectStore((s) => s.updateProject);- const [loading, setLoading] = useState(false);const [name, setName] = useState(project.name);const normalizedName = name.trim();- const handleRename = async () => {- if (!normalizedName || normalizedName === project.name || loading) return;- setLoading(true);- try {- await updateProject(project.id, { name: normalizedName });- close();- toast.success(t('rename.success'));- } catch (error) {- console.error('Failed to rename project', error);- toast.error(t('rename.error'));- } finally {- setLoading(false);- }+ const handleRename = () => {+ if (!normalizedName || normalizedName === project.name) return;+ const operation = updateProject(project.id, { name: normalizedName });+ close();+ void operation+ .then(() => toast.success(t('rename.success')))+ .catch((error) => {+ console.error('Failed to rename project', error);+ toast.error(t('rename.error'));+ });};return (@@ -61,7 +57,6 @@ const RenameProjectContent = ({ project }: RenameProjectContentProps) => {<Button onClick={close}>{t('cancel', { ns: 'common' })}</Button><Buttondisabled={!normalizedName || normalizedName === project.name}- loading={loading}type={'primary'}onClick={handleRename}>diff --git a/src/features/Projects/Workspace/index.tsx b/src/features/Projects/Workspace/index.tsxindex f52d69b6bb6..9f62608e7bc 100644--- a/src/features/Projects/Workspace/index.tsx+++ b/src/features/Projects/Workspace/index.tsx@@ -92,11 +92,11 @@ const ProjectWorkspace = memo(() => {const enabled = useUserStore(labPreferSelectors.enableProjects);const detail = useCurrentProjectDetail(projectId);const [message, setMessage] = useState('');- const { error, isLoading, mutate } = useProjectStore((s) => s.useFetchProjectDetail)(projectId);+ const { error, mutate } = useProjectStore((s) => s.useFetchProjectDetail)(projectId);if (!enabled) return <ProjectDisabled />;if (error) return <AsyncError error={error} variant={'page'} onRetry={() => mutate()} />;- if (isLoading || !detail)+ if (!detail)return (<Center height={'100%'}><Spin size="small" />diff --git a/src/features/ResourceTransferRequest/refreshAfterOwnershipChange.test.ts b/src/features/ResourceTransferRequest/refreshAfterOwnershipChange.test.tsindex fd324723268..677d00bcf8c 100644--- a/src/features/ResourceTransferRequest/refreshAfterOwnershipChange.test.ts+++ b/src/features/ResourceTransferRequest/refreshAfterOwnershipChange.test.ts@@ -13,6 +13,7 @@ const mocks = vi.hoisted(() => ({// a hook-BOUND `mutate` (which treats a key as replacement data for its own// cache). The refresh must go through the GLOBAL mutator from `@/libs/swr`.vi.mock('@/libs/swr', () => ({ mutate: (...args: unknown[]) => mocks.globalMutate(...args) }));+vi.mock('@/libs/swr/useCacheScope', () => ({ getCacheScope: () => 'user:workspace' }));vi.mock('@/store/home', () => ({useHomeStore: { getState: () => ({ refreshAgentList: mocks.refreshAgentList }) },}));@@ -26,7 +27,9 @@ describe('refreshCachesAfterOwnershipChange', () => {await refreshCachesAfterOwnershipChange('agent', 'agent-1');expect(mocks.globalMutate).toHaveBeenCalledTimes(1);- expect(mocks.globalMutate).toHaveBeenCalledWith(agentConfigKeys.config('agent-1'));+ expect(mocks.globalMutate).toHaveBeenCalledWith(+ agentConfigKeys.config('agent-1', 'user:workspace'),+ );expect(mocks.refreshAgentList).toHaveBeenCalled();});diff --git a/src/features/ResourceTransferRequest/refreshAfterOwnershipChange.ts b/src/features/ResourceTransferRequest/refreshAfterOwnershipChange.tsindex fec40402b4b..9b445f3a65a 100644--- a/src/features/ResourceTransferRequest/refreshAfterOwnershipChange.ts+++ b/src/features/ResourceTransferRequest/refreshAfterOwnershipChange.ts@@ -1,5 +1,6 @@import { mutate } from '@/libs/swr';import { agentConfigKeys, groupKeys } from '@/libs/swr/keys';+import { getCacheScope } from '@/libs/swr/useCacheScope';import { useHomeStore } from '@/store/home';/**@@ -19,7 +20,7 @@ export const refreshCachesAfterOwnershipChange = async (): Promise<void> => {await Promise.all([resourceType === 'agent'- ? mutate(agentConfigKeys.config(resourceId))+ ? mutate(agentConfigKeys.config(resourceId, getCacheScope())): mutate(groupKeys.detail(resourceId)),useHomeStore.getState().refreshAgentList(),]);diff --git a/src/hooks/useInitAgentConfig.test.ts b/src/hooks/useInitAgentConfig.test.tsnew file mode 100644index 00000000000..249258b870f--- /dev/null+++ b/src/hooks/useInitAgentConfig.test.ts@@ -0,0 +1,40 @@+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useAgentStore } from '@/store/agent';+import { useUserStore } from '@/store/user';++import { useInitAgentConfig } from './useInitAgentConfig';++const scope = vi.hoisted(() => ({ current: 'user-1:workspace-a' }));++vi.mock('@/libs/swr/useCacheScope', () => ({ useCacheScope: () => scope.current }));+vi.mock('react-router', () => ({ useParams: () => ({}) }));++describe('useInitAgentConfig', () => {+ beforeEach(() => {+ scope.current = 'user-1:workspace-a';+ useUserStore.setState({ isSignedIn: true } as any);+ act(() => {+ useAgentStore.setState({+ agentConfigScopeMap: { 'agent-1': 'user-1:workspace-a' },+ agentMap: { 'agent-1': { title: 'From workspace A' } },+ useFetchAgentConfig: (() => ({ isLoading: true })) as any,+ });+ });+ });++ it('lets a config cached for the active scope stand in while loading', () => {+ const { result } = renderHook(() => useInitAgentConfig('agent-1'));++ expect(result.current.isLoading).toBe(false);+ });++ it('keeps loading when the cached config belongs to the previous workspace', () => {+ scope.current = 'user-1:workspace-b';++ const { result } = renderHook(() => useInitAgentConfig('agent-1'));++ expect(result.current.isLoading).toBe(true);+ });+});diff --git a/src/hooks/useInitAgentConfig.ts b/src/hooks/useInitAgentConfig.tsindex 90961720e91..312da7678bf 100644--- a/src/hooks/useInitAgentConfig.ts+++ b/src/hooks/useInitAgentConfig.ts@@ -1,6 +1,8 @@import { useParams } from 'react-router';+import { useCacheScope } from '@/libs/swr/useCacheScope';import { useAgentStore } from '@/store/agent';+import { agentByIdSelectors } from '@/store/agent/selectors';import { useUserStore } from '@/store/user';import { authSelectors } from '@/store/user/selectors';@@ -22,6 +24,9 @@ export const useInitAgentConfig = (agentId?: string) => {const id = agentId || params.aid || activeAgentId || '';const data = useFetchAgentConfig(isLogin, id);+ const scope = useCacheScope();+ // Only a config cached for the active scope may stand in while loading.+ const hasConfig = useAgentStore(agentByIdSelectors.hasAgentConfigInScope(id, scope));- return { ...data, isLoading: data.isLoading && isLogin };+ return { ...data, isLoading: data.isLoading && isLogin && !hasConfig };};diff --git a/src/hooks/usePrefetchAgent.test.ts b/src/hooks/usePrefetchAgent.test.tsnew file mode 100644index 00000000000..fe21bc87105--- /dev/null+++ b/src/hooks/usePrefetchAgent.test.ts@@ -0,0 +1,31 @@+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { mutate } from '@/libs/swr';+import { agentConfigKeys } from '@/libs/swr/keys';+import { agentService } from '@/services/agent';++import { usePrefetchAgent } from './usePrefetchAgent';++vi.mock('@/libs/swr', () => ({ mutate: vi.fn() }));+vi.mock('@/libs/swr/useCacheScope', () => ({ getCacheScope: () => 'user-1:workspace-1' }));+vi.mock('@/services/agent', () => ({+ agentService: { getAgentConfigById: vi.fn().mockResolvedValue({ id: 'agent-1' }) },+}));++describe('usePrefetchAgent', () => {+ beforeEach(() => vi.clearAllMocks());++ it('passes one unaugmented identity-scoped key to the scoped mutate wrapper', () => {+ const { result } = renderHook(() => usePrefetchAgent());++ act(() => result.current('agent-1'));++ expect(mutate).toHaveBeenCalledWith(+ agentConfigKeys.config('agent-1', 'user-1:workspace-1'),+ expect.any(Promise),+ { revalidate: false },+ );+ expect(agentService.getAgentConfigById).toHaveBeenCalledWith('agent-1');+ });+});diff --git a/src/hooks/usePrefetchAgent.ts b/src/hooks/usePrefetchAgent.tsindex 08222fc74fb..400e371941b 100644--- a/src/hooks/usePrefetchAgent.ts+++ b/src/hooks/usePrefetchAgent.ts@@ -1,26 +1,22 @@import { useCallback } from 'react';-import { getActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';-import { augmentKey, mutate } from '@/libs/swr';+import { mutate } from '@/libs/swr';import { agentConfigKeys } from '@/libs/swr/keys';+import { getCacheScope } from '@/libs/swr/useCacheScope';import { agentService } from '@/services/agent';/*** Returns a callback to prefetch agent config data into the SWR cache.* Call the returned function on mouseEnter to warm the cache before navigation.*- * Warms the exact key `useFetchAgentConfig` reads — the workspace-augmented- * form of `agentConfigKeys.config(agentId)` — so the prefetch actually hits the- * consumer's cache entry.+ * Warms the exact identity-scoped key `useFetchAgentConfig` reads. The scoped+ * mutate wrapper appends the workspace once; callers must not pre-augment it.*/export const usePrefetchAgent = () => {return useCallback((agentId: string) => {if (!agentId) return;- const key = augmentKey(- agentConfigKeys.config(agentId),- getActiveWorkspaceId(),- ) as readonly unknown[];+ const key = agentConfigKeys.config(agentId, getCacheScope());// Populate the SWR cache without triggering re-renders on consuming hooksmutate(key, agentService.getAgentConfigById(agentId), {diff --git a/src/libs/queryProjectionStorage/index.ts b/src/libs/queryProjectionStorage/index.tsindex 61594cb3286..9526da1afe8 100644--- a/src/libs/queryProjectionStorage/index.ts+++ b/src/libs/queryProjectionStorage/index.ts@@ -1,2 +1,4 @@+export * from './indexedDB';export * from './localStorage';export type * from './types';+export * from './writeQueue';diff --git a/src/libs/queryProjectionStorage/indexedDB.test.ts b/src/libs/queryProjectionStorage/indexedDB.test.tsnew file mode 100644index 00000000000..6827e1bf211--- /dev/null+++ b/src/libs/queryProjectionStorage/indexedDB.test.ts@@ -0,0 +1,30 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { localDatabase } from '@/libs/localDatabase';++import { IndexedDBQueryProjectionStorage } from './indexedDB';++describe('IndexedDBQueryProjectionStorage', () => {+ beforeEach(() => vi.restoreAllMocks());++ it('uses one scoped row per query projection', async () => {+ vi.spyOn(localDatabase, 'initialize').mockResolvedValue();+ const set = vi.spyOn(localDatabase, 'set').mockResolvedValue();+ const storage = new IndexedDBQueryProjectionStorage<string[]>({ namespace: 'projects' });+ const key = { queryKey: 'detail:1', scope: 'user:workspace' };++ await storage.set(key, { data: ['cached'], updatedAt: 1 });++ expect(set).toHaveBeenCalledWith('query-projections', 'projects:user%3Aworkspace:detail%3A1', {+ data: ['cached'],+ updatedAt: 1,+ });+ });++ it('treats persistence failures as a cache miss', async () => {+ vi.spyOn(localDatabase, 'initialize').mockRejectedValue(new Error('unavailable'));+ const storage = new IndexedDBQueryProjectionStorage<string[]>({ namespace: 'projects' });++ await expect(storage.get({ queryKey: 'all', scope: 'personal' })).resolves.toBeUndefined();+ });+});diff --git a/src/libs/queryProjectionStorage/indexedDB.ts b/src/libs/queryProjectionStorage/indexedDB.tsnew file mode 100644index 00000000000..732d7cf2e79--- /dev/null+++ b/src/libs/queryProjectionStorage/indexedDB.ts@@ -0,0 +1,47 @@+import { localDatabase } from '@/libs/localDatabase';++import type { QueryProjection, QueryProjectionKey, QueryProjectionStorage } from './types';++interface IndexedDBQueryProjectionStorageOptions {+ namespace: string;+}++const COLLECTION = 'query-projections';++export class IndexedDBQueryProjectionStorage<T> implements QueryProjectionStorage<T> {+ readonly #namespace: string;++ constructor({ namespace }: IndexedDBQueryProjectionStorageOptions) {+ this.#namespace = namespace;+ }++ #key = ({ queryKey, scope }: QueryProjectionKey) =>+ `${this.#namespace}:${encodeURIComponent(scope)}:${encodeURIComponent(queryKey)}`;++ get = async (key: QueryProjectionKey): Promise<QueryProjection<T> | undefined> => {+ try {+ await localDatabase.initialize();+ return await localDatabase.get<QueryProjection<T>>(COLLECTION, this.#key(key));+ } catch {+ return undefined;+ }+ };++ remove = async (key: QueryProjectionKey): Promise<void> => {+ try {+ await localDatabase.initialize();+ await localDatabase.delete(COLLECTION, this.#key(key));+ } catch {+ // Projection persistence is best-effort; the server remains the durable SoT.+ }+ };++ set = async (key: QueryProjectionKey, projection: QueryProjection<T>): Promise<void> => {+ try {+ await localDatabase.initialize();+ await localDatabase.set(COLLECTION, this.#key(key), projection);+ } catch {+ // Projection persistence is best-effort; the server remains the durable SoT.+ }+ };+}diff --git a/src/libs/queryProjectionStorage/writeQueue.test.ts b/src/libs/queryProjectionStorage/writeQueue.test.tsnew file mode 100644index 00000000000..eff23aafbf9--- /dev/null+++ b/src/libs/queryProjectionStorage/writeQueue.test.ts@@ -0,0 +1,29 @@+import { describe, expect, it, vi } from 'vitest';++import type { QueryProjectionStorage } from './types';+import { QueryProjectionWriteQueue } from './writeQueue';++describe('QueryProjectionWriteQueue', () => {+ it('serializes writes for the same projection key', async () => {+ let releaseFirst!: () => void;+ const first = new Promise<void>((resolve) => (releaseFirst = resolve));+ const calls: number[] = [];+ const storage: QueryProjectionStorage<number> = {+ get: vi.fn(),+ remove: vi.fn(),+ set: vi.fn(async (_key, projection) => {+ calls.push(projection.data);+ if (projection.data === 1) await first;+ }),+ };+ const queue = new QueryProjectionWriteQueue(storage);+ const key = { queryKey: 'list', scope: 'scope' };++ queue.set(key, { data: 1, updatedAt: 1 });+ queue.set(key, { data: 2, updatedAt: 2 });+ await vi.waitFor(() => expect(calls).toEqual([1]));++ releaseFirst();+ await vi.waitFor(() => expect(calls).toEqual([1, 2]));+ });+});diff --git a/src/libs/queryProjectionStorage/writeQueue.ts b/src/libs/queryProjectionStorage/writeQueue.tsnew file mode 100644index 00000000000..8481e275aa2--- /dev/null+++ b/src/libs/queryProjectionStorage/writeQueue.ts@@ -0,0 +1,36 @@+import type { QueryProjection, QueryProjectionKey, QueryProjectionStorage } from './types';++/**+ * Serializes writes for one projection key. A later snapshot can never be overwritten by an+ * earlier, slower IndexedDB write.+ */+export class QueryProjectionWriteQueue<T> {+ readonly #pending = new Map<string, Promise<void>>();+ readonly #storage: QueryProjectionStorage<T>;++ constructor(storage: QueryProjectionStorage<T>) {+ this.#storage = storage;+ }++ #id = ({ queryKey, scope }: QueryProjectionKey) => `${scope}:${queryKey}`;++ remove = (key: QueryProjectionKey): void => {+ this.#enqueue(key, () => this.#storage.remove(key));+ };++ set = (key: QueryProjectionKey, value: QueryProjection<T>): void => {+ this.#enqueue(key, () => this.#storage.set(key, value));+ };++ #enqueue = (key: QueryProjectionKey, operation: () => Promise<void>): void => {+ const id = this.#id(key);+ const previous = this.#pending.get(id) ?? Promise.resolve();+ const current = previous.catch(() => undefined).then(operation);+ this.#pending.set(id, current);+ void current+ .catch(() => undefined)+ .finally(() => {+ if (this.#pending.get(id) === current) this.#pending.delete(id);+ });+ };+}diff --git a/src/libs/swr/keys.test.ts b/src/libs/swr/keys.test.tsindex 4329c9bfab9..5bb57d873fb 100644--- a/src/libs/swr/keys.test.ts+++ b/src/libs/swr/keys.test.ts@@ -3,9 +3,13 @@ import { describe, expect, it } from 'vitest';import {agentBuilderKeys,+ agentConfigKeys,+ agentKeys,+ agentProjectionKeys,documentCommentKeys,isAcceptanceListKey,isDocumentCommentKeyForEvent,+ projectKeys,recentKeys,resourceKeys,taskKeys,@@ -64,6 +68,48 @@ describe('recentKeys', () => {});});+describe('agent projection keys', () => {+ it('keeps network sync and hydration isolated by identity scope', () => {+ expect(agentKeys.list(true, 'user-1:workspace-1')).not.toEqual(+ agentKeys.list(true, 'user-2:workspace-1'),+ );+ expect(agentConfigKeys.config('agent-1', 'user-1:workspace-1')).not.toEqual(+ agentConfigKeys.config('agent-1', 'user-1:workspace-2'),+ );+ expect(agentProjectionKeys.configHydration('user-1:workspace-1', 'agent-1')).toEqual([+ 'agentProjection:configHydration',+ 'user-1:workspace-1',+ 'agent-1',+ ]);+ });++ it('keeps SWR orchestration entries out of the persistence tiers', () => {+ for (const key of [+ agentKeys.list(true, 'user-1:personal'),+ agentConfigKeys.config('agent-1', 'user-1:personal'),+ ]) {+ const serialized = unstable_serialize(key);+ expect(+ [...CACHE_TIERS.idb, ...CACHE_TIERS.local].some((pattern) => serialized.includes(pattern)),+ ).toBe(false);+ }+ });+});++describe('projectKeys', () => {+ it('uses the same scoped factory family for list, detail, and hydration', () => {+ expect(projectKeys.list('user-1:workspace-1')).toEqual(['project:list', 'user-1:workspace-1']);+ expect(projectKeys.detail('user-1:workspace-1', 'project-1')).toEqual([+ 'project:detail',+ 'user-1:workspace-1',+ 'project-1',+ ]);+ expect(projectKeys.listHydration('user-1:workspace-1')).not.toEqual(+ projectKeys.listHydration('user-1:workspace-2'),+ );+ });+});+describe('isAcceptanceListKey', () => {it('matches every Acceptance list variant without matching detail keys', () => {expect(isAcceptanceListKey(['verify:acceptances', '', '', 'active'])).toBe(true);diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex c0660e04e85..311d63ad850 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -251,8 +251,27 @@ export const isDocumentCommentKeyForEvent = (// ---- agent --------------------------------------------------------------export const agentKeys = {- /** Sidebar agent list. */- list: def('agent:list', (isLogin: boolean) => ['agent:list', isLogin]),+ /** Sidebar agent list network sync. Zustand owns the persisted UI projection. */+ list: def('agentSync:list', (isLogin: boolean, scope: string) => [+ 'agentSync:list',+ isLogin,+ scope,+ ]),+};++export const isAgentListKey = (key: unknown, scope: string): boolean =>+ Array.isArray(key) && key[0] === agentKeys.list.root && key[2] === scope;++export const agentProjectionKeys = {+ configHydration: def('agentProjection:configHydration', (scope: string, agentId: string) => [+ 'agentProjection:configHydration',+ scope,+ agentId,+ ]),+ listHydration: def('agentProjection:listHydration', (scope: string) => [+ 'agentProjection:listHydration',+ scope,+ ]),};// ---- agent labels -------------------------------------------------------@@ -537,13 +556,40 @@ export const homeInboxKeys = {// (agentKeys.list defined above)export const agentConfigKeys = {available: def('agent:available', () => ['agent:available']),- config: def('agent:config', (agentId: string) => ['agent:config', agentId]),+ config: def('agentSync:config', (agentId: string, scope: string) => [+ 'agentSync:config',+ agentId,+ scope,+ ]),search: def('agent:search', (keyword?: string) => ['agent:search', keyword]),serverDefaultHeterogeneousCapability: def('agent:serverDefaultHeterogeneousCapability', () => ['agent:serverDefaultHeterogeneousCapability',]),};+export const isAgentConfigKey = (key: unknown, agentId: string, scope: string): boolean =>+ Array.isArray(key) &&+ key[0] === agentConfigKeys.config.root &&+ key[1] === agentId &&+ key[2] === scope;++// ---- project ------------------------------------------------------------+export const projectKeys = {+ detail: def('project:detail', (scope: string, id: string) => ['project:detail', scope, id]),+ detailHydration: def('project:detailHydration', (scope: string, id: string) => [+ 'project:detailHydration',+ scope,+ id,+ ]),+ list: def('project:list', (scope: string) => ['project:list', scope]),+ listHydration: def('project:listHydration', (scope: string) => ['project:listHydration', scope]),+};++export const isProjectDetailKey = (key: unknown, scope: string, id: string): boolean =>+ Array.isArray(key) && key[0] === projectKeys.detail.root && key[1] === scope && key[2] === id;+export const isProjectListKey = (key: unknown, scope: string): boolean =>+ Array.isArray(key) && key[0] === projectKeys.list.root && key[1] === scope;+// ---- aiModel ------------------------------------------------------------export const aiModelKeys = {disabledModelsPage: def('aiModel:disabledModelsPage', (providerId: string, offset: number) => [@@ -1529,7 +1575,7 @@ export const matchDomain =* Aggregate registry — one entry point for every domain's keys.*/export const swrKeys = {- agent: { ...agentKeys, ...agentConfigKeys },+ agent: { ...agentKeys, ...agentConfigKeys, ...agentProjectionKeys },agentBot: agentBotKeys,agentBuilder: agentBuilderKeys,agentDocument: agentDocumentSWRKeys,@@ -1571,6 +1617,7 @@ export const swrKeys = {onboarding: onboardingKeys,openInApp: openInAppKeys,portal: portalKeys,+ project: projectKeys,provider: providerKeys,ragEval: ragEvalKeys,recent: recentKeys,diff --git a/src/libs/swr/useClientDataSWRWithSync.ts b/src/libs/swr/useClientDataSWRWithSync.tsindex 07749b3d699..79b3e2c2192 100644--- a/src/libs/swr/useClientDataSWRWithSync.ts+++ b/src/libs/swr/useClientDataSWRWithSync.ts@@ -38,7 +38,7 @@ interface UseClientDataSWRWithSyncOptions<T> extends SWRConfiguration<T> {* @example* ```ts* useClientDataSWRWithSync(- * isLogin ? agentKeys.list(isLogin) : null,+ * isLogin ? agentKeys.list(isLogin, scope) : null,* () => homeService.getSidebarAgentList(),* {* onData: (data) => {diff --git a/src/store/agent/selectors/agentByIdSelectors.test.ts b/src/store/agent/selectors/agentByIdSelectors.test.tsindex 97888961143..a9328981774 100644--- a/src/store/agent/selectors/agentByIdSelectors.test.ts+++ b/src/store/agent/selectors/agentByIdSelectors.test.ts@@ -210,6 +210,25 @@ describe('agentByIdSelectors', () => {});});+ describe('hasAgentConfigInScope', () => {+ it('only treats a cached config as renderable in the scope that wrote it', () => {+ const state = createState({+ agentConfigScopeMap: { 'agent-1': 'user-1:workspace-a' },+ agentMap: { 'agent-1': { title: 'From workspace A' } },+ });++ expect(agentByIdSelectors.hasAgentConfigInScope('agent-1', 'user-1:workspace-a')(state)).toBe(+ true,+ );+ // After a workspace switch the entry is still in `agentMap`, but it+ // belongs to the previous scope.+ expect(agentByIdSelectors.hasAgentConfigInScope('agent-1', 'user-1:workspace-b')(state)).toBe(+ false,+ );+ expect(agentByIdSelectors.hasAgentConfigInScope('', 'user-1:workspace-a')(state)).toBe(false);+ });+ });+describe('isAgentNotFoundById', () => {it('returns true only for agents flagged in agentNotFoundMap', () => {const state = createState({ agentNotFoundMap: { 'agent-gone': true } });diff --git a/src/store/agent/selectors/agentByIdSelectors.ts b/src/store/agent/selectors/agentByIdSelectors.tsindex 4c9f41394cd..89c45137a48 100644--- a/src/store/agent/selectors/agentByIdSelectors.ts+++ b/src/store/agent/selectors/agentByIdSelectors.ts@@ -83,6 +83,16 @@ const isAgentConfigLoadingById = (agentId: string) => (s: AgentStoreState) =>// data-presence check would report "loading" forever.!agentId || (!s.agentMap[agentId] && !s.agentNotFoundMap[agentId]);+/**+ * Whether the cached config for `agentId` belongs to `scope` and may be+ * rendered. `agentMap` is not partitioned by workspace, so an entry left by+ * the previous scope must not stand in for the active one while it loads.+ */+const hasAgentConfigInScope =+ (agentId: string, scope: string) =>+ (s: AgentStoreState): boolean =>+ !!agentId && !!s.agentMap[agentId] && s.agentConfigScopeMap[agentId] === scope;+/*** Get agent mode by agentId.* Agent mode is the default — only an explicit `chatConfig.enableAgentMode === false`@@ -227,6 +237,7 @@ export const agentByIdSelectors = {getAgentTTSById,getAgentTTSVoiceById,getAgentWorkingDirectoryById,+ hasAgentConfigInScope,isAgentConfigLoadingById,isAgentHeterogeneousById,isAgentNotFoundById,diff --git a/src/store/agent/slices/agent/action.test.ts b/src/store/agent/slices/agent/action.test.tsindex 68f831d18cd..28f844aaaa4 100644--- a/src/store/agent/slices/agent/action.test.ts+++ b/src/store/agent/slices/agent/action.test.ts@@ -9,6 +9,7 @@ import * as activeWorkspaceModule from '@/business/client/hooks/useActiveWorkspaimport { setScopedMutate } from '@/libs/swr';import { agentConfigKeys, builtinAgentKeys } from '@/libs/swr/keys';import * as cacheScopeModule from '@/libs/swr/useCacheScope';+import { getCacheScope } from '@/libs/swr/useCacheScope';import { agentService } from '@/services/agent';import { agentDocumentService } from '@/services/agentDocument';import { useGlobalStore } from '@/store/global';@@ -150,9 +151,13 @@ describe('AgentSlice Actions', () => {.optimisticUpdateAgentMeta('inbox-1', { name: 'Renamed chief' });expect(agentService.getBuiltinAgent).not.toHaveBeenCalled();- expect(scopedMutate).toHaveBeenCalledWith(agentConfigKeys.config('inbox-1'), updatedAgent, {- revalidate: false,- });+ expect(scopedMutate).toHaveBeenCalledWith(+ agentConfigKeys.config('inbox-1', getCacheScope()),+ updatedAgent,+ {+ revalidate: false,+ },+ );expect(scopedMutate).toHaveBeenCalledWith(builtinAgentKeys.init('inbox', cacheScopeModule.getCacheScope()),updatedAgent,@@ -197,7 +202,8 @@ describe('AgentSlice Actions', () => {expect(scopedMutate.mock.calls.some(([key]) =>- JSON.stringify(key) === JSON.stringify(agentConfigKeys.config('inbox-1')) ||+ JSON.stringify(key) ===+ JSON.stringify(agentConfigKeys.config('inbox-1', getCacheScope())) ||JSON.stringify(key) ===JSON.stringify(builtinAgentKeys.init('inbox', 'user-b:personal')),),@@ -888,7 +894,7 @@ describe('AgentSlice Actions', () => {expect(toast.error).toHaveBeenCalled();// Optimistic value must not survive a rejected write — refetch server truth.- expect(refreshSpy).toHaveBeenCalledWith('agent-1');+ expect(refreshSpy).toHaveBeenCalledWith('agent-1', undefined, getCacheScope());expect(result.current.saveStatus).toBe('idle');});@@ -1139,7 +1145,7 @@ describe('AgentSlice Actions', () => {// Note: refreshSessions is no longer called after optimistic update// as the implementation now uses API returned data directly- it('should refresh agent config SWR cache after a confirmed config update', async () => {+ it('seeds the scoped config cache with the confirmed response without another request', async () => {const { result } = renderHook(() => useAgentStore());const scopedMutate = vi.fn().mockResolvedValue(undefined);setScopedMutate(scopedMutate as any);@@ -1162,10 +1168,11 @@ describe('AgentSlice Actions', () => {});});- const configCacheCalls = scopedMutate.mock.calls.filter(- ([key]) => JSON.stringify(key) === JSON.stringify(agentConfigKeys.config('agent-1')),+ expect(scopedMutate).toHaveBeenCalledWith(+ agentConfigKeys.config('agent-1', getCacheScope()),+ { id: 'agent-1', model: 'model-b', provider: 'lobehub' },+ { revalidate: false },);- expect(configCacheCalls).toEqual([[agentConfigKeys.config('agent-1')]]);});it('should not refresh agent config SWR cache when save fails', async () => {@@ -1189,10 +1196,14 @@ describe('AgentSlice Actions', () => {});});- const configCacheCalls = scopedMutate.mock.calls.filter(- ([key]) => JSON.stringify(key) === JSON.stringify(agentConfigKeys.config('agent-1')),- );- expect(configCacheCalls).toHaveLength(0);+ const configCacheMatchers = scopedMutate.mock.calls+ .map(([key]) => key)+ .filter((key): key is (candidate: unknown) => boolean => typeof key === 'function');+ expect(+ configCacheMatchers.some((matcher) =>+ matcher(agentConfigKeys.config('agent-1', getCacheScope())),+ ),+ ).toBe(false);expect(result.current.agentMap['agent-1']).toMatchObject({ model: 'model-b' });});});@@ -1234,6 +1245,22 @@ describe('AgentSlice Actions', () => {expect(result.current.availableAgents).toBeUndefined();});+ it('rolls back and rethrows when an optimistic projection owns the failure UI', async () => {+ const { result } = renderHook(() => useAgentStore());+ vi.mocked(agentService.updateAgentMeta).mockRejectedValue(new Error('save failed'));+ act(() => {+ useAgentStore.setState({ agentMap: { 'agent-1': { title: 'Original' } as any } });+ });++ await expect(+ result.current.optimisticUpdateAgentMeta('agent-1', { title: 'Renamed' }, undefined, {+ rethrow: true,+ }),+ ).rejects.toThrow('save failed');++ expect(result.current.agentMap['agent-1']?.title).toBe('Original');+ });+// Note: refreshSessions is no longer called after optimistic update// as the implementation now uses API returned data directly});diff --git a/src/store/agent/slices/agent/action.ts b/src/store/agent/slices/agent/action.tsindex 506d8c242d9..d042b182dcc 100644--- a/src/store/agent/slices/agent/action.ts+++ b/src/store/agent/slices/agent/action.ts@@ -17,7 +17,13 @@ import { getActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceimport { MESSAGE_CANCEL_FLAT } from '@/const/message';import { analyticsClient } from '@/libs/analytics/client';import { mutate, useClientDataSWR, useClientDataSWRWithSync } from '@/libs/swr';-import { agentConfigKeys, builtinAgentKeys } from '@/libs/swr/keys';+import {+ agentConfigKeys,+ agentProjectionKeys,+ builtinAgentKeys,+ isAgentConfigKey,+ isAgentListKey,+} 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';@@ -45,8 +51,10 @@ import type { AgentStore } from '../../store';import { heteroAgentDefaultName } from '../../utils/heteroAgentDefaultName';import { setLocalAgentWorkingDirectory } from '../../utils/localAgentWorkingDirectoryStorage';import type { AgentSliceState, LoadingState, SaveStatus } from './initialState';+import { agentConfigProjection, agentConfigWriteQueue } from './projection';+import { agentConfigReducer } from './reducer';-type AgentMetaUpdate = Partial<+export type AgentMetaUpdate = Partial<Pick<AgentItem,| 'avatar'@@ -70,6 +78,11 @@ interface AgentConfigUpdateOptions {showErrorMessage?: boolean;}+interface AgentMetaUpdateOptions {+ /** Propagate persistence failure to an optimistic projection so it can roll back. */+ rethrow?: boolean;+}+const preserveWorkingDirDeleteMarkers = (merged: LobeAgentAgencyConfig,patch: AgencyConfigPatch,@@ -113,6 +126,35 @@ export class AgentSliceActionImpl {this.#get = get;}+ #hydrateAgentConfig = async (agentId: string, scope: string): Promise<number> => {+ const cached = await agentConfigProjection.get({ queryKey: agentId, scope });+ if (!cached || getCacheScope() !== scope) return Date.now();++ const transition = agentConfigReducer(this.#get(), {+ data: cached.data,+ id: agentId,+ scope,+ type: 'hydrate',+ });+ this.#set(transition.state, false, 'hydrateAgentConfig');+ return Date.now();+ };++ #replaceConfirmedAgentConfig = (agentId: string, scope: string, data: LobeAgentConfig): void => {+ const transition = agentConfigReducer(this.#get(), {+ data,+ id: agentId,+ scope,+ type: 'replace',+ });+ this.#set(transition.state, false, 'replaceConfirmedAgentConfig');+ for (const effect of transition.effects)+ agentConfigWriteQueue.set(+ { queryKey: effect.id, scope: effect.scope },+ { data: effect.data, updatedAt: Date.now() },+ );+ };+#createAgentScopedAbortController = (controllers: Map<string, AbortController>,agentId: string,@@ -370,7 +412,11 @@ export class AgentSliceActionImpl {await this.#get().updateAgentMetaById(activeAgentId, meta);};- updateAgentMetaById = async (agentId: string, meta: AgentMetaUpdate): Promise<void> => {+ updateAgentMetaById = async (+ agentId: string,+ meta: AgentMetaUpdate,+ options?: AgentMetaUpdateOptions,+ ): Promise<void> => {if (!agentId) return;const controller = this.#createAgentScopedAbortController(@@ -379,7 +425,7 @@ export class AgentSliceActionImpl {);try {- await this.#get().optimisticUpdateAgentMeta(agentId, meta, controller.signal);+ await this.#get().optimisticUpdateAgentMeta(agentId, meta, controller.signal, options);} finally {if (this.#updateAgentMetaControllers.get(agentId) === controller) {this.#updateAgentMetaControllers.delete(agentId);@@ -410,19 +456,24 @@ export class AgentSliceActionImpl {isLogin: boolean | undefined,agentId: string,): SWRResponse<LobeAgentConfig> => {+ const scope = getCacheScope();const swrKey =isLogin === true && agentId && !isChatGroupSessionId(agentId)- ? agentConfigKeys.config(agentId)+ ? agentConfigKeys.config(agentId, scope): null;- return useClientDataSWRWithSync<LobeAgentConfig>(+ useClientDataSWR(swrKey ? agentProjectionKeys.configHydration(scope, agentId) : null, () =>+ this.#hydrateAgentConfig(agentId, scope),+ );++ return useClientDataSWR<LobeAgentConfig>(swrKey,async () => {const data = await agentService.getAgentConfigById(agentId);return data as LobeAgentConfig;},{- onData: (data) => {+ onSuccess: (data) => {// A successful fetch that resolves to null means the agent doesn't// exist or the caller lost access (e.g. a workspace agent switched// back to private) — a settled state, not "still loading".@@ -435,13 +486,8 @@ export class AgentSliceActionImpl {// Replace the cached entry instead of applying patch semantics: fields// cleared on the server (for example editorData: null) may be omitted// from the response and must not survive from an older local profile.- if (!isEqual(this.#get().agentMap[agentId], data)) {- this.#set(- (state) => ({ agentMap: { ...state.agentMap, [agentId]: data } }),- false,- 'fetchAgentConfig',- );- }+ if (getCacheScope() !== scope) return;+ this.#replaceConfirmedAgentConfig(agentId, scope, data);// Only adopt the fetched agent as the active one when nothing is// active yet. The active agent is owned by the route-level sync// (AgentIdSync on desktop/mobile, the popup pages' own setState).@@ -485,12 +531,11 @@ export class AgentSliceActionImpl {retryAgentConfigFetch = async (agentId?: string): Promise<void> => {const id = agentId ?? this.#get().activeAgentId;if (!id) return;+ const scope = getCacheScope();this.#clearAgentConfigError(id);- await mutate(- (key) => Array.isArray(key) && key[0] === agentConfigKeys.config.root && key[1] === id,- );+ await mutate((key) => isAgentConfigKey(key, id, scope));};#markAgentNotFound = (agentId: string) => {@@ -512,6 +557,7 @@ export class AgentSliceActionImpl {false,'markAgentNotFound',);+ agentConfigWriteQueue.remove({ queryKey: agentId, scope: getCacheScope() });};#clearAgentNotFound = (agentId: string) => {@@ -546,25 +592,30 @@ export class AgentSliceActionImpl {isLogin: boolean | undefined,agentId: string,): SWRResponse<LobeAgentConfig> => {+ const scope = getCacheScope();const swrKey =isLogin === true && agentId && !isChatGroupSessionId(agentId)- ? agentConfigKeys.config(agentId)+ ? agentConfigKeys.config(agentId, scope): null;- return useClientDataSWRWithSync<LobeAgentConfig>(+ useClientDataSWR(swrKey ? agentProjectionKeys.configHydration(scope, agentId) : null, () =>+ this.#hydrateAgentConfig(agentId, scope),+ );++ return useClientDataSWR<LobeAgentConfig>(swrKey,async () => {const data = await agentService.getAgentConfigById(agentId);return data as LobeAgentConfig;},{- onData: (data) => {+ onSuccess: (data) => {if (!data) {this.#markAgentNotFound(agentId);return;}this.#clearAgentNotFound(agentId);- this.#get().internal_dispatchAgentMap(agentId, data);+ if (getCacheScope() === scope) this.#replaceConfirmedAgentConfig(agentId, scope, data);},},);@@ -674,6 +725,7 @@ export class AgentSliceActionImpl {): Promise<void> => {const { internal_dispatchAgentMap, updateSaveStatus } = this.#get();const mergedData = this.#mergeLatestAgencyConfigPatch(id, data);+ const scope = getCacheScope();// 1. Optimistic update (instant UI feedback)internal_dispatchAgentMap(id, mergedData);@@ -686,9 +738,11 @@ export class AgentSliceActionImpl {// 3. Apply returned data, then invalidate the SWR key for later subscribers.if (result?.success && result.agent) {internal_dispatchAgentMap(id, result.agent);+ const confirmed = this.#get().agentMap[id];+ if (confirmed) this.#replaceConfirmedAgentConfig(id, scope, confirmed as LobeAgentConfig);// Refresh agent:config so cached model A cannot replay after a// successful model A -> B update.- await this.#get().internal_refreshAgentConfig(id);+ await this.#get().internal_refreshAgentConfig(id, result.agent, scope);this.#get().invalidateAvailableAgents();}updateSaveStatus('saved');@@ -710,7 +764,7 @@ export class AgentSliceActionImpl {// just shows a selection that never persisted. Other config fields keep// the optimistic value on purpose — refetching would clobber in-flight// form edits on a transient failure (see #16337).- if (data.agencyConfig) await this.#get().internal_refreshAgentConfig(id);+ if (data.agencyConfig) await this.#get().internal_refreshAgentConfig(id, undefined, scope);}if (options?.rethrow) throw error;}@@ -720,9 +774,11 @@ export class AgentSliceActionImpl {id: string,meta: AgentMetaUpdate,signal?: AbortSignal,+ options?: AgentMetaUpdateOptions,): Promise<void> => {const { internal_dispatchAgentMap, updateSaveStatus } = this.#get();const scope = getCacheScope();+ const previous = this.#get().agentMap[id];// 1. Optimistic update - meta fields are at the top level of agent configinternal_dispatchAgentMap(id, meta as PartialDeep<LobeAgentConfig>);@@ -736,16 +792,28 @@ export class AgentSliceActionImpl {// 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);+ const confirmed = this.#get().agentMap[id];+ if (confirmed) this.#replaceConfirmedAgentConfig(id, scope, confirmed as LobeAgentConfig);+ await this.#get().internal_refreshAgentConfig(id, result.agent, scope);+ void mutate((key) => isAgentListKey(key, scope));this.#get().invalidateAvailableAgents();}updateSaveStatus('saved');} catch (error: any) {- if (error?.name === 'AbortError' || error?.message?.includes('aborted')) {+ if (signal?.aborted || error?.name === 'AbortError' || error?.message?.includes('aborted')) {updateSaveStatus('idle');} else {console.error('[AgentStore] Failed to save meta:', error);updateSaveStatus('idle');+ if (options?.rethrow) {+ if (previous) this.#replaceConfirmedAgentConfig(id, scope, previous as LobeAgentConfig);+ else {+ const agentMap = { ...this.#get().agentMap };+ delete agentMap[id];+ this.#set({ agentMap }, false, 'rollbackAgentMeta');+ }+ throw error;+ }}}};@@ -753,6 +821,7 @@ export class AgentSliceActionImpl {internal_refreshAgentConfig = async (id: string,updatedAgent?: LobeAgentConfig,+ scope = getCacheScope(),): Promise<void> => {/** Keep related agent and builtin-agent snapshots current after a successful edit. */const slugs = Object.entries(this.#get().builtinAgentIdMap)@@ -761,9 +830,8 @@ export class AgentSliceActionImpl {/** 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 }),+ mutate(agentConfigKeys.config(id, scope), updatedAgent, { revalidate: false }),...slugs.map((slug) =>mutate(builtinAgentKeys.init(slug, scope), updatedAgent as AgentItem, {revalidate: false,@@ -774,7 +842,7 @@ export class AgentSliceActionImpl {}await Promise.all([- mutate(agentConfigKeys.config(id)),+ mutate((key) => isAgentConfigKey(key, id, scope)),...slugs.map((slug) => this.#get().refreshBuiltinAgent(slug)),]);};diff --git a/src/store/agent/slices/agent/initialState.ts b/src/store/agent/slices/agent/initialState.tsindex 2c871cfa7ee..9f0139a379e 100644--- a/src/store/agent/slices/agent/initialState.ts+++ b/src/store/agent/slices/agent/initialState.ts@@ -19,6 +19,8 @@ export interface AgentSliceState {* (e.g. 401s are not retried by SWR). Cleared on successful fetch / retry.*/agentConfigErrorMap: Record<string, string>;+ agentConfigScopeMap: Record<string, string>;+ agentConfigSourceMap: Record<string, 'server' | 'storage'>;agentDocumentsMap: Record<string, AgentContextDocument[]>;agentMap: Record<string, PartialDeep<AgentItem>>;/**@@ -76,6 +78,8 @@ export interface AgentSliceState {export const initialAgentSliceState: AgentSliceState = {agentConfigErrorMap: {},+ agentConfigScopeMap: {},+ agentConfigSourceMap: {},agentDocumentsMap: {},agentMap: {},agentNotFoundMap: {},diff --git a/src/store/agent/slices/agent/projection.ts b/src/store/agent/slices/agent/projection.tsnew file mode 100644index 00000000000..7c9bd88ba4c--- /dev/null+++ b/src/store/agent/slices/agent/projection.ts@@ -0,0 +1,10 @@+import {+ IndexedDBQueryProjectionStorage,+ QueryProjectionWriteQueue,+} from '@/libs/queryProjectionStorage';+import type { LobeAgentConfig } from '@/types/agent';++export const agentConfigProjection = new IndexedDBQueryProjectionStorage<LobeAgentConfig>({+ namespace: 'lobechat-agent-config-v1',+});+export const agentConfigWriteQueue = new QueryProjectionWriteQueue(agentConfigProjection);diff --git a/src/store/agent/slices/agent/reducer.test.ts b/src/store/agent/slices/agent/reducer.test.tsnew file mode 100644index 00000000000..29639110a41--- /dev/null+++ b/src/store/agent/slices/agent/reducer.test.ts@@ -0,0 +1,47 @@+import { describe, expect, it } from 'vitest';++import type { LobeAgentConfig } from '@/types/agent';++import { initialAgentSliceState } from './initialState';+import { agentConfigReducer } from './reducer';++const config = (title: string) => ({ id: 'agent-1', title }) as LobeAgentConfig;++describe('agentConfigReducer', () => {+ it('hydrates without persisting the storage snapshot again', () => {+ const transition = agentConfigReducer(initialAgentSliceState, {+ data: config('Cached'),+ id: 'agent-1',+ scope: 'personal',+ type: 'hydrate',+ });+ expect(transition.state.agentMap?.['agent-1']?.title).toBe('Cached');+ expect(transition.effects).toEqual([]);+ });++ it('rejects late storage hydration after the server projection is installed', () => {+ const server = agentConfigReducer(initialAgentSliceState, {+ data: config('Server'),+ id: 'agent-1',+ scope: 'personal',+ type: 'replace',+ });+ const transition = agentConfigReducer(+ { ...initialAgentSliceState, ...server.state },+ { data: config('Cached'), id: 'agent-1', scope: 'personal', type: 'hydrate' },+ );+ expect(transition.state).toEqual({});+ });++ it('emits persistence only for confirmed server data', () => {+ const transition = agentConfigReducer(initialAgentSliceState, {+ data: config('Server'),+ id: 'agent-1',+ scope: 'personal',+ type: 'replace',+ });+ expect(transition.effects).toEqual([+ { data: config('Server'), id: 'agent-1', scope: 'personal', type: 'persist' },+ ]);+ });+});diff --git a/src/store/agent/slices/agent/reducer.ts b/src/store/agent/slices/agent/reducer.tsnew file mode 100644index 00000000000..aae81577951--- /dev/null+++ b/src/store/agent/slices/agent/reducer.ts@@ -0,0 +1,54 @@+import isEqual from 'fast-deep-equal';+import type { PartialDeep } from 'type-fest';++import type { LobeAgentConfig } from '@/types/agent';++import type { AgentSliceState } from './initialState';++export type AgentConfigEffect = {+ data: LobeAgentConfig;+ id: string;+ scope: string;+ type: 'persist';+};+export type AgentConfigDispatchAction = {+ data: LobeAgentConfig;+ id: string;+ scope: string;+ type: 'hydrate' | 'replace';+};+export interface AgentConfigTransition {+ effects: AgentConfigEffect[];+ state: Partial<AgentSliceState>;+}++export const agentConfigReducer = (+ state: AgentSliceState,+ action: AgentConfigDispatchAction,+): AgentConfigTransition => {+ if (+ action.type === 'hydrate' &&+ state.agentConfigScopeMap[action.id] === action.scope &&+ state.agentConfigSourceMap[action.id] === 'server'+ )+ return { effects: [], state: {} };++ const agentMap = isEqual(state.agentMap[action.id], action.data)+ ? state.agentMap+ : { ...state.agentMap, [action.id]: action.data as PartialDeep<LobeAgentConfig> };++ return {+ effects:+ action.type === 'replace'+ ? [{ data: action.data, id: action.id, scope: action.scope, type: 'persist' }]+ : [],+ state: {+ agentConfigScopeMap: { ...state.agentConfigScopeMap, [action.id]: action.scope },+ agentConfigSourceMap: {+ ...state.agentConfigSourceMap,+ [action.id]: action.type === 'replace' ? 'server' : 'storage',+ },+ agentMap,+ },+ };+};diff --git a/src/store/home/slices/agentList/action.ts b/src/store/home/slices/agentList/action.tsindex 40d6e5ef74f..e6ab9c9b230 100644--- a/src/store/home/slices/agentList/action.ts+++ b/src/store/home/slices/agentList/action.ts@@ -1,16 +1,19 @@-import isEqual from 'fast-deep-equal';+import type { SidebarAgentItem, SidebarAgentListResponse } from '@lobechat/types';import { type SWRResponse } from 'swr';-import { type SidebarAgentItem, type SidebarAgentListResponse } from '@/database/repositories/home';-import { mutate, useClientDataSWR, useClientDataSWRWithSync } from '@/libs/swr';-import { agentConfigKeys, agentKeys } from '@/libs/swr/keys';+import { mutate, useClientDataSWR } from '@/libs/swr';+import { agentConfigKeys, agentKeys, agentProjectionKeys, isAgentListKey } from '@/libs/swr/keys';+import { getCacheScope } from '@/libs/swr/useCacheScope';import { homeService } from '@/services/home';import { getAgentStoreState } from '@/store/agent';import { type HomeStore } from '@/store/home/store';import { type StoreSetter } from '@/store/types';import { setNamespace } from '@/utils/storeDebug';-import { mapResponseToState } from './initialState';+import type { SidebarAgentMetaPatch } from './initialState';+import { AGENT_LIST_QUERY, agentListProjection, agentListWriteQueue } from './projection';+import type { AgentListDispatchAction } from './reducer';+import { agentListReducer } from './reducer';const n = setNamespace('agentList');@@ -21,6 +24,7 @@ export const createAgentListSlice = (set: Setter, get: () => HomeStore, _api?: uexport class AgentListActionImpl {readonly #get: () => HomeStore;readonly #set: Setter;+ #updateMutationId = 0;constructor(set: Setter, get: () => HomeStore, _api?: unknown) {void _api;@@ -37,40 +41,56 @@ export class AgentListActionImpl {};refreshAgentList = async (): Promise<void> => {+ const scope = getCacheScope();getAgentStoreState().invalidateAvailableAgents();- await mutate(agentKeys.list(true));+ await mutate((key) => isAgentListKey(key, scope));+ };++ internal_dispatchAgentList = (action: AgentListDispatchAction): void => {+ const transition = agentListReducer(this.#get(), action);+ this.#set(transition.state, false, n(`dispatch/${action.type}`));+ for (const effect of transition.effects) {+ agentListWriteQueue.set(+ { queryKey: AGENT_LIST_QUERY, scope: effect.scope },+ { data: effect.data, updatedAt: Date.now() },+ );+ }+ };++ updateAgentMeta = async (id: string, patch: SidebarAgentMetaPatch): Promise<void> => {+ const scope = getCacheScope();+ const mutationId = ++this.#updateMutationId;+ this.internal_dispatchAgentList({ id, mutationId, patch, scope, type: 'optimisticUpdate' });++ try {+ await getAgentStoreState().updateAgentMetaById(id, patch, { rethrow: true });+ this.internal_dispatchAgentList({ id, mutationId, patch, scope, type: 'commitUpdate' });+ } catch (error) {+ this.internal_dispatchAgentList({ id, mutationId, scope, type: 'rollbackUpdate' });+ throw error;+ }};useFetchAgentList = (isLogin: boolean | undefined): SWRResponse<SidebarAgentListResponse> => {- return useClientDataSWRWithSync<SidebarAgentListResponse>(- isLogin === true ? agentKeys.list(isLogin) : null,+ const scope = getCacheScope();+ useClientDataSWR(+ isLogin === true ? agentProjectionKeys.listHydration(scope) : null,+ async () => {+ const cached = await agentListProjection.get({ queryKey: AGENT_LIST_QUERY, scope });+ if (cached && getCacheScope() === scope) {+ this.internal_dispatchAgentList({ data: cached.data, scope, type: 'hydrate' });+ }+ return Date.now();+ },+ );++ return useClientDataSWR<SidebarAgentListResponse>(+ isLogin === true ? agentKeys.list(isLogin, scope) : null,() => homeService.getSidebarAgentList(),{- onData: (data) => {- const state = this.#get();- const newState = mapResponseToState(data);-- // Skip update if data is the same- if (- state.isAgentListInit &&- isEqual(state.pinnedAgents, newState.pinnedAgents) &&- isEqual(state.agentGroups, newState.agentGroups) &&- isEqual(state.ungroupedAgents, newState.ungroupedAgents) &&- isEqual(state.privateAgentGroups, newState.privateAgentGroups) &&- isEqual(state.privatePinnedAgents, newState.privatePinnedAgents) &&- isEqual(state.privateUngroupedAgents, newState.privateUngroupedAgents)- ) {- return;- }-- this.#set(- {- ...newState,- isAgentListInit: true,- },- false,- n('useFetchAgentList/onData'),- );+ onSuccess: (data) => {+ if (getCacheScope() === scope)+ this.internal_dispatchAgentList({ data, scope, type: 'replace' });},},);diff --git a/src/store/home/slices/agentList/initialState.ts b/src/store/home/slices/agentList/initialState.tsindex 884363f6b21..282046072fa 100644--- a/src/store/home/slices/agentList/initialState.ts+++ b/src/store/home/slices/agentList/initialState.ts@@ -2,13 +2,26 @@ import {type SidebarAgentItem,type SidebarAgentListResponse,type SidebarGroup,-} from '@/database/repositories/home';+} from '@lobechat/types';++import type { AgentMetaUpdate } from '@/store/agent/slices/agent/action';++export type SidebarAgentMetaPatch = Pick<+ AgentMetaUpdate,+ 'avatar' | 'backgroundColor' | 'description' | 'name' | 'title'+>;export interface AgentListState {/*** Agent groups (user-defined folders)*/agentGroups: SidebarGroup[];+ agentListScope?: string;+ agentListSource?: 'server' | 'storage';+ agentOptimisticPatches: Record<+ string,+ { mutationId: number; patch: SidebarAgentMetaPatch; scope: string }+ >;/*** Whether all agents drawer is open*/@@ -45,6 +58,9 @@ export interface AgentListState {export const initialAgentListState: AgentListState = {agentGroups: [],+ agentOptimisticPatches: {},+ agentListScope: undefined,+ agentListSource: undefined,allAgentsDrawerOpen: false,isAgentListInit: false,pinnedAgents: [],diff --git a/src/store/home/slices/agentList/projection.ts b/src/store/home/slices/agentList/projection.tsnew file mode 100644index 00000000000..e069224e1ae--- /dev/null+++ b/src/store/home/slices/agentList/projection.ts@@ -0,0 +1,14 @@+import type { SidebarAgentListResponse } from '@lobechat/types';++import {+ LocalStorageQueryProjectionStorage,+ QueryProjectionWriteQueue,+} from '@/libs/queryProjectionStorage';++export const AGENT_LIST_QUERY = 'sidebar';+export const agentListProjection = new LocalStorageQueryProjectionStorage<SidebarAgentListResponse>(+ {+ namespace: 'lobechat-agent-list-v1',+ },+);+export const agentListWriteQueue = new QueryProjectionWriteQueue(agentListProjection);diff --git a/src/store/home/slices/agentList/reducer.test.ts b/src/store/home/slices/agentList/reducer.test.tsnew file mode 100644index 00000000000..ce8d8e007c9--- /dev/null+++ b/src/store/home/slices/agentList/reducer.test.ts@@ -0,0 +1,93 @@+import type { SidebarAgentListResponse } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { initialAgentListState, mapResponseToState } from './initialState';+import { agentListReducer } from './reducer';++const response = (id: string): SidebarAgentListResponse => ({+ groups: [],+ pinned: [],+ privateGroups: [],+ privatePinned: [],+ privateUngrouped: [],+ ungrouped: [{ id } as SidebarAgentListResponse['ungrouped'][number]],+});++describe('agentListReducer', () => {+ it('exposes an optimistic rename immediately and rolls it back on failure', () => {+ const loaded = {+ ...initialAgentListState,+ agentListScope: 'personal',+ ...mapResponseToState(response('agent-1')),+ };+ loaded.ungroupedAgents[0] = { ...loaded.ungroupedAgents[0], title: 'Original' };++ const optimistic = agentListReducer(loaded, {+ id: 'agent-1',+ mutationId: 1,+ patch: { title: 'Renamed' },+ scope: 'personal',+ type: 'optimisticUpdate',+ });+ const optimisticState = { ...loaded, ...optimistic.state };++ expect(optimisticState.agentOptimisticPatches['agent-1'].patch.title).toBe('Renamed');+ expect(+ agentListReducer(optimisticState, {+ id: 'agent-1',+ mutationId: 1,+ scope: 'personal',+ type: 'rollbackUpdate',+ }).state.agentOptimisticPatches,+ ).toEqual({});+ });++ it('commits an optimistic rename into the durable sidebar projection', () => {+ const loaded = {+ ...initialAgentListState,+ agentListScope: 'personal',+ ...mapResponseToState(response('agent-1')),+ agentOptimisticPatches: {+ 'agent-1': { mutationId: 1, patch: { title: 'Renamed' }, scope: 'personal' },+ },+ };+ const transition = agentListReducer(loaded, {+ id: 'agent-1',+ mutationId: 1,+ patch: { title: 'Renamed' },+ scope: 'personal',+ type: 'commitUpdate',+ });++ expect(transition.state.ungroupedAgents?.[0].title).toBe('Renamed');+ expect(transition.effects[0]).toMatchObject({ scope: 'personal', type: 'persist' });+ });++ it('hydrates the UI projection without producing a persistence effect', () => {+ const transition = agentListReducer(initialAgentListState, {+ data: response('cached'),+ scope: 'personal',+ type: 'hydrate',+ });+ expect(transition.state.ungroupedAgents?.[0].id).toBe('cached');+ expect(transition.state.agentListSource).toBe('storage');+ expect(transition.effects).toEqual([]);+ });++ it('does not let late hydration overwrite server data for the same scope', () => {+ const current = {+ ...initialAgentListState,+ ...agentListReducer(initialAgentListState, {+ data: response('server'),+ scope: 'personal',+ type: 'replace',+ }).state,+ };+ const transition = agentListReducer(current, {+ data: response('cached'),+ scope: 'personal',+ type: 'hydrate',+ });+ expect(transition.state).toEqual({});+ });+});diff --git a/src/store/home/slices/agentList/reducer.ts b/src/store/home/slices/agentList/reducer.tsnew file mode 100644index 00000000000..e1812016e94--- /dev/null+++ b/src/store/home/slices/agentList/reducer.ts@@ -0,0 +1,125 @@+import type { SidebarAgentItem, SidebarAgentListResponse, SidebarGroup } from '@lobechat/types';+import isEqual from 'fast-deep-equal';++import type { AgentListState, SidebarAgentMetaPatch } from './initialState';+import { mapResponseToState } from './initialState';++export type AgentListEffect = { data: SidebarAgentListResponse; scope: string; type: 'persist' };+export type AgentListDispatchAction =+ | { data: SidebarAgentListResponse; scope: string; type: 'hydrate' | 'replace' }+ | {+ id: string;+ mutationId: number;+ patch: SidebarAgentMetaPatch;+ scope: string;+ type: 'commitUpdate';+ }+ | {+ id: string;+ mutationId: number;+ patch: SidebarAgentMetaPatch;+ scope: string;+ type: 'optimisticUpdate';+ }+ | { id: string; mutationId: number; scope: string; type: 'rollbackUpdate' };+export interface AgentListTransition {+ effects: AgentListEffect[];+ state: Partial<AgentListState>;+}++const patchItems = (items: SidebarAgentItem[], id: string, patch: SidebarAgentMetaPatch) =>+ items.map((item) => (item.id === id ? { ...item, ...patch } : item));++const patchGroups = (groups: SidebarGroup[], id: string, patch: SidebarAgentMetaPatch) =>+ groups.map((group) => ({ ...group, items: patchItems(group.items, id, patch) }));++const toResponse = (state: AgentListState): SidebarAgentListResponse => ({+ groups: state.agentGroups,+ pinned: state.pinnedAgents,+ privateGroups: state.privateAgentGroups,+ privatePinned: state.privatePinnedAgents,+ privateUngrouped: state.privateUngroupedAgents,+ ungrouped: state.ungroupedAgents,+});++export const agentListReducer = (+ state: AgentListState,+ action: AgentListDispatchAction,+): AgentListTransition => {+ if (action.type === 'optimisticUpdate') {+ return {+ effects: [],+ state: {+ agentOptimisticPatches: {+ ...state.agentOptimisticPatches,+ [action.id]: { mutationId: action.mutationId, patch: action.patch, scope: action.scope },+ },+ },+ };+ }++ if (action.type === 'rollbackUpdate') {+ if (state.agentOptimisticPatches[action.id]?.mutationId !== action.mutationId)+ return { effects: [], state: {} };+ const agentOptimisticPatches = { ...state.agentOptimisticPatches };+ delete agentOptimisticPatches[action.id];+ return { effects: [], state: { agentOptimisticPatches } };+ }++ if (action.type === 'commitUpdate') {+ if (state.agentOptimisticPatches[action.id]?.mutationId !== action.mutationId)+ return { effects: [], state: {} };+ const agentOptimisticPatches = { ...state.agentOptimisticPatches };+ delete agentOptimisticPatches[action.id];+ if (state.agentListScope !== action.scope)+ return { effects: [], state: { agentOptimisticPatches } };+ const nextState: AgentListState = {+ ...state,+ agentGroups: patchGroups(state.agentGroups, action.id, action.patch),+ agentOptimisticPatches,+ pinnedAgents: patchItems(state.pinnedAgents, action.id, action.patch),+ privateAgentGroups: patchGroups(state.privateAgentGroups, action.id, action.patch),+ privatePinnedAgents: patchItems(state.privatePinnedAgents, action.id, action.patch),+ privateUngroupedAgents: patchItems(state.privateUngroupedAgents, action.id, action.patch),+ ungroupedAgents: patchItems(state.ungroupedAgents, action.id, action.patch),+ };+ return {+ effects: [{ data: toResponse(nextState), scope: action.scope, type: 'persist' }],+ state: nextState,+ };+ }++ if (+ action.type === 'hydrate' &&+ state.agentListScope === action.scope &&+ state.agentListSource === 'server'+ ) {+ return { effects: [], state: {} };+ }++ const projection = mapResponseToState(action.data);+ if (+ state.agentListScope === action.scope &&+ state.isAgentListInit &&+ isEqual(state.agentGroups, projection.agentGroups) &&+ isEqual(state.pinnedAgents, projection.pinnedAgents) &&+ isEqual(state.privateAgentGroups, projection.privateAgentGroups) &&+ isEqual(state.privatePinnedAgents, projection.privatePinnedAgents) &&+ isEqual(state.privateUngroupedAgents, projection.privateUngroupedAgents) &&+ isEqual(state.ungroupedAgents, projection.ungroupedAgents)+ )+ return { effects: [], state: {} };++ return {+ effects:+ action.type === 'replace'+ ? [{ data: action.data, scope: action.scope, type: 'persist' }]+ : [],+ state: {+ ...projection,+ agentListScope: action.scope,+ agentListSource: action.type === 'replace' ? 'server' : 'storage',+ isAgentListInit: true,+ },+ };+};diff --git a/src/store/home/slices/agentList/selectors.test.ts b/src/store/home/slices/agentList/selectors.test.tsindex dedbfe34523..74564397189 100644--- a/src/store/home/slices/agentList/selectors.test.ts+++ b/src/store/home/slices/agentList/selectors.test.ts@@ -7,6 +7,8 @@ import { homeAgentListSelectors } from './selectors';const createState = (overrides: Partial<HomeStore>): HomeStore =>({agentGroups: [],+ agentListScope: 'personal',+ agentOptimisticPatches: {},pinnedAgents: [],privateAgentGroups: [],privatePinnedAgents: [],@@ -28,6 +30,19 @@ const agent = (id: string) => ({});describe('homeAgentListSelectors - private pinned', () => {+ it('projects an optimistic agent rename without mutating confirmed list data', () => {+ const original = agent('a1');+ const state = createState({+ agentOptimisticPatches: {+ a1: { mutationId: 1, patch: { title: 'Renamed' }, scope: 'personal' },+ },+ ungroupedAgents: [original],+ });++ expect(homeAgentListSelectors.ungroupedAgents(state)[0].title).toBe('Renamed');+ expect(state.ungroupedAgents[0].title).toBe('a1');+ });+it('privatePinnedAgents returns the private pinned bucket', () => {const state = createState({ privatePinnedAgents: [agent('a1')] });expect(homeAgentListSelectors.privatePinnedAgents(state)).toEqual([agent('a1')]);diff --git a/src/store/home/slices/agentList/selectors.ts b/src/store/home/slices/agentList/selectors.tsindex ffc29ee1773..3b1fdb5ebce 100644--- a/src/store/home/slices/agentList/selectors.ts+++ b/src/store/home/slices/agentList/selectors.ts@@ -1,38 +1,58 @@import { type SidebarAgentItem, type SidebarGroup } from '@/database/repositories/home';import { type HomeStore } from '@/store/home/store';+const applyOptimisticPatch = (item: SidebarAgentItem, state: HomeStore): SidebarAgentItem => {+ const optimistic = state.agentOptimisticPatches[item.id];+ return optimistic?.scope === state.agentListScope ? { ...item, ...optimistic.patch } : item;+};++const applyOptimisticPatches = (items: SidebarAgentItem[], state: HomeStore) =>+ Object.keys(state.agentOptimisticPatches).length === 0+ ? items+ : items.map((item) => applyOptimisticPatch(item, state));++const applyGroupOptimisticPatches = (groups: SidebarGroup[], state: HomeStore) =>+ Object.keys(state.agentOptimisticPatches).length === 0+ ? groups+ : groups.map((group) => ({ ...group, items: applyOptimisticPatches(group.items, state) }));+/*** Get all pinned agents*/-const pinnedAgents = (s: HomeStore): SidebarAgentItem[] => s.pinnedAgents;+const pinnedAgents = (s: HomeStore): SidebarAgentItem[] =>+ applyOptimisticPatches(s.pinnedAgents, s);/*** Get all agent groups (folders)*/-const agentGroups = (s: HomeStore): SidebarGroup[] => s.agentGroups;+const agentGroups = (s: HomeStore): SidebarGroup[] => applyGroupOptimisticPatches(s.agentGroups, s);/*** Get private agent groups (folders) owned by the current user.* Empty array in personal mode.*/-const privateAgentGroups = (s: HomeStore): SidebarGroup[] => s.privateAgentGroups;+const privateAgentGroups = (s: HomeStore): SidebarGroup[] =>+ applyGroupOptimisticPatches(s.privateAgentGroups, s);/*** Get pinned private agents owned by the current user.* Empty array in personal mode.*/-const privatePinnedAgents = (s: HomeStore): SidebarAgentItem[] => s.privatePinnedAgents;+const privatePinnedAgents = (s: HomeStore): SidebarAgentItem[] =>+ applyOptimisticPatches(s.privatePinnedAgents, s);/*** Get all ungrouped agents*/-const ungroupedAgents = (s: HomeStore): SidebarAgentItem[] => s.ungroupedAgents;+const ungroupedAgents = (s: HomeStore): SidebarAgentItem[] =>+ applyOptimisticPatches(s.ungroupedAgents, s);/*** Get ungrouped private agents owned by the current user.* Empty array in personal mode.*/-const privateUngroupedAgents = (s: HomeStore): SidebarAgentItem[] => s.privateUngroupedAgents;+const privateUngroupedAgents = (s: HomeStore): SidebarAgentItem[] =>+ applyOptimisticPatches(s.privateUngroupedAgents, s);/*** Whether the current user has any private content in this workspace.@@ -48,7 +68,7 @@ const hasPrivateAgents = (s: HomeStore): boolean =>const ungroupedAgentsLimited =(pageSize: number) =>(s: HomeStore): SidebarAgentItem[] =>- s.ungroupedAgents.slice(0, pageSize);+ applyOptimisticPatches(s.ungroupedAgents.slice(0, pageSize), s);/*** Limit private ungrouped agents for the Private sidebar bucket@@ -56,7 +76,7 @@ const ungroupedAgentsLimited =const privateUngroupedAgentsLimited =(pageSize: number) =>(s: HomeStore): SidebarAgentItem[] =>- s.privateUngroupedAgents.slice(0, pageSize);+ applyOptimisticPatches(s.privateUngroupedAgents.slice(0, pageSize), s);/*** Get ungrouped agents count@@ -86,7 +106,7 @@ const allAgents = (s: HomeStore): SidebarAgentItem[] => {...s.privatePinnedAgents,...privateGroupedAgents,...s.privateUngroupedAgents,- ];+ ].map((item) => applyOptimisticPatch(item, s));};/**diff --git a/src/store/project/projection.ts b/src/store/project/projection.tsnew file mode 100644index 00000000000..33883c7b824--- /dev/null+++ b/src/store/project/projection.ts@@ -0,0 +1,16 @@+import {+ IndexedDBQueryProjectionStorage,+ QueryProjectionWriteQueue,+} from '@/libs/queryProjectionStorage';++import type { ProjectDetail, ProjectListItem } from './store';++export const PROJECT_LIST_QUERY = 'all';+export const projectListProjection = new IndexedDBQueryProjectionStorage<ProjectListItem[]>({+ namespace: 'lobechat-project-list-v1',+});+export const projectDetailProjection = new IndexedDBQueryProjectionStorage<ProjectDetail>({+ namespace: 'lobechat-project-detail-v1',+});+export const projectListWriteQueue = new QueryProjectionWriteQueue(projectListProjection);+export const projectDetailWriteQueue = new QueryProjectionWriteQueue(projectDetailProjection);diff --git a/src/store/project/reducer.test.ts b/src/store/project/reducer.test.tsnew file mode 100644index 00000000000..a8ae640898f--- /dev/null+++ b/src/store/project/reducer.test.ts@@ -0,0 +1,56 @@+import { describe, expect, it } from 'vitest';++import { projectReducer } from './reducer';+import type { ProjectDetail, ProjectListItem, ProjectStoreState } from './store';++const project = (name: string) => ({ id: 'project-1', name, slug: 'launch' }) as ProjectListItem;+const state = (): ProjectStoreState => ({+ projectDetails: { personal: { launch: { project: project('Old') } as ProjectDetail } },+ projectLists: { personal: [project('Old')] },+ projectOptimisticPatches: {},+});++describe('projectReducer', () => {+ it('keeps optimistic patches transient and emits no persistence effect', () => {+ const transition = projectReducer(state(), {+ id: 'project-1',+ patch: { name: 'Draft' },+ scope: 'personal',+ type: 'optimisticUpdate',+ });++ expect(transition.state.projectOptimisticPatches.personal['project-1']).toEqual({+ name: 'Draft',+ });+ expect(transition.effects).toEqual([]);+ });++ it('fans a confirmed update out to related list and detail projections only', () => {+ const unrelated = [project('Other')];+ const current = state();+ current.projectLists.workspace = unrelated;+ const transition = projectReducer(current, {+ id: 'project-1',+ project: project('Renamed'),+ scope: 'personal',+ type: 'commitUpdate',+ });++ expect(transition.state.projectLists.personal[0].name).toBe('Renamed');+ expect(transition.state.projectDetails.personal.launch.project.name).toBe('Renamed');+ expect(transition.state.projectLists.workspace).toBe(unrelated);+ expect(transition.effects.map((effect) => effect.projection.kind)).toEqual(['list', 'detail']);+ });++ it('does not let storage hydration overwrite an existing server projection', () => {+ const current = state();+ const transition = projectReducer(current, {+ data: [project('Cached')],+ scope: 'personal',+ type: 'hydrateList',+ });++ expect(transition.state.projectLists).toBe(current.projectLists);+ expect(transition.effects).toEqual([]);+ });+});diff --git a/src/store/project/reducer.ts b/src/store/project/reducer.tsnew file mode 100644index 00000000000..180bca2fa05--- /dev/null+++ b/src/store/project/reducer.ts@@ -0,0 +1,159 @@+import type { ProjectDetail, ProjectListItem, ProjectStoreState } from './store';++export type ProjectProjectionRef =+ | { kind: 'detail'; queryKey: string; scope: string }+ | { kind: 'list'; queryKey: string; scope: string };+export type ProjectEffect =+ | { projection: ProjectProjectionRef; type: 'invalidate' | 'remove' }+ | { projection: ProjectProjectionRef; type: 'persist'; value: ProjectDetail | ProjectListItem[] };+export type ProjectDispatchAction =+ | { data: ProjectDetail; id: string; scope: string; type: 'hydrateDetail' | 'replaceDetail' }+ | { data: ProjectListItem[]; scope: string; type: 'hydrateList' | 'replaceList' }+ | { id: string; patch: Partial<ProjectListItem>; scope: string; type: 'optimisticUpdate' }+ | { id: string; project: ProjectListItem; scope: string; type: 'commitUpdate' }+ | { id: string; scope: string; type: 'rollbackUpdate' | 'commitDelete' }+ | { project: ProjectListItem; scope: string; type: 'commitCreate' };+export interface ProjectTransition {+ effects: ProjectEffect[];+ state: Pick<ProjectStoreState, 'projectDetails' | 'projectLists' | 'projectOptimisticPatches'>;+}++const detailRef = (scope: string, queryKey: string): ProjectProjectionRef => ({+ kind: 'detail',+ queryKey,+ scope,+});+const listRef = (scope: string): ProjectProjectionRef => ({ kind: 'list', queryKey: 'all', scope });+const reconcileList = (items: ProjectListItem[], project: ProjectListItem) => {+ let changed = false;+ const next = items.map((item) => {+ if (item.id !== project.id || item === project) return item;+ changed = true;+ return project;+ });+ return changed ? next : items;+};+const clearPatch = (state: ProjectStoreState, scope: string, id: string) => {+ const patches = state.projectOptimisticPatches[scope];+ if (!patches?.[id]) return state.projectOptimisticPatches;+ const next = { ...patches };+ delete next[id];+ return { ...state.projectOptimisticPatches, [scope]: next };+};++export const projectReducer = (+ state: ProjectStoreState,+ action: ProjectDispatchAction,+): ProjectTransition => {+ const effects: ProjectEffect[] = [];+ let projectDetails = state.projectDetails;+ let projectLists = state.projectLists;+ let projectOptimisticPatches = state.projectOptimisticPatches;++ switch (action.type) {+ case 'hydrateDetail': {+ if (!projectDetails[action.scope]?.[action.id])+ projectDetails = {+ ...projectDetails,+ [action.scope]: { ...projectDetails[action.scope], [action.id]: action.data },+ };+ break;+ }+ case 'replaceDetail': {+ projectDetails = {+ ...projectDetails,+ [action.scope]: { ...projectDetails[action.scope], [action.id]: action.data },+ };+ effects.push({+ projection: detailRef(action.scope, action.id),+ type: 'persist',+ value: action.data,+ });+ break;+ }+ case 'hydrateList': {+ if (!projectLists[action.scope])+ projectLists = { ...projectLists, [action.scope]: action.data };+ break;+ }+ case 'replaceList': {+ projectLists = { ...projectLists, [action.scope]: action.data };+ effects.push({ projection: listRef(action.scope), type: 'persist', value: action.data });+ break;+ }+ case 'optimisticUpdate': {+ projectOptimisticPatches = {+ ...projectOptimisticPatches,+ [action.scope]: {+ ...projectOptimisticPatches[action.scope],+ [action.id]: { ...projectOptimisticPatches[action.scope]?.[action.id], ...action.patch },+ },+ };+ break;+ }+ case 'rollbackUpdate': {+ projectOptimisticPatches = clearPatch(state, action.scope, action.id);+ break;+ }+ case 'commitUpdate': {+ projectOptimisticPatches = clearPatch(state, action.scope, action.id);+ const currentList = projectLists[action.scope];+ if (currentList) {+ const nextList = reconcileList(currentList, action.project);+ if (nextList !== currentList) {+ projectLists = { ...projectLists, [action.scope]: nextList };+ effects.push({ projection: listRef(action.scope), type: 'persist', value: nextList });+ }+ }+ const currentDetails = projectDetails[action.scope];+ if (currentDetails) {+ let nextDetails = currentDetails;+ for (const [queryKey, detail] of Object.entries(currentDetails)) {+ if (detail.project.id !== action.id) continue;+ const nextDetail = { ...detail, project: action.project };+ if (nextDetails === currentDetails) nextDetails = { ...currentDetails };+ nextDetails[queryKey] = nextDetail;+ effects.push({+ projection: detailRef(action.scope, queryKey),+ type: 'persist',+ value: nextDetail,+ });+ }+ if (nextDetails !== currentDetails)+ projectDetails = { ...projectDetails, [action.scope]: nextDetails };+ }+ break;+ }+ case 'commitCreate': {+ const current = projectLists[action.scope];+ if (current && !current.some((item) => item.id === action.project.id)) {+ const next = [action.project, ...current];+ projectLists = { ...projectLists, [action.scope]: next };+ effects.push({ projection: listRef(action.scope), type: 'persist', value: next });+ } else if (!current) effects.push({ projection: listRef(action.scope), type: 'invalidate' });+ break;+ }+ case 'commitDelete': {+ const current = projectLists[action.scope];+ if (current) {+ const next = current.filter((item) => item.id !== action.id);+ if (next.length !== current.length) {+ projectLists = { ...projectLists, [action.scope]: next };+ effects.push({ projection: listRef(action.scope), type: 'persist', value: next });+ }+ }+ const details = projectDetails[action.scope];+ if (details) {+ const next = { ...details };+ for (const [queryKey, detail] of Object.entries(details))+ if (detail.project.id === action.id) {+ delete next[queryKey];+ effects.push({ projection: detailRef(action.scope, queryKey), type: 'remove' });+ }+ projectDetails = { ...projectDetails, [action.scope]: next };+ }+ break;+ }+ }+ return { effects, state: { projectDetails, projectLists, projectOptimisticPatches } };+};diff --git a/src/store/project/store.test.ts b/src/store/project/store.test.tsindex abc629c88e0..873e932a005 100644--- a/src/store/project/store.test.ts+++ b/src/store/project/store.test.ts@@ -2,8 +2,10 @@ import { act, renderHook } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';import { mutate } from '@/libs/swr';+import { projectKeys } from '@/libs/swr/keys';import { projectService } from '@/services/project';+import { projectListProjection } from './projection';import type { ProjectDetail, ProjectListItem } from './store';import { useCurrentProjectDetail, useCurrentProjectList, useProjectStore } from './store';@@ -15,6 +17,7 @@ const mocks = vi.hoisted(() => ({swrDataByKey: {} as Record<string, unknown>,swrConfigs: [] as Array<{ onSuccess?: (response: unknown) => void }>,swrKeys: [] as unknown[],+ fetchers: [] as Array<() => Promise<unknown>>,}));vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({@@ -30,7 +33,12 @@ vi.mock('@/libs/swr/useCacheScope', () => ({vi.mock('@/libs/swr', () => ({mutate: vi.fn(),useClientDataSWR: vi.fn(- (key: unknown, _fetcher: unknown, config: { onSuccess?: (response: unknown) => void } = {}) => {+ (+ key: unknown,+ _fetcher: () => Promise<unknown>,+ config: { onSuccess?: (response: unknown) => void } = {},+ ) => {+ mocks.fetchers.push(_fetcher);mocks.swrConfigs.push(config);mocks.swrKeys.push(key);const serializedKey = JSON.stringify(key);@@ -51,15 +59,26 @@ describe('project store cache scope', () => {mocks.swrDataByKey = {};mocks.swrConfigs = [];mocks.swrKeys = [];- useProjectStore.setState({ projectDetails: {}, projectLists: {} });+ mocks.fetchers = [];+ useProjectStore.setState({+ projectDetails: {},+ projectLists: {},+ projectOptimisticPatches: {},+ });});- it('restores a persisted project list into the store before the first paint', () => {+ it('restores a persisted project list without waiting for the network', async () => {const cachedProject = { id: 'cached-project', name: 'Cached project' } as ProjectListItem;- mocks.swrData = { data: [cachedProject], message: 'cached', success: true };+ vi.spyOn(projectListProjection, 'get').mockResolvedValueOnce({+ data: [cachedProject],+ updatedAt: 1,+ });renderHook(() => useProjectStore.getState().useFetchProjectList());+ await act(async () => {+ await mocks.fetchers[0]();+ });expect(useProjectStore.getState().projectLists['user-1:personal']).toEqual([cachedProject]);});@@ -70,6 +89,7 @@ describe('project store cache scope', () => {mocks.currentCacheScope = 'user-1:workspace-1';renderHook(() => useProjectStore.getState().useFetchProjectList());+ act(() => mocks.swrConfigs.at(-1)?.onSuccess?.({ data: [staleProject], success: true }));expect(useProjectStore.getState().projectLists['user-1:personal']).toBeUndefined();expect(useProjectStore.getState().projectLists['user-1:workspace-1']).toBeUndefined();@@ -90,8 +110,10 @@ describe('project store cache scope', () => {rerender();expect(mocks.swrKeys).toEqual([- ['project/list', 'user-1:personal'],- ['project/list', 'user-2:personal'],+ projectKeys.listHydration('user-1:personal'),+ projectKeys.list('user-1:personal'),+ projectKeys.listHydration('user-2:personal'),+ projectKeys.list('user-2:personal'),]);expect(renderHook(() => useCurrentProjectList()).result.current).toEqual([]);});@@ -118,12 +140,14 @@ describe('project store cache scope', () => {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;@@ -147,8 +171,10 @@ describe('project store cache scope', () => {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'],+ projectKeys.detailHydration('user-1:personal', 'shared-id'),+ projectKeys.detail('user-1:personal', 'shared-id'),+ projectKeys.detailHydration('user-1:workspace-1', 'shared-id'),+ projectKeys.detail('user-1:workspace-1', 'shared-id'),]);expect(renderHook(() => useCurrentProjectDetail('shared-id')).result.current).toBe(workspaceDetail,@@ -189,35 +215,45 @@ describe('project store cache scope', () => {message: 'Project deleted',success: true,});-await useProjectStore.getState().deleteProject('project-1');expect(projectService.delete).toHaveBeenCalledWith('project-1');- expect(mutate).toHaveBeenCalledWith(['project/list', 'user-1:personal']);+ const matcher = vi.mocked(mutate).mock.calls.at(-1)?.[0];+ expect(typeof matcher === 'function' && matcher(projectKeys.list('user-1:personal'))).toBe(+ true,+ );});it('updates project list and detail caches after renaming', async () => {const project = { id: 'project-1', name: 'Original', slug: 'launch' } as ProjectListItem;const renamed = { ...project, name: 'Renamed' };const detail = { project } as ProjectDetail;- const refreshProjectList = vi.fn().mockResolvedValue(undefined);- vi.spyOn(projectService, 'update').mockResolvedValue({- data: renamed,- message: 'Project updated',- success: true,- });+ let resolveUpdate!: (value: { data: ProjectListItem; message: string; success: true }) => void;+ vi.spyOn(projectService, 'update').mockImplementation(+ () => new Promise((resolve) => (resolveUpdate = resolve)),+ );useProjectStore.setState({projectDetails: { 'user-1:personal': { launch: detail } },projectLists: { 'user-1:personal': [project] },- refreshProjectList,});- await useProjectStore.getState().updateProject('project-1', { name: 'Renamed' });+ const operation = useProjectStore.getState().updateProject('project-1', { name: 'Renamed' });++ expect(renderHook(() => useCurrentProjectList()).result.current[0].name).toBe('Renamed');+ expect(renderHook(() => useCurrentProjectDetail('launch')).result.current?.project.name).toBe(+ 'Renamed',+ );++ resolveUpdate({ data: renamed, message: 'Project updated', success: true });+ await operation;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();+ const matcher = vi.mocked(mutate).mock.calls.at(-1)?.[0];+ expect(typeof matcher === 'function' && matcher(projectKeys.list('user-1:personal'))).toBe(+ true,+ );});});diff --git a/src/store/project/store.ts b/src/store/project/store.tsindex 51efae8348d..60f9db797bf 100644--- a/src/store/project/store.ts+++ b/src/store/project/store.ts@@ -1,33 +1,46 @@-import { useLayoutEffect } from 'react';import type { SWRResponse } from 'swr';import { shallow } from 'zustand/shallow';import { createWithEqualityFn } from 'zustand/traditional';import { getActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import { mutate, useClientDataSWR } from '@/libs/swr';+import { isProjectDetailKey, isProjectListKey, projectKeys } from '@/libs/swr/keys';import { getCacheScope, useCacheScope } from '@/libs/swr/useCacheScope';import { projectService } from '@/services/project';import { createDevtools } from '@/store/middleware/createDevtools';import { expose } from '@/store/middleware/expose';+import {+ PROJECT_LIST_QUERY,+ projectDetailProjection,+ projectDetailWriteQueue,+ projectListProjection,+ projectListWriteQueue,+} from './projection';+import type { ProjectDispatchAction, ProjectEffect } from './reducer';+import { projectReducer } from './reducer';+type ProjectListResponse = Awaited<ReturnType<typeof projectService.listAll>>;type ProjectDetailResponse = Awaited<ReturnType<typeof projectService.detail>>;export type ProjectListItem = ProjectListResponse['data'][number];export type ProjectDetail = ProjectDetailResponse['data'];-const LIST_KEY = 'project/list';-const listKey = (scope: string) => [LIST_KEY, scope] as const;-const detailKey = (scope: string, id: string) => ['project/detail', scope, id] as const;+const currentScope = () => getCacheScope();-interface ProjectStore {+export interface ProjectStoreState {+ projectDetails: Record<string, Record<string, ProjectDetail>>;+ projectLists: Record<string, ProjectListItem[]>;+ projectOptimisticPatches: Record<string, Record<string, Partial<ProjectListItem>>>;+}++interface ProjectStore extends ProjectStoreState {createProject: (input: {identifier: string;name: string;slug?: string;}) => Promise<ProjectListItem>;deleteProject: (id: string) => Promise<void>;- projectDetails: Record<string, Record<string, ProjectDetail>>;- projectLists: Record<string, ProjectListItem[]>;+ internal_dispatchProject: (action: ProjectDispatchAction) => void;refreshProjectList: () => Promise<void>;updateProject: (id: string, input: { name: string }) => Promise<ProjectListItem>;useFetchProjectDetail: (id?: string) => SWRResponse<ProjectDetailResponse>;@@ -37,94 +50,113 @@ interface ProjectStore {const devtools = createDevtools('project');export const useProjectStore = createWithEqualityFn<ProjectStore>()(- devtools((set, get) => ({- createProject: async (input) => {- const response = await projectService.create(input, getActiveWorkspaceId());- await get().refreshProjectList();- return response.data;- },- deleteProject: async (id) => {- await projectService.delete(id);- await get().refreshProjectList();- },- projectDetails: {},- projectLists: {},- refreshProjectList: async () => mutate(listKey(getCacheScope())),- updateProject: async (id, input) => {- const response = await projectService.update(id, input);- const project = response.data;-- set(- (state) => ({- projectDetails: Object.fromEntries(- Object.entries(state.projectDetails).map(([scope, details]) => [- scope,- Object.fromEntries(- Object.entries(details).map(([reference, detail]) => [- reference,- detail.project.id === id ? { ...detail, project } : detail,- ]),- ),- ]),- ),- projectLists: Object.fromEntries(- Object.entries(state.projectLists).map(([scope, projects]) => [- scope,- projects.map((item) => (item.id === id ? project : item)),- ]),- ),- }),- false,- 'updateProject/success',- );- await get().refreshProjectList();- return project;- },- useFetchProjectDetail: (id) => {- const scope = useCacheScope();-- return useClientDataSWR(id ? detailKey(scope, id) : null, () => projectService.detail(id!), {- onSuccess: (response: ProjectDetailResponse) => {- if (scope !== getCacheScope()) return;-- set(- (state) => ({- projectDetails: {- ...state.projectDetails,- [scope]: { ...state.projectDetails[scope], [id!]: response.data },- },- }),- false,- 'useFetchProjectDetail/success',+ devtools((set, get) => {+ const executeEffects = (effects: ProjectEffect[]) => {+ for (const effect of effects) {+ const key = { queryKey: effect.projection.queryKey, scope: effect.projection.scope };+ if (effect.type === 'invalidate') {+ void mutate((key) =>+ effect.projection.kind === 'list'+ ? isProjectListKey(key, effect.projection.scope)+ : isProjectDetailKey(key, effect.projection.scope, effect.projection.queryKey),);- },- });- },- useFetchProjectList: (enabled = true) => {- const scope = useCacheScope();- const response = useClientDataSWR(enabled ? listKey(scope) : null, () =>- projectService.listAll(),- );- const { data } = response;+ } else if (effect.projection.kind === 'list') {+ if (effect.type === 'remove') projectListWriteQueue.remove(key);+ else if ('value' in effect)+ projectListWriteQueue.set(key, {+ data: effect.value as ProjectListItem[],+ updatedAt: Date.now(),+ });+ } else if (effect.type === 'remove') projectDetailWriteQueue.remove(key);+ else if ('value' in effect)+ projectDetailWriteQueue.set(key, {+ data: effect.value as ProjectDetail,+ updatedAt: Date.now(),+ });+ }+ };+ const dispatch = (action: ProjectDispatchAction) => {+ const transition = projectReducer(get(), action);+ set(transition.state, false, `project/${action.type}`);+ executeEffects(transition.effects);+ };+ const refreshList = async (scope: string) => mutate((key) => isProjectListKey(key, scope));- 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',+ return {+ createProject: async (input) => {+ const scope = currentScope();+ const response = await projectService.create(input, getActiveWorkspaceId());+ dispatch({ project: response.data, scope, type: 'commitCreate' });+ void refreshList(scope);+ return response.data;+ },+ deleteProject: async (id) => {+ const scope = currentScope();+ await projectService.delete(id);+ dispatch({ id, scope, type: 'commitDelete' });+ void refreshList(scope);+ },+ internal_dispatchProject: dispatch,+ projectDetails: {},+ projectLists: {},+ projectOptimisticPatches: {},+ refreshProjectList: async () => {+ const scope = currentScope();+ await refreshList(scope);+ },+ updateProject: async (id, input) => {+ const scope = currentScope();+ dispatch({ id, patch: input, scope, type: 'optimisticUpdate' });+ try {+ const response = await projectService.update(id, input);+ dispatch({ id, project: response.data, scope, type: 'commitUpdate' });+ void refreshList(scope);+ return response.data;+ } catch (error) {+ dispatch({ id, scope, type: 'rollbackUpdate' });+ throw error;+ }+ },+ useFetchProjectDetail: (id) => {+ const scope = useCacheScope();+ useClientDataSWR(id ? projectKeys.detailHydration(scope, id) : null, async () => {+ const cached = await projectDetailProjection.get({ queryKey: id!, scope });+ if (cached && currentScope() === scope)+ dispatch({ data: cached.data, id: id!, scope, type: 'hydrateDetail' });+ return Date.now();+ });+ return useClientDataSWR(+ id ? projectKeys.detail(scope, id) : null,+ () => projectService.detail(id!),+ {+ onSuccess: (response: ProjectDetailResponse) => {+ if (currentScope() === scope)+ dispatch({ data: response.data, id: id!, scope, type: 'replaceDetail' });+ },+ },);- }, [data, enabled, scope]);-- return response;- },- })),+ },+ useFetchProjectList: (enabled = true) => {+ const scope = useCacheScope();+ useClientDataSWR(enabled ? projectKeys.listHydration(scope) : null, async () => {+ const cached = await projectListProjection.get({ queryKey: PROJECT_LIST_QUERY, scope });+ if (cached && currentScope() === scope)+ dispatch({ data: cached.data, scope, type: 'hydrateList' });+ return Date.now();+ });+ return useClientDataSWR(+ enabled ? projectKeys.list(scope) : null,+ () => projectService.listAll(),+ {+ onSuccess: (response: ProjectListResponse) => {+ if (currentScope() === scope)+ dispatch({ data: response.data, scope, type: 'replaceList' });+ },+ },+ );+ },+ };+ }),shallow,);@@ -132,10 +164,22 @@ expose('project', useProjectStore);export const useCurrentProjectList = () => {const scope = useCacheScope();- return useProjectStore((state) => state.projectLists[scope] ?? []);+ return useProjectStore((state) => {+ const patches = state.projectOptimisticPatches[scope];+ const list = state.projectLists[scope] ?? [];+ if (!patches || Object.keys(patches).length === 0) return list;+ return list.map((project) =>+ patches[project.id] ? { ...project, ...patches[project.id] } : project,+ );+ });};export const useCurrentProjectDetail = (id?: string) => {const scope = useCacheScope();- return useProjectStore((state) => (id ? state.projectDetails[scope]?.[id] : undefined));+ return useProjectStore((state) => {+ if (!id) return undefined;+ const detail = state.projectDetails[scope]?.[id];+ const patch = state.projectOptimisticPatches[scope]?.[detail?.project.id ?? id];+ return detail && patch ? { ...detail, project: { ...detail.project, ...patch } } : detail;+ });};