🤯 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(replica): move projects, recents, agent list and agent config onto @lobechat/replica (#20390)
Arvin Xuac6a20a3a60e
diff --git a/packages/replica/src/core/engine.ts b/packages/replica/src/core/engine.tsindex 1bab6badfe5..9df8a923e47 100644--- a/packages/replica/src/core/engine.ts+++ b/packages/replica/src/core/engine.ts@@ -42,20 +42,26 @@ export interface ReplicaStorePort<TData> {}/**- * How an entity (e.g. one topic) appears inside this resource's value. Paged- * resources get it for free from `paging.getId`; a single-entity resource- * (a detail cache) passes `getId`.+ * How entities (e.g. topics) appear inside a non-paged resource value. Paged+ * resources get this for free from `paging.getId`. Build one with+ * `singleEntity` (a detail value), `arrayEntity` (a plain list) or by hand for+ * nested shapes (grouped lists).*/export interface ReplicaEntityAdapter<TData, TItem> {- /** Map the entity value into the resource value; defaults to identity. */- apply?: (data: TData, item: TItem) => TData;- getId: (data: TData) => string;+ /** Whether `data` holds the entity. */+ has: (data: TData, id: string) => boolean;+ /**+ * Map the entity inside `data` (`fn` returning `undefined` deletes it).+ * Return `data` itself when nothing changed, or `undefined` when the whole+ * value goes away with the entity (a detail value).+ */+ map: (data: TData, id: string, fn: (item: TItem) => TItem | undefined) => TData | undefined;}export interface ReplicaEngineOptions<TParams, TData, TFetched> {/** Label prefix of host updates (devtools action names). Defaults to the resource name. */actionPrefix?: string;- /** Single-entity resources only: how to find / patch the entity. */+ /** Non-paged resources: how entities sit in the value (see `linkReplicaEntity`). */entity?: ReplicaEntityAdapter<TData, any>;/** Overrides `resource.fetcher` when the fetch needs store context. */fetcher?: (params: TParams, cursor?: any) => Promise<TFetched>;@@ -426,11 +432,11 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(const data = port.read(key);if (data === undefined) return false;if (paging) return hasPagedItem(data as any, id, paging);- return options.entity ? options.entity.getId(data) === id : false;+ return options.entity ? options.entity.has(data, id) : false;});};- /** Map one entity inside a value; `undefined` from `fn` removes it (paged only). */+ /** Map one entity inside a value; `undefined` means the whole value goes away. */const mapEntity = <TItem>(data: TData,id: string,@@ -438,10 +444,8 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(): TData | undefined => {if (paging) return mapPagedItem(data as any, id, fn as any, paging) as TData;const entity = options.entity;- if (!entity || entity.getId(data) !== id) return data;- const next = fn(data as unknown as TItem);- if (next === undefined) return undefined;- return entity.apply ? entity.apply(data, next) : (next as unknown as TData);+ if (!entity || !entity.has(data, id)) return data;+ return entity.map(data, id, fn);};/**@@ -504,7 +508,7 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(fn: (item: TItem) => TItem | undefined,): ReplicaOptimisticToken<TData>[] =>entityKeys(id).flatMap((key) => {- // Removing a single-entity value is applied on commit, not optimistically.+ // Removing a whole value (a detail) is applied on commit, not optimistically.if (!paging) {const current = port.read(key);if (current !== undefined && mapEntity(current, id, fn) === undefined) return [];diff --git a/packages/replica/src/core/entityAdapters.test.ts b/packages/replica/src/core/entityAdapters.test.tsnew file mode 100644index 00000000000..08c14777300--- /dev/null+++ b/packages/replica/src/core/entityAdapters.test.ts@@ -0,0 +1,143 @@+import { describe, expect, it } from 'vitest';++import { defineReplica } from './defineReplica';+import { createReplicaEngine, type ReplicaStorePort } from './engine';+import { linkReplicaEntity } from './entity';+import { arrayEntity, singleEntity } from './entityAdapters';+import { createReplicaState } from './reducer';+import type { ReplicaState } from './types';++interface Row {+ id: string;+ name: string;+}+interface Detail {+ members: string[];+ project: Row;+}++/** A host without Zustand: a plain object behind the store port. */+const createHost = <T>() => {+ const host = { slot: createReplicaState<T>() as ReplicaState<T>, views: {} as Record<string, T> };+ const port: ReplicaStorePort<T> = {+ commit: (writes, state) => {+ for (const write of writes) {+ if ('type' in write) host.views = {};+ else if (write.data === undefined) delete host.views[write.key];+ else host.views[write.key] = write.data;+ }+ host.slot = state;+ },+ getState: () => host.slot,+ keys: () => Object.keys(host.views),+ read: (key) => host.views[key],+ };+ return { host, port };+};++const rowById = (id: string) => (row: Row) => row.id === id;++describe('arrayEntity', () => {+ const adapter = arrayEntity<Row>((row) => row.id);+ const list = [+ { id: 'a', name: 'A' },+ { id: 'b', name: 'B' },+ ];++ it('patches and removes one row', () => {+ expect(adapter.has(list, 'b')).toBe(true);+ expect(adapter.map(list, 'b', (row) => ({ ...row, name: 'B2' }))).toEqual([+ { id: 'a', name: 'A' },+ { id: 'b', name: 'B2' },+ ]);+ expect(adapter.map(list, 'a', () => undefined)).toEqual([{ id: 'b', name: 'B' }]);+ });++ it('keeps the reference when nothing changed', () => {+ expect(adapter.map(list, 'missing', (row) => ({ ...row, name: 'x' }))).toBe(list);+ expect(adapter.map(list, 'a', (row) => row)).toBe(list);+ });+});++describe('singleEntity with a lens', () => {+ const adapter = singleEntity<Detail, Row>((row) => row.id, {+ get: (detail) => detail.project,+ set: (detail, project) => ({ ...detail, project }),+ });+ const detail: Detail = { members: ['m'], project: { id: 'p', name: 'P' } };++ it('patches the wrapped entity and keeps the rest of the value', () => {+ expect(adapter.map(detail, 'p', (row) => ({ ...row, name: 'P2' }))).toEqual({+ members: ['m'],+ project: { id: 'p', name: 'P2' },+ });+ });++ it('drops the whole value when the entity is deleted', () => {+ expect(adapter.map(detail, 'p', () => undefined)).toBeUndefined();+ });+});++describe('entity link over non-paged replicas (engine without Zustand)', () => {+ const setup = () => {+ const listHost = createHost<Row[]>();+ const detailHost = createHost<Detail>();+ const list = createReplicaEngine(+ defineReplica<void, Row[]>({ key: () => 'all', name: 'rows', version: 1 }),+ { entity: arrayEntity<Row>((row) => row.id), port: listHost.port },+ );+ const detail = createReplicaEngine(+ defineReplica<string, Detail>({ key: (id) => id, name: 'rowDetail', version: 1 }),+ {+ entity: singleEntity<Detail, Row>((row) => row.id, {+ get: (value) => value.project,+ set: (value, project) => ({ ...value, project }),+ }),+ port: detailHost.port,+ },+ );+ list.replace(undefined, [+ { id: 'a', name: 'A' },+ { id: 'b', name: 'B' },+ ]);+ detail.replace('b', { members: ['m'], project: { id: 'b', name: 'B' } });+ return { detailHost, link: linkReplicaEntity<Row>([list, detail]), listHost };+ };++ it('patches the row in the list and the wrapped entity in the detail', () => {+ const { detailHost, link, listHost } = setup();++ link.update('b', (row) => ({ ...row, name: 'B2' }));++ expect(listHost.host.views.all.find(rowById('b'))?.name).toBe('B2');+ expect(detailHost.host.views.b.project.name).toBe('B2');+ expect(detailHost.host.views.b.members).toEqual(['m']);+ });++ it('rolls both back when the server call fails', async () => {+ const { detailHost, link, listHost } = setup();++ const pending = link.optimistic(+ 'b',+ (row) => ({ ...row, name: 'B2' }),+ async () => {+ expect(listHost.host.views.all.find(rowById('b'))?.name).toBe('B2');+ expect(detailHost.host.views.b.project.name).toBe('B2');+ throw new Error('boom');+ },+ );++ await expect(pending).rejects.toThrow('boom');+ expect(listHost.host.views.all.find(rowById('b'))?.name).toBe('B');+ expect(detailHost.host.views.b.project.name).toBe('B');+ });++ it('removes the list row and the detail value on delete', async () => {+ const { detailHost, link, listHost } = setup();++ await link.optimistic('b', 'remove', async () => undefined);++ expect(listHost.host.views.all.map((row) => row.id)).toEqual(['a']);+ expect(detailHost.host.views.b).toBeUndefined();+ });+});diff --git a/packages/replica/src/core/entityAdapters.ts b/packages/replica/src/core/entityAdapters.tsnew file mode 100644index 00000000000..8378cc8bd35--- /dev/null+++ b/packages/replica/src/core/entityAdapters.ts@@ -0,0 +1,43 @@+import type { ReplicaEntityAdapter } from './engine';++/**+ * The value IS one entity, or wraps one (`{ project, members }`). Deleting the+ * entity drops the whole value.+ */+export const singleEntity = <TData, TItem = TData>(+ getId: (item: TItem) => string,+ lens?: { get: (data: TData) => TItem; set: (data: TData, item: TItem) => TData },+): ReplicaEntityAdapter<TData, TItem> => {+ const pick = (data: TData) => (lens ? lens.get(data) : (data as unknown as TItem));+ return {+ has: (data, id) => getId(pick(data)) === id,+ map: (data, _id, fn) => {+ const current = pick(data);+ const next = fn(current);+ if (next === undefined) return undefined;+ if (next === current) return data;+ return lens ? lens.set(data, next) : (next as unknown as TData);+ },+ };+};++/** The value is a plain list of entities; deleting one filters it out. */+export const arrayEntity = <TItem>(+ getId: (item: TItem) => string,+): ReplicaEntityAdapter<TItem[], TItem> => ({+ has: (data, id) => data.some((item) => getId(item) === id),+ map: (data, id, fn) => {+ let changed = false;+ const next: TItem[] = [];+ for (const item of data) {+ if (getId(item) !== id) {+ next.push(item);+ continue;+ }+ const mapped = fn(item);+ if (mapped !== item) changed = true;+ if (mapped !== undefined) next.push(mapped);+ }+ return changed ? next : data;+ },+});diff --git a/packages/replica/src/index.ts b/packages/replica/src/index.tsindex d22053f7917..340e525c05c 100644--- a/packages/replica/src/index.ts+++ b/packages/replica/src/index.ts@@ -1,6 +1,7 @@export * from './core/defineReplica';export * from './core/engine';export * from './core/entity';+export * from './core/entityAdapters';export * from './core/keys';export * from './core/paging';export * from './core/reducer';diff --git a/packages/replica/src/zustand/createReplicaSlice.test.ts b/packages/replica/src/zustand/createReplicaSlice.test.tsindex 451acbcc95b..3ee18d566ef 100644--- a/packages/replica/src/zustand/createReplicaSlice.test.ts+++ b/packages/replica/src/zustand/createReplicaSlice.test.ts@@ -115,6 +115,32 @@ describe('createReplicaSlice', () => {await waitFor(() => expect(storage.rows.get('user-1:personal|a')?.data).toEqual(['server']));});+ it('runs onSuccess after the response is folded in, and onError on a failed fetch', async () => {+ const { slice, store } = setup();+ const seen: unknown[] = [];+ renderHook(+ () =>+ slice.useSync(+ { id: 'a' },+ { onSuccess: (data) => seen.push([data, store.getState().lists.a]) },+ ),+ { wrapper },+ );+ // The callback already sees the store view the response produced.+ await waitFor(() => expect(seen).toEqual([[['server'], ['server']]]));++ const failure = new Error('offline');+ const onError = vi.fn();+ const failing = setup({+ fetcher: vi.fn(async () => {+ throw failure;+ }),+ });+ renderHook(() => failing.slice.useSync({ id: 'b' }, { onError }), { wrapper });+ await waitFor(() => expect(onError).toHaveBeenCalledWith(failure));+ expect(failing.store.getState().lists.b).toBeUndefined();+ });+it('does not let a slow hydration overwrite a faster server response', async () => {const storage = createMemoryStorage();storage.rows.set('user-1:personal|a', { data: ['cached'], updatedAt: 1 });diff --git a/packages/replica/src/zustand/createReplicaSlice.ts b/packages/replica/src/zustand/createReplicaSlice.tsindex 366db7a29a4..b9f330751d8 100644--- a/packages/replica/src/zustand/createReplicaSlice.ts+++ b/packages/replica/src/zustand/createReplicaSlice.ts@@ -35,8 +35,15 @@ export interface CreateReplicaSliceOptions<TStore, TParams, TData, TFetched> extview: ReplicaLens<TStore, TData>;}-export interface ReplicaSyncOptions {+export interface ReplicaSyncOptions<TFetched = unknown> {enabled?: boolean;+ /** Side effects of a failed fetch (error side-maps); the store view is left as is. */+ onError?: (error: unknown) => void;+ /**+ * Side effects of a response, run after it is folded into the replica+ * (e.g. adopting an active id, or settling a "not found" state).+ */+ onSuccess?: (data: TFetched) => void;}export interface ReplicaSyncResult {@@ -104,7 +111,7 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(*/const useSync = (params: TParams | null | undefined,- { enabled = true }: ReplicaSyncOptions = {},+ { enabled = true, onError, onSuccess }: ReplicaSyncOptions<TFetched> = {},): ReplicaSyncResult => {const scope = resource.scope.use();const key = params ? resource.key(params) : undefined;@@ -132,7 +139,13 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(? replicaKeys.sync(resource.name, resource.version, scope, key!, params): null,() => fetcher!(params!, undefined),- { onSuccess: (data) => replace(params!, data, scope) },+ {+ onError,+ onSuccess: (data) => {+ replace(params!, data, scope);+ onSuccess?.(data);+ },+ },);return {diff --git a/packages/replica/src/zustand/driver.ts b/packages/replica/src/zustand/driver.tsindex e74e32de8bf..ae4f46cb434 100644--- a/packages/replica/src/zustand/driver.ts+++ b/packages/replica/src/zustand/driver.ts@@ -1,6 +1,7 @@export interface ReplicaQueryOptions<T> {/** Run once per key: no refetch on focus, reconnect or remount (hydration reads). */once?: boolean;+ onError?: (error: unknown) => void;onSuccess?: (data: T) => void;}@@ -45,13 +46,14 @@ export const createSWRDriver = ({useSWR: SWRLikeHook;}): ReplicaSyncDriver => ({revalidate: (match) => mutate(match),- useQuery: (key, fetcher, { once, onSuccess }) =>+ useQuery: (key, fetcher, { once, onError, onSuccess }) =>useSWR(key, fetcher, {...(once && {revalidateIfStale: false,revalidateOnFocus: false,revalidateOnReconnect: false,}),+ ...(onError && { onError: (error: unknown) => onError(error) }),...(onSuccess && { onSuccess: (data: unknown) => onSuccess(data as never) }),}),});diff --git a/packages/replica/src/zustand/pagedSlice.test.ts b/packages/replica/src/zustand/pagedSlice.test.tsindex 87eae9656b5..2f057cbc10c 100644--- a/packages/replica/src/zustand/pagedSlice.test.ts+++ b/packages/replica/src/zustand/pagedSlice.test.ts@@ -4,6 +4,7 @@ import { createStore } from 'zustand/vanilla';import { testDriver as driver } from '../../tests/testDriver';import { definePagedReplica, defineReplica } from '../core/defineReplica';import { linkReplicaEntity } from '../core/entity';+import { singleEntity } from '../core/entityAdapters';import type { ReplicaPagedData, ReplicaPageResult } from '../core/paging';import { createReplicaState } from '../core/reducer';import type { ReplicaRow, ReplicaScope, ReplicaState, ReplicaStorage } from '../core/types';@@ -115,7 +116,7 @@ const setup = (});const detail = createReplicaSlice(detailResource, {driver,- entity: { getId: (item) => item.id },+ entity: singleEntity<Row>((item) => item.id),get: store.getState,set: (partial) => store.setState(partial),stateKey: 'detailsReplica',diff --git a/src/features/AgentTaskManager/AgentSelectorAction.test.tsx b/src/features/AgentTaskManager/AgentSelectorAction.test.tsxindex 808904f6c1a..6c343fdb1e7 100644--- a/src/features/AgentTaskManager/AgentSelectorAction.test.tsx+++ b/src/features/AgentTaskManager/AgentSelectorAction.test.tsx@@ -27,7 +27,6 @@ const mocks = vi.hoisted(() => ({fetchAgentList: vi.fn(),homeState: {agentGroups: [] as any[],- agentOptimisticPatches: {},isAgentListInit: true,pinnedAgents: [] as any[],privateAgentGroups: [] as any[],diff --git a/src/features/Home/AgentSelect/useHomeAgentRows.test.ts b/src/features/Home/AgentSelect/useHomeAgentRows.test.tsindex be67568ab55..7147eef8e68 100644--- a/src/features/Home/AgentSelect/useHomeAgentRows.test.ts+++ b/src/features/Home/AgentSelect/useHomeAgentRows.test.ts@@ -15,7 +15,6 @@ const mocks = vi.hoisted(() => ({currentUserId: 'member-1',homeState: {agentGroups: [] as any[],- agentOptimisticPatches: {},pinnedAgents: [] as any[],privateAgentGroups: [] as any[],privatePinnedAgents: [] as any[],diff --git a/src/features/Home/InputArea/index.tsx b/src/features/Home/InputArea/index.tsxindex c542af6ec37..2e7185e4b2d 100644--- a/src/features/Home/InputArea/index.tsx+++ b/src/features/Home/InputArea/index.tsx@@ -45,10 +45,10 @@ const InputArea = ({}: InputAreaProps) => {const { t } = useTranslation('home');const { agentId, contextSelectionKey, loading, send } = useSend(mode);- // Subscribe to the SWR key so `internal_refreshAgentConfig`'s `mutate(...)`- // has a listener after toggleFile / toggleKnowledgeBase — otherwise the- // Library submenu doesn't reflect server-side toggles. Pass `agentId`- // explicitly so AgentSelect switches refetch too.+ // Mount the config sync so `internal_refreshAgentConfig`'s revalidation has+ // a listener after toggleFile / toggleKnowledgeBase — otherwise the Library+ // submenu doesn't reflect server-side toggles. Pass `agentId` explicitly so+ // AgentSelect switches refetch too.useInitAgentConfig(agentId);// Use the "config absent from agentMap" loading shape (same as Memory /// Search / History) instead of SWR's `isLoading`, which would flash ondiff --git a/src/features/Home/InputArea/useSend.test.ts b/src/features/Home/InputArea/useSend.test.tsindex 8b0164e254f..a0229b68f19 100644--- a/src/features/Home/InputArea/useSend.test.ts+++ b/src/features/Home/InputArea/useSend.test.ts@@ -44,7 +44,6 @@ const fileState = vi.hoisted(() => ({const homeState = vi.hoisted(() => ({agentGroups: [],- agentOptimisticPatches: {},homeInputLoading: false,inputActiveMode: null as any,isAgentListInit: true,diff --git a/src/features/Home/Recents/AllRecentsDrawer.tsx b/src/features/Home/Recents/AllRecentsDrawer.tsxindex 31657a2ed42..5bf11b12026 100644--- a/src/features/Home/Recents/AllRecentsDrawer.tsx+++ b/src/features/Home/Recents/AllRecentsDrawer.tsx@@ -7,7 +7,6 @@ import { useTranslation } from 'react-i18next';import SkeletonList from '@/features/NavPanel/components/SkeletonList';import SideBarDrawer from '@/features/NavPanel/SideBarDrawer';-import { useCacheScope } from '@/libs/swr/useCacheScope';import { useHomeStore } from '@/store/home';import { homeRecentSelectors } from '@/store/home/selectors';import { createRecentQueryKey } from '@/store/home/slices/recent/initialState';@@ -22,13 +21,12 @@ interface AllRecentsDrawerProps {const AllRecentsDrawer = memo<AllRecentsDrawerProps>(({ open, onClose }) => {const { t } = useTranslation('common');const [searchKeyword, setSearchKeyword] = useState('');- const scope = useCacheScope();const useFetchAllRecents = useHomeStore((s) => s.useFetchAllRecents);const queryKey = createRecentQueryKey(50);- const query = useHomeStore(homeRecentSelectors.query(scope, queryKey));- const items = query?.items;+ const items = useHomeStore(homeRecentSelectors.query(queryKey));- const { isLoading } = useFetchAllRecents(open, scope);+ const { isHydrated, isValidating } = useFetchAllRecents(open);+ const isLoading = !isHydrated || isValidating;const filteredItems = useMemo(() => {const keyword = searchKeyword.trim().toLowerCase();@@ -56,7 +54,7 @@ const AllRecentsDrawer = memo<AllRecentsDrawerProps>(({ open, onClose }) => {onClose={onClose}><Flexbox gap={1} paddingBlock={1} paddingInline={4}>- {isLoading && !query ? (+ {isLoading && !items ? (<SkeletonList rows={5} />) : filteredItems.length === 0 && searchKeyword.trim() ? (<Empty@@ -67,9 +65,7 @@ const AllRecentsDrawer = memo<AllRecentsDrawerProps>(({ open, onClose }) => {) : (filteredItems.map((item) => {const itemRef = `${item.type}:${item.id}` as const;- return (- <ConnectedItem itemRef={itemRef} key={itemRef} queryKey={queryKey} scope={scope} />- );+ return <ConnectedItem itemRef={itemRef} key={itemRef} queryKey={queryKey} />;}))}</Flexbox>diff --git a/src/features/Home/Recents/ConnectedItem.tsx b/src/features/Home/Recents/ConnectedItem.tsxindex 7d67f5baa6f..668fbd1b125 100644--- a/src/features/Home/Recents/ConnectedItem.tsx+++ b/src/features/Home/Recents/ConnectedItem.tsx@@ -11,11 +11,10 @@ import RecentListItem from './Item';interface ConnectedItemProps {itemRef: RecentEntityRef;queryKey: string;- scope: string;}-const ConnectedItem = memo<ConnectedItemProps>(({ itemRef, queryKey, scope }) => {- const item = useHomeStore(homeRecentSelectors.item(scope, queryKey, itemRef));+const ConnectedItem = memo<ConnectedItemProps>(({ itemRef, queryKey }) => {+ const item = useHomeStore(homeRecentSelectors.item(queryKey, itemRef));if (!item) return null;// `slugTitle`, not `title`: the displayed title falls back to the task'sdiff --git a/src/features/Home/Recents/List.tsx b/src/features/Home/Recents/List.tsxindex 992ac1059fc..aacaad44846 100644--- a/src/features/Home/Recents/List.tsx+++ b/src/features/Home/Recents/List.tsx@@ -19,15 +19,13 @@ interface RecentsListProps {/** Thrown error from the recents SWR — surfaced as a failure state. */error?: unknown;onRetry?: () => void;- scope: string;}-const RecentsList = memo<RecentsListProps>(({ error, onRetry, scope }) => {+const RecentsList = memo<RecentsListProps>(({ error, onRetry }) => {const { t } = useTranslation('chat');const recentPageSize = useGlobalStore(systemStatusSelectors.recentPageSize);const queryKey = createRecentQueryKey(recentPageSize + 1);- const query = useHomeStore(homeRecentSelectors.query(scope, queryKey));- const items = query?.items;+ const items = useHomeStore(homeRecentSelectors.query(queryKey));const [drawerOpen, openDrawer, closeDrawer] = useHomeStore((s) => [s.allRecentsDrawerOpen,s.openAllRecentsDrawer,@@ -46,18 +44,16 @@ const RecentsList = memo<RecentsListProps>(({ error, onRetry, scope }) => {return (<AsyncBoundarydata={items}- error={query ? undefined : error}+ error={items ? undefined : error}errorVariant={'inline'}- isLoading={!query && !error}+ isLoading={!items && !error}loading={<SkeletonList rows={3} />}onRetry={onRetry}><Flexbox gap={1}>{displayItems.map((item) => {const itemRef = `${item.type}:${item.id}` as const;- return (- <ConnectedItem itemRef={itemRef} key={itemRef} queryKey={queryKey} scope={scope} />- );+ return <ConnectedItem itemRef={itemRef} key={itemRef} queryKey={queryKey} />;})}{hasMore && (<NavItem icon={MoreHorizontalIcon} title={t('input.more')} onClick={openDrawer} />diff --git a/src/features/Home/Recents/index.tsx b/src/features/Home/Recents/index.tsxindex 38825651dd1..fea7f0d5721 100644--- a/src/features/Home/Recents/index.tsx+++ b/src/features/Home/Recents/index.tsx@@ -26,7 +26,6 @@ import { useTranslation } from 'react-i18next';import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import { openCustomizeSidebarModal } from '@/features/HomeSidebar/Body/CustomizeSidebarModal';import SkeletonList from '@/features/NavPanel/components/SkeletonList';-import { useCacheScope } from '@/libs/swr/useCacheScope';import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';import { reorderSidebarItems } from '@/store/global/selectors/systemStatus';@@ -44,13 +43,13 @@ interface RecentsProps {const Recents = memo<RecentsProps>(({ itemKey }) => {const { t } = useTranslation('common');- const scope = useCacheScope();const isLogin = useUserStore(authSelectors.isLogin);const activeWorkspaceId = useActiveWorkspaceId();const recentPageSize = useGlobalStore(systemStatusSelectors.recentPageSize);const queryKey = createRecentQueryKey(recentPageSize + 1);- const query = useHomeStore(homeRecentSelectors.query(scope, queryKey));- const syncStatus = useHomeStore(homeRecentSelectors.syncStatus(scope, queryKey));+ const items = useHomeStore(homeRecentSelectors.query(queryKey));+ const useFetchRecents = useHomeStore((s) => s.useFetchRecents);+ const syncStatus = useFetchRecents(isLogin, recentPageSize);const refreshRecents = useHomeStore((s) => s.refreshRecents);const sidebarItems = useGlobalStore(systemStatusSelectors.sidebarItems(activeWorkspaceId));const hiddenSections = useGlobalStore(@@ -129,7 +128,7 @@ const Recents = memo<RecentsProps>(({ itemKey }) => {}, [recentPageSize, updateSystemStatus, t, isFirst, isLast, moveSection, hideSection]);if (!isLogin) return null;- if (query && query.items.length === 0) return null;+ if (items && items.length === 0) return null;return (<AccordionItem value={itemKey}>@@ -140,7 +139,7 @@ const Recents = memo<RecentsProps>(({ itemKey }) => {<Text ellipsis fontSize={12} type={'secondary'} weight={500}>{t('recents')}</Text>- {syncStatus?.isValidating && query && <Spin size="small" variant="network" />}+ {syncStatus.isValidating && items && <Spin size="small" variant="network" />}</Flexbox></AccordionTrigger><div@@ -158,11 +157,7 @@ const Recents = memo<RecentsProps>(({ itemKey }) => {</ContextMenuTrigger><AccordionPanel><Suspense fallback={<SkeletonList rows={3} />}>- <RecentsList- error={syncStatus?.error}- scope={scope}- onRetry={() => void refreshRecents(scope)}- />+ <RecentsList error={syncStatus.error} onRetry={() => void refreshRecents()} /></Suspense></AccordionPanel></AccordionItem>diff --git a/src/features/Home/Recents/useDropdownMenu.tsx b/src/features/Home/Recents/useDropdownMenu.tsxindex 13dea31a865..49fb4a79435 100644--- a/src/features/Home/Recents/useDropdownMenu.tsx+++ b/src/features/Home/Recents/useDropdownMenu.tsx@@ -12,7 +12,6 @@ import { openRenameModal } from '@/components/RenameModal';import { confirmRemoveTopic } from '@/features/DeleteTopicConfirm';import { usePermission } from '@/hooks/usePermission';import type { NativeContextMenuItem } from '@/libs/contextMenu/types';-import { useCacheScope } from '@/libs/swr/useCacheScope';import { documentService } from '@/services/document';import { taskService } from '@/services/task';import { topicService } from '@/services/topic';@@ -20,7 +19,6 @@ import { useHomeStore } from '@/store/home';export const useRecentItemDropdownMenu = (item: RecentItem) => {const { t } = useTranslation(['common', 'topic', 'components']);- const scope = useCacheScope();const [renameRecent, refreshRecents] = useHomeStore((s) => [s.renameRecent, s.refreshRecents]);// Viewer can read recents but cannot rename/delete them — keep the menu@@ -38,8 +36,8 @@ export const useRecentItemDropdownMenu = (item: RecentItem) => {const transferMenuItems = documentTransferItems ?? taskTransferItems;const handleRename = useCallback(- (newTitle: string) => renameRecent({ id: item.id, scope, title: newTitle, type: item.type }),- [item.id, item.type, renameRecent, scope],+ (newTitle: string) => renameRecent({ id: item.id, title: newTitle, type: item.type }),+ [item.id, item.type, renameRecent],);const handleDelete = useCallback(() => {@@ -48,7 +46,7 @@ export const useRecentItemDropdownMenu = (item: RecentItem) => {onConfirm: async (removeFiles) => {// Home has no active agent/group, so chatStore.removeTopic early-returns; call the service directly.await topicService.removeTopic(item.id, removeFiles);- await refreshRecents(scope);+ await refreshRecents();},topicIds: [item.id],});@@ -75,11 +73,11 @@ export const useRecentItemDropdownMenu = (item: RecentItem) => {break;}}- await refreshRecents(scope);+ await refreshRecents();},title: t('delete', { ns: 'common' }),});- }, [item, refreshRecents, scope, t]);+ }, [item, refreshRecents, t]);const dropdownMenu = useCallback((): MenuProps['items'] => {const items: NativeContextMenuItem[] = [diff --git a/src/features/HomeSidebar/Body/Project/index.tsx b/src/features/HomeSidebar/Body/Project/index.tsxindex f39f6bc7d6b..a70fb526b36 100644--- a/src/features/HomeSidebar/Body/Project/index.tsx+++ b/src/features/HomeSidebar/Body/Project/index.tsx@@ -34,7 +34,11 @@ const Project = memo<ProjectProps>(({ itemKey }) => {const enabled = useUserStore(labPreferSelectors.enableProjects);const navigate = useWorkspaceAwareNavigate();const projects = useCurrentProjectList();- const { error, isLoading, mutate } = useProjectStore((s) => s.useFetchProjectList)(enabled);+ const { error, isHydrated, isValidating, revalidate } = useProjectStore(+ (s) => s.useFetchProjectList,+ )(enabled);+ // Rows come from the store; the hook only reports fetch progress.+ const isLoading = !isHydrated || isValidating;if (!enabled) return null;@@ -62,8 +66,8 @@ const Project = memo<ProjectProps>(({ itemKey }) => {</div></AccordionHeader><AccordionPanel>- {error ? (- <AsyncError error={error} variant="inline" onRetry={() => mutate()} />+ {error && projects.length === 0 ? (+ <AsyncError error={error} variant="inline" onRetry={() => revalidate()} />) : isLoading && projects.length === 0 ? (<SkeletonList rows={3} />) : projects.length === 0 ? (diff --git a/src/features/Projects/Acceptance/index.tsx b/src/features/Projects/Acceptance/index.tsxindex d7532b09cba..85a16ae689d 100644--- a/src/features/Projects/Acceptance/index.tsx+++ b/src/features/Projects/Acceptance/index.tsx@@ -4,20 +4,22 @@ import AsyncError from '@/components/AsyncError';import { RouteLoading } from '@/components/Skeleton/RouteSegment';import { AcceptanceWorkspace } from '@/features/Acceptance';import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';-import { useProjectStore } from '@/store/project';+import { useCurrentProjectDetail, useProjectStore } from '@/store/project';const ProjectAcceptance = () => {const { projectId } = useActiveRouteParams<{ projectId: string }>();- const { data, error, isLoading, mutate } = useProjectStore((s) => s.useFetchProjectDetail)(- projectId,- );+ // The persisted project paints on the first frame; the hook only syncs it.+ const detail = useCurrentProjectDetail(projectId);+ const { error, isHydrated, isValidating, revalidate } = useProjectStore(+ (s) => s.useFetchProjectDetail,+ )(projectId);- if (isLoading && !data) return <RouteLoading />;- if (error && !data)- return <AsyncError error={error} variant={'page'} onRetry={() => void mutate()} />;- if (!data) return null;+ if (!detail && (!isHydrated || isValidating)) return <RouteLoading />;+ if (error && !detail)+ return <AsyncError error={error} variant={'page'} onRetry={() => void revalidate()} />;+ if (!detail) return null;- return <AcceptanceWorkspace projectId={data.data.project.id} />;+ return <AcceptanceWorkspace projectId={detail.project.id} />;};export default ProjectAcceptance;diff --git a/src/features/Projects/Conversation/index.tsx b/src/features/Projects/Conversation/index.tsxindex 19294d8a4ec..df029cfa5c0 100644--- a/src/features/Projects/Conversation/index.tsx+++ b/src/features/Projects/Conversation/index.tsx@@ -55,8 +55,8 @@ const ProjectConversation = memo(() => {[projectSlug],);- if (detailSWR.error) {- return <AsyncError error={detailSWR.error} variant="page" onRetry={detailSWR.mutate} />;+ if (detailSWR.error && !detail) {+ return <AsyncError error={detailSWR.error} variant="page" onRetry={detailSWR.revalidate} />;}if (!detail || !coordinatorAgentId) {return (diff --git a/src/features/Projects/Goals/index.tsx b/src/features/Projects/Goals/index.tsxindex e82717bb88d..000bec79251 100644--- a/src/features/Projects/Goals/index.tsx+++ b/src/features/Projects/Goals/index.tsx@@ -4,20 +4,22 @@ import AsyncError from '@/components/AsyncError';import { RouteLoading } from '@/components/Skeleton/RouteSegment';import { AgentGoalsPage } from '@/features/AgentGoals';import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';-import { useProjectStore } from '@/store/project';+import { useCurrentProjectDetail, useProjectStore } from '@/store/project';const ProjectGoals = () => {const { projectId } = useActiveRouteParams<{ projectId: string }>();- const { data, error, isLoading, mutate } = useProjectStore((s) => s.useFetchProjectDetail)(- projectId,- );+ // The persisted project paints on the first frame; the hook only syncs it.+ const detail = useCurrentProjectDetail(projectId);+ const { error, isHydrated, isValidating, revalidate } = useProjectStore(+ (s) => s.useFetchProjectDetail,+ )(projectId);- if (isLoading && !data) return <RouteLoading />;- if (error && !data)- return <AsyncError error={error} variant={'page'} onRetry={() => void mutate()} />;- if (!data) return null;+ if (!detail && (!isHydrated || isValidating)) return <RouteLoading />;+ if (error && !detail)+ return <AsyncError error={error} variant={'page'} onRetry={() => void revalidate()} />;+ if (!detail) return null;- return <AgentGoalsPage projectId={data.data.project.id} />;+ return <AgentGoalsPage projectId={detail.project.id} />;};export default ProjectGoals;diff --git a/src/features/Projects/Layout/ProjectHeader.tsx b/src/features/Projects/Layout/ProjectHeader.tsxindex 3fbde0af3e1..ed9936f8453 100644--- a/src/features/Projects/Layout/ProjectHeader.tsx+++ b/src/features/Projects/Layout/ProjectHeader.tsx@@ -22,7 +22,11 @@ const ProjectHeader = memo<ProjectHeaderProps>(({ project }) => {const { t } = useTranslation(['project', 'common']);const navigate = useWorkspaceAwareNavigate();const projects = useCurrentProjectList();- const { error, isLoading, mutate } = useProjectStore((s) => s.useFetchProjectList)(true);+ const { error, isHydrated, isValidating, revalidate } = useProjectStore(+ (s) => s.useFetchProjectList,+ )(true);+ // Rows come from the store; the hook only reports fetch progress.+ const isLoading = !isHydrated || isValidating;const items = useMemo<SwitcherItem[]>(() =>@@ -48,12 +52,12 @@ const ProjectHeader = memo<ProjectHeaderProps>(({ project }) => {content={<SwitcherMenuactiveId={project?.slug ?? project?.id}- error={error}+ error={items.length === 0 ? error : undefined}isLoading={isLoading && items.length === 0}items={items}kind={'project'}searchPlaceholder={t('navPanel.searchProject', { ns: 'common' })}- onRetry={() => mutate()}+ onRetry={() => revalidate()}onSelect={handleSelect}/>}diff --git a/src/features/Projects/Layout/Sidebar.tsx b/src/features/Projects/Layout/Sidebar.tsxindex 6166af8e84c..7a503891b8c 100644--- a/src/features/Projects/Layout/Sidebar.tsx+++ b/src/features/Projects/Layout/Sidebar.tsx@@ -30,10 +30,12 @@ const ProjectSidebarContent = memo(() => {const header = <ProjectHeader project={detail?.project} />;- if (detailSWR.error)+ if (detailSWR.error && !detail)return (<SideBarLayout- body={<AsyncError error={detailSWR.error} variant="inline" onRetry={detailSWR.mutate} />}+ body={+ <AsyncError error={detailSWR.error} variant="inline" onRetry={detailSWR.revalidate} />+ }header={header}/>);diff --git a/src/features/Projects/List/index.tsx b/src/features/Projects/List/index.tsxindex ad5ea189e6c..7b5871f058a 100644--- a/src/features/Projects/List/index.tsx+++ b/src/features/Projects/List/index.tsx@@ -197,7 +197,11 @@ const ProjectListPage = memo(() => {const [keyword, setKeyword] = useState('');const enabled = useUserStore(labPreferSelectors.enableProjects);const projects = useCurrentProjectList();- const { error, isLoading, mutate } = useProjectStore((s) => s.useFetchProjectList)(enabled);+ const { error, isHydrated, isValidating, revalidate } = useProjectStore(+ (s) => s.useFetchProjectList,+ )(enabled);+ // Rows come from the store; the hook only reports fetch progress.+ const isLoading = !isHydrated || isValidating;const filteredProjects = useMemo(() => {const normalizedKeyword = keyword.trim().toLocaleLowerCase();@@ -234,8 +238,8 @@ const ProjectListPage = memo(() => {{t('create.action')}</Button></Flexbox>- {error ? (- <AsyncError error={error} onRetry={() => mutate()} />+ {error && projects.length === 0 ? (+ <AsyncError error={error} onRetry={() => revalidate()} />) : isLoading && projects.length === 0 ? (<SkeletonList rows={8} />) : filteredProjects.length === 0 ? (diff --git a/src/features/Projects/Workspace/index.tsx b/src/features/Projects/Workspace/index.tsxindex c3486fbc133..1121ded9b0e 100644--- a/src/features/Projects/Workspace/index.tsx+++ b/src/features/Projects/Workspace/index.tsx@@ -92,10 +92,11 @@ const ProjectWorkspace = memo(() => {const enabled = useUserStore(labPreferSelectors.enableProjects);const detail = useCurrentProjectDetail(projectId);const [message, setMessage] = useState('');- const { error, mutate } = useProjectStore((s) => s.useFetchProjectDetail)(projectId);+ const { error, revalidate } = useProjectStore((s) => s.useFetchProjectDetail)(projectId);if (!enabled) return <ProjectDisabled />;- if (error) return <AsyncError error={error} variant={'page'} onRetry={() => mutate()} />;+ if (error && !detail)+ return <AsyncError error={error} variant={'page'} onRetry={() => revalidate()} />;if (!detail)return (<Center height={'100%'}>diff --git a/src/features/ResourceTransferRequest/refreshAfterOwnershipChange.test.ts b/src/features/ResourceTransferRequest/refreshAfterOwnershipChange.test.tsindex 677d00bcf8c..cb1359d8154 100644--- a/src/features/ResourceTransferRequest/refreshAfterOwnershipChange.test.ts+++ b/src/features/ResourceTransferRequest/refreshAfterOwnershipChange.test.ts@@ -1,11 +1,12 @@import { beforeEach, describe, expect, it, vi } from 'vitest';-import { agentConfigKeys, groupKeys } from '@/libs/swr/keys';+import { groupKeys } from '@/libs/swr/keys';import { refreshCachesAfterOwnershipChange } from './refreshAfterOwnershipChange';const mocks = vi.hoisted(() => ({globalMutate: vi.fn(),+ refreshAgentConfig: vi.fn(),refreshAgentList: vi.fn(),}));@@ -13,7 +14,9 @@ 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/agent', () => ({+ getAgentStoreState: () => ({ internal_refreshAgentConfig: mocks.refreshAgentConfig }),+}));vi.mock('@/store/home', () => ({useHomeStore: { getState: () => ({ refreshAgentList: mocks.refreshAgentList }) },}));@@ -23,13 +26,11 @@ describe('refreshCachesAfterOwnershipChange', () => {vi.clearAllMocks();});- it('revalidates the agent config cache via the global mutator', async () => {+ it('refreshes the agent config through the agent store', async () => {await refreshCachesAfterOwnershipChange('agent', 'agent-1');- expect(mocks.globalMutate).toHaveBeenCalledTimes(1);- expect(mocks.globalMutate).toHaveBeenCalledWith(- agentConfigKeys.config('agent-1', 'user:workspace'),- );+ expect(mocks.refreshAgentConfig).toHaveBeenCalledWith('agent-1');+ expect(mocks.globalMutate).not.toHaveBeenCalled();expect(mocks.refreshAgentList).toHaveBeenCalled();});diff --git a/src/features/ResourceTransferRequest/refreshAfterOwnershipChange.ts b/src/features/ResourceTransferRequest/refreshAfterOwnershipChange.tsindex 9b445f3a65a..9c90563e2d7 100644--- a/src/features/ResourceTransferRequest/refreshAfterOwnershipChange.ts+++ b/src/features/ResourceTransferRequest/refreshAfterOwnershipChange.ts@@ -1,6 +1,6 @@import { mutate } from '@/libs/swr';-import { agentConfigKeys, groupKeys } from '@/libs/swr/keys';-import { getCacheScope } from '@/libs/swr/useCacheScope';+import { groupKeys } from '@/libs/swr/keys';+import { getAgentStoreState } from '@/store/agent';import { useHomeStore } from '@/store/home';/**@@ -20,7 +20,7 @@ export const refreshCachesAfterOwnershipChange = async (): Promise<void> => {await Promise.all([resourceType === 'agent'- ? mutate(agentConfigKeys.config(resourceId, getCacheScope()))+ ? getAgentStoreState().internal_refreshAgentConfig(resourceId): mutate(groupKeys.detail(resourceId)),useHomeStore.getState().refreshAgentList(),]);diff --git a/src/hooks/useFetchAgentList.ts b/src/hooks/useFetchAgentList.tsindex 5728e3a2563..6890da468c3 100644--- a/src/hooks/useFetchAgentList.ts+++ b/src/hooks/useFetchAgentList.ts@@ -1,23 +1,26 @@import { useHomeStore } from '@/store/home';+import { homeAgentListSelectors } from '@/store/home/selectors';import { useUserStore } from '@/store/user';import { authSelectors } from '@/store/user/slices/auth/selectors';/**- * Hook to fetch agent list+ * Sync the sidebar agent list (the rows come from `homeAgentListSelectors`).* @returns isRevalidating - true when background revalidation is in progress (has cached data but fetching new)- * @returns error - the thrown SWR error, so consumers can surface a failure state instead of a permanent skeleton+ * @returns error - the network error, so consumers can surface a failure state instead of a permanent skeleton* @returns mutate - retry the same request (wired into the error state's Retry)*/export const useFetchAgentList = () => {const isLogin = useUserStore(authSelectors.isLogin);const useFetchAgentListHook = useHomeStore((s) => s.useFetchAgentList);- const { isValidating, data, error, mutate } = useFetchAgentListHook(isLogin);+ const isAgentListInit = useHomeStore(homeAgentListSelectors.isAgentListInit);++ const { error, isValidating, revalidate } = useFetchAgentListHook(isLogin);return {error,// isRevalidating: has cached data, updating in background- isRevalidating: isValidating && !!data,- mutate,+ isRevalidating: isValidating && isAgentListInit,+ mutate: revalidate,};};diff --git a/src/hooks/useInitAgentConfig.test.ts b/src/hooks/useInitAgentConfig.test.tsindex 249258b870f..b90efeda167 100644--- a/src/hooks/useInitAgentConfig.test.ts+++ b/src/hooks/useInitAgentConfig.test.ts@@ -1,6 +1,7 @@import { act, renderHook } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';+import type * as CacheScopeModule from '@/libs/swr/useCacheScope';import { useAgentStore } from '@/store/agent';import { useUserStore } from '@/store/user';@@ -8,7 +9,10 @@ import { useInitAgentConfig } from './useInitAgentConfig';const scope = vi.hoisted(() => ({ current: 'user-1:workspace-a' }));-vi.mock('@/libs/swr/useCacheScope', () => ({ useCacheScope: () => scope.current }));+vi.mock('@/libs/swr/useCacheScope', async (importOriginal) => ({+ ...(await importOriginal<typeof CacheScopeModule>()),+ useCacheScope: () => scope.current,+}));vi.mock('react-router', () => ({ useParams: () => ({}) }));describe('useInitAgentConfig', () => {@@ -17,7 +21,7 @@ describe('useInitAgentConfig', () => {useUserStore.setState({ isSignedIn: true } as any);act(() => {useAgentStore.setState({- agentConfigScopeMap: { 'agent-1': 'user-1:workspace-a' },+ agentConfigReplica: { entries: {}, scope: 'user-1:workspace-a' },agentMap: { 'agent-1': { title: 'From workspace A' } },useFetchAgentConfig: (() => ({ isLoading: true })) as any,});diff --git a/src/hooks/usePrefetchAgent.test.ts b/src/hooks/usePrefetchAgent.test.tsindex fe21bc87105..5d18a454681 100644--- a/src/hooks/usePrefetchAgent.test.ts+++ b/src/hooks/usePrefetchAgent.test.ts@@ -1,31 +1,30 @@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' }) },+const mocks = vi.hoisted(() => ({ prefetchAgentConfig: vi.fn() }));++vi.mock('@/store/agent', () => ({+ getAgentStoreState: () => ({ prefetchAgentConfig: mocks.prefetchAgentConfig }),}));describe('usePrefetchAgent', () => {beforeEach(() => vi.clearAllMocks());- it('passes one unaugmented identity-scoped key to the scoped mutate wrapper', () => {+ it('warms the agent config replica', () => {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');+ expect(mocks.prefetchAgentConfig).toHaveBeenCalledWith('agent-1');+ });++ it('ignores an empty id', () => {+ const { result } = renderHook(() => usePrefetchAgent());++ act(() => result.current(''));++ expect(mocks.prefetchAgentConfig).not.toHaveBeenCalled();});});diff --git a/src/hooks/usePrefetchAgent.ts b/src/hooks/usePrefetchAgent.tsindex 400e371941b..364e216220b 100644--- a/src/hooks/usePrefetchAgent.ts+++ b/src/hooks/usePrefetchAgent.ts@@ -1,27 +1,16 @@import { useCallback } from 'react';-import { mutate } from '@/libs/swr';-import { agentConfigKeys } from '@/libs/swr/keys';-import { getCacheScope } from '@/libs/swr/useCacheScope';-import { agentService } from '@/services/agent';+import { getAgentStoreState } from '@/store/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 identity-scoped key `useFetchAgentConfig` reads. The scoped- * mutate wrapper appends the workspace once; callers must not pre-augment it.+ * Returns a callback that warms an agent's config before navigation (call it+ * on mouseEnter). The config lands in `agentMap`, so the page paints it on+ * its first frame; agents already there are skipped.*/export const usePrefetchAgent = () => {return useCallback((agentId: string) => {if (!agentId) return;- const key = agentConfigKeys.config(agentId, getCacheScope());-- // Populate the SWR cache without triggering re-renders on consuming hooks- mutate(key, agentService.getAgentConfigById(agentId), {- // Don't revalidate if data already exists- revalidate: false,- });+ void getAgentStoreState().prefetchAgentConfig(agentId);}, []);};diff --git a/src/hooks/useSyncRecents.ts b/src/hooks/useSyncRecents.tsindex 66d4250bba0..6edb7b48718 100644--- a/src/hooks/useSyncRecents.ts+++ b/src/hooks/useSyncRecents.ts@@ -1,4 +1,3 @@-import { useCacheScope } from '@/libs/swr/useCacheScope';import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';import { useHomeStore } from '@/store/home';@@ -8,8 +7,7 @@ import { authSelectors } from '@/store/user/selectors';export const useSyncRecents = (): void => {const useFetchRecents = useHomeStore((s) => s.useFetchRecents);const isLogin = useUserStore(authSelectors.isLogin);- const scope = useCacheScope();const recentPageSize = useGlobalStore(systemStatusSelectors.recentPageSize);- useFetchRecents(isLogin, scope, recentPageSize);+ useFetchRecents(isLogin, recentPageSize);};diff --git a/src/libs/replica/index.ts b/src/libs/replica/index.tsindex 5645dbb4d67..e6927ef9bab 100644--- a/src/libs/replica/index.ts+++ b/src/libs/replica/index.ts@@ -3,6 +3,7 @@ import {type DefinePagedReplicaOptions,defineReplica as defineCoreReplica,type DefineReplicaOptions,+ isReplicaSyncKey,type ReplicaPagedData,type ReplicaResource,type ReplicaScope,@@ -84,6 +85,18 @@ export const replicaSWRDriver = createSWRDriver({useSWR: (key, fetcher, config) => useClientDataSWR(key, fetcher, config),});+/**+ * Revalidate a replica's sync queries (one entry, or all of the active scope)+ * from code that cannot reach the owning store without an import cycle.+ */+export const revalidateReplica = (+ resource: Pick<ReplicaResource<any, any, any>, 'name' | 'scope'>,+ key?: string,+) =>+ replicaSWRDriver.revalidate((queryKey) =>+ isReplicaSyncKey(queryKey, resource.name, { key, scope: resource.scope.get() }),+ );+/** `createReplicaSlice` bound to the app's SWR driver. */export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(resource: ReplicaResource<TParams, TData, TFetched>,@@ -91,4 +104,4 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>() => createCoreReplicaSlice(resource, { driver: replicaSWRDriver, ...options });export * from '@lobechat/replica';-export { recordLens, type ReplicaSyncResult } from '@lobechat/replica/zustand';+export { recordLens, type ReplicaLens, type ReplicaSyncResult } from '@lobechat/replica/zustand';diff --git a/src/libs/swr/keys.test.ts b/src/libs/swr/keys.test.tsindex 5bb57d873fb..1087646ffd9 100644--- a/src/libs/swr/keys.test.ts+++ b/src/libs/swr/keys.test.ts@@ -1,15 +1,12 @@+import { replicaKeys } from '@lobechat/replica';import { unstable_serialize } from 'swr';import { describe, expect, it } from 'vitest';import {agentBuilderKeys,- agentConfigKeys,- agentKeys,- agentProjectionKeys,documentCommentKeys,isAcceptanceListKey,isDocumentCommentKeyForEvent,- projectKeys,recentKeys,resourceKeys,taskKeys,@@ -19,27 +16,6 @@ import {import { CACHE_TIERS } from './localStorageProvider';describe('recentKeys', () => {- it('keys the Home recent list by identity cache scope', () => {- expect(recentKeys.list(true, 10, 'user-1:workspace-1')).toEqual([- 'recent:list',- true,- 10,- 'user-1:workspace-1',- ]);- });-- it('keeps users isolated in the same workspace', () => {- expect(recentKeys.list(true, 10, 'user-1:workspace-1')).not.toEqual(- recentKeys.list(true, 10, 'user-2:workspace-1'),- );- });-- it('keeps workspaces isolated for the same user', () => {- expect(recentKeys.allDrawer(true, 'user-1:workspace-1')).not.toEqual(- recentKeys.allDrawer(true, 'user-1:workspace-2'),- );- });-it('keys the Home topic-only list independently from mixed recents', () => {expect(recentKeys.topicList(9, 'user-1:workspace-1', 'mine')).toEqual(['recent:topicList',@@ -68,25 +44,12 @@ 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',- ]);- });-+describe('replica sync keys', () => {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'),+ // Replicas persist through their own storage, never through the SWR tiers.+ replicaKeys.sync('agentList', 1, 'user-1:personal', 'sidebar', {}),+ replicaKeys.sync('agentConfig', 1, 'user-1:personal', 'agent-1', { agentId: 'agent-1' }),]) {const serialized = unstable_serialize(key);expect(@@ -96,20 +59,6 @@ describe('agent projection keys', () => {});});-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 c30e8d58603..99d9209eb1b 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -243,31 +243,6 @@ export const isDocumentCommentKeyForEvent = (return false;};-// ---- agent ---------------------------------------------------------------export const agentKeys = {- /** 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 -------------------------------------------------------export const agentLabelKeys = {/**@@ -330,19 +305,6 @@ export const threadKeys = {// ---- recent -------------------------------------------------------------export const recentKeys = {- /** Home "all recents" drawer list, keyed by open state and identity scope. */- allDrawer: def('recent:allDrawer', (open: boolean, scope: string) => [- 'recent:allDrawer',- open,- scope,- ]),- /** Home recents list, keyed by login + limit + identity scope. */- list: def('recent:list', (isLogin: boolean, limit: number, scope: string) => [- 'recent:list',- isLogin,- limit,- scope,- ]),/** Home chat-only list; filtering happens before the server-side limit. */topicList: def('recent:topicList', (limit: number, scope: string, view: 'mine' | 'team') => ['recent:topicList',@@ -547,43 +509,14 @@ export const homeInboxKeys = {};// ---- agent config / available / search -----------------------------------// (agentKeys.list defined above)export const agentConfigKeys = {available: def('agent:available', () => ['agent:available']),- 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) => [@@ -1569,7 +1502,7 @@ export const matchDomain =* Aggregate registry — one entry point for every domain's keys.*/export const swrKeys = {- agent: { ...agentKeys, ...agentConfigKeys, ...agentProjectionKeys },+ agent: agentConfigKeys,agentBot: agentBotKeys,agentBuilder: agentBuilderKeys,agentDocument: agentDocumentSWRKeys,@@ -1611,7 +1544,6 @@ export const swrKeys = {onboarding: onboardingKeys,openInApp: openInAppKeys,portal: portalKeys,- project: projectKeys,provider: providerKeys,ragEval: ragEvalKeys,recent: recentKeys,diff --git a/src/libs/swr/localStorageProvider.ts b/src/libs/swr/localStorageProvider.tsindex 4cf77d08a5a..e30838f58cf 100644--- a/src/libs/swr/localStorageProvider.ts+++ b/src/libs/swr/localStorageProvider.ts@@ -484,7 +484,6 @@ export const CACHE_TIERS = {'topic:', // topic lists / agent view / search'agent:', // sidebar agent list + agent documents'builtinAgent:', // builtin identity and configuration used by the first paint- 'project/list', // project sidebar lists restored before their background refresh'group:detail', // group detail (group list stays in localStorage)'task:', // task lists + detail'document:', // editor document contentdiff --git a/src/libs/swr/useClientDataSWRWithSync.ts b/src/libs/swr/useClientDataSWRWithSync.tsindex 79b3e2c2192..39ea88e4484 100644--- a/src/libs/swr/useClientDataSWRWithSync.ts+++ b/src/libs/swr/useClientDataSWRWithSync.ts@@ -38,12 +38,12 @@ interface UseClientDataSWRWithSyncOptions<T> extends SWRConfiguration<T> {* @example* ```ts* useClientDataSWRWithSync(- * isLogin ? agentKeys.list(isLogin, scope) : null,- * () => homeService.getSidebarAgentList(),+ * isLogin ? groupKeys.list(scope) : null,+ * () => groupService.getGroups(),* {* onData: (data) => {* // Auto sync to store, whether cached or fresh data- * set({ ...mapResponseToState(data), isInit: true });+ * set({ groups: data, isInit: true });* },* skipSync: state.isInit, // Optional: skip after initialized* }diff --git a/src/routes/(main)/project/[projectId]/tasks/index.tsx b/src/routes/(main)/project/[projectId]/tasks/index.tsxindex 3f2e6a565c4..1ee1e46b195 100644--- a/src/routes/(main)/project/[projectId]/tasks/index.tsx+++ b/src/routes/(main)/project/[projectId]/tasks/index.tsx@@ -4,20 +4,22 @@ import AsyncError from '@/components/AsyncError';import { RouteLoading } from '@/components/Skeleton/RouteSegment';import { AgentTasksPage } from '@/features/AgentTasks';import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';-import { useProjectStore } from '@/store/project';+import { useCurrentProjectDetail, useProjectStore } from '@/store/project';const ProjectTasks = () => {const { projectId } = useActiveRouteParams<{ projectId: string }>();- const { data, error, isLoading, mutate } = useProjectStore((s) => s.useFetchProjectDetail)(- projectId,- );+ // The persisted project paints on the first frame; the hook only syncs it.+ const detail = useCurrentProjectDetail(projectId);+ const { error, isHydrated, isValidating, revalidate } = useProjectStore(+ (s) => s.useFetchProjectDetail,+ )(projectId);- if (isLoading && !data) return <RouteLoading />;- if (error && !data)- return <AsyncError error={error} variant={'page'} onRetry={() => void mutate()} />;- if (!data) return null;+ if (!detail && (!isHydrated || isValidating)) return <RouteLoading />;+ if (error && !detail)+ return <AsyncError error={error} variant={'page'} onRetry={() => void revalidate()} />;+ if (!detail) return null;- return <AgentTasksPage projectId={data.data.project.id} />;+ return <AgentTasksPage projectId={detail.project.id} />;};export default ProjectTasks;diff --git a/src/store/agent/selectors/agentByIdSelectors.test.ts b/src/store/agent/selectors/agentByIdSelectors.test.tsindex a9328981774..dfb1fc03f1d 100644--- a/src/store/agent/selectors/agentByIdSelectors.test.ts+++ b/src/store/agent/selectors/agentByIdSelectors.test.ts@@ -213,7 +213,7 @@ 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' },+ agentConfigReplica: { entries: {}, scope: 'user-1:workspace-a' },agentMap: { 'agent-1': { title: 'From workspace A' } },});diff --git a/src/store/agent/selectors/agentByIdSelectors.ts b/src/store/agent/selectors/agentByIdSelectors.tsindex 89c45137a48..3a2a885d520 100644--- a/src/store/agent/selectors/agentByIdSelectors.ts+++ b/src/store/agent/selectors/agentByIdSelectors.ts@@ -84,14 +84,14 @@ const isAgentConfigLoadingById = (agentId: string) => (s: AgentStoreState) =>!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.+ * Whether the config for `agentId` belongs to `scope` and may be rendered.+ * `agentMap` only ever holds one scope; this guards the frame between a scope+ * switch and the replica dropping the previous identity's entries.*/const hasAgentConfigInScope =(agentId: string, scope: string) =>(s: AgentStoreState): boolean =>- !!agentId && !!s.agentMap[agentId] && s.agentConfigScopeMap[agentId] === scope;+ !!agentId && !!s.agentMap[agentId] && s.agentConfigReplica.scope === scope;/*** Get agent mode by agentId.diff --git a/src/store/agent/slices/agent/action.test.ts b/src/store/agent/slices/agent/action.test.tsindex 28f844aaaa4..defc2f0e092 100644--- a/src/store/agent/slices/agent/action.test.ts+++ b/src/store/agent/slices/agent/action.test.ts@@ -6,8 +6,9 @@ import { SWRConfig, unstable_serialize } from 'swr';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import * as activeWorkspaceModule from '@/business/client/hooks/useActiveWorkspaceId';+import { cacheScope, createReplicaState, replicaKeys } from '@/libs/replica';import { setScopedMutate } from '@/libs/swr';-import { agentConfigKeys, builtinAgentKeys } from '@/libs/swr/keys';+import { builtinAgentKeys } from '@/libs/swr/keys';import * as cacheScopeModule from '@/libs/swr/useCacheScope';import { getCacheScope } from '@/libs/swr/useCacheScope';import { agentService } from '@/services/agent';@@ -18,6 +19,7 @@ import { type LobeAgentConfig } from '@/types/agent';import { withSWR } from '~test-utils';import { useAgentStore } from '../../store';+import { agentConfigResource } from './projection';// Mock agentServicevi.mock('@/services/agent', () => ({@@ -75,7 +77,10 @@ beforeEach(() => {setScopedMutate(vi.fn() as any);useAgentStore.setState({activeAgentId: undefined,+ agentConfigErrorMap: {},+ agentConfigReplica: createReplicaState(),agentMap: {},+ agentNotFoundMap: {},builtinAgentIdMap: {},availableAgents: undefined,updateAgentConfigSignal: undefined,@@ -151,13 +156,7 @@ describe('AgentSlice Actions', () => {.optimisticUpdateAgentMeta('inbox-1', { name: 'Renamed chief' });expect(agentService.getBuiltinAgent).not.toHaveBeenCalled();- expect(scopedMutate).toHaveBeenCalledWith(- agentConfigKeys.config('inbox-1', getCacheScope()),- updatedAgent,- {- revalidate: false,- },- );+ expect(useAgentStore.getState().agentMap['inbox-1']).toMatchObject({ name: 'Renamed chief' });expect(scopedMutate).toHaveBeenCalledWith(builtinAgentKeys.init('inbox', cacheScopeModule.getCacheScope()),updatedAgent,@@ -203,9 +202,7 @@ describe('AgentSlice Actions', () => {scopedMutate.mock.calls.some(([key]) =>JSON.stringify(key) ===- JSON.stringify(agentConfigKeys.config('inbox-1', getCacheScope())) ||- JSON.stringify(key) ===- JSON.stringify(builtinAgentKeys.init('inbox', 'user-b:personal')),+ JSON.stringify(builtinAgentKeys.init('inbox', 'user-b:personal')),),).toBe(false);});@@ -1145,7 +1142,7 @@ describe('AgentSlice Actions', () => {// Note: refreshSessions is no longer called after optimistic update// as the implementation now uses API returned data directly- it('seeds the scoped config cache with the confirmed response without another request', async () => {+ it('confirms the saved response in the replica without another request', async () => {const { result } = renderHook(() => useAgentStore());const scopedMutate = vi.fn().mockResolvedValue(undefined);setScopedMutate(scopedMutate as any);@@ -1168,11 +1165,14 @@ describe('AgentSlice Actions', () => {});});- expect(scopedMutate).toHaveBeenCalledWith(- agentConfigKeys.config('agent-1', getCacheScope()),- { id: 'agent-1', model: 'model-b', provider: 'lobehub' },- { revalidate: false },- );+ expect(agentService.getAgentConfigById).not.toHaveBeenCalled();+ expect(useAgentStore.getState().agentMap['agent-1']).toEqual({+ id: 'agent-1',+ model: 'model-b',+ provider: 'lobehub',+ });+ // Confirmed (and persisted) as a server value, not left as a local edit.+ expect(useAgentStore.getState().agentConfigReplica.entries['agent-1'].source).toBe('server');});it('should not refresh agent config SWR cache when save fails', async () => {@@ -1201,7 +1201,9 @@ describe('AgentSlice Actions', () => {.filter((key): key is (candidate: unknown) => boolean => typeof key === 'function');expect(configCacheMatchers.some((matcher) =>- matcher(agentConfigKeys.config('agent-1', getCacheScope())),+ matcher(+ replicaKeys.sync('agentConfig', 1, getCacheScope(), 'agent-1', { agentId: 'agent-1' }),+ ),),).toBe(false);expect(result.current.agentMap['agent-1']).toMatchObject({ model: 'model-b' });@@ -1272,7 +1274,8 @@ describe('AgentSlice Actions', () => {});expect(agentService.getAgentConfigById).not.toHaveBeenCalled();- expect(result.current.data).toBeUndefined();+ expect(result.current.isLoading).toBe(false);+ expect(useAgentStore.getState().agentMap['agent-1']).toBeUndefined();});it('should not fetch when isLogin is undefined', async () => {@@ -1282,7 +1285,7 @@ describe('AgentSlice Actions', () => {);expect(agentService.getAgentConfigById).not.toHaveBeenCalled();- expect(result.current.data).toBeUndefined();+ expect(result.current.isLoading).toBe(false);});it('should not fetch when agentId is a chat-group session id', async () => {@@ -1293,7 +1296,7 @@ describe('AgentSlice Actions', () => {);expect(agentService.getAgentConfigById).not.toHaveBeenCalled();- expect(result.current.data).toBeUndefined();+ expect(result.current.isLoading).toBe(false);});it('should fetch agent config when logged in with valid agentId', async () => {@@ -1309,7 +1312,10 @@ describe('AgentSlice Actions', () => {wrapper: withSWR,});- await waitFor(() => expect(result.current.data).toEqual(mockAgentConfig));+ await waitFor(() =>+ expect(useAgentStore.getState().agentMap['agent-1']).toEqual(mockAgentConfig),+ );+ expect(result.current.isLoading).toBe(false);expect(agentService.getAgentConfigById).toHaveBeenCalledWith('agent-1');expect(useAgentStore.getState().activeAgentId).toBe('agent-1');@@ -1345,7 +1351,10 @@ describe('AgentSlice Actions', () => {wrapper: withSWR,});- await waitFor(() => expect(result.current.data).toEqual(mockAgentConfig));+ await waitFor(() =>+ expect(useAgentStore.getState().agentMap['agent-1']).toEqual(mockAgentConfig),+ );+ expect(result.current.isLoading).toBe(false);expect(useAgentStore.getState().agentConfigErrorMap['agent-1']).toBeUndefined();});@@ -1394,12 +1403,110 @@ describe('AgentSlice Actions', () => {wrapper: withSWR,});- await waitFor(() => expect(result.current.data).toEqual(mockAgentConfig));+ await waitFor(() =>+ expect(useAgentStore.getState().agentMap['agent-1']).toEqual(mockAgentConfig),+ );+ expect(result.current.isLoading).toBe(false);expect(useAgentStore.getState().agentNotFoundMap['agent-1']).toBeUndefined();});});+ describe('agent config replica', () => {+ const scopeOf = (id: string) => `agent-config-${id}:personal`;+ /** The replica reads its own scope binding; keep the app's getter in step. */+ const useScope = (get: () => string) => {+ vi.spyOn(cacheScopeModule, 'getCacheScope').mockImplementation(get);+ vi.spyOn(cacheScope, 'get').mockImplementation(get);+ vi.spyOn(cacheScope, 'use').mockImplementation(get);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ };++ it('paints the persisted config before the network answers', async () => {+ const scope = scopeOf(crypto.randomUUID());+ useScope(() => scope);+ await agentConfigResource.storage!.set(+ { queryKey: 'agent-1', scope },+ { data: { id: 'agent-1', title: 'Cached' }, updatedAt: 1 },+ );+ let resolveFetch!: (value: any) => void;+ vi.mocked(agentService.getAgentConfigById).mockImplementation(+ () => new Promise((resolve) => (resolveFetch = resolve)),+ );++ renderHook(() => useAgentStore().useFetchAgentConfig(true, 'agent-1'), { wrapper: withSWR });++ await waitFor(() =>+ expect(useAgentStore.getState().agentMap['agent-1']).toMatchObject({ title: 'Cached' }),+ );+ expect(useAgentStore.getState().agentConfigReplica.entries['agent-1'].source).toBe('storage');++ await act(async () => resolveFetch({ id: 'agent-1', title: 'Server' }));+ await waitFor(() =>+ expect(useAgentStore.getState().agentMap['agent-1']).toEqual({+ id: 'agent-1',+ title: 'Server',+ }),+ );+ });++ it('keeps optimistic edits out of the persisted row', async () => {+ const scope = scopeOf(crypto.randomUUID());+ useScope(() => scope);+ vi.spyOn(console, 'error').mockImplementation(() => {});+ vi.mocked(agentService.updateAgentConfig).mockRejectedValue(new Error('offline'));+ act(() => {+ useAgentStore.getState().internal_dispatchAgentMap('agent-1', { model: 'model-a' });+ });++ await act(async () => {+ await useAgentStore+ .getState()+ .updateAgentConfigById('agent-1', { model: 'model-b' }, { showErrorMessage: false });+ });++ // The failed edit stays on screen (#16337) but never becomes the cached truth.+ expect(useAgentStore.getState().agentMap['agent-1']).toMatchObject({ model: 'model-b' });+ expect(+ await agentConfigResource.storage!.get({ queryKey: 'agent-1', scope }),+ ).toBeUndefined();+ });++ it('drops the previous identity configs on a scope switch', () => {+ let scope = scopeOf('a');+ useScope(() => scope);+ act(() => {+ useAgentStore.getState().internal_dispatchAgentMap('agent-a', { title: 'From A' });+ });+ expect(useAgentStore.getState().agentMap['agent-a']).toBeDefined();++ scope = scopeOf('b');+ act(() => {+ useAgentStore.getState().internal_dispatchAgentMap('agent-b', { title: 'From B' });+ });++ expect(useAgentStore.getState().agentMap).toEqual({ 'agent-b': { title: 'From B' } });+ expect(useAgentStore.getState().agentConfigReplica.scope).toBe(scopeOf('b'));+ });++ it('prefetches a config into agentMap, skipping agents already loaded', async () => {+ vi.mocked(agentService.getAgentConfigById).mockResolvedValue({+ id: 'agent-1',+ title: 'Prefetched',+ } as any);++ await act(async () => {+ await useAgentStore.getState().prefetchAgentConfig('agent-1');+ });+ expect(useAgentStore.getState().agentMap['agent-1']).toMatchObject({ title: 'Prefetched' });++ await act(async () => {+ await useAgentStore.getState().prefetchAgentConfig('agent-1');+ });+ expect(agentService.getAgentConfigById).toHaveBeenCalledTimes(1);+ });+ });+describe('useHydrateAgentConfig', () => {it('should hydrate agent config without changing activeAgentId', async () => {const mockAgentConfig = {@@ -1415,7 +1522,10 @@ describe('AgentSlice Actions', () => {wrapper: withSWR,});- await waitFor(() => expect(result.current.data).toEqual(mockAgentConfig));+ await waitFor(() =>+ expect(useAgentStore.getState().agentMap['agent-1']).toEqual(mockAgentConfig),+ );+ expect(result.current.isLoading).toBe(false);expect(agentService.getAgentConfigById).toHaveBeenCalledWith('agent-1');expect(useAgentStore.getState().activeAgentId).toBe('agent-current');diff --git a/src/store/agent/slices/agent/action.ts b/src/store/agent/slices/agent/action.tsindex d042b182dcc..6b7c6ae0a2d 100644--- a/src/store/agent/slices/agent/action.ts+++ b/src/store/agent/slices/agent/action.ts@@ -16,14 +16,14 @@ import type { PartialDeep } from 'type-fest';import { getActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import { MESSAGE_CANCEL_FLAT } from '@/const/message';import { analyticsClient } from '@/libs/analytics/client';-import { mutate, useClientDataSWR, useClientDataSWRWithSync } from '@/libs/swr';import {- agentConfigKeys,- agentProjectionKeys,- builtinAgentKeys,- isAgentConfigKey,- isAgentListKey,-} from '@/libs/swr/keys';+ createReplicaSlice,+ recordLens,+ type ReplicaSyncResult,+ revalidateReplica,+} from '@/libs/replica';+import { mutate, useClientDataSWR, useClientDataSWRWithSync } from '@/libs/swr';+import { agentConfigKeys, builtinAgentKeys } from '@/libs/swr/keys';import { getCacheScope } from '@/libs/swr/useCacheScope';import type { AvailableAgentItem, CreateAgentParams, CreateAgentResult } from '@/services/agent';import { agentService, AVAILABLE_AGENTS_CONTEXT_QUERY_LIMIT } from '@/services/agent';@@ -36,6 +36,8 @@ import {import { aiAgentService } from '@/services/aiAgent';import { useGlobalStore } from '@/store/global';import { globalGeneralSelectors } from '@/store/global/selectors';+// Projection module only (no store import), so this does not cycle through the home store.+import { agentListResource } from '@/store/home/slices/agentList/projection';import type { StoreSetter } from '@/store/types';import { getUserStoreState } from '@/store/user';import { userProfileSelectors } from '@/store/user/selectors';@@ -51,8 +53,7 @@ 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';+import { agentConfigResource } from './projection';export type AgentMetaUpdate = Partial<Pick<@@ -104,6 +105,37 @@ const preserveWorkingDirDeleteMarkers = (merged.workingDirByDevice = workingDirByDevice as Record<string, string>;};+/**+ * Deep-merge a partial config into the current one. `profile` is replaced as a+ * whole and `undefined` working directories are deletes (see the call sites).+ * Returns `current` itself when nothing changed, so readers keep their reference.+ */+const mergeAgentConfig = (+ current: PartialDeep<AgentItem> | undefined,+ config: PartialDeep<LobeAgentConfig>,+): PartialDeep<AgentItem> => {+ if (!current) return config;+ const { value } = produce({ value: current }, (draft) => {+ draft.value = merge(draft.value, config);+ // The character sheet is authored as one document — `AgentModel`+ // replaces it rather than merging — so mirror that here, or a trait the+ // user just cleared reappears until the next full fetch.+ if (Object.hasOwn(config, 'profile')) draft.value.profile = config.profile;+ // merge() can't drop keys; honor `undefined` as a per-device delete so+ // clearing a working directory takes effect optimistically.+ pruneWorkingDirByDeviceDeletes(draft.value.agencyConfig, config.agencyConfig);+ });+ return isEqual(current, value) ? current : value;+};++/** `useFetchAgentConfig` result: replica sync flags plus the SWR-era aliases. */+export interface AgentConfigSyncResult extends ReplicaSyncResult {+ /** A request is in flight and there is nothing in `agentMap` to show yet. */+ isLoading: boolean;+ /** Alias of `revalidate`. */+ mutate: () => Promise<unknown>;+}+/*** Agent Slice Actions* Handles agent CRUD operations (config/meta updates)@@ -119,41 +151,57 @@ export class AgentSliceActionImpl {readonly #pendingAgentDocuments = new Map<string, Promise<AgentContextDocument[] | undefined>>();readonly #updateAgentConfigControllers = new Map<string, AbortController>();readonly #updateAgentMetaControllers = new Map<string, AbortController>();+ readonly #config;constructor(set: Setter, get: () => AgentStore, _api?: unknown) {void _api;this.#set = set;this.#get = get;+ this.#config = createReplicaSlice(agentConfigResource, {+ actionPrefix: 'agentConfig',+ fetcher: async ({ agentId }) =>+ (await agentService.getAgentConfigById(agentId)) as LobeAgentConfig | null,+ get,+ // The endpoint returns a complete, authoritative profile: replace the+ // entry instead of patching it, so fields cleared on the server (e.g.+ // `editorData: null`) don't survive from an older local copy. `null`+ // (not found) is settled by the sync hooks; an unchanged profile keeps+ // its reference.+ merge: (incoming, confirmed) =>+ !incoming || isEqual(incoming, confirmed) ? undefined : incoming,+ set,+ stateKey: 'agentConfigReplica',+ view: recordLens<AgentStore, PartialDeep<AgentItem>>('agentMap'),+ });}- #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();+ /** Confirmed, persisted value of an agent's config. */+ #replaceConfirmedAgentConfig = (+ agentId: string,+ scope: string,+ data: PartialDeep<AgentItem>,+ ): void => {+ this.#config.replace({ agentId }, data as LobeAgentConfig, scope);+ };++ /** Fetch result of `useFetchAgentConfig` / `useHydrateAgentConfig`. */+ #settleAgentConfigFetch = (agentId: string, data: LobeAgentConfig | null): boolean => {+ // 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".+ if (!data) {+ this.#markAgentNotFound(agentId);+ return false;+ }+ this.#clearAgentNotFound(agentId);+ return true;};- #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() },- );- };+ #toAgentConfigSyncResult = (sync: ReplicaSyncResult, agentId: string): AgentConfigSyncResult => ({+ ...sync,+ isLoading: sync.isValidating && !this.#get().agentMap[agentId],+ mutate: sync.revalidate,+ });#createAgentScopedAbortController = (controllers: Map<string, AbortController>,@@ -452,69 +500,40 @@ export class AgentSliceActionImpl {);};- useFetchAgentConfig = (- isLogin: boolean | undefined,- agentId: string,- ): SWRResponse<LobeAgentConfig> => {- const scope = getCacheScope();- const swrKey =- isLogin === true && agentId && !isChatGroupSessionId(agentId)- ? agentConfigKeys.config(agentId, scope)- : null;-- 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;+ useFetchAgentConfig = (isLogin: boolean | undefined, agentId: string): AgentConfigSyncResult => {+ const sync = this.#config.useSync(agentId ? { agentId } : null, {+ enabled: isLogin === true && !isChatGroupSessionId(agentId),+ onError: (error: any) => {+ this.#set(+ (state) => ({+ agentConfigErrorMap: {+ ...state.agentConfigErrorMap,+ [agentId]: error?.message || String(error),+ },+ }),+ false,+ 'fetchAgentConfig/error',+ );},- {- 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".- if (!data) {- this.#markAgentNotFound(agentId);- return;- }- this.#clearAgentNotFound(agentId);- // This endpoint returns a complete, authoritative profile snapshot.- // 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 (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).- // A background or secondary config fetch — e.g. the inbox config- // requested by the home input, a side-panel copilot, or another- // open tab — must NOT hijack `activeAgentId` away from the routed- // agent, which would otherwise flash the conversation header/welcome- // back to the inbox ("Lobe AI") agent.- if (!this.#get().activeAgentId) {- this.#set({ activeAgentId: data.id }, false, 'fetchAgentConfig');- }- this.#clearAgentConfigError(agentId);- },- onError: (error) => {- this.#set(- (state) => ({- agentConfigErrorMap: {- ...state.agentConfigErrorMap,- [agentId]: error?.message || String(error),- },- }),- false,- 'fetchAgentConfig/error',- );- },+ onSuccess: (data) => {+ if (!this.#settleAgentConfigFetch(agentId, data)) return;+ // 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).+ // A background or secondary config fetch — e.g. the inbox config+ // requested by the home input, a side-panel copilot, or another+ // open tab — must NOT hijack `activeAgentId` away from the routed+ // agent, which would otherwise flash the conversation header/welcome+ // back to the inbox ("Lobe AI") agent. A response of a previous scope+ // never lands in `agentMap`, so it adopts nothing either.+ if (!this.#get().activeAgentId && this.#get().agentMap[agentId]) {+ this.#set({ activeAgentId: data!.id }, false, 'fetchAgentConfig');+ }+ this.#clearAgentConfigError(agentId);},- );+ });++ return this.#toAgentConfigSyncResult(sync, agentId);};useFetchServerDefaultHeterogeneousCapability = (enabled: boolean) =>@@ -525,17 +544,26 @@ export class AgentSliceActionImpl {/*** Re-trigger the agent config fetch after a failure. Clears the recorded* error first so consumers fall back to the loading skeleton, then- * revalidates every SWR entry for this agent (keys may carry a workspace- * suffix, hence the filter form).+ * revalidates this agent's sync in the active scope.*/retryAgentConfigFetch = async (agentId?: string): Promise<void> => {const id = agentId ?? this.#get().activeAgentId;if (!id) return;- const scope = getCacheScope();this.#clearAgentConfigError(id);- await mutate((key) => isAgentConfigKey(key, id, scope));+ await this.#config.revalidate(id);+ };++ /**+ * Warm an agent's config before navigation (sidebar hover). Skips agents+ * already in `agentMap`; the page's own sync revalidates them on mount.+ */+ prefetchAgentConfig = async (agentId: string): Promise<void> => {+ if (!agentId || this.#get().agentMap[agentId]) return;+ const scope = getCacheScope();+ const data = await agentService.getAgentConfigById(agentId);+ if (data) this.#replaceConfirmedAgentConfig(agentId, scope, data as LobeAgentConfig);};#markAgentNotFound = (agentId: string) => {@@ -543,21 +571,14 @@ export class AgentSliceActionImpl {if (agentNotFoundMap[agentId] && !agentMap[agentId]) return;this.#set(- (state) => {- // Also drop the previously cached config: surfaces reading `agentMap`- // (title/avatar in the sidebar or header) must not keep showing an- // agent the viewer lost access to next to the 404 content area.- const nextAgentMap = { ...state.agentMap };- delete nextAgentMap[agentId];- return {- agentMap: nextAgentMap,- agentNotFoundMap: { ...state.agentNotFoundMap, [agentId]: true },- };- },+ (state) => ({ agentNotFoundMap: { ...state.agentNotFoundMap, [agentId]: true } }),false,'markAgentNotFound',);- agentConfigWriteQueue.remove({ queryKey: agentId, scope: getCacheScope() });+ // Also drop the previously cached config (and its persisted row): surfaces+ // reading `agentMap` (title/avatar in the sidebar or header) must not keep+ // showing an agent the viewer lost access to next to the 404 content area.+ this.#config.remove(agentId);};#clearAgentNotFound = (agentId: string) => {@@ -588,37 +609,17 @@ export class AgentSliceActionImpl {);};+ /** Like `useFetchAgentConfig`, but never touches `activeAgentId` or the error map. */useHydrateAgentConfig = (isLogin: boolean | undefined,agentId: string,- ): SWRResponse<LobeAgentConfig> => {- const scope = getCacheScope();- const swrKey =- isLogin === true && agentId && !isChatGroupSessionId(agentId)- ? agentConfigKeys.config(agentId, scope)- : null;-- useClientDataSWR(swrKey ? agentProjectionKeys.configHydration(scope, agentId) : null, () =>- this.#hydrateAgentConfig(agentId, scope),- );+ ): AgentConfigSyncResult => {+ const sync = this.#config.useSync(agentId ? { agentId } : null, {+ enabled: isLogin === true && !isChatGroupSessionId(agentId),+ onSuccess: (data) => void this.#settleAgentConfigFetch(agentId, data),+ });- return useClientDataSWR<LobeAgentConfig>(- swrKey,- async () => {- const data = await agentService.getAgentConfigById(agentId);- return data as LobeAgentConfig;- },- {- onSuccess: (data) => {- if (!data) {- this.#markAgentNotFound(agentId);- return;- }- this.#clearAgentNotFound(agentId);- if (getCacheScope() === scope) this.#replaceConfirmedAgentConfig(agentId, scope, data);- },- },- );+ return this.#toAgentConfigSyncResult(sync, agentId);};useFetchAgentDocuments = (agentId?: string | null): SWRResponse<AgentDocumentListItem[]> => {@@ -677,25 +678,13 @@ export class AgentSliceActionImpl {return request;};+ /**+ * Merge a partial config into `agentMap` (optimistic edits, configs other+ * stores already fetched). In-memory only: the persisted row holds confirmed+ * server values, written through `#replaceConfirmedAgentConfig`.+ */internal_dispatchAgentMap = (id: string, config: PartialDeep<LobeAgentConfig>): void => {- const agentMap = produce(this.#get().agentMap, (draft) => {- if (!draft[id]) {- draft[id] = config;- } else {- draft[id] = merge(draft[id], config);- // The character sheet is authored as one document — `AgentModel`- // replaces it rather than merging — so mirror that here, or a trait the- // user just cleared reappears until the next full fetch.- if (Object.hasOwn(config, 'profile')) draft[id].profile = config.profile;- // merge() can't drop keys; honor `undefined` as a per-device delete so- // clearing a working directory takes effect optimistically.- pruneWorkingDirByDeviceDeletes(draft[id].agencyConfig, config.agencyConfig);- }- });-- if (isEqual(this.#get().agentMap, agentMap)) return;-- this.#set({ agentMap }, false, 'dispatchAgentMap');+ this.#config.update(id, (current) => mergeAgentConfig(current, config), { persist: false });};#mergeLatestAgencyConfigPatch = (@@ -739,7 +728,7 @@ export class AgentSliceActionImpl {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);+ if (confirmed) this.#replaceConfirmedAgentConfig(id, scope, confirmed);// Refresh agent:config so cached model A cannot replay after a// successful model A -> B update.await this.#get().internal_refreshAgentConfig(id, result.agent, scope);@@ -793,9 +782,9 @@ export class AgentSliceActionImpl {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);+ if (confirmed) this.#replaceConfirmedAgentConfig(id, scope, confirmed);await this.#get().internal_refreshAgentConfig(id, result.agent, scope);- void mutate((key) => isAgentListKey(key, scope));+ void revalidateReplica(agentListResource);this.#get().invalidateAvailableAgents();}updateSaveStatus('saved');@@ -806,12 +795,8 @@ export class AgentSliceActionImpl {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');- }+ if (previous) this.#replaceConfirmedAgentConfig(id, scope, previous);+ else this.#config.update(id, () => undefined, { persist: false });throw error;}}@@ -828,21 +813,24 @@ export class AgentSliceActionImpl {.filter(([, agentId]) => agentId === id).map(([slug]) => slug);- /** Reuse the authoritative update response; other mutations still need a network refresh. */+ /**+ * Reuse the authoritative update response (the replica already holds it);+ * other mutations still need a network refresh.+ */if (updatedAgent) {- await Promise.all([- mutate(agentConfigKeys.config(id, scope), updatedAgent, { revalidate: false }),- ...slugs.map((slug) =>+ await Promise.all(+ slugs.map((slug) =>mutate(builtinAgentKeys.init(slug, scope), updatedAgent as AgentItem, {revalidate: false,}),),- ]);+ );return;}+ if (scope !== getCacheScope()) return;await Promise.all([- mutate((key) => isAgentConfigKey(key, id, scope)),+ this.#config.revalidate(id),...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 9f0139a379e..221c228bfd9 100644--- a/src/store/agent/slices/agent/initialState.ts+++ b/src/store/agent/slices/agent/initialState.ts@@ -2,6 +2,7 @@ import type { AgentContextDocument } from '@lobechat/context-engine';import type { PartialDeep } from 'type-fest';import { type AgentSettingsInstance } from '@/features/AgentSetting';+import { createReplicaState, type ReplicaState } from '@/libs/replica';import { type AvailableAgentItem } from '@/services/agent';import { type AgentItem } from '@/types/agent';import { type MetaData } from '@/types/meta';@@ -19,8 +20,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'>;+ /** Replica bookkeeping for agent configs (`agentMap` is its view). */+ agentConfigReplica: ReplicaState<PartialDeep<AgentItem>>;agentDocumentsMap: Record<string, AgentContextDocument[]>;agentMap: Record<string, PartialDeep<AgentItem>>;/**@@ -78,8 +79,7 @@ export interface AgentSliceState {export const initialAgentSliceState: AgentSliceState = {agentConfigErrorMap: {},- agentConfigScopeMap: {},- agentConfigSourceMap: {},+ agentConfigReplica: createReplicaState(),agentDocumentsMap: {},agentMap: {},agentNotFoundMap: {},diff --git a/src/store/agent/slices/agent/projection.ts b/src/store/agent/slices/agent/projection.tsindex 7c9bd88ba4c..4343bfdd0df 100644--- a/src/store/agent/slices/agent/projection.ts+++ b/src/store/agent/slices/agent/projection.ts@@ -1,10 +1,22 @@-import {- IndexedDBQueryProjectionStorage,- QueryProjectionWriteQueue,-} from '@/libs/queryProjectionStorage';-import type { LobeAgentConfig } from '@/types/agent';+import type { PartialDeep } from 'type-fest';-export const agentConfigProjection = new IndexedDBQueryProjectionStorage<LobeAgentConfig>({- namespace: 'lobechat-agent-config-v1',+import { defineReplica } from '@/libs/replica';+import type { AgentItem, LobeAgentConfig } from '@/types/agent';++export interface AgentConfigParams {+ agentId: string;+}++/**+ * One agent's config per entry, keyed by agent id. The fetch resolves `null`+ * when the agent is gone or no longer visible to the viewer.+ */+export const agentConfigResource = defineReplica<+ AgentConfigParams,+ PartialDeep<AgentItem>,+ LobeAgentConfig | null+>({+ key: ({ agentId }) => agentId,+ name: 'agentConfig',+ version: 1,});-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.tsdeleted file mode 100644index 29639110a41..00000000000--- a/src/store/agent/slices/agent/reducer.test.ts+++ /dev/null@@ -1,47 +0,0 @@-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.tsdeleted file mode 100644index aae81577951..00000000000--- a/src/store/agent/slices/agent/reducer.ts+++ /dev/null@@ -1,54 +0,0 @@-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/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.tsindex a76e2026189..aa9bdb0020f 100644--- a/src/store/chat/slices/topic/action.ts+++ b/src/store/chat/slices/topic/action.ts@@ -28,6 +28,7 @@ import {recordLens,type ReplicaPageResult,type ReplicaSyncResult,+ singleEntity,} from '@/libs/replica';import { mutate, useClientDataSWRWithSync } from '@/libs/swr';import { cronKeys, deviceKeys, topicKeys } from '@/libs/swr/keys';@@ -268,7 +269,7 @@ export class ChatTopicActionImpl {});this.#topicDetail = createReplicaSlice(topicDetailResource, {actionPrefix: n('topicDetail'),- entity: { getId: (topic) => topic.id },+ entity: singleEntity<ChatTopic>((topic) => topic.id),fetcher: (topicId) => topicService.getTopicDetail(topicId),get,// A missing topic keeps whatever is cached (the list may still hold it).diff --git a/src/store/home/slices/agentList/action.test.ts b/src/store/home/slices/agentList/action.test.tsnew file mode 100644index 00000000000..bb7ac702b74--- /dev/null+++ b/src/store/home/slices/agentList/action.test.ts@@ -0,0 +1,133 @@+/**+ * @vitest-environment happy-dom+ *+ * The sidebar agent list is a replica whose view is the store's flat bucket+ * fields: it paints from localStorage on the first frame, and a rename shows+ * in whichever bucket (pinned, folder, private …) holds the agent.+ */+import { randomUUID } from 'node:crypto';++import type { SidebarAgentItem, SidebarAgentListResponse } from '@lobechat/types';+import { act, renderHook, waitFor } from '@testing-library/react';+import type { PropsWithChildren } from 'react';+import { createElement, useEffect } from 'react';+import { SWRConfig, useSWRConfig } from 'swr';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { cacheScope } from '@/libs/replica';+import { setScopedMutate } from '@/libs/swr/mutate';+import { homeService } from '@/services/home';+import { getAgentStoreState } from '@/store/agent';+import { useHomeStore } from '@/store/home';+import { homeAgentListSelectors } from '@/store/home/selectors';++import { initialAgentListState } from './initialState';+import { agentListResource } from './projection';++vi.mock('@/store/agent', () => ({+ getAgentStoreState: vi.fn(() => ({+ invalidateAvailableAgents: vi.fn(),+ updateAgentMetaById: vi.fn(),+ })),+}));++const MutateBridge = () => {+ const { mutate } = useSWRConfig();+ useEffect(() => setScopedMutate(mutate), [mutate]);+ return null;+};+const wrapper = ({ children }: PropsWithChildren) =>+ createElement(+ SWRConfig,+ { value: { dedupingInterval: 0, provider: () => new Map() } },+ createElement(MutateBridge),+ children,+ );++const UPDATED_AT = new Date('2026-01-01T00:00:00.000Z');+const agent = (id: string, title = id): SidebarAgentItem =>+ ({ id, pinned: false, title, type: 'agent', updatedAt: UPDATED_AT }) as SidebarAgentItem;++const response = (overrides: Partial<SidebarAgentListResponse> = {}): SidebarAgentListResponse => ({+ groups: [],+ pinned: [],+ privateGroups: [],+ privatePinned: [],+ privateUngrouped: [],+ ungrouped: [],+ ...overrides,+});++let scope = '';+beforeEach(() => {+ scope = `agent-list-user-${randomUUID()}:personal`;+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ act(() => useHomeStore.setState({ ...initialAgentListState }));+});++afterEach(() => {+ vi.restoreAllMocks();+ localStorage.clear();+});++const sync = () => renderHook(() => useHomeStore((s) => s.useFetchAgentList)(true), { wrapper });++describe('sidebar agent list replica', () => {+ it('paints the persisted list before the network answers', async () => {+ await agentListResource.storage!.set(+ { queryKey: agentListResource.storageKey({}), scope },+ { data: response({ pinned: [agent('a1', 'Cached')] }), updatedAt: 1 },+ );+ vi.spyOn(homeService, 'getSidebarAgentList').mockImplementation(() => new Promise(() => {}));++ sync();++ await waitFor(() => expect(useHomeStore.getState().isAgentListInit).toBe(true));+ expect(homeAgentListSelectors.pinnedAgents(useHomeStore.getState())[0].title).toBe('Cached');+ });++ it('keeps bucket references when the server returns an unchanged list', async () => {+ const list = response({ ungrouped: [agent('a1')] });+ const getList = vi+ .spyOn(homeService, 'getSidebarAgentList')+ .mockResolvedValue(structuredClone(list));+ sync();+ await waitFor(() => expect(useHomeStore.getState().ungroupedAgents).toHaveLength(1));+ const before = useHomeStore.getState().ungroupedAgents;++ getList.mockResolvedValue(structuredClone(list));+ await act(() => useHomeStore.getState().refreshAgentList());++ expect(useHomeStore.getState().ungroupedAgents).toBe(before);+ });++ it('renames the agent in its folder right away and rolls back on failure', async () => {+ vi.spyOn(homeService, 'getSidebarAgentList').mockResolvedValue(+ response({+ groups: [{ id: 'g1', items: [agent('a1', 'Old')], title: 'Folder' } as any],+ privatePinned: [agent('a2')],+ }),+ );+ sync();+ await waitFor(() => expect(useHomeStore.getState().agentGroups).toHaveLength(1));++ let reject!: (error: Error) => void;+ const updateAgentMetaById = vi.fn(() => new Promise<void>((_, fail) => (reject = fail)));+ vi.mocked(getAgentStoreState).mockReturnValue({+ invalidateAvailableAgents: vi.fn(),+ updateAgentMetaById,+ } as any);++ const rename = useHomeStore.getState().updateAgentMeta('a1', { title: 'New' });+ expect(useHomeStore.getState().agentGroups[0].items[0].title).toBe('New');+ // Other buckets are untouched.+ expect(useHomeStore.getState().privatePinnedAgents[0].title).toBe('a2');+ expect(updateAgentMetaById).toHaveBeenCalledWith('a1', { title: 'New' }, { rethrow: true });++ reject(new Error('boom'));+ await expect(rename).rejects.toThrow('boom');+ expect(useHomeStore.getState().agentGroups[0].items[0].title).toBe('Old');+ });+});diff --git a/src/store/home/slices/agentList/action.ts b/src/store/home/slices/agentList/action.tsindex e6ab9c9b230..912df568b53 100644--- a/src/store/home/slices/agentList/action.ts+++ b/src/store/home/slices/agentList/action.ts@@ -1,35 +1,114 @@-import type { SidebarAgentItem, SidebarAgentListResponse } from '@lobechat/types';+import type { SidebarAgentItem, SidebarAgentListResponse, SidebarGroup } from '@lobechat/types';+import isEqual from 'fast-deep-equal';import { type SWRResponse } from 'swr';-import { mutate, useClientDataSWR } from '@/libs/swr';-import { agentConfigKeys, agentKeys, agentProjectionKeys, isAgentListKey } from '@/libs/swr/keys';-import { getCacheScope } from '@/libs/swr/useCacheScope';+import {+ createReplicaSlice,+ linkReplicaEntity,+ type ReplicaEntityAdapter,+ type ReplicaLens,+ type ReplicaSyncResult,+} from '@/libs/replica';+import { useClientDataSWR } from '@/libs/swr';+import { agentConfigKeys } from '@/libs/swr/keys';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 type { SidebarAgentMetaPatch } from './initialState';-import { AGENT_LIST_QUERY, agentListProjection, agentListWriteQueue } from './projection';-import type { AgentListDispatchAction } from './reducer';-import { agentListReducer } from './reducer';+import {+ initialAgentListState,+ mapResponseToState,+ mapStateToResponse,+ type SidebarAgentMetaPatch,+} from './initialState';+import { AGENT_LIST_KEY, agentListResource } from './projection';const n = setNamespace('agentList');+const LIST_PARAMS = {} as Record<string, never>;++const EMPTY_RESPONSE: SidebarAgentListResponse = mapStateToResponse(initialAgentListState);++/**+ * The sidebar list keeps its long-standing flat fields (`pinnedAgents`,+ * `agentGroups` …) as the replica view, so every selector reads what it did.+ */+const agentListLens: ReplicaLens<HomeStore, SidebarAgentListResponse> = {+ clear: () => ({ ...mapResponseToState(EMPTY_RESPONSE), isAgentListInit: false }),+ get: (state) => (state.isAgentListInit ? mapStateToResponse(state) : undefined),+ keys: (state) => (state.isAgentListInit ? [AGENT_LIST_KEY] : []),+ set: (_state, _key, data) =>+ data+ ? { ...mapResponseToState(data), isAgentListInit: true }+ : { ...mapResponseToState(EMPTY_RESPONSE), isAgentListInit: false },+};++type ItemFn = (item: SidebarAgentItem) => SidebarAgentItem | undefined;++const mapItems = (items: SidebarAgentItem[], id: string, fn: ItemFn) => {+ if (!items.some((item) => item.id === id)) return items;+ return items.flatMap((item) => {+ if (item.id !== id) return [item];+ const next = fn(item);+ return next ? [next] : [];+ });+};++const mapGroups = (groups: SidebarGroup[], id: string, fn: ItemFn) => {+ if (!groups.some((group) => group.items.some((item) => item.id === id))) return groups;+ return groups.map((group) => {+ const items = mapItems(group.items, id, fn);+ return items === group.items ? group : { ...group, items };+ });+};++/** One agent can sit in any bucket, including a folder of either section. */+const sidebarAgentEntity: ReplicaEntityAdapter<SidebarAgentListResponse, SidebarAgentItem> = {+ has: (data, id) =>+ [data.pinned, data.ungrouped, data.privatePinned, data.privateUngrouped].some((items) =>+ items?.some((item) => item.id === id),+ ) ||+ [data.groups, data.privateGroups].some((groups) =>+ groups?.some((group) => group.items.some((item) => item.id === id)),+ ),+ // Private buckets may be absent on rows persisted before they existed.+ map: (data, id, fn) => ({+ ...data,+ groups: mapGroups(data.groups, id, fn),+ pinned: mapItems(data.pinned, id, fn),+ privateGroups: mapGroups(data.privateGroups ?? [], id, fn),+ privatePinned: mapItems(data.privatePinned ?? [], id, fn),+ privateUngrouped: mapItems(data.privateUngrouped ?? [], id, fn),+ ungrouped: mapItems(data.ungrouped, id, fn),+ }),+};+type Setter = StoreSetter<HomeStore>;export const createAgentListSlice = (set: Setter, get: () => HomeStore, _api?: unknown) =>new AgentListActionImpl(set, get, _api);export class AgentListActionImpl {- readonly #get: () => HomeStore;readonly #set: Setter;- #updateMutationId = 0;+ readonly #agentList;+ readonly #agents;constructor(set: Setter, get: () => HomeStore, _api?: unknown) {void _api;this.#set = set;- this.#get = get;+ this.#agentList = createReplicaSlice(agentListResource, {+ actionPrefix: n('agentList'),+ entity: sidebarAgentEntity,+ fetcher: () => homeService.getSidebarAgentList(),+ get,+ // An unchanged list must not re-render every sidebar section.+ merge: (incoming, confirmed) => (isEqual(incoming, confirmed) ? undefined : incoming),+ set,+ stateKey: 'agentListReplica',+ view: agentListLens,+ });+ this.#agents = linkReplicaEntity<SidebarAgentItem>([this.#agentList]);}closeAllAgentsDrawer = (): void => {@@ -41,61 +120,23 @@ export class AgentListActionImpl {};refreshAgentList = async (): Promise<void> => {- const scope = getCacheScope();getAgentStoreState().invalidateAvailableAgents();- 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() },- );- }+ await this.#agentList.revalidate(AGENT_LIST_KEY);};+ /** Rename / re-avatar an agent: the sidebar row changes now, rolls back on failure. */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> => {- 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(),- {- onSuccess: (data) => {- if (getCacheScope() === scope)- this.internal_dispatchAgentList({ data, scope, type: 'replace' });- },- },+ await this.#agents.optimistic(+ id,+ (item) => ({ ...item, ...patch }),+ () => getAgentStoreState().updateAgentMetaById(id, patch, { rethrow: true }),);};+ /** Fetch orchestration only; read the list through `homeAgentListSelectors`. */+ useFetchAgentList = (isLogin: boolean | undefined): ReplicaSyncResult =>+ this.#agentList.useSync(LIST_PARAMS, { enabled: isLogin === true });+useSearchAgents = (keyword?: string): SWRResponse<SidebarAgentItem[]> => {return useClientDataSWR<SidebarAgentItem[]>(agentConfigKeys.search(keyword), async () => {if (!keyword) return [];diff --git a/src/store/home/slices/agentList/initialState.ts b/src/store/home/slices/agentList/initialState.tsindex 282046072fa..5ffeb03e644 100644--- a/src/store/home/slices/agentList/initialState.ts+++ b/src/store/home/slices/agentList/initialState.ts@@ -4,6 +4,7 @@ import {type SidebarGroup,} from '@lobechat/types';+import { createReplicaState, type ReplicaState } from '@/libs/replica';import type { AgentMetaUpdate } from '@/store/agent/slices/agent/action';export type SidebarAgentMetaPatch = Pick<@@ -16,12 +17,8 @@ export interface AgentListState {* Agent groups (user-defined folders)*/agentGroups: SidebarGroup[];- agentListScope?: string;- agentListSource?: 'server' | 'storage';- agentOptimisticPatches: Record<- string,- { mutationId: number; patch: SidebarAgentMetaPatch; scope: string }- >;+ /** Replica bookkeeping for the sidebar agent list (the flat fields are its view). */+ agentListReplica: ReplicaState<SidebarAgentListResponse>;/*** Whether all agents drawer is open*/@@ -58,9 +55,7 @@ export interface AgentListState {export const initialAgentListState: AgentListState = {agentGroups: [],- agentOptimisticPatches: {},- agentListScope: undefined,- agentListSource: undefined,+ agentListReplica: createReplicaState(),allAgentsDrawerOpen: false,isAgentListInit: false,pinnedAgents: [],@@ -70,9 +65,7 @@ export const initialAgentListState: AgentListState = {ungroupedAgents: [],};-/**- * Helper to update state from API response- */+/** The view fields an agent list response is spread into. */export const mapResponseToState = (response: SidebarAgentListResponse,): Pick<@@ -91,3 +84,13 @@ export const mapResponseToState = (privateUngroupedAgents: response.privateUngrouped ?? [],ungroupedAgents: response.ungrouped,});++/** Inverse of {@link mapResponseToState}: the replica value behind the flat fields. */+export const mapStateToResponse = (state: AgentListState): SidebarAgentListResponse => ({+ groups: state.agentGroups,+ pinned: state.pinnedAgents,+ privateGroups: state.privateAgentGroups,+ privatePinned: state.privatePinnedAgents,+ privateUngrouped: state.privateUngroupedAgents,+ ungrouped: state.ungroupedAgents,+});diff --git a/src/store/home/slices/agentList/projection.ts b/src/store/home/slices/agentList/projection.tsindex e069224e1ae..5472b2e88f2 100644--- a/src/store/home/slices/agentList/projection.ts+++ b/src/store/home/slices/agentList/projection.ts@@ -1,14 +1,15 @@import type { SidebarAgentListResponse } from '@lobechat/types';-import {- LocalStorageQueryProjectionStorage,- QueryProjectionWriteQueue,-} from '@/libs/queryProjectionStorage';+import { defineReplica } from '@/libs/replica';-export const AGENT_LIST_QUERY = 'sidebar';-export const agentListProjection = new LocalStorageQueryProjectionStorage<SidebarAgentListResponse>(- {- namespace: 'lobechat-agent-list-v1',- },-);-export const agentListWriteQueue = new QueryProjectionWriteQueue(agentListProjection);+/** The sidebar agent list is one entry per scope. */+export const AGENT_LIST_KEY = 'sidebar';++/** Sidebar agents (pinned / grouped / ungrouped, plus private buckets). */+export const agentListResource = defineReplica<Record<string, never>, SidebarAgentListResponse>({+ key: () => AGENT_LIST_KEY,+ name: 'agentList',+ // localStorage: the sidebar is the first thing painted on boot.+ storage: 'localStorage',+ version: 1,+});diff --git a/src/store/home/slices/agentList/reducer.test.ts b/src/store/home/slices/agentList/reducer.test.tsdeleted file mode 100644index ce8d8e007c9..00000000000--- a/src/store/home/slices/agentList/reducer.test.ts+++ /dev/null@@ -1,93 +0,0 @@-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.tsdeleted file mode 100644index e1812016e94..00000000000--- a/src/store/home/slices/agentList/reducer.ts+++ /dev/null@@ -1,125 +0,0 @@-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 74564397189..dedbfe34523 100644--- a/src/store/home/slices/agentList/selectors.test.ts+++ b/src/store/home/slices/agentList/selectors.test.ts@@ -7,8 +7,6 @@ import { homeAgentListSelectors } from './selectors';const createState = (overrides: Partial<HomeStore>): HomeStore =>({agentGroups: [],- agentListScope: 'personal',- agentOptimisticPatches: {},pinnedAgents: [],privateAgentGroups: [],privatePinnedAgents: [],@@ -30,19 +28,6 @@ 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 fc11fa94e51..ffc29ee1773 100644--- a/src/store/home/slices/agentList/selectors.ts+++ b/src/store/home/slices/agentList/selectors.ts@@ -1,60 +1,38 @@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 && 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[] =>- applyOptimisticPatches(s.pinnedAgents, s);+const pinnedAgents = (s: HomeStore): SidebarAgentItem[] => s.pinnedAgents;/*** Get all agent groups (folders)*/-const agentGroups = (s: HomeStore): SidebarGroup[] => applyGroupOptimisticPatches(s.agentGroups, s);+const agentGroups = (s: HomeStore): SidebarGroup[] => s.agentGroups;/*** Get private agent groups (folders) owned by the current user.* Empty array in personal mode.*/-const privateAgentGroups = (s: HomeStore): SidebarGroup[] =>- applyGroupOptimisticPatches(s.privateAgentGroups, s);+const privateAgentGroups = (s: HomeStore): SidebarGroup[] => s.privateAgentGroups;/*** Get pinned private agents owned by the current user.* Empty array in personal mode.*/-const privatePinnedAgents = (s: HomeStore): SidebarAgentItem[] =>- applyOptimisticPatches(s.privatePinnedAgents, s);+const privatePinnedAgents = (s: HomeStore): SidebarAgentItem[] => s.privatePinnedAgents;/*** Get all ungrouped agents*/-const ungroupedAgents = (s: HomeStore): SidebarAgentItem[] =>- applyOptimisticPatches(s.ungroupedAgents, s);+const ungroupedAgents = (s: HomeStore): SidebarAgentItem[] => s.ungroupedAgents;/*** Get ungrouped private agents owned by the current user.* Empty array in personal mode.*/-const privateUngroupedAgents = (s: HomeStore): SidebarAgentItem[] =>- applyOptimisticPatches(s.privateUngroupedAgents, s);+const privateUngroupedAgents = (s: HomeStore): SidebarAgentItem[] => s.privateUngroupedAgents;/*** Whether the current user has any private content in this workspace.@@ -70,7 +48,7 @@ const hasPrivateAgents = (s: HomeStore): boolean =>const ungroupedAgentsLimited =(pageSize: number) =>(s: HomeStore): SidebarAgentItem[] =>- applyOptimisticPatches(s.ungroupedAgents.slice(0, pageSize), s);+ s.ungroupedAgents.slice(0, pageSize);/*** Limit private ungrouped agents for the Private sidebar bucket@@ -78,7 +56,7 @@ const ungroupedAgentsLimited =const privateUngroupedAgentsLimited =(pageSize: number) =>(s: HomeStore): SidebarAgentItem[] =>- applyOptimisticPatches(s.privateUngroupedAgents.slice(0, pageSize), s);+ s.privateUngroupedAgents.slice(0, pageSize);/*** Get ungrouped agents count@@ -108,7 +86,7 @@ const allAgents = (s: HomeStore): SidebarAgentItem[] => {...s.privatePinnedAgents,...privateGroupedAgents,...s.privateUngroupedAgents,- ].map((item) => applyOptimisticPatch(item, s));+ ];};/**diff --git a/src/store/home/slices/recent/action.test.ts b/src/store/home/slices/recent/action.test.tsindex c682e324514..e1ff259ffe7 100644--- a/src/store/home/slices/recent/action.test.ts+++ b/src/store/home/slices/recent/action.test.ts@@ -1,14 +1,25 @@+/**+ * @vitest-environment happy-dom+ *+ * Recents are a replica: the sidebar paints the persisted rows on the first+ * frame, and a rename shows at once in every loaded recents query.+ */+import { randomUUID } from 'node:crypto';+import type { RecentItem } from '@lobechat/types';-import { act, waitFor } from '@testing-library/react';+import { act, renderHook, waitFor } from '@testing-library/react';+import type { PropsWithChildren } from 'react';+import { createElement, useEffect } from 'react';+import { SWRConfig, useSWRConfig } from 'swr';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import * as swr from '@/libs/swr';-import { recentKeys } from '@/libs/swr/keys';-import * as cacheScope from '@/libs/swr/useCacheScope';+import { cacheScope } from '@/libs/replica';+import { setScopedMutate } from '@/libs/swr/mutate';+import { recentService } from '@/services/recent';import { taskService } from '@/services/task';import { useHomeStore } from '@/store/home';import { createRecentQueryKey, initialRecentState } from '@/store/home/slices/recent/initialState';-import { recentProjection } from '@/store/home/slices/recent/projection';+import { recentListResource } from '@/store/home/slices/recent/projection';import { homeRecentSelectors } from '@/store/home/slices/recent/selectors';const item = (id: string, title: string, type: RecentItem['type'] = 'task'): RecentItem => ({@@ -34,12 +45,53 @@ const deferred = <T>() => {return { promise, reject, resolve };};-const replaceQuery = (scope: string, queryKey: string, items: RecentItem[]) =>- useHomeStore.getState().internal_replaceRecentQuery(scope, queryKey, items);+const MutateBridge = () => {+ const { mutate } = useSWRConfig();+ useEffect(() => setScopedMutate(mutate), [mutate]);+ return null;+};+const wrapper = ({ children }: PropsWithChildren) =>+ createElement(+ SWRConfig,+ { value: { dedupingInterval: 0, provider: () => new Map() } },+ createElement(MutateBridge),+ children,+ );++const SIDEBAR = createRecentQueryKey(11);+const DRAWER = createRecentQueryKey(50);+const titleOf = (queryKey: string, ref: `${RecentItem['type']}:${string}`) =>+ homeRecentSelectors.item(queryKey, ref)(useHomeStore.getState())?.title;++let scope = '';+const useScope = (next: string) => {+ scope = next;+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+};++/** Load the sidebar (10 + 1 rows) and, optionally, the drawer through the real sync path. */+const load = async (sidebar: RecentItem[], drawer?: RecentItem[]) => {+ vi.spyOn(recentService, 'getAll').mockImplementation(async (limit) =>+ limit === 50 ? (drawer ?? []) : sidebar,+ );+ renderHook(+ () => {+ useHomeStore((s) => s.useFetchRecents)(true, 10);+ useHomeStore((s) => s.useFetchAllRecents)(!!drawer);+ },+ { wrapper },+ );+ await waitFor(() => {+ expect(useHomeStore.getState().recentListMap[SIDEBAR]).toBeDefined();+ if (drawer) expect(useHomeStore.getState().recentListMap[DRAWER]).toBeDefined();+ });+};beforeEach(() => {- useHomeStore.setState({ ...initialRecentState });- vi.spyOn(cacheScope, 'getCacheScope').mockReturnValue('user-1:ws-A');+ useScope(`recent-user-${randomUUID()}:personal`);+ act(() => useHomeStore.setState({ ...initialRecentState }));});afterEach(() => {@@ -47,148 +99,120 @@ afterEach(() => {localStorage.clear();});-describe('RecentActionImpl', () => {- it('keeps list projections isolated by scope and query', () => {- const compactQuery = createRecentQueryKey(11);- const drawerQuery = createRecentQueryKey(50);+describe('recents replica', () => {+ it('paints the persisted rows before the network answers', async () => {+ await recentListResource.storage!.set(+ { queryKey: recentListResource.storageKey({ limit: 11 }), scope },+ { data: [item('a', 'Cached')], updatedAt: 1 },+ );+ vi.spyOn(recentService, 'getAll').mockImplementation(() => new Promise(() => {}));- act(() => {- replaceQuery('user-1:ws-A', compactQuery, [item('a', 'Compact')]);- replaceQuery('user-1:ws-A', drawerQuery, [item('a', 'Drawer'), item('b', 'B')]);+ const { result } = renderHook(() => useHomeStore((s) => s.useFetchRecents)(true, 10), {+ wrapper,});- expect(- homeRecentSelectors.query('user-1:ws-A', compactQuery)(useHomeStore.getState())?.items,- ).toEqual([item('a', 'Compact')]);- expect(- homeRecentSelectors.query('user-1:ws-A', drawerQuery)(useHomeStore.getState())?.items,- ).toEqual([item('a', 'Drawer'), item('b', 'B')]);+ await waitFor(() => expect(titleOf(SIDEBAR, 'task:a')).toBe('Cached'));+ expect(result.current.isValidating).toBe(true);});- it('persists query projections through the async storage contract', async () => {- const queryKey = createRecentQueryKey(11);- act(() => replaceQuery('user-1:ws-A', queryKey, [item('a', 'Cached')]));-- const persisted = await recentProjection.get({ queryKey, scope: 'user-1:ws-A' });- expect(persisted?.data[0].title).toBe('Cached');- expect(persisted?.data[0].updatedAt).toEqual(new Date(0));- });-- it('ignores storage hydration that resolves after server data', async () => {- const queryKey = createRecentQueryKey(11);- const cached = deferred<Awaited<ReturnType<typeof recentProjection.get>>>();- vi.spyOn(recentProjection, 'get').mockReturnValue(cached.promise);-- const hydration = useHomeStore.getState().hydrateRecentQuery('user-1:ws-A', queryKey);- act(() => replaceQuery('user-1:ws-A', queryKey, [item('a', 'Server')]));- cached.resolve({ data: [item('a', 'Cached')], updatedAt: 1 });- await hydration;-- expect(- homeRecentSelectors.query('user-1:ws-A', queryKey)(useHomeStore.getState())?.items[0].title,- ).toBe('Server');- });-- it('ignores a query update after the active cache scope changed', () => {- act(() => replaceQuery('user-1:ws-B', createRecentQueryKey(11), [item('stale', 'STALE')]));- expect(useHomeStore.getState().recentsByScope['user-1:ws-B']).toBeUndefined();+ it('does not fetch while logged out', () => {+ const getAll = vi.spyOn(recentService, 'getAll');+ renderHook(() => useHomeStore((s) => s.useFetchRecents)(false, 10), { wrapper });+ expect(getAll).not.toHaveBeenCalled();});it('shows an optimistic title and rolls it back when persistence fails', async () => {- const queryKey = createRecentQueryKey(11);+ await load([item('a', 'Old')]);const request = deferred<TaskUpdateResult>();vi.spyOn(taskService, 'update').mockReturnValue(request.promise);- act(() => replaceQuery('user-1:ws-A', queryKey, [item('a', 'Old')]));const renamePromise = useHomeStore.getState()- .renameRecent({ id: 'a', scope: 'user-1:ws-A', title: 'Draft', type: 'task' });- expect(- homeRecentSelectors.item('user-1:ws-A', queryKey, 'task:a')(useHomeStore.getState())?.title,- ).toBe('Draft');+ .renameRecent({ id: 'a', title: 'Draft', type: 'task' });+ expect(titleOf(SIDEBAR, 'task:a')).toBe('Draft');- await Promise.resolve();request.reject(new Error('failed'));await expect(renamePromise).rejects.toThrow('failed');- expect(- homeRecentSelectors.item('user-1:ws-A', queryKey, 'task:a')(useHomeStore.getState())?.title,- ).toBe('Old');+ expect(titleOf(SIDEBAR, 'task:a')).toBe('Old');});- it('fans a confirmed rename out to every loaded query projection', async () => {- const compactQuery = createRecentQueryKey(11);- const drawerQuery = createRecentQueryKey(50);+ it('renames the entity in every loaded query, not same-id rows of other types', async () => {+ await load(+ [item('same', 'Task')],+ [item('same', 'Task'), item('same', 'Document', 'document')],+ );vi.spyOn(taskService, 'update').mockResolvedValue(taskUpdateResult);- act(() => {- replaceQuery('user-1:ws-A', compactQuery, [item('same', 'Task', 'task')]);- replaceQuery('user-1:ws-A', drawerQuery, [- item('same', 'Task', 'task'),- item('same', 'Document', 'document'),- ]);- });- await useHomeStore- .getState()- .renameRecent({ id: 'same', scope: 'user-1:ws-A', title: 'Renamed', type: 'task' });-- expect(- homeRecentSelectors.item('user-1:ws-A', compactQuery, 'task:same')(useHomeStore.getState())- ?.title,- ).toBe('Renamed');- expect(- homeRecentSelectors.item('user-1:ws-A', drawerQuery, 'task:same')(useHomeStore.getState())- ?.title,- ).toBe('Renamed');- expect(- homeRecentSelectors.item('user-1:ws-A', drawerQuery, 'document:same')(useHomeStore.getState())- ?.title,- ).toBe('Document');+ await act(() =>+ useHomeStore.getState().renameRecent({ id: 'same', title: 'Renamed', type: 'task' }),+ );++ expect(titleOf(SIDEBAR, 'task:same')).toBe('Renamed');+ expect(titleOf(DRAWER, 'task:same')).toBe('Renamed');+ expect(titleOf(DRAWER, 'document:same')).toBe('Document');+ });++ it('carries the slug source with a task rename', async () => {+ await load([item('a', 'Old')]);+ vi.spyOn(taskService, 'update').mockResolvedValue(taskUpdateResult);++ await act(() => useHomeStore.getState().renameRecent({ id: 'a', title: 'New', type: 'task' }));++ expect(homeRecentSelectors.item(SIDEBAR, 'task:a')(useHomeStore.getState())).toMatchObject({+ slugTitle: 'New',+ title: 'New',+ });});it('serializes repeated renames and keeps the latest optimistic title', async () => {- const queryKey = createRecentQueryKey(11);+ await load([item('a', 'Old')]);const firstRequest = deferred<TaskUpdateResult>();const secondRequest = deferred<TaskUpdateResult>();const updateSpy = vi.spyOn(taskService, 'update').mockReturnValueOnce(firstRequest.promise).mockReturnValueOnce(secondRequest.promise);- act(() => replaceQuery('user-1:ws-A', queryKey, [item('a', 'Old')]));const firstRename = useHomeStore.getState()- .renameRecent({ id: 'a', scope: 'user-1:ws-A', title: 'First', type: 'task' });+ .renameRecent({ id: 'a', title: 'First', type: 'task' });const secondRename = useHomeStore.getState()- .renameRecent({ id: 'a', scope: 'user-1:ws-A', title: 'Second', type: 'task' });+ .renameRecent({ id: 'a', title: 'Second', type: 'task' });await waitFor(() => expect(updateSpy).toHaveBeenCalledTimes(1));- expect(- homeRecentSelectors.item('user-1:ws-A', queryKey, 'task:a')(useHomeStore.getState())?.title,- ).toBe('Second');+ expect(titleOf(SIDEBAR, 'task:a')).toBe('Second');firstRequest.resolve(taskUpdateResult);await firstRename;await waitFor(() => expect(updateSpy).toHaveBeenCalledTimes(2));- expect(- homeRecentSelectors.item('user-1:ws-A', queryKey, 'task:a')(useHomeStore.getState())?.title,- ).toBe('Second');+ expect(titleOf(SIDEBAR, 'task:a')).toBe('Second');secondRequest.resolve(taskUpdateResult);await secondRename;- expect(- homeRecentSelectors.item('user-1:ws-A', queryKey, 'task:a')(useHomeStore.getState())?.title,- ).toBe('Second');+ expect(titleOf(SIDEBAR, 'task:a')).toBe('Second');});- it('revalidates both list surfaces only in the requested scope', async () => {- const mutateSpy = vi.spyOn(swr, 'mutate').mockResolvedValue(undefined as never);+ it('keeps a newer pending rename when an older one fails', async () => {+ await load([item('a', 'Old')]);+ const firstRequest = deferred<TaskUpdateResult>();+ const secondRequest = deferred<TaskUpdateResult>();+ vi.spyOn(taskService, 'update')+ .mockReturnValueOnce(firstRequest.promise)+ .mockReturnValueOnce(secondRequest.promise);++ const firstRename = useHomeStore+ .getState()+ .renameRecent({ id: 'a', title: 'First', type: 'task' });+ const secondRename = useHomeStore+ .getState()+ .renameRecent({ id: 'a', title: 'Second', type: 'task' });- await act(() => useHomeStore.getState().refreshRecents('user-1:ws-A'));+ firstRequest.reject(new Error('failed'));+ await expect(firstRename).rejects.toThrow('failed');+ expect(titleOf(SIDEBAR, 'task:a')).toBe('Second');- expect(mutateSpy).toHaveBeenCalledTimes(2);- const matcher = mutateSpy.mock.calls[0][0] as (key: unknown) => boolean;- expect(matcher(recentKeys.list(true, 10, 'user-1:ws-A'))).toBe(true);- expect(matcher(recentKeys.list(true, 10, 'user-1:ws-B'))).toBe(false);+ secondRequest.resolve(taskUpdateResult);+ await secondRename;});});diff --git a/src/store/home/slices/recent/action.ts b/src/store/home/slices/recent/action.tsindex bb7227ad430..ae81c75e43b 100644--- a/src/store/home/slices/recent/action.ts+++ b/src/store/home/slices/recent/action.ts@@ -1,9 +1,12 @@import type { RecentItem } from '@lobechat/types';-import type { SWRResponse } from 'swr';-import { mutate, useClientDataSWR } from '@/libs/swr';-import { recentKeys } from '@/libs/swr/keys';-import { getCacheScope } from '@/libs/swr/useCacheScope';+import {+ createReplicaSlice,+ linkReplicaEntity,+ recordLens,+ type ReplicaEntityAdapter,+ type ReplicaSyncResult,+} from '@/libs/replica';import { documentService } from '@/services/document';import { RECENT_SIDEBAR_TYPES, recentService } from '@/services/recent';import { taskService } from '@/services/task';@@ -12,45 +15,78 @@ import type { HomeStore } from '@/store/home/store';import type { StoreSetter } from '@/store/types';import { setNamespace } from '@/utils/storeDebug';-import { createRecentQueryKey } from './initialState';-import { recentProjection } from './projection';-import type { RecentDispatchAction } from './reducer';-import { recentReducer } from './reducer';+import { type RecentEntityRef, toRecentEntityRef } from './initialState';+import { recentListResource } from './projection';const n = setNamespace('recent');-const RECENT_PROJECTION_KEY = 'home-recents-projection';-const matchesScopedRecentKey = (key: unknown, root: string, scope: string) =>- Array.isArray(key) && key[0] === root && key.at(-1) === scope;+/** Rows in the "all recents" drawer. */+export const ALL_RECENTS_LIMIT = 50;interface RenameRecentParams {id: string;- scope: string;title: string;type: RecentItem['type'];}+/** Recents mix entity types, so rows are addressed by `${type}:${id}`. */+const recentEntity: ReplicaEntityAdapter<RecentItem[], RecentItem> = {+ has: (items, ref) => items.some((item) => toRecentEntityRef(item) === ref),+ map: (items, ref, fn) => {+ let changed = false;+ const next: RecentItem[] = [];+ for (const item of items) {+ if (toRecentEntityRef(item) !== ref) {+ next.push(item);+ continue;+ }+ const mapped = fn(item);+ if (mapped !== item) changed = true;+ if (mapped) next.push(mapped);+ }+ return changed ? next : items;+ },+};++const withTitle = (item: RecentItem, title: string): RecentItem =>+ // A task rename carries the slug source with it, so the row's link is built+ // from the name the user just typed rather than the one the server still has.+ item.type === 'task' ? { ...item, slugTitle: title, title } : { ...item, title };+type Setter = StoreSetter<HomeStore>;export const createRecentSlice = (set: Setter, get: () => HomeStore, _api?: unknown) =>new RecentActionImpl(set, get, _api);export class RecentActionImpl {- readonly #get: () => HomeStore;- readonly #hydrationPromises = new Map<string, Promise<void>>();- readonly #renameQueues = new Map<string, Promise<void>>();readonly #set: Setter;- #mutationId = 0;+ /** Server writes per entity run in order; the newest optimistic title stays on top. */+ readonly #renameQueues = new Map<RecentEntityRef, Promise<unknown>>();+ readonly #recentList;+ readonly #recents;constructor(set: Setter, get: () => HomeStore, _api?: unknown) {void _api;this.#set = set;- this.#get = get;+ this.#recentList = createReplicaSlice(recentListResource, {+ actionPrefix: n('recentList'),+ entity: recentEntity,+ fetcher: ({ limit }) => recentService.getAll(limit, RECENT_SIDEBAR_TYPES),+ get,+ set,+ stateKey: 'recentListReplica',+ view: recordLens<HomeStore, RecentItem[]>('recentListMap'),+ });+ this.#recents = linkReplicaEntity<RecentItem>([this.#recentList]);}closeAllRecentsDrawer = (): void => {this.#set({ allRecentsDrawerOpen: false }, false, n('closeAllRecentsDrawer'));};+ openAllRecentsDrawer = (): void => {+ this.#set({ allRecentsDrawerOpen: true }, false, n('openAllRecentsDrawer'));+ };+#persistRecentTitle = async ({ id, title, type }: RenameRecentParams): Promise<void> => {switch (type) {case 'document': {@@ -68,183 +104,42 @@ export class RecentActionImpl {}};- #persistQuery = (scope: string, queryKey: string): void => {- const query = this.#get().recentsByScope[scope]?.queries[queryKey];- if (!query) return;-- void recentProjection- .set({ queryKey, scope }, { data: query.items, updatedAt: query.updatedAt })- .catch((error) => console.error('Failed to persist recent projection', error));- };-- #persistScopeQueries = (scope: string): void => {- const queries = this.#get().recentsByScope[scope]?.queries;- if (!queries) return;- for (const queryKey of Object.keys(queries)) this.#persistQuery(scope, queryKey);- };-- internal_dispatchRecent = (action: RecentDispatchAction): void => {- this.#set((state) => recentReducer(state, action), false, n(action.type));- };-- internal_replaceRecentQuery = (scope: string, queryKey: string, items: RecentItem[]): void => {- if (getCacheScope() !== scope) return;-- this.internal_dispatchRecent({- items,- queryKey,- scope,- type: 'replaceQuery',- updatedAt: Date.now(),- });- this.#persistQuery(scope, queryKey);- };-- hydrateRecentQuery = async (scope: string, queryKey: string): Promise<void> => {- const hydrationKey = `${scope}:${queryKey}`;- const existing = this.#hydrationPromises.get(hydrationKey);- if (existing) return existing;-- const hydration = (async () => {- this.internal_dispatchRecent({ queryKey, scope, type: 'startHydration' });-- try {- const projection = await recentProjection.get({ queryKey, scope });- if (getCacheScope() !== scope) return;-- if (projection) {- this.internal_dispatchRecent({- items: projection.data,- queryKey,- scope,- type: 'hydrateQuery',- updatedAt: projection.updatedAt,- });- } else {- this.internal_dispatchRecent({ queryKey, scope, type: 'finishHydration' });- }- } catch (error) {- console.error('Failed to hydrate recent projection', error);- this.internal_dispatchRecent({ queryKey, scope, type: 'failHydration' });- }- })();-- this.#hydrationPromises.set(hydrationKey, hydration);- try {- await hydration;- } finally {- this.#hydrationPromises.delete(hydrationKey);- }- };-- openAllRecentsDrawer = (): void => {- this.#set({ allRecentsDrawerOpen: true }, false, n('openAllRecentsDrawer'));- };-- refreshRecents = async (scope: string): Promise<void> => {- await Promise.all([- mutate((key: unknown) => matchesScopedRecentKey(key, recentKeys.list.root, scope)),- mutate((key: unknown) => matchesScopedRecentKey(key, recentKeys.allDrawer.root, scope)),- ]);+ /** Revalidate every recents query of the active identity. */+ refreshRecents = async (): Promise<void> => {+ await this.#recentList.revalidate();};+ /**+ * Show the new title in every loaded recents query right away, write it to+ * the owning entity, and roll back on failure. Renames of one entity reach+ * the server in order.+ */renameRecent = async (params: RenameRecentParams): Promise<void> => {- const { id, scope, title, type } = params;- const mutationId = ++this.#mutationId;- const queueKey = `${scope}:${type}:${id}`;- this.internal_dispatchRecent({- entityType: type,- id,- mutationId,- scope,- title,- type: 'setOptimisticTitle',- });-- const previous = this.#renameQueues.get(queueKey) ?? Promise.resolve();- const operation = previous.catch(() => undefined).then(() => this.#persistRecentTitle(params));- this.#renameQueues.set(queueKey, operation);-+ const ref = toRecentEntityRef(params);+ const previous = this.#renameQueues.get(ref) ?? Promise.resolve();+ const operation = this.#recents.optimistic(+ ref,+ (item) => withTitle(item, params.title),+ () => previous.catch(() => undefined).then(() => this.#persistRecentTitle(params)),+ );+ this.#renameQueues.set(ref, operation);try {await operation;- this.internal_dispatchRecent({- entityType: type,- id,- mutationId,- scope,- title,- type: 'commitTitle',- });- this.#persistScopeQueries(scope);- } catch (error) {- this.internal_dispatchRecent({- entityType: type,- id,- mutationId,- scope,- type: 'rollbackTitle',- });- throw error;} finally {- if (this.#renameQueues.get(queueKey) === operation) this.#renameQueues.delete(queueKey);+ if (this.#renameQueues.get(ref) === operation) this.#renameQueues.delete(ref);}};- useFetchAllRecents = (open: boolean, scope: string): SWRResponse<number> => {- const limit = 50;- const queryKey = createRecentQueryKey(limit);- useClientDataSWR<number>(open ? [RECENT_PROJECTION_KEY, scope, queryKey] : null, async () => {- await this.hydrateRecentQuery(scope, queryKey);- return Date.now();- });+ /** "All recents" drawer. Read the rows with `homeRecentSelectors.query`. */+ useFetchAllRecents = (open: boolean): ReplicaSyncResult =>+ this.#recentList.useSync({ limit: ALL_RECENTS_LIMIT }, { enabled: open });- return useClientDataSWR<number>(open ? recentKeys.allDrawer(open, scope) : null, async () => {- this.internal_dispatchRecent({ queryKey, scope, type: 'startSync' });-- try {- const items = await recentService.getAll(limit, RECENT_SIDEBAR_TYPES);- this.internal_replaceRecentQuery(scope, queryKey, items);- this.internal_dispatchRecent({ queryKey, scope, type: 'finishSync' });- return Date.now();- } catch (error) {- this.internal_dispatchRecent({ error, queryKey, scope, type: 'failSync' });- throw error;- }- });- };-- useFetchRecents = (- isLogin: boolean | undefined,- scope: string,- limit: number = 10,- ): SWRResponse<number> => {- const requestLimit = limit + 1;- const queryKey = createRecentQueryKey(requestLimit);- useClientDataSWR<number>(- isLogin === true ? [RECENT_PROJECTION_KEY, scope, queryKey] : null,- async () => {- await this.hydrateRecentQuery(scope, queryKey);- return Date.now();- },- );-- return useClientDataSWR<number>(- isLogin === true ? recentKeys.list(isLogin, limit, scope) : null,- async () => {- this.internal_dispatchRecent({ queryKey, scope, type: 'startSync' });-- try {- const items = await recentService.getAll(requestLimit, RECENT_SIDEBAR_TYPES);- this.internal_replaceRecentQuery(scope, queryKey, items);- this.internal_dispatchRecent({ queryKey, scope, type: 'finishSync' });- return Date.now();- } catch (error) {- this.internal_dispatchRecent({ error, queryKey, scope, type: 'failSync' });- throw error;- }- },- );- };+ /**+ * Sidebar recents. Asks for `limit + 1` rows to know whether "view all" is+ * needed; read them with `homeRecentSelectors.query`.+ */+ useFetchRecents = (isLogin: boolean | undefined, limit: number = 10): ReplicaSyncResult =>+ this.#recentList.useSync({ limit: limit + 1 }, { enabled: isLogin === true });}export type RecentAction = Pick<RecentActionImpl, keyof RecentActionImpl>;diff --git a/src/store/home/slices/recent/initialState.ts b/src/store/home/slices/recent/initialState.tsindex 6c3e9b62d7c..8d2dd83d0d2 100644--- a/src/store/home/slices/recent/initialState.ts+++ b/src/store/home/slices/recent/initialState.ts@@ -1,38 +1,25 @@import type { RecentItem } from '@lobechat/types';-export type RecentEntityRef = `${RecentItem['type']}:${string}`;--export const createRecentQueryKey = (limit: number): string => `limit:${limit}`;--export interface RecentOptimisticTitle {- mutationId: number;- title: string;-}+import { createReplicaState, type ReplicaState } from '@/libs/replica';-export interface RecentScopeState {- hydrationStatusByQuery: Record<string, 'failed' | 'hydrated' | 'hydrating'>;- optimisticTitles: Partial<Record<RecentEntityRef, RecentOptimisticTitle>>;- queries: Record<string, RecentQueryState>;- syncStatusByQuery: Record<string, RecentSyncState>;-}+export { createRecentQueryKey } from './projection';-export interface RecentQueryState {- items: RecentItem[];- source: 'server' | 'storage';- updatedAt: number;-}+/** `${type}:${id}`: ids of different entity types can collide. */+export type RecentEntityRef = `${RecentItem['type']}:${string}`;-export interface RecentSyncState {- error?: unknown;- isValidating: boolean;-}+export const toRecentEntityRef = (item: Pick<RecentItem, 'id' | 'type'>): RecentEntityRef =>+ `${item.type}:${item.id}`;export interface RecentState {allRecentsDrawerOpen: boolean;- recentsByScope: Record<string, RecentScopeState>;+ /** Recents per query (`limit:N`), the view of the `recentList` replica. */+ recentListMap: Record<string, RecentItem[]>;+ /** Replica bookkeeping for `recentListMap`. */+ recentListReplica: ReplicaState<RecentItem[]>;}export const initialRecentState: RecentState = {allRecentsDrawerOpen: false,- recentsByScope: {},+ recentListMap: {},+ recentListReplica: createReplicaState(),};diff --git a/src/store/home/slices/recent/projection.ts b/src/store/home/slices/recent/projection.tsindex 37fbcbf7d91..26729c59f5b 100644--- a/src/store/home/slices/recent/projection.ts+++ b/src/store/home/slices/recent/projection.ts@@ -1,7 +1,22 @@import type { RecentItem } from '@lobechat/types';-import { LocalStorageQueryProjectionStorage } from '@/libs/queryProjectionStorage';+import { defineReplica } from '@/libs/replica';-export const recentProjection = new LocalStorageQueryProjectionStorage<RecentItem[]>({- namespace: 'lobechat-home-recents-v3',+export interface RecentListParams {+ limit: number;+}++/** Entry key of one recents query (`recentListMap[limit:N]`). */+export const createRecentQueryKey = (limit: number): string => `limit:${limit}`;++/**+ * Recent documents / tasks / topics, one entry per requested limit (the sidebar+ * asks for `pageSize + 1`, the drawer for 50). localStorage keeps the first+ * frame of the home sidebar instant.+ */+export const recentListResource = defineReplica<RecentListParams, RecentItem[]>({+ key: ({ limit }) => createRecentQueryKey(limit),+ name: 'recentList',+ storage: 'localStorage',+ version: 1,});diff --git a/src/store/home/slices/recent/reducer.test.ts b/src/store/home/slices/recent/reducer.test.tsdeleted file mode 100644index d8ad60a8639..00000000000--- a/src/store/home/slices/recent/reducer.test.ts+++ /dev/null@@ -1,159 +0,0 @@-import type { RecentItem } from '@lobechat/types';-import { describe, expect, it } from 'vitest';--import type { RecentState } from './initialState';-import { recentReducer } from './reducer';--const item = (id: string, title: string, type: RecentItem['type'] = 'task'): RecentItem => ({- icon: type,- id,- routePath: '/',- // Mirrors the server payload: a task's slug source is its name, topics and- // documents have none.- slugTitle: type === 'task' ? title : null,- status: null,- title,- type,- updatedAt: new Date(0),-});--const state = (items: RecentItem[]): RecentState => ({- allRecentsDrawerOpen: false,- recentsByScope: {- scope: {- hydrationStatusByQuery: {},- optimisticTitles: {},- queries: {- compact: { items, source: 'server', updatedAt: 1 },- drawer: {- items: [...items, item('document', 'Document', 'document')],- source: 'server',- updatedAt: 1,- },- },- syncStatusByQuery: {},- },- },-});--describe('recentReducer', () => {- it('replaces one query without changing the other projections', () => {- const current = state([item('task', 'Task')]);- const next = recentReducer(current, {- items: [item('new', 'New')],- queryKey: 'compact',- scope: 'scope',- type: 'replaceQuery',- updatedAt: 2,- });-- expect(next.recentsByScope.scope.queries.compact).toEqual({- items: [item('new', 'New')],- source: 'server',- updatedAt: 2,- });- expect(next.recentsByScope.scope.queries.drawer).toBe(- current.recentsByScope.scope.queries.drawer,- );- });-- it('commits an entity title to every loaded query projection', () => {- const current = state([item('task', 'Draft')]);- const optimistic = recentReducer(current, {- entityType: 'task',- id: 'task',- mutationId: 1,- scope: 'scope',- title: 'Renamed',- type: 'setOptimisticTitle',- });- const next = recentReducer(- { ...current, ...optimistic },- {- entityType: 'task',- id: 'task',- mutationId: 1,- scope: 'scope',- title: 'Renamed',- type: 'commitTitle',- },- );-- expect(next.recentsByScope.scope.optimisticTitles).toEqual({});- expect(next.recentsByScope.scope.queries.compact.items[0].title).toBe('Renamed');- expect(next.recentsByScope.scope.queries.drawer.items[0].title).toBe('Renamed');- expect(next.recentsByScope.scope.queries.drawer.items[1].title).toBe('Document');- });-- it('moves a task slug source with a committed rename', () => {- // Regression: the row's link is built from `slugTitle`, so leaving it on the- // old name made the href slug the previous title until the next server sync- // — the same link/canonicaliser disagreement this feature exists to remove.- const next = recentReducer(state([item('task', 'Draft')]), {- entityType: 'task',- id: 'task',- mutationId: 1,- scope: 'scope',- title: 'Renamed',- type: 'commitTitle',- });-- const renamed = next.recentsByScope.scope.queries.compact.items[0];- expect(renamed.title).toBe('Renamed');- expect(renamed.slugTitle).toBe('Renamed');- });-- it('leaves a document slug source alone on rename', () => {- const next = recentReducer(state([item('task', 'Draft')]), {- entityType: 'document',- id: 'document',- mutationId: 1,- scope: 'scope',- title: 'Renamed doc',- type: 'commitTitle',- });-- const renamed = next.recentsByScope.scope.queries.drawer.items.find((i) => i.id === 'document');- expect(renamed?.title).toBe('Renamed doc');- expect(renamed?.slugTitle).toBeNull();- });-- it('does not roll back a newer optimistic mutation', () => {- const current = state([item('task', 'Draft')]);- const optimistic = recentReducer(current, {- entityType: 'task',- id: 'task',- mutationId: 2,- scope: 'scope',- title: 'Latest',- type: 'setOptimisticTitle',- });- const next = recentReducer(- { ...current, ...optimistic },- {- entityType: 'task',- id: 'task',- mutationId: 1,- scope: 'scope',- type: 'rollbackTitle',- },- );-- expect(next.recentsByScope).toBe(optimistic.recentsByScope);- expect(next.recentsByScope.scope.optimisticTitles['task:task']?.title).toBe('Latest');- });-- it('does not let late storage hydration overwrite server data', () => {- const current = state([item('task', 'Server')]);- const next = recentReducer(current, {- items: [item('task', 'Cached')],- queryKey: 'compact',- scope: 'scope',- type: 'hydrateQuery',- updatedAt: 2,- });-- expect(next.recentsByScope.scope.queries.compact.items[0].title).toBe('Server');- expect(next.recentsByScope.scope.hydrationStatusByQuery.compact).toBe('hydrated');- });-});diff --git a/src/store/home/slices/recent/reducer.ts b/src/store/home/slices/recent/reducer.tsdeleted file mode 100644index 84f51dff2f2..00000000000--- a/src/store/home/slices/recent/reducer.ts+++ /dev/null@@ -1,217 +0,0 @@-import type { RecentItem } from '@lobechat/types';--import type { RecentEntityRef, RecentScopeState, RecentState } from './initialState';--interface RecentTitleAction {- entityType: RecentItem['type'];- id: string;- mutationId: number;- scope: string;-}--export type RecentDispatchAction =- | (RecentTitleAction & { title: string; type: 'commitTitle' | 'setOptimisticTitle' })- | (RecentTitleAction & { type: 'rollbackTitle' })- | { queryKey: string; scope: string; type: 'failHydration' | 'finishHydration' }- | { error: unknown; queryKey: string; scope: string; type: 'failSync' }- | {- items: RecentItem[];- queryKey: string;- scope: string;- type: 'hydrateQuery';- updatedAt: number;- }- | {- items: RecentItem[];- queryKey: string;- scope: string;- type: 'replaceQuery';- updatedAt: number;- }- | { queryKey: string; scope: string; type: 'startHydration' | 'startSync' }- | { queryKey: string; scope: string; type: 'finishSync' };--const createScopeState = (): RecentScopeState => ({- hydrationStatusByQuery: {},- optimisticTitles: {},- queries: {},- syncStatusByQuery: {},-});--const updateRecentTitle = (- items: RecentItem[],- entityType: RecentItem['type'],- id: string,- title: string,-) => {- let changed = false;- const nextItems = items.map((item) => {- if (item.type !== entityType || item.id !== id || item.title === title) return item;- changed = true;- // Renaming a task sets `tasks.name`, which is exactly what `slugTitle`- // carries — move it with the title or the row's link keeps slugging the old- // name until the next server sync. Topics and documents have no slug- // source, so leave theirs alone.- return item.type === 'task' ? { ...item, slugTitle: title, title } : { ...item, title };- });-- return changed ? nextItems : items;-};--export const recentReducer = (- state: RecentState,- action: RecentDispatchAction,-): Pick<RecentState, 'recentsByScope'> => {- const scopedState = state.recentsByScope[action.scope];-- switch (action.type) {- case 'commitTitle': {- if (!scopedState) return { recentsByScope: state.recentsByScope };-- const ref = `${action.entityType}:${action.id}` as RecentEntityRef;- const optimisticTitles = { ...scopedState.optimisticTitles };- if (optimisticTitles[ref]?.mutationId === action.mutationId) delete optimisticTitles[ref];-- const queries = Object.fromEntries(- Object.entries(scopedState.queries).map(([queryKey, query]) => {- const items = updateRecentTitle(query.items, action.entityType, action.id, action.title);- return [queryKey, items === query.items ? query : { ...query, items }];- }),- );-- return {- recentsByScope: {- ...state.recentsByScope,- [action.scope]: { ...scopedState, optimisticTitles, queries },- },- };- }-- case 'failHydration':- case 'finishHydration':- case 'startHydration': {- const currentScope = scopedState ?? createScopeState();- return {- recentsByScope: {- ...state.recentsByScope,- [action.scope]: {- ...currentScope,- hydrationStatusByQuery: {- ...currentScope.hydrationStatusByQuery,- [action.queryKey]:- action.type === 'startHydration'- ? 'hydrating'- : action.type === 'finishHydration'- ? 'hydrated'- : 'failed',- },- },- },- };- }-- case 'failSync':- case 'finishSync':- case 'startSync': {- const currentScope = scopedState ?? createScopeState();- return {- recentsByScope: {- ...state.recentsByScope,- [action.scope]: {- ...currentScope,- syncStatusByQuery: {- ...currentScope.syncStatusByQuery,- [action.queryKey]: {- error: action.type === 'failSync' ? action.error : undefined,- isValidating: action.type === 'startSync',- },- },- },- },- };- }-- case 'hydrateQuery': {- const currentScope = scopedState ?? createScopeState();- const currentQuery = currentScope.queries[action.queryKey];- const queries =- currentQuery?.source === 'server'- ? currentScope.queries- : {- ...currentScope.queries,- [action.queryKey]: {- items: action.items,- source: 'storage' as const,- updatedAt: action.updatedAt,- },- };-- return {- recentsByScope: {- ...state.recentsByScope,- [action.scope]: {- ...currentScope,- hydrationStatusByQuery: {- ...currentScope.hydrationStatusByQuery,- [action.queryKey]: 'hydrated',- },- queries,- },- },- };- }-- case 'replaceQuery': {- const currentScope = scopedState ?? createScopeState();- return {- recentsByScope: {- ...state.recentsByScope,- [action.scope]: {- ...currentScope,- queries: {- ...currentScope.queries,- [action.queryKey]: {- items: action.items,- source: 'server',- updatedAt: action.updatedAt,- },- },- },- },- };- }-- case 'rollbackTitle': {- const ref = `${action.entityType}:${action.id}` as RecentEntityRef;- if (!scopedState || scopedState.optimisticTitles[ref]?.mutationId !== action.mutationId) {- return { recentsByScope: state.recentsByScope };- }-- const optimisticTitles = { ...scopedState.optimisticTitles };- delete optimisticTitles[ref];- return {- recentsByScope: {- ...state.recentsByScope,- [action.scope]: { ...scopedState, optimisticTitles },- },- };- }-- case 'setOptimisticTitle': {- const currentScope = scopedState ?? createScopeState();- const ref = `${action.entityType}:${action.id}` as RecentEntityRef;- return {- recentsByScope: {- ...state.recentsByScope,- [action.scope]: {- ...currentScope,- optimisticTitles: {- ...currentScope.optimisticTitles,- [ref]: { mutationId: action.mutationId, title: action.title },- },- },- },- };- }- }-};diff --git a/src/store/home/slices/recent/selectors.ts b/src/store/home/slices/recent/selectors.tsindex fca0d01eb8d..558e31b3dd5 100644--- a/src/store/home/slices/recent/selectors.ts+++ b/src/store/home/slices/recent/selectors.ts@@ -1,30 +1,14 @@import { type HomeStore } from '@/store/home/store';-import type { RecentEntityRef } from './initialState';+import { type RecentEntityRef, toRecentEntityRef } from './initialState';-const query = (scope: string, queryKey: string) => (s: HomeStore) =>- s.recentsByScope[scope]?.queries[queryKey];-const syncStatus = (scope: string, queryKey: string) => (s: HomeStore) =>- s.recentsByScope[scope]?.syncStatusByQuery[queryKey];-const item = (scope: string, queryKey: string, ref: RecentEntityRef) => (s: HomeStore) => {- const scopedState = s.recentsByScope[scope];- const recentItem = scopedState?.queries[queryKey]?.items.find(- (item) => `${item.type}:${item.id}` === ref,- );- const optimisticTitle = scopedState?.optimisticTitles[ref]?.title;+/** Items of one recents query; `undefined` until it is hydrated or fetched. */+const query = (queryKey: string) => (s: HomeStore) => s.recentListMap[queryKey];- if (!recentItem || optimisticTitle === undefined) return recentItem;-- // A pending task rename has to carry the slug source with it, so the row's- // link is built from the name the user just typed rather than the one the- // server still has.- return recentItem.type === 'task'- ? { ...recentItem, slugTitle: optimisticTitle, title: optimisticTitle }- : { ...recentItem, title: optimisticTitle };-};+const item = (queryKey: string, ref: RecentEntityRef) => (s: HomeStore) =>+ s.recentListMap[queryKey]?.find((recent) => toRecentEntityRef(recent) === ref);export const homeRecentSelectors = {item,query,- syncStatus,};diff --git a/src/store/project/projection.ts b/src/store/project/projection.tsindex 33883c7b824..36cae1b0edb 100644--- a/src/store/project/projection.ts+++ b/src/store/project/projection.ts@@ -1,16 +1,30 @@-import {- IndexedDBQueryProjectionStorage,- QueryProjectionWriteQueue,-} from '@/libs/queryProjectionStorage';+import { defineReplica } from '@/libs/replica';+import type { projectService } from '@/services/project';-import type { ProjectDetail, ProjectListItem } from './store';+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'];-export const PROJECT_LIST_QUERY = 'all';-export const projectListProjection = new IndexedDBQueryProjectionStorage<ProjectListItem[]>({- namespace: 'lobechat-project-list-v1',+/** The sidebar / list page reads every project, so the list has one entry. */+export const PROJECT_LIST_KEY = 'all';++/** Every project of the active scope (`projectListMap.all`). */+export const projectListResource = defineReplica<+ Record<string, never>,+ ProjectListItem[],+ ProjectListResponse+>({+ key: () => PROJECT_LIST_KEY,+ name: 'projectList',+ storage: 'indexedDB',+ version: 1,});-export const projectDetailProjection = new IndexedDBQueryProjectionStorage<ProjectDetail>({- namespace: 'lobechat-project-detail-v1',++/** One project page, keyed by the route param (id or slug) (`projectDetailMap[idOrSlug]`). */+export const projectDetailResource = defineReplica<string, ProjectDetail, ProjectDetailResponse>({+ key: (idOrSlug) => idOrSlug,+ name: 'projectDetail',+ storage: 'indexedDB',+ version: 1,});-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.tsdeleted file mode 100644index a8ae640898f..00000000000--- a/src/store/project/reducer.test.ts+++ /dev/null@@ -1,56 +0,0 @@-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.tsdeleted file mode 100644index 180bca2fa05..00000000000--- a/src/store/project/reducer.ts+++ /dev/null@@ -1,159 +0,0 @@-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 873e932a005..0db096a671c 100644--- a/src/store/project/store.test.ts+++ b/src/store/project/store.test.ts@@ -1,259 +1,259 @@-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';+/**+ * @vitest-environment happy-dom+ *+ * The project list and project pages are replicas: they paint from the+ * persisted copy on the first frame, the network only confirms, and a rename+ * or delete reaches the list row and every loaded project page at once.+ */+import { randomUUID } from 'node:crypto';++import { act, renderHook, waitFor } from '@testing-library/react';+import type { PropsWithChildren } from 'react';+import { createElement, useEffect } from 'react';+import { SWRConfig, useSWRConfig } from 'swr';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { cacheScope } from '@/libs/replica';+import { setScopedMutate } from '@/libs/swr/mutate';import { projectService } from '@/services/project';-import { projectListProjection } from './projection';-import type { ProjectDetail, ProjectListItem } from './store';-import { useCurrentProjectDetail, useCurrentProjectList, useProjectStore } from './store';--const mocks = vi.hoisted(() => ({- activeWorkspaceId: null as string | null,- cacheScope: 'user-1:personal',- currentCacheScope: 'user-1:personal',- swrData: undefined as unknown,- swrDataByKey: {} as Record<string, unknown>,- swrConfigs: [] as Array<{ onSuccess?: (response: unknown) => void }>,- swrKeys: [] as unknown[],- fetchers: [] as Array<() => Promise<unknown>>,-}));+import type { ProjectDetail, ProjectListItem } from './projection';+import { PROJECT_LIST_KEY, projectDetailResource, projectListResource } from './projection';+import {+ initialProjectState,+ useCurrentProjectDetail,+ useCurrentProjectList,+ useProjectStore,+} from './store';++const mocks = vi.hoisted(() => ({ activeWorkspaceId: null as string | null }));vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({getActiveWorkspaceId: () => mocks.activeWorkspaceId,useActiveWorkspaceId: () => mocks.activeWorkspaceId,}));-vi.mock('@/libs/swr/useCacheScope', () => ({- getCacheScope: () => mocks.currentCacheScope,- useCacheScope: () => mocks.cacheScope,+vi.mock('@/services/project', () => ({+ projectService: {+ create: vi.fn(),+ delete: vi.fn(),+ detail: vi.fn(),+ listAll: vi.fn(),+ update: vi.fn(),+ },}));-vi.mock('@/libs/swr', () => ({- mutate: vi.fn(),- useClientDataSWR: vi.fn(- (- 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);- return {- data:- serializedKey in mocks.swrDataByKey ? mocks.swrDataByKey[serializedKey] : mocks.swrData,- };- },- ),-}));+const MutateBridge = () => {+ const { mutate } = useSWRConfig();+ useEffect(() => setScopedMutate(mutate), [mutate]);+ return null;+};++const wrapper = ({ children }: PropsWithChildren) =>+ createElement(+ SWRConfig,+ { value: { dedupingInterval: 0, provider: () => new Map() } },+ createElement(MutateBridge),+ children,+ );++const project = (id: string, name = id): ProjectListItem =>+ ({ id, name, slug: `${id}-slug` }) as ProjectListItem;+const detailOf = (item: ProjectListItem): ProjectDetail => ({ project: item }) as ProjectDetail;+const ok = <T>(data: T) => ({ data, message: 'ok', success: true as const });++/** Never-resolving fetch: the first frame can only come from storage. */+const pending = () => new Promise<never>(() => {});++const LIST_STORAGE_KEY = projectListResource.storageKey({});++describe('project store replicas', () => {+ const scopes = new Set<string>();+ let scope = '';+ const useScope = (next: string) => {+ scope = next;+ scopes.add(next);+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ };-describe('project store cache scope', () => {beforeEach(() => {mocks.activeWorkspaceId = null;- mocks.cacheScope = 'user-1:personal';- mocks.currentCacheScope = 'user-1:personal';- mocks.swrData = undefined;- mocks.swrDataByKey = {};- mocks.swrConfigs = [];- mocks.swrKeys = [];- mocks.fetchers = [];- useProjectStore.setState({- projectDetails: {},- projectLists: {},- projectOptimisticPatches: {},- });+ useScope(`project-user-${randomUUID()}:personal`);+ act(() => useProjectStore.setState(initialProjectState));});- it('restores a persisted project list without waiting for the network', async () => {- const cachedProject = { id: 'cached-project', name: 'Cached project' } as ProjectListItem;- 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]);- });-- it('ignores a project response from a workspace that is no longer active', () => {- const staleProject = { id: 'stale-project' } as ProjectListItem;- mocks.swrData = { data: [staleProject], message: 'stale', success: true };- mocks.cacheScope = 'user-1:personal';- mocks.currentCacheScope = 'user-1:workspace-1';-- renderHook(() => useProjectStore.getState().useFetchProjectList());- 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();- });-- it('hides the previous account project list while old SWR data is still present', () => {- const previousProject = { id: 'previous-project', name: 'Previous account' } as ProjectListItem;- const previousResponse = { data: [previousProject], success: true };- // Simulate the old shared key remaining populated until Query reloads the new scope.- mocks.swrDataByKey = {- [JSON.stringify('project/list')]: previousResponse,- [JSON.stringify(['project/list', 'user-1:personal'])]: previousResponse,- };- const { rerender } = renderHook(() => useProjectStore.getState().useFetchProjectList());-- mocks.cacheScope = 'user-2:personal';- mocks.currentCacheScope = 'user-2:personal';- rerender();-- expect(mocks.swrKeys).toEqual([- 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([]);+ afterEach(async () => {+ await Promise.all(+ [...scopes].flatMap((value) => [+ projectListResource.storage!.remove({ queryKey: LIST_STORAGE_KEY, scope: value }),+ projectDetailResource.storage!.remove({ queryKey: 'launch', scope: value }),+ ]),+ );+ scopes.clear();+ vi.restoreAllMocks();+ vi.clearAllMocks();});- it('hides the previous account project detail after switching accounts', () => {- const previousDetail = {- project: { id: 'shared-id', name: 'Previous account' },- } as ProjectDetail;- const { rerender } = renderHook(() =>- useProjectStore.getState().useFetchProjectDetail('shared-id'),+ it('paints the persisted list before the network answers', async () => {+ await projectListResource.storage!.set(+ { queryKey: LIST_STORAGE_KEY, scope },+ { data: [project('p1', 'Cached')], updatedAt: 1 },);+ vi.mocked(projectService.listAll).mockImplementation(pending);- act(() => mocks.swrConfigs.at(-1)?.onSuccess?.({ data: previousDetail, success: true }));- mocks.cacheScope = 'user-2:personal';- mocks.currentCacheScope = 'user-2:personal';- rerender();+ const sync = renderHook(() => useProjectStore((s) => s.useFetchProjectList)(true), {+ wrapper,+ });+ const list = renderHook(() => useCurrentProjectList());- expect(renderHook(() => useCurrentProjectDetail('shared-id')).result.current).toBeUndefined();+ await waitFor(() => expect(list.result.current.map((p) => p.name)).toEqual(['Cached']));+ expect(sync.result.current.isHydrated).toBe(true);+ expect(sync.result.current.isValidating).toBe(true);});- it('keeps project lists isolated between personal and workspace contexts', () => {- const personalProject = { id: 'personal-project' } as ProjectListItem;- const workspaceProject = { id: 'workspace-project' } as ProjectListItem;- mocks.swrData = { data: [personalProject], success: true };- const { rerender } = renderHook(() => useProjectStore.getState().useFetchProjectList());-- act(() => mocks.swrConfigs.at(-1)?.onSuccess?.({ data: [personalProject], success: true }));- mocks.activeWorkspaceId = 'workspace-1';- mocks.cacheScope = 'user-1:workspace-1';- mocks.currentCacheScope = 'user-1:workspace-1';- mocks.swrData = { data: [workspaceProject], success: true };- rerender();+ it('replaces the list with the server response and persists it', async () => {+ vi.mocked(projectService.listAll).mockResolvedValue(ok([project('p1', 'Server')]) as any);- act(() => mocks.swrConfigs.at(-1)?.onSuccess?.({ data: [workspaceProject], success: true }));- expect(renderHook(() => useCurrentProjectList()).result.current).toEqual([workspaceProject]);+ renderHook(() => useProjectStore((s) => s.useFetchProjectList)(true), { wrapper });- mocks.activeWorkspaceId = null;- mocks.cacheScope = 'user-1:personal';- mocks.currentCacheScope = 'user-1:personal';- expect(renderHook(() => useCurrentProjectList()).result.current).toEqual([personalProject]);+ await waitFor(() =>+ expect(useProjectStore.getState().projectListMap[PROJECT_LIST_KEY]?.[0]?.name).toBe('Server'),+ );+ await waitFor(async () =>+ expect(+ (await projectListResource.storage!.get({ queryKey: LIST_STORAGE_KEY, scope }))?.data,+ ).toEqual([project('p1', 'Server')]),+ );});- it('keeps project details isolated between personal and workspace contexts', () => {- const personalDetail = { project: { id: 'shared-id', name: 'Personal' } } as ProjectDetail;- const workspaceDetail = { project: { id: 'shared-id', name: 'Workspace' } } as ProjectDetail;- const { rerender } = renderHook(() =>- useProjectStore.getState().useFetchProjectDetail('shared-id'),+ it('paints a project page from the persisted copy, keyed by the route slug', async () => {+ await projectDetailResource.storage!.set(+ { queryKey: 'launch', scope },+ { data: detailOf(project('p1', 'Cached page')), updatedAt: 1 },);+ vi.mocked(projectService.detail).mockImplementation(pending);- act(() => mocks.swrConfigs.at(-1)?.onSuccess?.({ data: personalDetail, success: true }));- mocks.activeWorkspaceId = 'workspace-1';- mocks.cacheScope = 'user-1:workspace-1';- mocks.currentCacheScope = 'user-1:workspace-1';- rerender();- act(() => mocks.swrConfigs.at(-1)?.onSuccess?.({ data: workspaceDetail, success: true }));-- expect(mocks.swrKeys).toEqual([- 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,- );- mocks.activeWorkspaceId = null;- mocks.cacheScope = 'user-1:personal';- mocks.currentCacheScope = 'user-1:personal';- expect(renderHook(() => useCurrentProjectDetail('shared-id')).result.current).toBe(- personalDetail,- );+ renderHook(() => useProjectStore((s) => s.useFetchProjectDetail)('launch'), { wrapper });+ const detail = renderHook(() => useCurrentProjectDetail('launch'));++ await waitFor(() => expect(detail.result.current?.project.name).toBe('Cached page'));});- it('pins project creation to the active workspace', async () => {- mocks.activeWorkspaceId = 'workspace-1';- const project = { id: 'project-1', slug: 'launch' } as ProjectListItem;- vi.spyOn(projectService, 'create').mockResolvedValue({- data: project,- message: 'Project created',- success: true,+ it('drops the previous identity’s projects before the next one paints', async () => {+ vi.mocked(projectService.listAll).mockResolvedValue(ok([project('p1', 'Mine')]) as any);+ const sync = renderHook(() => useProjectStore((s) => s.useFetchProjectList)(true), {+ wrapper,});+ await waitFor(() => expect(useProjectStore.getState().projectListMap.all).toHaveLength(1));- await expect(- useProjectStore- .getState()- .createProject({ identifier: 'LOB', name: 'Launch', slug: 'launch' }),- ).resolves.toBe(project);+ vi.mocked(projectService.listAll).mockImplementation(pending);+ useScope(`project-user-${randomUUID()}:personal`);+ sync.rerender();- expect(projectService.create).toHaveBeenCalledWith(- { identifier: 'LOB', name: 'Launch', slug: 'launch' },- 'workspace-1',- );+ await waitFor(() => expect(useProjectStore.getState().projectListMap.all).toBeUndefined());});- it('refreshes the project list after deletion', async () => {- vi.mocked(mutate).mockClear();- vi.spyOn(projectService, 'delete').mockResolvedValue({- data: { id: 'project-1' } as ProjectListItem,- message: 'Project deleted',- success: true,+ describe('mutations', () => {+ const seed = () => {+ const original = project('p1', 'Original');+ act(() => {+ useProjectStore.getState(); // store constructed+ useProjectStore.setState(initialProjectState);+ });+ // Land both copies through the replicas (not a raw setState) so they hold bookkeeping.+ vi.mocked(projectService.listAll).mockResolvedValue(ok([original, project('p2')]) as any);+ vi.mocked(projectService.detail).mockResolvedValue(ok(detailOf(original)) as any);+ renderHook(+ () => {+ useProjectStore((s) => s.useFetchProjectList)(true);+ useProjectStore((s) => s.useFetchProjectDetail)('launch');+ },+ { wrapper },+ );+ return original;+ };+ const waitSeeded = () =>+ waitFor(() => {+ expect(useProjectStore.getState().projectListMap.all).toHaveLength(2);+ expect(useProjectStore.getState().projectDetailMap.launch).toBeDefined();+ });++ it('renames the list row and the project page optimistically', async () => {+ const original = seed();+ await waitSeeded();+ let resolveUpdate!: (value: unknown) => void;+ vi.mocked(projectService.update).mockImplementation(+ () => new Promise((resolve) => (resolveUpdate = resolve)) as any,+ );++ const operation = useProjectStore.getState().updateProject('p1', { name: 'Renamed' });++ expect(useProjectStore.getState().projectListMap.all[0].name).toBe('Renamed');+ expect(useProjectStore.getState().projectDetailMap.launch.project.name).toBe('Renamed');++ const renamed = { ...original, name: 'Renamed', updatedAt: 'server' };+ // The refresh that follows the rename sees the server's new state.+ vi.mocked(projectService.listAll).mockResolvedValue(ok([renamed, project('p2')]) as any);+ await act(async () => {+ resolveUpdate(ok(renamed));+ await operation;+ });+ expect(useProjectStore.getState().projectListMap.all[0]).toMatchObject({+ name: 'Renamed',+ updatedAt: 'server',+ });+ expect(useProjectStore.getState().projectDetailMap.launch.project.updatedAt).toBe('server');});- await useProjectStore.getState().deleteProject('project-1');- expect(projectService.delete).toHaveBeenCalledWith('project-1');- const matcher = vi.mocked(mutate).mock.calls.at(-1)?.[0];- expect(typeof matcher === 'function' && matcher(projectKeys.list('user-1:personal'))).toBe(- true,- );- });+ it('rolls both copies back when the rename fails', async () => {+ seed();+ await waitSeeded();+ vi.mocked(projectService.update).mockRejectedValue(new Error('boom'));- 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;- 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] },+ await expect(+ useProjectStore.getState().updateProject('p1', { name: 'Renamed' }),+ ).rejects.toThrow('boom');++ expect(useProjectStore.getState().projectListMap.all[0].name).toBe('Original');+ expect(useProjectStore.getState().projectDetailMap.launch.project.name).toBe('Original');});- const operation = useProjectStore.getState().updateProject('project-1', { name: 'Renamed' });+ it('removes a deleted project from the list and its page', async () => {+ seed();+ await waitSeeded();+ vi.mocked(projectService.delete).mockResolvedValue(ok(project('p1')) as any);+ vi.mocked(projectService.listAll).mockResolvedValue(ok([project('p2')]) as any);- expect(renderHook(() => useCurrentProjectList()).result.current[0].name).toBe('Renamed');- expect(renderHook(() => useCurrentProjectDetail('launch')).result.current?.project.name).toBe(- 'Renamed',- );+ await act(() => useProjectStore.getState().deleteProject('p1'));- resolveUpdate({ data: renamed, message: 'Project updated', success: true });- await operation;+ expect(useProjectStore.getState().projectListMap.all.map((p) => p.id)).toEqual(['p2']);+ expect(useProjectStore.getState().projectDetailMap.launch).toBeUndefined();+ });- expect(useProjectStore.getState().projectLists['user-1:personal'][0].name).toBe('Renamed');- expect(useProjectStore.getState().projectDetails['user-1:personal'].launch.project.name).toBe(- 'Renamed',- );- const matcher = vi.mocked(mutate).mock.calls.at(-1)?.[0];- expect(typeof matcher === 'function' && matcher(projectKeys.list('user-1:personal'))).toBe(- true,- );+ it('creates the project in the active workspace and shows it at the top', async () => {+ seed();+ await waitSeeded();+ mocks.activeWorkspaceId = 'workspace-1';+ const created = project('p3', 'Launch');+ vi.mocked(projectService.create).mockResolvedValue(ok(created) as any);+ // Keep the follow-up refresh in flight: the new row must show before it lands.+ vi.mocked(projectService.listAll).mockImplementation(pending);++ await act(async () => {+ await expect(+ useProjectStore+ .getState()+ .createProject({ identifier: 'LOB', name: 'Launch', slug: 'launch' }),+ ).resolves.toBe(created);+ });++ expect(projectService.create).toHaveBeenCalledWith(+ { identifier: 'LOB', name: 'Launch', slug: 'launch' },+ 'workspace-1',+ );+ expect(useProjectStore.getState().projectListMap.all[0].id).toBe('p3');+ });});});diff --git a/src/store/project/store.ts b/src/store/project/store.tsindex 60f9db797bf..cc602e6a028 100644--- a/src/store/project/store.ts+++ b/src/store/project/store.ts@@ -1,36 +1,40 @@-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 {+ arrayEntity,+ createReplicaSlice,+ createReplicaState,+ linkReplicaEntity,+ recordLens,+ type ReplicaState,+ type ReplicaSyncResult,+ singleEntity,+} from '@/libs/replica';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,+ PROJECT_LIST_KEY,+ type ProjectDetail,+ projectDetailResource,+ type ProjectListItem,+ projectListResource,} 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 currentScope = () => getCacheScope();+export type { ProjectDetail, ProjectListItem } from './projection';export interface ProjectStoreState {- projectDetails: Record<string, Record<string, ProjectDetail>>;- projectLists: Record<string, ProjectListItem[]>;- projectOptimisticPatches: Record<string, Record<string, Partial<ProjectListItem>>>;+ /** Project pages by route param (id or slug). */+ projectDetailMap: Record<string, ProjectDetail>;+ /** Replica bookkeeping for `projectDetailMap`. */+ projectDetailReplica: ReplicaState<ProjectDetail>;+ /** `projectListMap.all`: every project of the active scope. */+ projectListMap: Record<string, ProjectListItem[]>;+ /** Replica bookkeeping for `projectListMap`. */+ projectListReplica: ReplicaState<ProjectListItem[]>;}interface ProjectStore extends ProjectStoreState {@@ -40,121 +44,87 @@ interface ProjectStore extends ProjectStoreState {slug?: string;}) => Promise<ProjectListItem>;deleteProject: (id: string) => Promise<void>;- internal_dispatchProject: (action: ProjectDispatchAction) => void;refreshProjectList: () => Promise<void>;updateProject: (id: string, input: { name: string }) => Promise<ProjectListItem>;- useFetchProjectDetail: (id?: string) => SWRResponse<ProjectDetailResponse>;- useFetchProjectList: (enabled?: boolean) => SWRResponse<ProjectListResponse>;+ /** Fetch orchestration only; read the value with `useCurrentProjectDetail`. */+ useFetchProjectDetail: (idOrSlug?: string) => ReplicaSyncResult;+ /** Fetch orchestration only; read the rows with `useCurrentProjectList`. */+ useFetchProjectList: (enabled?: boolean) => ReplicaSyncResult;}+export const initialProjectState: ProjectStoreState = {+ projectDetailMap: {},+ projectDetailReplica: createReplicaState(),+ projectListMap: {},+ projectListReplica: createReplicaState(),+};++const LIST_PARAMS = {} as Record<string, never>;+const devtools = createDevtools('project');export const useProjectStore = createWithEqualityFn<ProjectStore>()(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),- );- } 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));+ const list = createReplicaSlice(projectListResource, {+ actionPrefix: 'project/list',+ entity: arrayEntity<ProjectListItem>((project) => project.id),+ fetcher: () => projectService.listAll(),+ get,+ merge: (response) => response.data,+ set,+ stateKey: 'projectListReplica',+ view: recordLens<ProjectStore, ProjectListItem[]>('projectListMap'),+ });+ const detail = createReplicaSlice(projectDetailResource, {+ actionPrefix: 'project/detail',+ entity: singleEntity<ProjectDetail, ProjectListItem>((project) => project.id, {+ get: (value) => value.project,+ set: (value, project) => ({ ...value, project }),+ }),+ fetcher: (idOrSlug) => projectService.detail(idOrSlug),+ get,+ merge: (response) => response.data,+ set,+ stateKey: 'projectDetailReplica',+ view: recordLens<ProjectStore, ProjectDetail>('projectDetailMap'),+ });+ // The same project lives in the list and in every loaded project page.+ const projectEntity = linkReplicaEntity<ProjectListItem>([list, detail]);++ const refreshList = () => list.revalidate(PROJECT_LIST_KEY);return {+ ...initialProjectState,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;+ const project = response.data;+ list.update(PROJECT_LIST_KEY, (items) =>+ items && !items.some((item) => item.id === project.id) ? [project, ...items] : items,+ );+ void refreshList();+ return project;},deleteProject: async (id) => {- const scope = currentScope();await projectService.delete(id);- dispatch({ id, scope, type: 'commitDelete' });- void refreshList(scope);+ projectEntity.remove(id);+ void refreshList();},- internal_dispatchProject: dispatch,- projectDetails: {},- projectLists: {},- projectOptimisticPatches: {},refreshProjectList: async () => {- const scope = currentScope();- await refreshList(scope);+ await refreshList();},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' });- },- },- );- },- 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' });- },- },+ const response = await projectEntity.optimistic(+ id,+ (project) => ({ ...project, ...input }),+ () => projectService.update(id, input),);+ // Server-owned fields (updatedAt, slug normalisation) land in every copy.+ projectEntity.update(id, (project) => ({ ...project, ...response.data }));+ void refreshList();+ return response.data;},+ useFetchProjectDetail: (idOrSlug) => detail.useSync(idOrSlug || null),+ useFetchProjectList: (enabled = true) => list.useSync(LIST_PARAMS, { enabled }),};}),shallow,@@ -162,24 +132,10 @@ export const useProjectStore = createWithEqualityFn<ProjectStore>()(expose('project', useProjectStore);-export const useCurrentProjectList = () => {- const scope = useCacheScope();- 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,- );- });-};+const EMPTY_PROJECTS: ProjectListItem[] = [];-export const useCurrentProjectDetail = (id?: string) => {- const scope = useCacheScope();- 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;- });-};+export const useCurrentProjectList = () =>+ useProjectStore((state) => state.projectListMap[PROJECT_LIST_KEY] ?? EMPTY_PROJECTS);++export const useCurrentProjectDetail = (idOrSlug?: string) =>+ useProjectStore((state) => (idOrSlug ? state.projectDetailMap[idOrSlug] : undefined));