π€― 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(home): pilot local-first recents store (#18894)
Arvin Xuc411a8de3237
diff --git a/src/features/Home/Recents/AllRecentsDrawer.tsx b/src/features/Home/Recents/AllRecentsDrawer.tsxindex ee5340e4c84..31657a2ed42 100644--- a/src/features/Home/Recents/AllRecentsDrawer.tsx+++ b/src/features/Home/Recents/AllRecentsDrawer.tsx@@ -2,19 +2,17 @@import { Empty, Flexbox, SearchBar } from '@lobehub/ui';import { SearchIcon } from 'lucide-react';-import { memo, useCallback, useMemo, useState } from 'react';+import { memo, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';-import { taskDetailPath } from '@/features/AgentTasks/shared/taskDetailPath';import SkeletonList from '@/features/NavPanel/components/SkeletonList';import SideBarDrawer from '@/features/NavPanel/SideBarDrawer';-import WorkspaceLink from '@/features/Workspace/WorkspaceLink';-import { useClientDataSWR } from '@/libs/swr';-import { recentKeys } from '@/libs/swr/keys';import { useCacheScope } from '@/libs/swr/useCacheScope';-import { RECENT_SIDEBAR_TYPES, recentService } from '@/services/recent';+import { useHomeStore } from '@/store/home';+import { homeRecentSelectors } from '@/store/home/selectors';+import { createRecentQueryKey } from '@/store/home/slices/recent/initialState';-import RecentListItem from './Item';+import ConnectedItem from './ConnectedItem';interface AllRecentsDrawerProps {onClose: () => void;@@ -25,26 +23,18 @@ 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 { data: recents, isLoading } = useClientDataSWR(- open ? recentKeys.allDrawer(open, scope) : null,- () => recentService.getAll(50, RECENT_SIDEBAR_TYPES),- );+ const { isLoading } = useFetchAllRecents(open, scope);- const filteredRecents = useMemo(() => {- if (!recents) return [];+ const filteredItems = useMemo(() => {const keyword = searchKeyword.trim().toLowerCase();- if (!keyword) return recents;- return recents.filter((item) => item.title.toLowerCase().includes(keyword));- }, [recents, searchKeyword]);-- const getRecentRoute = useCallback((item: (typeof filteredRecents)[number]) => {- if (item.type !== 'task') return item.routePath;- const taskId = item.id;- if (!taskId) return item.routePath;-- return taskDetailPath(taskId, item.agentId ?? undefined);- }, []);+ if (!keyword) return items ?? [];+ return items?.filter((item) => item.title.toLowerCase().includes(keyword)) ?? [];+ }, [items, searchKeyword]);return (<SideBarDrawer@@ -66,24 +56,21 @@ const AllRecentsDrawer = memo<AllRecentsDrawerProps>(({ open, onClose }) => {onClose={onClose}><Flexbox gap={1} paddingBlock={1} paddingInline={4}>- {isLoading || !recents ? (+ {isLoading && !query ? (<SkeletonList rows={5} />- ) : filteredRecents.length === 0 && searchKeyword.trim() ? (+ ) : filteredItems.length === 0 && searchKeyword.trim() ? (<Emptydescription={t('navPanel.searchResultEmpty')}icon={SearchIcon}style={{ paddingBlock: 24 }}/>) : (- filteredRecents.map((item) => (- <WorkspaceLink- key={`${item.type}-${item.id}`}- style={{ color: 'inherit', textDecoration: 'none' }}- to={getRecentRoute(item)}- >- <RecentListItem {...item} />- </WorkspaceLink>- ))+ filteredItems.map((item) => {+ const itemRef = `${item.type}:${item.id}` as const;+ return (+ <ConnectedItem itemRef={itemRef} key={itemRef} queryKey={queryKey} scope={scope} />+ );+ }))}</Flexbox></SideBarDrawer>diff --git a/src/features/Home/Recents/ConnectedItem.tsx b/src/features/Home/Recents/ConnectedItem.tsxnew file mode 100644index 00000000000..0ea812ea5f4--- /dev/null+++ b/src/features/Home/Recents/ConnectedItem.tsx@@ -0,0 +1,33 @@+import { memo } from 'react';++import { taskDetailPath } from '@/features/AgentTasks/shared/taskDetailPath';+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';+import { useHomeStore } from '@/store/home';+import { homeRecentSelectors } from '@/store/home/selectors';+import type { RecentEntityRef } from '@/store/home/slices/recent/initialState';++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));+ if (!item) return null;++ const route =+ item.type === 'task' ? taskDetailPath(item.id, item.agentId ?? undefined) : item.routePath;++ return (+ <WorkspaceLink style={{ color: 'inherit', textDecoration: 'none' }} to={route}>+ <RecentListItem {...item} />+ </WorkspaceLink>+ );+});++ConnectedItem.displayName = 'ConnectedRecentItem';++export default ConnectedItem;diff --git a/src/features/Home/Recents/List.tsx b/src/features/Home/Recents/List.tsxindex 63052ae5b25..992ac1059fc 100644--- a/src/features/Home/Recents/List.tsx+++ b/src/features/Home/Recents/List.tsx@@ -1,71 +1,64 @@import { Flexbox } from '@lobehub/ui';import { MoreHorizontalIcon } from 'lucide-react';-import { memo, useCallback, useMemo } from 'react';+import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';import AsyncBoundary from '@/components/AsyncBoundary';-import { taskDetailPath } from '@/features/AgentTasks/shared/taskDetailPath';import NavItem from '@/features/NavPanel/components/NavItem';import SkeletonList from '@/features/NavPanel/components/SkeletonList';-import WorkspaceLink from '@/features/Workspace/WorkspaceLink';import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';import { useHomeStore } from '@/store/home';import { homeRecentSelectors } from '@/store/home/selectors';+import { createRecentQueryKey } from '@/store/home/slices/recent/initialState';import AllRecentsDrawer from './AllRecentsDrawer';-import RecentListItem from './Item';+import ConnectedItem from './ConnectedItem';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 }) => {+const RecentsList = memo<RecentsListProps>(({ error, onRetry, scope }) => {const { t } = useTranslation('chat');- const recents = useHomeStore(homeRecentSelectors.recents);- const isInit = useHomeStore(homeRecentSelectors.isRecentsInit);const recentPageSize = useGlobalStore(systemStatusSelectors.recentPageSize);+ const queryKey = createRecentQueryKey(recentPageSize + 1);+ const query = useHomeStore(homeRecentSelectors.query(scope, queryKey));+ const items = query?.items;const [drawerOpen, openDrawer, closeDrawer] = useHomeStore((s) => [s.allRecentsDrawerOpen,s.openAllRecentsDrawer,s.closeAllRecentsDrawer,]);- const displayItems = useMemo(() => recents.slice(0, recentPageSize), [recents, recentPageSize]);- const hasMore = recents.length > recentPageSize;-- const getRecentRoute = useCallback((item: (typeof displayItems)[number]) => {- if (item.type !== 'task') return item.routePath;- const taskId = item.id;- if (!taskId) return item.routePath;-- return taskDetailPath(taskId, item.agentId ?? undefined);- }, []);+ const displayItems = useMemo(+ () => items?.slice(0, recentPageSize) ?? [],+ [items, recentPageSize],+ );+ const hasMore = (items?.length ?? 0) > recentPageSize;// Error gated ahead of the skeleton so a failed recents fetch shows Retry// instead of a permanent skeleton (`isRecentsInit` only flips on success β//return (<AsyncBoundary- data={isInit ? recents : undefined}- error={error}+ data={items}+ error={query ? undefined : error}errorVariant={'inline'}- isLoading={!isInit && !error}+ isLoading={!query && !error}loading={<SkeletonList rows={3} />}onRetry={onRetry}><Flexbox gap={1}>- {displayItems.map((item) => (- <WorkspaceLink- key={`${item.type}-${item.id}`}- style={{ color: 'inherit', textDecoration: 'none' }}- to={getRecentRoute(item)}- >- <RecentListItem {...item} />- </WorkspaceLink>- ))}+ {displayItems.map((item) => {+ const itemRef = `${item.type}:${item.id}` as const;+ return (+ <ConnectedItem itemRef={itemRef} key={itemRef} queryKey={queryKey} scope={scope} />+ );+ })}{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 9ace0333609..a2b9edfd96d 100644--- a/src/features/Home/Recents/index.tsx+++ b/src/features/Home/Recents/index.tsx@@ -17,12 +17,13 @@ import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceimport NeuralNetworkLoading from '@/components/NeuralNetworkLoading';import { openCustomizeSidebarModal } from '@/features/HomeSidebar/Body/CustomizeSidebarModal';import SkeletonList from '@/features/NavPanel/components/SkeletonList';-import { useInitRecents } from '@/hooks/useInitRecents';+import { useCacheScope } from '@/libs/swr/useCacheScope';import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';import { reorderSidebarItems } from '@/store/global/selectors/systemStatus';import { useHomeStore } from '@/store/home';import { homeRecentSelectors } from '@/store/home/selectors';+import { createRecentQueryKey } from '@/store/home/slices/recent/initialState';import { useUserStore } from '@/store/user';import { authSelectors } from '@/store/user/slices/auth/selectors';@@ -34,15 +35,14 @@ interface RecentsProps {const Recents = memo<RecentsProps>(({ itemKey }) => {const { t } = useTranslation('common');- const recents = useHomeStore(homeRecentSelectors.recents);- const isInit = useHomeStore(homeRecentSelectors.isRecentsInit);+ const scope = useCacheScope();const isLogin = useUserStore(authSelectors.isLogin);- // Keep `error` / `mutate` so a failed recents fetch surfaces a Retry state- // instead of a permanent skeleton.- const { error, isRevalidating, mutate } = useInitRecents();-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 refreshRecents = useHomeStore((s) => s.refreshRecents);const sidebarItems = useGlobalStore(systemStatusSelectors.sidebarItems(activeWorkspaceId));const hiddenSections = useGlobalStore(systemStatusSelectors.hiddenSidebarSections(activeWorkspaceId),@@ -117,19 +117,10 @@ const Recents = memo<RecentsProps>(({ itemKey }) => {onClick: () => openCustomizeSidebarModal(),},] as MenuProps['items'];- }, [- recentPageSize,- updateSystemStatus,- t,- isFirst,- isLast,- moveSection,- hideSection,- visibleItems.length,- ]);+ }, [recentPageSize, updateSystemStatus, t, isFirst, isLast, moveSection, hideSection]);if (!isLogin) return null;- if (isInit && (!recents || recents.length === 0)) return null;+ if (query && query.items.length === 0) return null;return (<AccordionItem@@ -149,12 +140,16 @@ const Recents = memo<RecentsProps>(({ itemKey }) => {<Text ellipsis fontSize={12} type={'secondary'} weight={500}>{t('recents')}</Text>- {isRevalidating && <NeuralNetworkLoading size={14} />}+ {syncStatus?.isValidating && query && <NeuralNetworkLoading size={14} />}</Flexbox>}><Suspense fallback={<SkeletonList rows={3} />}>- <RecentsList error={error} onRetry={() => mutate()} />+ <RecentsList+ error={syncStatus?.error}+ scope={scope}+ onRetry={() => void refreshRecents(scope)}+ /></Suspense></AccordionItem>);diff --git a/src/features/Home/Recents/useDropdownMenu.tsx b/src/features/Home/Recents/useDropdownMenu.tsxindex 6f381f3340a..b0c417739d4 100644--- a/src/features/Home/Recents/useDropdownMenu.tsx+++ b/src/features/Home/Recents/useDropdownMenu.tsx@@ -11,6 +11,7 @@ import { useTaskTransferMenuItem } from '@/business/client/hooks/useTaskTransferimport { 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';@@ -21,10 +22,8 @@ export const useRecentItemDropdownMenu = (toggleEditing: (visible?: boolean) => void,) => {const { t } = useTranslation(['common', 'topic', 'components']);- const [updateRecentTitle, refreshRecents] = useHomeStore((s) => [- s.updateRecentTitle,- s.refreshRecents,- ]);+ const scope = useCacheScope();+ const [renameRecent, refreshRecents] = useHomeStore((s) => [s.renameRecent, s.refreshRecents]);// Viewer can read recents but cannot rename/delete them β keep the menu// items visible-but-disabled so the affordance is clear (per disabled-not-@@ -41,27 +40,8 @@ export const useRecentItemDropdownMenu = (const transferMenuItems = documentTransferItems ?? taskTransferItems;const handleRename = useCallback(- async (newTitle: string) => {- // Optimistic update- updateRecentTitle(item.id, newTitle);-- // Persist to server- switch (item.type) {- case 'document': {- await documentService.updateDocument({ id: item.id, title: newTitle });- break;- }- case 'task': {- await taskService.update(item.id, { name: newTitle });- break;- }- case 'topic': {- await topicService.updateTopic(item.id, { title: newTitle });- break;- }- }- },- [item, updateRecentTitle],+ (newTitle: string) => renameRecent({ id: item.id, scope, title: newTitle, type: item.type }),+ [item.id, item.type, renameRecent, scope],);const handleDelete = useCallback(() => {@@ -70,7 +50,7 @@ export const useRecentItemDropdownMenu = (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();+ await refreshRecents(scope);},topicIds: [item.id],});@@ -97,11 +77,11 @@ export const useRecentItemDropdownMenu = (break;}}- await refreshRecents();+ await refreshRecents(scope);},title: t('delete', { ns: 'common' }),});- }, [item, t, refreshRecents]);+ }, [item, refreshRecents, scope, t]);const dropdownMenu = useCallback((): MenuProps['items'] => {const items: NativeContextMenuItem[] = [diff --git a/src/features/HomeLayout/RecentHydration.tsx b/src/features/HomeLayout/RecentHydration.tsxdeleted file mode 100644index af4c230c15b..00000000000--- a/src/features/HomeLayout/RecentHydration.tsx+++ /dev/null@@ -1,11 +0,0 @@-import { memo } from 'react';--import { useInitRecents } from '@/hooks/useInitRecents';--const RecentHydration = memo(() => {- useInitRecents();-- return null;-});--export default RecentHydration;diff --git a/src/features/HomeLayout/RecentSync.tsx b/src/features/HomeLayout/RecentSync.tsxnew file mode 100644index 00000000000..2164c015333--- /dev/null+++ b/src/features/HomeLayout/RecentSync.tsx@@ -0,0 +1,9 @@+import { useSyncRecents } from '@/hooks/useSyncRecents';++const RecentSync = () => {+ useSyncRecents();++ return null;+};++export default RecentSync;diff --git a/src/features/HomeLayout/index.tsx b/src/features/HomeLayout/index.tsxindex 019e896c649..d7e12d4e06e 100644--- a/src/features/HomeLayout/index.tsx+++ b/src/features/HomeLayout/index.tsx@@ -7,7 +7,7 @@ import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaimport { useIsDark } from '@/hooks/useIsDark';import HomeAgentIdSync from './HomeAgentIdSync';-import RecentHydration from './RecentHydration';+import RecentSync from './RecentSync';import { styles } from './style';interface LayoutProps {@@ -62,7 +62,7 @@ const Layout: FC<LayoutProps> = ({ children }) => {</Flexbox><HomeAgentIdSync />- <RecentHydration />+ <RecentSync /></Flexbox></Activity>);diff --git a/src/hooks/useInitRecents.ts b/src/hooks/useSyncRecents.tssimilarity index 68%rename from src/hooks/useInitRecents.tsrename to src/hooks/useSyncRecents.tsindex 7dd66b25728..66d4250bba0 100644--- a/src/hooks/useInitRecents.ts+++ b/src/hooks/useSyncRecents.ts@@ -5,18 +5,11 @@ import { useHomeStore } from '@/store/home';import { useUserStore } from '@/store/user';import { authSelectors } from '@/store/user/selectors';-export const useInitRecents = () => {+export const useSyncRecents = (): void => {const useFetchRecents = useHomeStore((s) => s.useFetchRecents);const isLogin = useUserStore(authSelectors.isLogin);const scope = useCacheScope();const recentPageSize = useGlobalStore(systemStatusSelectors.recentPageSize);- const { isValidating, data, ...rest } = useFetchRecents(isLogin, recentPageSize, scope);-- return {- ...rest,- data,- isLoading: rest.isLoading && isLogin,- isRevalidating: isValidating && !!data,- };+ useFetchRecents(isLogin, scope, recentPageSize);};diff --git a/src/libs/queryProjectionStorage/index.ts b/src/libs/queryProjectionStorage/index.tsnew file mode 100644index 00000000000..61594cb3286--- /dev/null+++ b/src/libs/queryProjectionStorage/index.ts@@ -0,0 +1,2 @@+export * from './localStorage';+export type * from './types';diff --git a/src/libs/queryProjectionStorage/localStorage.test.ts b/src/libs/queryProjectionStorage/localStorage.test.tsnew file mode 100644index 00000000000..d8797e55352--- /dev/null+++ b/src/libs/queryProjectionStorage/localStorage.test.ts@@ -0,0 +1,38 @@+import { afterEach, describe, expect, it } from 'vitest';++import { LocalStorageQueryProjectionStorage } from './localStorage';++afterEach(() => {+ localStorage.clear();+});++describe('LocalStorageQueryProjectionStorage', () => {+ it('reads and writes one scoped query through the async interface', async () => {+ const storage = new LocalStorageQueryProjectionStorage<string[]>({ namespace: 'test' });+ const key = { queryKey: 'limit:10', scope: 'user:workspace' };++ await storage.set(key, { data: ['cached'], updatedAt: 1 });++ await expect(storage.get(key)).resolves.toEqual({ data: ['cached'], updatedAt: 1 });+ });++ it('isolates projections by scope and query key', async () => {+ const storage = new LocalStorageQueryProjectionStorage<string[]>({ namespace: 'test' });++ await storage.set({ queryKey: 'limit:10', scope: 'scope-a' }, { data: ['a'], updatedAt: 1 });++ await expect(storage.get({ queryKey: 'limit:10', scope: 'scope-b' })).resolves.toBeUndefined();+ await expect(storage.get({ queryKey: 'limit:50', scope: 'scope-a' })).resolves.toBeUndefined();+ });++ it('preserves rich data types with the default codec', async () => {+ const storage = new LocalStorageQueryProjectionStorage<{ createdAt: Date }>({+ namespace: 'test',+ });+ const key = { queryKey: 'detail:1', scope: 'scope' };++ await storage.set(key, { data: { createdAt: new Date(0) }, updatedAt: 1 });++ expect((await storage.get(key))?.data.createdAt).toEqual(new Date(0));+ });+});diff --git a/src/libs/queryProjectionStorage/localStorage.ts b/src/libs/queryProjectionStorage/localStorage.tsnew file mode 100644index 00000000000..be268b83522--- /dev/null+++ b/src/libs/queryProjectionStorage/localStorage.ts@@ -0,0 +1,60 @@+import superjson from 'superjson';++import type {+ QueryProjection,+ QueryProjectionCodec,+ QueryProjectionKey,+ QueryProjectionStorage,+} from './types';++interface LocalStorageQueryProjectionStorageOptions<T> {+ codec?: QueryProjectionCodec<T>;+ namespace: string;+}++export class LocalStorageQueryProjectionStorage<T> implements QueryProjectionStorage<T> {+ readonly #codec: QueryProjectionCodec<T>;+ readonly #namespace: string;++ constructor(options: LocalStorageQueryProjectionStorageOptions<T>) {+ this.#namespace = options.namespace;+ this.#codec = options.codec ?? {+ parse: superjson.parse<QueryProjection<T>>,+ stringify: superjson.stringify,+ };+ }++ #key = ({ queryKey, scope }: QueryProjectionKey) =>+ `${this.#namespace}:${encodeURIComponent(scope)}:${encodeURIComponent(queryKey)}`;++ get = async (key: QueryProjectionKey): Promise<QueryProjection<T> | undefined> => {+ if (typeof window === 'undefined') return undefined;++ try {+ const value = localStorage.getItem(this.#key(key));+ return value ? this.#codec.parse(value) : undefined;+ } catch {+ return undefined;+ }+ };++ remove = async (key: QueryProjectionKey): Promise<void> => {+ if (typeof window === 'undefined') return;++ try {+ localStorage.removeItem(this.#key(key));+ } catch {+ // Projection persistence is best-effort; the server remains the durable SoT.+ }+ };++ set = async (key: QueryProjectionKey, projection: QueryProjection<T>): Promise<void> => {+ if (typeof window === 'undefined') return;++ try {+ localStorage.setItem(this.#key(key), this.#codec.stringify(projection));+ } catch {+ // Projection persistence is best-effort; the server remains the durable SoT.+ }+ };+}diff --git a/src/libs/queryProjectionStorage/types.ts b/src/libs/queryProjectionStorage/types.tsnew file mode 100644index 00000000000..dd95a02a00c--- /dev/null+++ b/src/libs/queryProjectionStorage/types.ts@@ -0,0 +1,20 @@+export interface QueryProjectionKey {+ queryKey: string;+ scope: string;+}++export interface QueryProjection<T> {+ data: T;+ updatedAt: number;+}++export interface QueryProjectionStorage<T> {+ get: (key: QueryProjectionKey) => Promise<QueryProjection<T> | undefined>;+ remove: (key: QueryProjectionKey) => Promise<void>;+ set: (key: QueryProjectionKey, projection: QueryProjection<T>) => Promise<void>;+}++export interface QueryProjectionCodec<T> {+ parse: (value: string) => QueryProjection<T>;+ stringify: (projection: QueryProjection<T>) => string;+}diff --git a/src/libs/swr/localStorageProvider.test.ts b/src/libs/swr/localStorageProvider.test.tsindex 37f2afe30fb..db026aad47a 100644--- a/src/libs/swr/localStorageProvider.test.ts+++ b/src/libs/swr/localStorageProvider.test.ts@@ -276,7 +276,7 @@ describe('createCacheProvider β tiering', () => {it('exposes the central tier config keyed by domain prefix', () => {expect(CACHE_TIERS.idb).toContain('message:');expect(CACHE_TIERS.idb).toContain('topic:');- expect(CACHE_TIERS.local).toContain('recent:list');+ expect(CACHE_TIERS.local).toContain('recent:topicList');expect(CACHE_TIERS.local).toContain('taskTemplate:');expect(CACHE_TIERS.local).toContain('modelConfig:');});diff --git a/src/libs/swr/localStorageProvider.ts b/src/libs/swr/localStorageProvider.tsindex b942e2bcd23..d849788e037 100644--- a/src/libs/swr/localStorageProvider.ts+++ b/src/libs/swr/localStorageProvider.ts@@ -492,10 +492,8 @@ export const CACHE_TIERS = {],/** Small, frequently-changing list shells β localStorage (sync first paint). */local: [- 'recent:list',- // Home's chat-mode recents. Matching is substring-based, so `recent:list`- // does not cover this sibling key β without its own entry the list is- // memory-only and every cold boot pays a skeleton for data we already had.+ // Home's chat-mode recents still uses the SWR persistence tier. The mixed+ // Recent projection is persisted by its Zustand localStorage snapshot.'recent:topicList','fetchRecentTopics','fetchRecentResources',diff --git a/src/store/home/slices/recent/action.test.ts b/src/store/home/slices/recent/action.test.tsindex 3dc7ef9fdf8..c682e324514 100644--- a/src/store/home/slices/recent/action.test.ts+++ b/src/store/home/slices/recent/action.test.ts@@ -1,186 +1,194 @@import type { RecentItem } from '@lobechat/types';-import { act, renderHook } from '@testing-library/react';+import { act, waitFor } from '@testing-library/react';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 { recentService } from '@/services/recent';+import { taskService } from '@/services/task';import { useHomeStore } from '@/store/home';-import { initialRecentState } from '@/store/home/slices/recent/initialState';--const item = (id: string, title: string): RecentItem => ({ id, title }) as unknown as RecentItem;--/**- * Render `useFetchRecents` with `useClientDataSWRWithSync` stubbed so we can grab- * the `onData` sync callback and drive the scope guard directly.- */-const captureOnData = (scope: string) => {- let onData: ((data: RecentItem[]) => void) | undefined;- vi.spyOn(swr, 'useClientDataSWRWithSync').mockImplementation(((- _key: unknown,- _fetcher: unknown,- opts: any,- ) => {- onData = opts?.onData;- return { data: undefined, isValidating: false, mutate: vi.fn() };- }) as any);-- renderHook(() => useHomeStore.getState().useFetchRecents(true, 10, scope));- return () => onData;+import { createRecentQueryKey, initialRecentState } from '@/store/home/slices/recent/initialState';+import { recentProjection } 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 => ({+ icon: type,+ id,+ routePath: '/',+ status: null,+ title,+ type,+ updatedAt: new Date(0),+});++type TaskUpdateResult = Awaited<ReturnType<typeof taskService.update>>;+const taskUpdateResult = {} as TaskUpdateResult;++const deferred = <T>() => {+ let reject!: (reason?: unknown) => void;+ let resolve!: (value: T | PromiseLike<T>) => void;+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {+ reject = rejectPromise;+ resolve = resolvePromise;+ });+ return { promise, reject, resolve };};+const replaceQuery = (scope: string, queryKey: string, items: RecentItem[]) =>+ useHomeStore.getState().internal_replaceRecentQuery(scope, queryKey, items);+beforeEach(() => {useHomeStore.setState({ ...initialRecentState });+ vi.spyOn(cacheScope, 'getCacheScope').mockReturnValue('user-1:ws-A');});afterEach(() => {vi.restoreAllMocks();+ localStorage.clear();});describe('RecentActionImpl', () => {- describe('useFetchRecents onData scope guard', () => {- it('fetches only document and task recents without polling', async () => {- const swrSpy = vi.spyOn(swr, 'useClientDataSWRWithSync').mockReturnValue({- data: undefined,- isValidating: false,- mutate: vi.fn(),- } as any);- const getAllSpy = vi.spyOn(recentService, 'getAll').mockResolvedValue([]);-- renderHook(() => useHomeStore.getState().useFetchRecents(true, 10, 'user-1:ws-A'));-- expect(swrSpy).toHaveBeenCalledWith(expect.any(Array), expect.any(Function), {- onData: expect.any(Function),- });+ it('keeps list projections isolated by scope and query', () => {+ const compactQuery = createRecentQueryKey(11);+ const drawerQuery = createRecentQueryKey(50);- const fetcher = swrSpy.mock.calls[0][1] as () => Promise<RecentItem[]>;- await fetcher();-- expect(getAllSpy).toHaveBeenCalledWith(11, ['document', 'task']);- });-- it('applies data for the matching scope and tags recentsScope', () => {- vi.spyOn(cacheScope, 'getCacheScope').mockReturnValue('user-1:ws-A');- const getOnData = captureOnData('user-1:ws-A');-- act(() => getOnData()!([item('a', 'A')]));-- const state = useHomeStore.getState();- expect(state.recents).toEqual([item('a', 'A')]);- expect(state.isRecentsInit).toBe(true);- expect(state.recentsScope).toBe('user-1:ws-A');+ act(() => {+ replaceQuery('user-1:ws-A', compactQuery, [item('a', 'Compact')]);+ replaceQuery('user-1:ws-A', drawerQuery, [item('a', 'Drawer'), item('b', 'B')]);});- it('ignores data whose scope no longer matches the active cache scope', () => {- // active scope moved to ws-A, but this callback belongs to the stale ws-B key- vi.spyOn(cacheScope, 'getCacheScope').mockReturnValue('user-1:ws-A');- const getOnData = captureOnData('user-1:ws-B');+ 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')]);+ });- act(() => getOnData()!([item('stale', 'STALE')]));+ 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 state = useHomeStore.getState();- expect(state.recents).toEqual([]);- expect(state.isRecentsInit).toBe(false);- expect(state.recentsScope).toBeNull();- });+ 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('keeps data isolated across users in the same workspace', () => {- useHomeStore.setState({- isRecentsInit: true,- recents: [item('u1', 'user1 item')],- recentsScope: 'user-1:ws-A',- });- // now signed in as user-2 in the same workspace- vi.spyOn(cacheScope, 'getCacheScope').mockReturnValue('user-2:ws-A');- const getOnData = captureOnData('user-2:ws-A');-- act(() => getOnData()!([item('u2', 'user2 item')]));-- const state = useHomeStore.getState();- expect(state.recents).toEqual([item('u2', 'user2 item')]);- expect(state.recentsScope).toBe('user-2:ws-A');- });+ 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);- it('skips redundant set when init, same scope and equal data', () => {- useHomeStore.setState({- isRecentsInit: true,- recents: [item('a', 'A')],- recentsScope: 'user-1:ws-A',- });- vi.spyOn(cacheScope, 'getCacheScope').mockReturnValue('user-1:ws-A');- const getOnData = captureOnData('user-1:ws-A');+ 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;- // an early return means no set() runs, so the state object keeps its identity- const before = useHomeStore.getState();- act(() => getOnData()!([item('a', 'A')]));+ expect(+ homeRecentSelectors.query('user-1:ws-A', queryKey)(useHomeStore.getState())?.items[0].title,+ ).toBe('Server');+ });- expect(useHomeStore.getState()).toBe(before);- });+ 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();});- describe('updateRecentTitle', () => {- it('renames in the store mirror and patches the scoped SWR caches', () => {- useHomeStore.setState({ recents: [item('a', 'old'), item('b', 'keep')] });- const mutateSpy = vi.spyOn(swr, 'mutate').mockResolvedValue(undefined as any);-- act(() => {- useHomeStore.getState().updateRecentTitle('a', 'new');- });-- expect(useHomeStore.getState().recents).toEqual([item('a', 'new'), item('b', 'keep')]);- // both the list and the drawer SWR caches get a non-revalidating patch- expect(mutateSpy).toHaveBeenCalledTimes(2);- expect(mutateSpy).toHaveBeenCalledWith(expect.any(Function), expect.any(Function), {- revalidate: false,- });- });+ it('shows an optimistic title and rolls it back when persistence fails', async () => {+ const queryKey = createRecentQueryKey(11);+ 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');++ 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');+ });- it('SWR cache updater matches keys by root and renames the target item only', () => {- useHomeStore.setState({ recents: [] });- let updater: (items?: RecentItem[]) => RecentItem[] | undefined = () => undefined;- const matchers: Array<(key: unknown) => boolean> = [];- vi.spyOn(swr, 'mutate').mockImplementation(((match: any, fn: any) => {- matchers.push(match);- updater = fn;- return Promise.resolve(undefined);- }) as any);-- act(() => {- useHomeStore.getState().updateRecentTitle('a', 'new');- });-- expect(matchers[0](recentKeys.list(true, 10, 's'))).toBe(true);- expect(matchers[0](['other:key'])).toBe(false);- expect(updater([item('a', 'old'), item('b', 'keep')])).toEqual([- item('a', 'new'),- item('b', 'keep'),+ it('fans a confirmed rename out to every loaded query projection', async () => {+ const compactQuery = createRecentQueryKey(11);+ const drawerQuery = createRecentQueryKey(50);+ 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'),]);- expect(updater(undefined)).toBeUndefined();});- });-- describe('refreshRecents', () => {- it('revalidates both the list and the drawer SWR caches', async () => {- const mutateSpy = vi.spyOn(swr, 'mutate').mockResolvedValue(undefined as any);- await act(async () => {- await useHomeStore.getState().refreshRecents();- });+ 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');+ });- expect(mutateSpy).toHaveBeenCalledTimes(2);- const matcher = mutateSpy.mock.calls[0][0] as (key: unknown) => boolean;- expect(matcher(recentKeys.list(true, 10, 's'))).toBe(true);- });+ it('serializes repeated renames and keeps the latest optimistic title', async () => {+ const queryKey = createRecentQueryKey(11);+ 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' });+ const secondRename = useHomeStore+ .getState()+ .renameRecent({ id: 'a', scope: 'user-1:ws-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');++ 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');++ secondRequest.resolve(taskUpdateResult);+ await secondRename;+ expect(+ homeRecentSelectors.item('user-1:ws-A', queryKey, 'task:a')(useHomeStore.getState())?.title,+ ).toBe('Second');});- describe('drawer visibility', () => {- it('opens and closes the all-recents drawer', () => {- act(() => useHomeStore.getState().openAllRecentsDrawer());- expect(useHomeStore.getState().allRecentsDrawerOpen).toBe(true);+ it('revalidates both list surfaces only in the requested scope', async () => {+ const mutateSpy = vi.spyOn(swr, 'mutate').mockResolvedValue(undefined as never);- act(() => useHomeStore.getState().closeAllRecentsDrawer());- expect(useHomeStore.getState().allRecentsDrawerOpen).toBe(false);- });+ await act(() => useHomeStore.getState().refreshRecents('user-1:ws-A'));++ 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);});});diff --git a/src/store/home/slices/recent/action.ts b/src/store/home/slices/recent/action.tsindex 8eb548ae218..bb7227ad430 100644--- a/src/store/home/slices/recent/action.ts+++ b/src/store/home/slices/recent/action.ts@@ -1,19 +1,34 @@import type { RecentItem } from '@lobechat/types';-import isEqual from 'fast-deep-equal';-import { type SWRResponse } from 'swr';+import type { SWRResponse } from 'swr';-import { mutate, useClientDataSWRWithSync } from '@/libs/swr';+import { mutate, useClientDataSWR } from '@/libs/swr';import { recentKeys } from '@/libs/swr/keys';import { getCacheScope } from '@/libs/swr/useCacheScope';+import { documentService } from '@/services/document';import { RECENT_SIDEBAR_TYPES, recentService } from '@/services/recent';-import { type HomeStore } from '@/store/home/store';-import { type StoreSetter } from '@/store/types';+import { taskService } from '@/services/task';+import { topicService } from '@/services/topic';+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';+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;-const updateRecentTitleInList = (id: string, title: string) => (items?: RecentItem[]) =>- items?.map((item) => (item.id === id ? { ...item, title } : item));+interface RenameRecentParams {+ id: string;+ scope: string;+ title: string;+ type: RecentItem['type'];+}type Setter = StoreSetter<HomeStore>;export const createRecentSlice = (set: Setter, get: () => HomeStore, _api?: unknown) =>@@ -21,7 +36,10 @@ export const createRecentSlice = (set: Setter, get: () => HomeStore, _api?: unknexport class RecentActionImpl {readonly #get: () => HomeStore;+ readonly #hydrationPromises = new Map<string, Promise<void>>();+ readonly #renameQueues = new Map<string, Promise<void>>();readonly #set: Setter;+ #mutationId = 0;constructor(set: Setter, get: () => HomeStore, _api?: unknown) {void _api;@@ -33,58 +51,197 @@ export class RecentActionImpl {this.#set({ allRecentsDrawerOpen: false }, false, n('closeAllRecentsDrawer'));};+ #persistRecentTitle = async ({ id, title, type }: RenameRecentParams): Promise<void> => {+ switch (type) {+ case 'document': {+ await documentService.updateDocument({ id, title });+ break;+ }+ case 'task': {+ await taskService.update(id, { name: title });+ break;+ }+ case 'topic': {+ await topicService.updateTopic(id, { title });+ break;+ }+ }+ };++ #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'));};- updateRecentTitle = (id: string, title: string): void => {- const recents = this.#get().recents.map((item) => (item.id === id ? { ...item, title } : item));- this.#set({ recents }, false, n('updateRecentTitle'));-- const updater = updateRecentTitleInList(id, title);- void Promise.all([- mutate((key: unknown) => Array.isArray(key) && key[0] === recentKeys.list.root, updater, {- revalidate: false,- }),- mutate(- (key: unknown) => Array.isArray(key) && key[0] === recentKeys.allDrawer.root,- updater,- { revalidate: false },- ),+ 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)),]);};- refreshRecents = async (): Promise<void> => {- await Promise.all([- mutate((key: unknown) => Array.isArray(key) && key[0] === recentKeys.list.root),- mutate((key: unknown) => Array.isArray(key) && key[0] === recentKeys.allDrawer.root),- ]);+ 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);++ 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);+ }+ };++ 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();+ });++ 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,- limit: number = 10,scope: string,- ): SWRResponse<RecentItem[]> => {- return useClientDataSWRWithSync<RecentItem[]>(+ 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 () => recentService.getAll(limit + 1, RECENT_SIDEBAR_TYPES),- {- onData: (data) => {- if (getCacheScope() !== scope) return;-- const state = this.#get();-- if (state.isRecentsInit && state.recentsScope === scope && isEqual(state.recents, data)) {- return;- }-- this.#set(- { isRecentsInit: true, recents: data, recentsScope: scope },- false,- n('useFetchRecents/onData'),- );- },+ 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;+ }},);};diff --git a/src/store/home/slices/recent/initialState.ts b/src/store/home/slices/recent/initialState.tsindex dafaf8517e3..6c3e9b62d7c 100644--- a/src/store/home/slices/recent/initialState.ts+++ b/src/store/home/slices/recent/initialState.ts@@ -1,15 +1,38 @@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;+}++export interface RecentScopeState {+ hydrationStatusByQuery: Record<string, 'failed' | 'hydrated' | 'hydrating'>;+ optimisticTitles: Partial<Record<RecentEntityRef, RecentOptimisticTitle>>;+ queries: Record<string, RecentQueryState>;+ syncStatusByQuery: Record<string, RecentSyncState>;+}++export interface RecentQueryState {+ items: RecentItem[];+ source: 'server' | 'storage';+ updatedAt: number;+}++export interface RecentSyncState {+ error?: unknown;+ isValidating: boolean;+}+export interface RecentState {allRecentsDrawerOpen: boolean;- isRecentsInit: boolean;- recents: RecentItem[];- recentsScope: string | null;+ recentsByScope: Record<string, RecentScopeState>;}export const initialRecentState: RecentState = {allRecentsDrawerOpen: false,- isRecentsInit: false,- recents: [],- recentsScope: null,+ recentsByScope: {},};diff --git a/src/store/home/slices/recent/projection.ts b/src/store/home/slices/recent/projection.tsnew file mode 100644index 00000000000..37fbcbf7d91--- /dev/null+++ b/src/store/home/slices/recent/projection.ts@@ -0,0 +1,7 @@+import type { RecentItem } from '@lobechat/types';++import { LocalStorageQueryProjectionStorage } from '@/libs/queryProjectionStorage';++export const recentProjection = new LocalStorageQueryProjectionStorage<RecentItem[]>({+ namespace: 'lobechat-home-recents-v3',+});diff --git a/src/store/home/slices/recent/reducer.test.ts b/src/store/home/slices/recent/reducer.test.tsnew file mode 100644index 00000000000..6b855666b4f--- /dev/null+++ b/src/store/home/slices/recent/reducer.test.ts@@ -0,0 +1,123 @@+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: '/',+ 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('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.tsnew file mode 100644index 00000000000..9d7a1f951a4--- /dev/null+++ b/src/store/home/slices/recent/reducer.ts@@ -0,0 +1,213 @@+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;+ return { ...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 2a8db954df2..993226a6671 100644--- a/src/store/home/slices/recent/selectors.ts+++ b/src/store/home/slices/recent/selectors.ts@@ -1,9 +1,25 @@import { type HomeStore } from '@/store/home/store';-const recents = (s: HomeStore) => s.recents;-const isRecentsInit = (s: HomeStore) => s.isRecentsInit;+import type { RecentEntityRef } 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;++ return recentItem && optimisticTitle !== undefined+ ? { ...recentItem, title: optimisticTitle }+ : recentItem;+};export const homeRecentSelectors = {- isRecentsInit,- recents,+ item,+ query,+ syncStatus,};