🤯 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): serve Home recent topics and tray recents from the recentList replica (#22759)
Arvin Xu5859fca0d242
diff --git a/src/features/Electron/titlebar/TrayMenu/useTrayMenuSync.test.tsx b/src/features/Electron/titlebar/TrayMenu/useTrayMenuSync.test.tsxindex d09fd675a6f..cf04c5d2411 100644--- a/src/features/Electron/titlebar/TrayMenu/useTrayMenuSync.test.tsx+++ b/src/features/Electron/titlebar/TrayMenu/useTrayMenuSync.test.tsx@@ -1,13 +1,28 @@-import { renderHook, waitFor } from '@testing-library/react';-import { beforeEach, describe, expect, it, vi } from 'vitest';+/**+ * @vitest-environment happy-dom+ */+import { randomUUID } from 'node:crypto';++import type { RecentItem } from '@lobechat/types';+import { act, renderHook, waitFor } from '@testing-library/react';+import type { PropsWithChildren } from 'react';+import { createElement } from 'react';+import { SWRConfig } from 'swr';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { cacheScope } from '@/libs/replica';+import { recentService } from '@/services/recent';+import { useHomeStore } from '@/store/home';+import { initialRecentState } from '@/store/home/slices/recent/initialState';+import { recentListResource } from '@/store/home/slices/recent/projection';import { useTrayMenuSync } from './useTrayMenuSync';const mocks = vi.hoisted(() => ({agents: [{ id: 'agent-1', title: 'Researcher', updatedAt: '2026-07-11T00:00:00.000Z' }],+ activeTopics: [] as { status: string; topicId: string }[],+ isLogin: true,useFetchAgentList: vi.fn(),- refreshRecents: vi.fn(),- swrKey: vi.fn(),updateNavigationSnapshot: vi.fn(),}));@@ -18,42 +33,15 @@ vi.mock('@/services/electron/tray', () => ({}));vi.mock('@/store/chat', () => ({- useChatStore: vi.fn(() => []),-}));--vi.mock('@/store/home', () => ({- useHomeStore: vi.fn(() => mocks.agents),+ useChatStore: vi.fn(() => mocks.activeTopics),}));vi.mock('@/store/user', () => ({- useUserStore: vi.fn(() => true),-}));--vi.mock('@/libs/swr/useCacheScope', () => ({ useCacheScope: () => 'personal' }));--vi.mock('@/libs/swr', () => ({- useClientDataSWR: vi.fn((key) => {- mocks.swrKey(key);- return {- data: [- {- agentId: 'agent-1',- icon: 'topic',- id: 'topic-1',- routePath: '/agent/agent-1/topic-1',- status: null,- title: 'Research',- type: 'topic',- updatedAt: new Date(0),- },- ],- mutate: mocks.refreshRecents,- };- }),+ useUserStore: vi.fn(() => mocks.isLogin),}));vi.mock('@/store/home/slices/agentList/selectors', () => ({- homeAgentListSelectors: { allAgents: vi.fn() },+ homeAgentListSelectors: { allAgents: () => mocks.agents },}));vi.mock('@/store/electron', () => ({@@ -77,40 +65,126 @@ vi.mock('../RecentlyViewed/hooks/useResolvedPages', () => ({}),}));+const TRAY_PARAMS = { limit: 10, types: 'all', view: 'mine' } as const;++const topic = (id: string, title: string): RecentItem => ({+ agentId: 'agent-1',+ icon: 'topic',+ id,+ routePath: `/agent/agent-1/${id}`,+ status: null,+ title,+ type: 'topic',+ updatedAt: new Date(0),+});++const wrapper = ({ children }: PropsWithChildren) =>+ createElement(SWRConfig, { value: { dedupingInterval: 0, provider: () => new Map() } }, children);++let scope = '';+const lastSnapshot = () => mocks.updateNavigationSnapshot.mock.lastCall?.[0];++beforeEach(() => {+ vi.clearAllMocks();+ mocks.activeTopics = [];+ mocks.isLogin = true;+ mocks.updateNavigationSnapshot.mockResolvedValue({ success: true });+ scope = `tray-user-${randomUUID()}:personal`;+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ act(() => useHomeStore.setState({ ...initialRecentState }));+});++afterEach(() => {+ vi.restoreAllMocks();+ localStorage.clear();+});+describe('useTrayMenuSync', () => {- beforeEach(() => {- vi.clearAllMocks();- mocks.updateNavigationSnapshot.mockResolvedValue({ success: true });+ it('pushes the persisted tray recents before the network answers, then the fresh ones', async () => {+ await recentListResource.storage!.set(+ { queryKey: recentListResource.storageKey(TRAY_PARAMS), scope },+ { data: [topic('topic-1', 'Cached research')], updatedAt: 1 },+ );+ let answer!: (rows: RecentItem[]) => void;+ const getAll = vi+ .spyOn(recentService, 'getAll')+ .mockReturnValue(new Promise((resolve) => (answer = resolve)));++ renderHook(() => useTrayMenuSync(), { wrapper });++ await waitFor(() =>+ expect(lastSnapshot()?.recent).toEqual([+ { subtitle: 'Researcher', title: 'Cached research', url: '/agent/agent-1/topic-1' },+ ]),+ );+ expect(getAll).toHaveBeenCalledWith(10, undefined, false, true, false);++ await act(async () => answer([topic('topic-1', 'Fresh research')]));++ await waitFor(() =>+ expect(lastSnapshot()?.recent).toEqual([+ { subtitle: 'Researcher', title: 'Fresh research', url: '/agent/agent-1/topic-1' },+ ]),+ );});it('pushes resolved navigation data and does not resend an identical render', async () => {- const { rerender } = renderHook(() => useTrayMenuSync());+ vi.spyOn(recentService, 'getAll').mockResolvedValue([topic('topic-1', 'Research')]);+ const { rerender } = renderHook(() => useTrayMenuSync(), { wrapper });- await waitFor(() => expect(mocks.updateNavigationSnapshot).toHaveBeenCalledTimes(1));+ await waitFor(() =>+ expect(mocks.updateNavigationSnapshot).toHaveBeenLastCalledWith({+ activeTopics: [],+ agents: [{ id: 'agent-1', title: 'Researcher', url: '/agent/agent-1/topic-1' }],+ pinned: [],+ recent: [{ subtitle: 'Researcher', title: 'Research', url: '/agent/agent-1/topic-1' }],+ }),+ );expect(mocks.useFetchAgentList).toHaveBeenCalled();- expect(mocks.swrKey).toHaveBeenCalledWith(['recent:trayList', 10, 'personal']);- expect(mocks.refreshRecents).not.toHaveBeenCalled();- expect(mocks.updateNavigationSnapshot).toHaveBeenCalledWith({- activeTopics: [],- agents: [{ id: 'agent-1', title: 'Researcher', url: '/agent/agent-1/topic-1' }],- pinned: [],- recent: [{ subtitle: 'Researcher', title: 'Research', url: '/agent/agent-1/topic-1' }],- });+ const calls = mocks.updateNavigationSnapshot.mock.calls.length;rerender();- expect(mocks.updateNavigationSnapshot).toHaveBeenCalledTimes(1);+ expect(mocks.updateNavigationSnapshot).toHaveBeenCalledTimes(calls);+ });++ it('refetches the recents when the active topics change', async () => {+ const getAll = vi.spyOn(recentService, 'getAll').mockResolvedValue([]);+ const { rerender } = renderHook(() => useTrayMenuSync(), { wrapper });+ await waitFor(() => expect(getAll).toHaveBeenCalledTimes(1));++ mocks.activeTopics = [{ status: 'running', topicId: 'topic-2' }];+ getAll.mockResolvedValueOnce([topic('topic-1', 'Running now')]);+ rerender();++ await waitFor(() => expect(getAll).toHaveBeenCalledTimes(2));+ await waitFor(() =>+ expect(lastSnapshot()?.recent?.map((row: { title: string }) => row.title)).toContain(+ 'Running now',+ ),+ );+ });++ it('does not fetch while logged out', async () => {+ mocks.isLogin = false;+ const getAll = vi.spyOn(recentService, 'getAll');++ renderHook(() => useTrayMenuSync(), { wrapper });++ await waitFor(() => expect(mocks.updateNavigationSnapshot).toHaveBeenCalled());+ expect(getAll).not.toHaveBeenCalled();});it('logs synchronization failures without throwing into the titlebar', async () => {+ vi.spyOn(recentService, 'getAll').mockResolvedValue([]);const error = new Error('IPC unavailable');const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});mocks.updateNavigationSnapshot.mockRejectedValue(error);- expect(() => renderHook(() => useTrayMenuSync())).not.toThrow();+ expect(() => renderHook(() => useTrayMenuSync(), { wrapper })).not.toThrow();await waitFor(() =>expect(consoleError).toHaveBeenCalledWith('Failed to synchronize tray menu:', error),);-- consoleError.mockRestore();});});diff --git a/src/features/Electron/titlebar/TrayMenu/useTrayMenuSync.ts b/src/features/Electron/titlebar/TrayMenu/useTrayMenuSync.tsindex b382a6a1757..2b0cc578e23 100644--- a/src/features/Electron/titlebar/TrayMenu/useTrayMenuSync.ts+++ b/src/features/Electron/titlebar/TrayMenu/useTrayMenuSync.ts@@ -4,15 +4,14 @@ import isEqual from 'fast-deep-equal';import { useEffect, useMemo, useRef } from 'react';import { useFetchAgentList } from '@/hooks/useFetchAgentList';-import { useClientDataSWR } from '@/libs/swr';-import { recentKeys } from '@/libs/swr/keys';-import { useCacheScope } from '@/libs/swr/useCacheScope';import { desktopTrayService } from '@/services/electron/tray';-import { recentService } from '@/services/recent';import { useChatStore } from '@/store/chat';import { useElectronStore } from '@/store/electron';import { useHomeStore } from '@/store/home';import { homeAgentListSelectors } from '@/store/home/slices/agentList/selectors';+import { TRAY_RECENTS_PARAMS } from '@/store/home/slices/recent/action';+import { createRecentQueryKey } from '@/store/home/slices/recent/initialState';+import { homeRecentSelectors } from '@/store/home/slices/recent/selectors';import { useUserStore } from '@/store/user';import { authSelectors } from '@/store/user/slices/auth/selectors';@@ -20,7 +19,10 @@ import { useResolvedPages } from '../RecentlyViewed/hooks/useResolvedPages';import { resolveTrayNavigationSnapshot } from './resolveSnapshot';import { selectActiveTopics } from './selectActiveTopics';-const TRAY_RECENT_FETCH_LIMIT = 10;+const TRAY_RECENTS_KEY = createRecentQueryKey(TRAY_RECENTS_PARAMS.limit, {+ types: TRAY_RECENTS_PARAMS.types,+ view: TRAY_RECENTS_PARAMS.view,+});export const useTrayMenuSync = () => {useFetchAgentList();@@ -29,11 +31,11 @@ export const useTrayMenuSync = () => {const { pinnedPages, recentPages } = useResolvedPages();const activeTopics = useChatStore(selectActiveTopics, isEqual);const isLogin = useUserStore(authSelectors.isLogin);- const cacheScope = useCacheScope();- const { data: recents, mutate: refreshRecents } = useClientDataSWR(- isLogin ? recentKeys.trayList(TRAY_RECENT_FETCH_LIMIT, cacheScope) : null,- () => recentService.getAll(TRAY_RECENT_FETCH_LIMIT, undefined, false, true),- );+ // The `recentList` replica: a restart paints the last tray rows before the+ // network answers.+ const useFetchTrayRecents = useHomeStore((s) => s.useFetchTrayRecents);+ const { revalidate: refreshRecents } = useFetchTrayRecents(!!isLogin);+ const recents = useHomeStore(homeRecentSelectors.query(TRAY_RECENTS_KEY));const activeSignature = activeTopics.map(({ status, topicId }) => topicId + status).join();const lastSnapshotRef = useRef<string | undefined>(undefined);diff --git a/src/features/Home/HomeModeContent.tsx b/src/features/Home/HomeModeContent.tsxindex 8fa936d5190..51efe2a6c00 100644--- a/src/features/Home/HomeModeContent.tsx+++ b/src/features/Home/HomeModeContent.tsx@@ -23,14 +23,14 @@ import { splitBriefs } from '@/features/HomeInbox/splitBriefs';import { useHomeInboxTopics } from '@/features/HomeInbox/useHomeInboxTopics';import Recommendations from '@/features/Recommendations';import WorkspaceLink from '@/features/Workspace/WorkspaceLink';-import { useClientDataSWR } from '@/libs/swr';-import { recentKeys } from '@/libs/swr/keys';-import { useCacheScope } from '@/libs/swr/useCacheScope';-import { recentService } from '@/services/recent';import { useBriefStore } from '@/store/brief';import { briefListSelectors } from '@/store/brief/selectors';import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';+import { useHomeStore } from '@/store/home';+import { HOME_TOPIC_RECENTS_PARAMS } from '@/store/home/slices/recent/action';+import { createRecentQueryKey } from '@/store/home/slices/recent/initialState';+import { homeRecentSelectors } from '@/store/home/slices/recent/selectors';import { useTaskStore } from '@/store/task';import { taskListSelectors } from '@/store/task/selectors';import type { TaskListItem } from '@/store/task/slices/list/initialState';@@ -45,7 +45,7 @@ import RunningGlyph from './components/RunningGlyph';import Time from './components/Time';import { isHomeWidgetHidden } from './CustomizeModal/config';import EmptySuggestions from './EmptySuggestions';-import { resolveHomeChatContentState } from './homeChatContentState';+import { isRecentsSnapshotSettled, resolveHomeChatContentState } from './homeChatContentState';import type { HomeMode } from './types';const styles = createStaticStyles(({ css, cssVar }) => ({@@ -133,7 +133,13 @@ export const RECENT_TASK_STATUSES: TaskStatus[] = TASK_STATUSES.filter((status) => status !== 'completed',);-export const HOME_TOPIC_RECENT_LIMIT = 15;+export { HOME_TOPIC_RECENT_LIMIT } from '@/store/home/slices/recent/action';++const HOME_TOPIC_RECENTS_KEY = createRecentQueryKey(HOME_TOPIC_RECENTS_PARAMS.limit, {+ types: HOME_TOPIC_RECENTS_PARAMS.types,+ view: HOME_TOPIC_RECENTS_PARAMS.view,+});+const EMPTY_RECENTS: RecentItem[] = [];const FLEX_MIN_WIDTH_0 = { minWidth: 0 };@@ -468,17 +474,14 @@ const HomeModeContent = memo<HomeModeContentProps>(({ inlineRail, mode, onSuggesconst recentsHidden = hiddenWidgets.includes('recents');const tasksHidden = hiddenWidgets.includes('tasks');const scheduledTasksHidden = isHomeWidgetHidden('scheduledTasks', hiddenWidgets);- const cacheScope = useCacheScope();-- // Workspace topics are shared, so "mine" must be narrowed server-side —- // client-filtering the top N of a team-wide feed could starve out the- // viewer's own topics entirely.- const recentsSWR = useClientDataSWR(- isLogin && !recentsHidden- ? recentKeys.topicList(HOME_TOPIC_RECENT_LIMIT, cacheScope, 'mine')- : null,- () => recentService.getAll(HOME_TOPIC_RECENT_LIMIT, ['topic'], true, true, false),- { revalidateOnFocus: false },+ // The `recentList` replica paints the last rows on a cold start and+ // revalidates in the background. Workspace topics are shared, so "mine" is+ // narrowed server-side (see `HOME_TOPIC_RECENTS_PARAMS`).+ const useFetchHomeTopicRecents = useHomeStore((s) => s.useFetchHomeTopicRecents);+ const recentsSync = useFetchHomeTopicRecents(!!isLogin && !recentsHidden);+ const storedTopicRecents = useHomeStore(homeRecentSelectors.query(HOME_TOPIC_RECENTS_KEY));+ const topicRecentsConfirmed = useHomeStore(+ homeRecentSelectors.isQueryConfirmed(HOME_TOPIC_RECENTS_KEY),);const inboxTopics = useHomeInboxTopics(isLogin);@@ -495,7 +498,8 @@ const HomeModeContent = memo<HomeModeContentProps>(({ inlineRail, mode, onSuggesconst briefs = useBriefStore(briefListSelectors.briefs);const briefsInit = useBriefStore(briefListSelectors.isBriefsInit);const needsYouCount = useMemo(() => splitBriefs(briefs).needsYou.length, [briefs]);- const topicRecents = recentsSWR.data ?? [];+ const topicRecents = storedTopicRecents ?? EMPTY_RECENTS;+ const recentsInit = isRecentsSnapshotSettled(storedTopicRecents, topicRecentsConfirmed);if (mode === 'chat') {// With the recents section switched off nothing is fetched, so it reports as@@ -503,10 +507,10 @@ const HomeModeContent = memo<HomeModeContentProps>(({ inlineRail, mode, onSugges// activity alone decides what this column is.const state = resolveHomeChatContentState({authLoaded: !!authLoaded,- hasError: !recentsHidden && !!recentsSWR.error,+ hasError: !recentsHidden && !!recentsSync.error,isLogin: !!isLogin,recentsCount: topicRecents.length,- recentsInit: recentsHidden || recentsSWR.data !== undefined,+ recentsInit: recentsHidden || recentsInit,activityCount: mineRunningCount + mineUnreadCount + needsYouCount,activityError: Boolean(inboxTopics.error || briefsSWR.error),activityResolved:@@ -548,7 +552,11 @@ const HomeModeContent = memo<HomeModeContentProps>(({ inlineRail, mode, onSuggestitle={t('dashboard.chat.recents')}>{state === 'error' ? (- <AsyncError error={recentsSWR.error} variant={'inline'} onRetry={recentsSWR.mutate} />+ <AsyncError+ error={recentsSync.error}+ variant={'inline'}+ onRetry={() => void recentsSync.revalidate()}+ />) : state === 'loading' ? (<LoadingRows withTime />) : (diff --git a/src/features/Home/homeChatContentState.test.ts b/src/features/Home/homeChatContentState.test.tsindex 9d6488b54e4..d98c10ddd8b 100644--- a/src/features/Home/homeChatContentState.test.ts+++ b/src/features/Home/homeChatContentState.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { resolveHomeChatContentState } from './homeChatContentState';+import { isRecentsSnapshotSettled, resolveHomeChatContentState } from './homeChatContentState';const baseState = {activityCount: 0,@@ -72,3 +72,18 @@ describe('resolveHomeChatContentState', () => {).toBe('ready');});});++describe('isRecentsSnapshotSettled', () => {+ it('waits while nothing is hydrated or fetched', () => {+ expect(isRecentsSnapshotSettled(undefined, false)).toBe(false);+ });++ it('paints hydrated rows before the server answers', () => {+ expect(isRecentsSnapshotSettled([{}], false)).toBe(true);+ });++ it('keeps a hydrated empty snapshot loading until the server confirms it', () => {+ expect(isRecentsSnapshotSettled([], false)).toBe(false);+ expect(isRecentsSnapshotSettled([], true)).toBe(true);+ });+});diff --git a/src/features/Home/homeChatContentState.ts b/src/features/Home/homeChatContentState.tsindex 5131f091f70..2187c228ae1 100644--- a/src/features/Home/homeChatContentState.ts+++ b/src/features/Home/homeChatContentState.ts@@ -30,3 +30,14 @@ export const resolveHomeChatContentState = ({if (recentsCount === 0 && activityCount === 0) return 'empty';return 'ready';};++/**+ * Whether the recents block may trust its rows. A snapshot hydrated from local+ * storage is not the server's answer: rows paint at once, but an empty one only+ * counts as empty after the server confirmed it — otherwise the starters would+ * flash in front of an account that has topics.+ */+export const isRecentsSnapshotSettled = (+ rows: readonly unknown[] | undefined,+ confirmed: boolean,+): boolean => rows !== undefined && (rows.length > 0 || confirmed);diff --git a/src/libs/swr/keys.frozen.test.ts b/src/libs/swr/keys.frozen.test.tsindex e82dee525d1..0e82dcbbbe8 100644--- a/src/libs/swr/keys.frozen.test.ts+++ b/src/libs/swr/keys.frozen.test.ts@@ -115,8 +115,6 @@ const LEGACY_SWR_KEYS = ['ragEvalKeys.datasetList','ragEvalKeys.datasetRecords','ragEvalKeys.evaluationList',- 'recentKeys.topicList',- 'recentKeys.trayList','recommendationsKeys.heteroDetections','resourceKeys.list','scmKeys.changeRequests',diff --git a/src/libs/swr/keys.test.ts b/src/libs/swr/keys.test.tsindex 80b34ff75c8..1dec1abefbc 100644--- a/src/libs/swr/keys.test.ts+++ b/src/libs/swr/keys.test.ts@@ -2,38 +2,9 @@ import { replicaKeys } from 'local-replica';import { unstable_serialize } from 'swr';import { describe, expect, it } from 'vitest';-import { documentCommentKeys, isDocumentCommentKeyForEvent, recentKeys, workKeys } from './keys';+import { documentCommentKeys, isDocumentCommentKeyForEvent, workKeys } from './keys';import { CACHE_TIERS } from './localStorageProvider';-describe('recentKeys', () => {- it('keys the Home topic-only list independently from mixed recents', () => {- expect(recentKeys.topicList(9, 'user-1:workspace-1', 'mine')).toEqual([- 'recent:topicList',- 9,- 'user-1:workspace-1',- 'mine',- ]);- });-- it('keeps the mine and team views of the Home topic list isolated', () => {- expect(recentKeys.topicList(9, 'user-1:workspace-1', 'mine')).not.toEqual(- recentKeys.topicList(9, 'user-1:workspace-1', 'team'),- );- });-- // Regression: `recent:topicList` had no CACHE_TIERS entry of its own, and the- // provider matches patterns as substrings — so `recent:list` never covered it.- // The Home recents list was memory-only and flashed a skeleton on every boot.- it('routes the Home topic-only recents key to a persisted cache tier', () => {- const serialized = unstable_serialize(recentKeys.topicList(9, 'user-1:workspace-1', 'mine'));- const persisted = [...CACHE_TIERS.idb, ...CACHE_TIERS.local].some((pattern) =>- serialized.includes(pattern),- );-- expect(persisted).toBe(true);- });-});-describe('replica sync keys', () => {it('keeps SWR orchestration entries out of the persistence tiers', () => {for (const key of [diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex d3916d6e791..a8369eda4af 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -245,22 +245,6 @@ export const threadKeys = {list: def('thread:list', (topicId: string) => ['thread:list', topicId]),};-// ---- recent --------------------------------------------------------------export const recentKeys = {- /** Home chat-only list; filtering happens before the server-side limit. */- topicList: def('recent:topicList', (limit: number, scope: string, view: 'mine' | 'team') => [- 'recent:topicList',- limit,- scope,- view,- ]),- trayList: def('recent:trayList', (limit: number, scope: string) => [- 'recent:trayList',- limit,- scope,- ]),-};-/*** Goal reads that have no local-first projection: the pending queues are live* "what needs you" feeds, and the topic link is a discovery poll.@@ -993,7 +977,6 @@ export const swrKeys = {onboarding: onboardingKeys,openInApp: openInAppKeys,ragEval: ragEvalKeys,- recent: recentKeys,recommendations: recommendationsKeys,resource: resourceKeys,serverConfig: serverConfigKeys,diff --git a/src/store/home/slices/recent/action.test.ts b/src/store/home/slices/recent/action.test.tsindex d80ab4f7179..b0a4c7c8139 100644--- a/src/store/home/slices/recent/action.test.ts+++ b/src/store/home/slices/recent/action.test.ts@@ -8,17 +8,21 @@ import { randomUUID } from 'node:crypto';import type { RecentItem } from '@lobechat/types';import { act, renderHook, waitFor } from '@testing-library/react';+import { replicaKeys } from 'local-replica';import type { PropsWithChildren } from 'react';import { createElement, useEffect } from 'react';-import { SWRConfig, useSWRConfig } from 'swr';+import { SWRConfig, unstable_serialize, useSWRConfig } from 'swr';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { cacheScope } from '@/libs/replica';+import { CACHE_TIERS } from '@/libs/swr/localStorageProvider';import { setScopedMutate } from '@/libs/swr/mutate';import { fileService } from '@/services/file';import { recentService } from '@/services/recent';import { taskService } from '@/services/task';+import { topicService } from '@/services/topic';import { useHomeStore } from '@/store/home';+import { HOME_TOPIC_RECENTS_PARAMS, TRAY_RECENTS_PARAMS } from '@/store/home/slices/recent/action';import {createConversationRecentQueryKey,createRecentQueryKey,@@ -240,6 +244,226 @@ describe('recents replica', () => {});});+const HOME_TOPICS = createRecentQueryKey(HOME_TOPIC_RECENTS_PARAMS.limit, {+ types: HOME_TOPIC_RECENTS_PARAMS.types,+ view: HOME_TOPIC_RECENTS_PARAMS.view,+});+const TRAY = createRecentQueryKey(TRAY_RECENTS_PARAMS.limit, {+ types: TRAY_RECENTS_PARAMS.types,+ view: TRAY_RECENTS_PARAMS.view,+});+const rowsOf = (queryKey: string) => homeRecentSelectors.query(queryKey)(useHomeStore.getState());+const seed = (+ params: typeof HOME_TOPIC_RECENTS_PARAMS | typeof TRAY_RECENTS_PARAMS,+ rows: RecentItem[],+ at = scope,+) =>+ recentListResource.storage!.set(+ { queryKey: recentListResource.storageKey(params), scope: at },+ { data: rows, updatedAt: 1 },+ );++describe('Home topic and tray recents on the recentList replica', () => {+ it('keeps each query in its own entry, apart from the sidebar', () => {+ expect(new Set([SIDEBAR, DRAWER, HOME_TOPICS, TRAY]).size).toBe(4);+ // Sidebar entries keep their original key, so persisted rows still hydrate.+ expect(SIDEBAR).toBe('limit:11');+ });++ it('keeps the new sync keys out of the legacy SWR persistence tiers', () => {+ for (const params of [HOME_TOPIC_RECENTS_PARAMS, TRAY_RECENTS_PARAMS]) {+ const serialized = unstable_serialize(+ replicaKeys.sync(+ recentListResource.name,+ recentListResource.version,+ scope,+ recentListResource.key(params),+ params,+ ),+ );+ expect(+ [...CACHE_TIERS.idb, ...CACHE_TIERS.local].filter((pattern) =>+ serialized.includes(pattern),+ ),+ ).toEqual([]);+ }+ });++ it('asks the server for the same rows as before', async () => {+ const getAll = vi.spyOn(recentService, 'getAll').mockResolvedValue([]);++ renderHook(+ () => {+ useHomeStore((s) => s.useFetchHomeTopicRecents)(true);+ useHomeStore((s) => s.useFetchTrayRecents)(true);+ },+ { wrapper },+ );++ await waitFor(() => expect(getAll).toHaveBeenCalledTimes(2));+ // Home: own topics with previews; tray: own recents of every type.+ expect(getAll).toHaveBeenCalledWith(15, ['topic'], true, true, false);+ expect(getAll).toHaveBeenCalledWith(10, undefined, false, true, false);+ });++ it('paints persisted Home topics and tray rows before the network, then replaces them', async () => {+ await seed(HOME_TOPIC_RECENTS_PARAMS, [item('t1', 'Cached topic', 'topic')]);+ await seed(TRAY_RECENTS_PARAMS, [item('d1', 'Cached doc', 'document')]);+ const response = deferred<RecentItem[]>();+ vi.spyOn(recentService, 'getAll').mockReturnValue(response.promise);++ renderHook(+ () => {+ useHomeStore((s) => s.useFetchHomeTopicRecents)(true);+ useHomeStore((s) => s.useFetchTrayRecents)(true);+ },+ { wrapper },+ );++ await waitFor(() => {+ expect(rowsOf(HOME_TOPICS)?.[0].title).toBe('Cached topic');+ expect(rowsOf(TRAY)?.[0].title).toBe('Cached doc');+ });+ expect(homeRecentSelectors.isQueryConfirmed(HOME_TOPICS)(useHomeStore.getState())).toBe(false);++ await act(async () => response.resolve([item('t2', 'Fresh', 'topic')]));++ await waitFor(() => {+ expect(rowsOf(HOME_TOPICS)?.map((row) => row.title)).toEqual(['Fresh']);+ expect(rowsOf(TRAY)?.map((row) => row.title)).toEqual(['Fresh']);+ });+ expect(homeRecentSelectors.isQueryConfirmed(HOME_TOPICS)(useHomeStore.getState())).toBe(true);+ });++ it('treats a hydrated empty snapshot as unconfirmed until the server answers', async () => {+ await seed(HOME_TOPIC_RECENTS_PARAMS, []);+ const response = deferred<RecentItem[]>();+ vi.spyOn(recentService, 'getAll').mockReturnValue(response.promise);++ const { result } = renderHook(() => useHomeStore((s) => s.useFetchHomeTopicRecents)(true), {+ wrapper,+ });++ await waitFor(() => expect(result.current.isHydrated).toBe(true));+ expect(rowsOf(HOME_TOPICS)).toEqual([]);+ expect(homeRecentSelectors.isQueryConfirmed(HOME_TOPICS)(useHomeStore.getState())).toBe(false);++ await act(async () => response.resolve([]));+ await waitFor(() =>+ expect(homeRecentSelectors.isQueryConfirmed(HOME_TOPICS)(useHomeStore.getState())).toBe(true),+ );+ });++ it("never paints another identity's rows", async () => {+ await seed(HOME_TOPIC_RECENTS_PARAMS, [item('t1', 'Theirs', 'topic')], `${scope}-other`);+ vi.spyOn(recentService, 'getAll').mockImplementation(() => new Promise(() => {}));++ const { result } = renderHook(() => useHomeStore((s) => s.useFetchHomeTopicRecents)(true), {+ wrapper,+ });++ await waitFor(() => expect(result.current.isHydrated).toBe(true));+ expect(rowsOf(HOME_TOPICS)).toBeUndefined();+ });++ it('keeps the last rows when a background refresh fails', async () => {+ const getAll = vi+ .spyOn(recentService, 'getAll')+ .mockResolvedValueOnce([item('t1', 'Kept', 'topic')]);+ const { result } = renderHook(() => useHomeStore((s) => s.useFetchTrayRecents)(true), {+ wrapper,+ });+ await waitFor(() => expect(rowsOf(TRAY)?.[0].title).toBe('Kept'));++ getAll.mockRejectedValueOnce(new Error('offline'));+ await act(async () => {+ await result.current.revalidate().catch(() => undefined);+ });++ expect(rowsOf(TRAY)?.map((row) => row.title)).toEqual(['Kept']);+ });++ it('sends one request when several surfaces mount the same query', async () => {+ const getAll = vi.spyOn(recentService, 'getAll').mockResolvedValue([]);++ const { rerender } = renderHook(+ ({ late }: { late: boolean }) => {+ useHomeStore((s) => s.useFetchTrayRecents)(true);+ useHomeStore((s) => s.useFetchTrayRecents)(true);+ // A surface that mounts after the first answer (e.g. the titlebar remounting).+ useHomeStore((s) => s.useFetchTrayRecents)(late);+ },+ { initialProps: { late: false }, wrapper },+ );+ await waitFor(() => expect(rowsOf(TRAY)).toEqual([]));+ rerender({ late: true });+ await act(async () => {});++ expect(getAll).toHaveBeenCalledTimes(1);+ });++ it('refreshes the tray on demand even inside the dedupe window', async () => {+ const getAll = vi.spyOn(recentService, 'getAll').mockResolvedValue([]);+ const { result } = renderHook(() => useHomeStore((s) => s.useFetchTrayRecents)(true), {+ wrapper,+ });+ await waitFor(() => expect(getAll).toHaveBeenCalledTimes(1));++ getAll.mockResolvedValueOnce([item('t1', 'Now running', 'topic')]);+ await act(() => result.current.revalidate());++ expect(getAll).toHaveBeenCalledTimes(2);+ expect(rowsOf(TRAY)?.[0].title).toBe('Now running');+ });++ it('carries a rename into the Home topics and the tray, and persists it', async () => {+ vi.spyOn(recentService, 'getAll').mockResolvedValue([item('t1', 'Old', 'topic')]);+ vi.spyOn(topicService, 'updateTopic').mockResolvedValue(undefined as never);+ renderHook(+ () => {+ useHomeStore((s) => s.useFetchHomeTopicRecents)(true);+ useHomeStore((s) => s.useFetchTrayRecents)(true);+ },+ { wrapper },+ );+ await waitFor(() => expect(rowsOf(TRAY)).toHaveLength(1));+ await waitFor(() => expect(rowsOf(HOME_TOPICS)).toHaveLength(1));++ await act(() =>+ useHomeStore.getState().renameRecent({ id: 't1', title: 'New', type: 'topic' }),+ );++ expect(rowsOf(HOME_TOPICS)?.[0].title).toBe('New');+ expect(rowsOf(TRAY)?.[0].title).toBe('New');+ await waitFor(async () =>+ expect(+ (+ await recentListResource.storage!.get({+ queryKey: recentListResource.storageKey(TRAY_RECENTS_PARAMS),+ scope,+ })+ )?.data[0].title,+ ).toBe('New'),+ );+ });++ it('refetches the Home topics and the tray with the other recents', async () => {+ const getAll = vi.spyOn(recentService, 'getAll').mockResolvedValue([]);+ renderHook(+ () => {+ useHomeStore((s) => s.useFetchHomeTopicRecents)(true);+ useHomeStore((s) => s.useFetchTrayRecents)(true);+ },+ { wrapper },+ );+ await waitFor(() => expect(getAll).toHaveBeenCalledTimes(2));++ await act(() => useHomeStore.getState().refreshRecents());++ expect(getAll).toHaveBeenCalledTimes(4);+ });+});+type DocsHomeItem = Awaited<ReturnType<typeof fileService.getDocsHomeItems>>[number];const homeItem = (id: string, sourceType: 'document' | 'file' = 'document'): DocsHomeItem =>diff --git a/src/store/home/slices/recent/action.ts b/src/store/home/slices/recent/action.tsindex e2d7fa6be96..1fac311ac3d 100644--- a/src/store/home/slices/recent/action.ts+++ b/src/store/home/slices/recent/action.ts@@ -23,6 +23,7 @@ import {docsHomeListResource,type DocsHomeRow,type DocsHomeTab,+ type RecentListParams,recentListResource,toDocsHomeRow,} from './projection';@@ -32,6 +33,51 @@ const n = setNamespace('recent');/** Rows in the "all recents" drawer. */export const ALL_RECENTS_LIMIT = 50;+/** Topics the Home chat-mode recents block fetches (the customize slider's max). */+export const HOME_TOPIC_RECENT_LIMIT = 15;++/** Rows the desktop tray menu fetches. */+export const TRAY_RECENT_LIMIT = 10;++/** The Home chat-mode recents block: the viewer's own topics, with previews. */+export const HOME_TOPIC_RECENTS_PARAMS = {+ limit: HOME_TOPIC_RECENT_LIMIT,+ types: 'topic',+ view: 'mine',+} as const satisfies RecentListParams;++/** The tray menu: the viewer's own recents of every type. */+export const TRAY_RECENTS_PARAMS = {+ limit: TRAY_RECENT_LIMIT,+ types: 'all',+ view: 'mine',+} as const satisfies RecentListParams;++/**+ * Several surfaces mount the same query (Home, the tray hook, the sidebar), so+ * identical mount requests within this window collapse into one. Manual,+ * post-write and active-topic refreshes still go through `revalidate`.+ */+const RECENT_SYNC_DEDUPE_MS = 10_000;++const fetchRecentList = ({ limit, types = 'sidebar', view }: RecentListParams) => {+ const mineOnly = view === undefined ? undefined : view === 'mine';+ const sharedOnly = view === undefined ? undefined : view === 'team';+ switch (types) {+ case 'all': {+ return recentService.getAll(limit, undefined, false, mineOnly, sharedOnly);+ }+ case 'topic': {+ return recentService.getAll(limit, ['topic'], true, mineOnly, sharedOnly);+ }+ default: {+ return view+ ? recentService.getAll(limit, RECENT_SIDEBAR_TYPES, undefined, mineOnly, sharedOnly)+ : recentService.getAll(limit, RECENT_SIDEBAR_TYPES);+ }+ }+};+interface RenameRecentParams {id: string;title: string;@@ -81,7 +127,7 @@ export class RecentActionImpl {this.#recentList = createReplicaSlice(recentListResource, {actionPrefix: n('recentList'),entity: recentEntity,- fetcher: ({ limit }) => recentService.getAll(limit, RECENT_SIDEBAR_TYPES),+ fetcher: fetchRecentList,get,set,stateKey: 'recentListReplica',@@ -171,6 +217,24 @@ export class RecentActionImpl {useFetchConversationRecents = (limit: number = ALL_RECENTS_LIMIT): ReplicaSyncResult =>this.#conversationRecents.useSync({ limit }, { enabled: true });+ /**+ * Home chat-mode recent topics (the viewer's own, server-narrowed). Read them+ * with `homeRecentSelectors.query(createRecentQueryKey(...HOME_TOPIC_RECENTS_PARAMS))`.+ */+ useFetchHomeTopicRecents = (enabled: boolean): ReplicaSyncResult =>+ this.#recentList.useSync(HOME_TOPIC_RECENTS_PARAMS, {+ dedupingInterval: RECENT_SYNC_DEDUPE_MS,+ enabled,+ revalidateOnFocus: false,+ });++ /** Desktop tray recents; `revalidate` refetches them when active topics change. */+ useFetchTrayRecents = (enabled: boolean): ReplicaSyncResult =>+ this.#recentList.useSync(TRAY_RECENTS_PARAMS, {+ dedupingInterval: RECENT_SYNC_DEDUPE_MS,+ enabled,+ });+/** Refetch every loaded Docs home tab, e.g. after a page or file was added. */refreshDocsHome = async (): Promise<void> => {await this.#docsHome.revalidate();diff --git a/src/store/home/slices/recent/projection.ts b/src/store/home/slices/recent/projection.tsindex 420043d414e..593189ef525 100644--- a/src/store/home/slices/recent/projection.ts+++ b/src/store/home/slices/recent/projection.ts@@ -3,20 +3,49 @@ import type { RecentItem } from '@lobechat/types';import { defineReplica } from '@/libs/replica';import type { fileService } from '@/services/file';+/**+ * Which entity types a recents query asks for:+ * - `sidebar`: documents and tasks (the home sidebar and the "all recents" drawer)+ * - `topic`: topics with their reply previews (the Home chat-mode recents block)+ * - `all`: every type, no previews (the desktop tray menu)+ */+export type RecentListTypes = 'all' | 'sidebar' | 'topic';++/**+ * Whose rows a recents query keeps. Workspace topics are shared, so `mine` is+ * narrowed on the server: client-filtering the top N of a team-wide feed could+ * starve out the viewer's own topics. `team` drops private agents / groups.+ */+export type RecentListView = 'mine' | 'team';+export interface RecentListParams {limit: number;+ /** Defaults to `sidebar`. */+ types?: RecentListTypes;+ /** Unset: no ownership filter. */+ view?: RecentListView;}-/** Entry key of one recents query (`recentListMap[limit:N]`). */-export const createRecentQueryKey = (limit: number): string => `limit:${limit}`;+/**+ * Entry key of one recents query (`recentListMap[...]`). Sidebar queries keep+ * the original `limit:N` key so their persisted rows still hydrate. The others+ * use `/` separators: the key ends up in the SWR sync key, and a `topic:`+ * substring would match a legacy CACHE_TIERS pattern and be persisted twice.+ */+export const createRecentQueryKey = (+ limit: number,+ { types = 'sidebar', view }: Omit<RecentListParams, 'limit'> = {},+): string =>+ types === 'sidebar' && !view ? `limit:${limit}` : `${types}/${view ?? 'any'}/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.+ * Recent documents / tasks / topics, one entry per query: the sidebar asks for+ * `pageSize + 1` documents and tasks, the drawer for 50, Home chat mode for its+ * own topics and the tray for every type. localStorage keeps their first frame+ * instant.*/export const recentListResource = defineReplica<RecentListParams, RecentItem[]>({- key: ({ limit }) => createRecentQueryKey(limit),+ key: ({ limit, types, view }) => createRecentQueryKey(limit, { types, view }),name: 'recentList',storage: 'localStorage',version: 1,diff --git a/src/store/home/slices/recent/selectors.ts b/src/store/home/slices/recent/selectors.tsindex f118d41dba9..88f197a764d 100644--- a/src/store/home/slices/recent/selectors.ts+++ b/src/store/home/slices/recent/selectors.ts@@ -10,6 +10,14 @@ const query = (queryKey: string) => (s: HomeStore) => s.recentListMap[queryKey];const conversationRecents = (queryKey: string) => (s: HomeStore) =>s.conversationRecentMap[queryKey];+/**+ * Whether a recents query has been answered by the server in this session. A+ * hydrated snapshot may be stale or empty, so "no rows" only means empty once+ * this is true.+ */+const isQueryConfirmed = (queryKey: string) => (s: HomeStore) =>+ s.recentListReplica.entries[queryKey]?.source === 'server';+const item = (queryKey: string, ref: RecentEntityRef) => (s: HomeStore) =>s.recentListMap[queryKey]?.find((recent) => toRecentEntityRef(recent) === ref);@@ -19,6 +27,7 @@ const docsHome = (tab: DocsHomeTab) => (s: HomeStore) => s.docsHomeMap[tab];export const homeRecentSelectors = {conversationRecents,docsHome,+ isQueryConfirmed,item,query,};