π€― 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(mcpStore): move the MCP marketplace list onto @lobechat/replica (#20574)
Arvin Xu35d442ec6a76
diff --git a/packages/replica/src/zustand/createReplicaSlice.test.ts b/packages/replica/src/zustand/createReplicaSlice.test.tsindex 88fc9e7bf74..5284701ee40 100644--- a/packages/replica/src/zustand/createReplicaSlice.test.ts+++ b/packages/replica/src/zustand/createReplicaSlice.test.ts@@ -173,6 +173,54 @@ describe('createReplicaSlice', () => {);});+ it('discards a head response from a query the entry has moved past', () => {+ // A driver that settles every request through its own callback lets two+ // queries of the same key resolve out of order. One entry backs one view,+ // so the query the entry no longer asks for must not repaint it.+ const requests: {+ onSuccess: (data: string[]) => void;+ params: { q?: string };+ }[] = [];+ const useQuery = vi.fn((key: any, _fetcher: unknown, options: any) => {+ if (key !== null) requests.push({ onSuccess: options.onSuccess, params: key.at(-1) });+ return { isValidating: false, mutate: vi.fn() };+ });+ const resource = defineReplica<{ q?: string }, string[]>({+ fetcher: async () => ['server'],+ key: () => 'all',+ name: 'orderedHead',+ query: ({ q }) => ({ q }),+ scope,+ version: 1,+ });+ const store = createStore<TestState>()(() => ({+ lists: {},+ listsReplica: createReplicaState(),+ }));+ const slice = createReplicaSlice<TestState, { q?: string }, string[]>(resource, {+ driver: { revalidate: vi.fn(), useQuery },+ get: store.getState,+ set: (partial) => store.setState(partial),+ stateKey: 'listsReplica',+ view: recordLens('lists'),+ });++ const { rerender } = renderHook((props: { q?: string }) => slice.useSync(props), {+ initialProps: {} as { q?: string },+ });+ rerender({ q: 'b' });++ const base = requests.find((request) => request.params.q === undefined)!;+ const search = requests.find((request) => request.params.q === 'b')!;++ act(() => search.onSuccess(['b-1']));+ expect(store.getState().lists.all).toEqual(['b-1']);++ // The superseded query settles late: it must not overwrite the search.+ act(() => base.onSuccess(['a-1']));+ expect(store.getState().lists.all).toEqual(['b-1']);+ });+it('does not let a slow hydration overwrite a faster server response', async () => {const storage = createMemoryStorage();storage.rows.set('user-1:personal|a', { data: ['cached'], updatedAt: 1 });diff --git a/packages/replica/src/zustand/createReplicaSlice.ts b/packages/replica/src/zustand/createReplicaSlice.tsindex 1a3a9575864..32e3b193852 100644--- a/packages/replica/src/zustand/createReplicaSlice.ts+++ b/packages/replica/src/zustand/createReplicaSlice.ts@@ -106,6 +106,16 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(});const { ensureScope, fetcher, hydrate, replace } = engine;+ /**+ * Row key of the head query each entry last asked for. One entry backs a+ * single view, so a response that belongs to a query the entry has already+ * moved past must not repaint it β it would show a superseded query, and a+ * view gated on the current query would then wait forever. Making this an+ * invariant of the slice (not of one driver) keeps it true for drivers that+ * leave a request's own callback live after the query changed.+ */+ const headQuery = new Map<string, string>();+/*** Hydrates the persisted row once per scope/key/query, then lets the driver* fetch and revalidate the head. Read the data from the store.@@ -117,6 +127,7 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(const scope = resource.scope.use();const key = params ? resource.key(params) : undefined;const active = enabled && !!params && key !== undefined;+ const queryKey = params ? resource.storageKey(params) : undefined;// Layout effect: runs before paint, so a scope switch never shows a frame// of the previous identity's data.@@ -124,6 +135,11 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(if (active) ensureScope(scope);}, [active, scope]);+ // Remember the query this entry now asks for (see `headQuery`).+ useLayoutEffect(() => {+ if (active && key !== undefined && queryKey !== undefined) headQuery.set(key, queryKey);+ }, [active, key, queryKey]);+const hydration = driver.useQuery<boolean>(active && resource.persisted && resource.persistKey(key!)? replicaKeys.hydrate(resource.name, resource.version, scope, resource.storageKey(params!))@@ -144,6 +160,9 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(...schedule,onError,onSuccess: (data) => {+ // Discard a head response the entry has moved past: the newer query+ // owns the view (see `headQuery`).+ if (queryKey === undefined || headQuery.get(key!) !== queryKey) return;replace(params!, data, scope);onSuccess?.(data);},diff --git a/src/features/MCP/MCPDetail/index.tsx b/src/features/MCP/MCPDetail/index.tsxindex 21eb0bb1dc4..2d670803a02 100644--- a/src/features/MCP/MCPDetail/index.tsx+++ b/src/features/MCP/MCPDetail/index.tsx@@ -29,19 +29,17 @@ const Detail = memo<DetailProps>(({ identifier: defaultIdentifier, defaultTab, nconst { t } = useTranslation('plugin');const theme = useTheme(); // Keep for colorBgContainerSecondary (not in cssVar)- const [activeMCPIdentifier, isMcpListInit] = useToolStore((s) => [- s.activeMCPIdentifier,- s.isMcpListInit,- ]);+ const list = useToolStore((s) => s.mcpPluginList);- const identifier = defaultIdentifier ?? activeMCPIdentifier;+ // Without an explicit identifier the detail defaults to the first marketplace+ // row, once the list has painted (from storage or the server).+ const identifier = defaultIdentifier ?? list?.items?.[0]?.identifier;const useMcpDetail = useDiscoverStore((s) => s.useFetchMcpDetail);const { data, isLoading } = useMcpDetail({ identifier });- // If an explicit identifier is passed in, skip the isMcpListInit check- const shouldWaitForInit = !defaultIdentifier && !isMcpListInit;- if (shouldWaitForInit || isLoading) return <Loading />;+ // An explicit identifier never waits on the list; otherwise wait for it to paint.+ if ((!defaultIdentifier && !list) || isLoading) return <Loading />;if (!identifier)return (diff --git a/src/features/SkillStore/Search/index.tsx b/src/features/SkillStore/Search/index.tsxindex a53fbb70fee..74bd07a0d82 100644--- a/src/features/SkillStore/Search/index.tsx+++ b/src/features/SkillStore/Search/index.tsx@@ -30,7 +30,7 @@ export const Search = memo<SearchProps>(({ activeTab, onLobeHubSearch, onSkillSevariant="outlined"onSearch={(keywords: string) => {if (activeTab === SkillStoreTab.MCP) {- useToolStore.setState({ mcpSearchKeywords: keywords, searchLoading: true });+ useToolStore.setState({ mcpSearchKeywords: keywords });} else if (activeTab === SkillStoreTab.Skills) {onSkillSearch(keywords);} else {diff --git a/src/features/SkillStore/SkillList/MCP/index.tsx b/src/features/SkillStore/SkillList/MCP/index.tsxindex 349a02f1f74..87119192207 100644--- a/src/features/SkillStore/SkillList/MCP/index.tsx+++ b/src/features/SkillStore/SkillList/MCP/index.tsx@@ -1,12 +1,13 @@'use client';-import { Center, Icon } from '@lobehub/ui';+import { Center, Flexbox, Icon } from '@lobehub/ui';import { Text } from '@lobehub/ui/base-ui';import { ServerCrash } from 'lucide-react';import { memo, useEffect, useRef } from 'react';import { useTranslation } from 'react-i18next';import { VirtuosoGrid } from 'react-virtuoso';+import AsyncError from '@/components/AsyncError';import { useToolStore } from '@/store/tool';import Item from '../Community/Item';@@ -15,31 +16,19 @@ import Loading from '../Loading';import { virtuosoGridStyles } from '../style';import VirtuosoLoading from '../VirtuosoLoading';import WantMoreSkills from '../WantMoreSkills';+import { canAutoLoadMore, resolveMCPListFooter } from './utils';export const MCPList = memo(() => {const { t } = useTranslation('setting');- const [- keywords,- isMcpListInit,- allItems,- currentPage,- totalPages,- searchLoading,- useFetchMCPPluginList,- loadMoreMCPPlugins,- resetMCPPluginList,- ] = useToolStore((s) => [- s.mcpSearchKeywords,- s.isMcpListInit,- s.mcpPluginItems,- s.currentPage,- s.totalPages,- s.searchLoading,- s.useFetchMCPPluginList,- s.loadMoreMCPPlugins,- s.resetMCPPluginList,- ]);+ const [keywords, list, useFetchMCPPluginList, loadMoreMCPPlugins, resetMCPPluginList] =+ useToolStore((s) => [+ s.mcpSearchKeywords,+ s.mcpPluginList,+ s.useFetchMCPPluginList,+ s.loadMoreMCPPlugins,+ s.resetMCPPluginList,+ ]);const prevKeywordsRef = useRef(keywords);@@ -50,17 +39,14 @@ export const MCPList = memo(() => {}}, [keywords, resetMCPPluginList]);- const { isLoading, error } = useFetchMCPPluginList({- page: currentPage,- pageSize: 20,- q: keywords,- });+ const { error, isValidating } = useFetchMCPPluginList({ pageSize: 20, q: keywords });+ const allItems = list?.items ?? [];const hasSearchKeywords = Boolean(keywords && keywords.trim());+ // A view painted for another search term is not the answer on screen yet.+ const isStaleQuery = !!list && (list.q ?? undefined) !== (keywords || undefined);- if (searchLoading || !isMcpListInit || (isLoading && allItems.length === 0)) return <Loading />;-- if (error) {+ if (error && !list) {return (<Center gap={12} padding={40}><Icon icon={ServerCrash} size={80} />@@ -69,27 +55,53 @@ export const MCPList = memo(() => {);}- if (allItems.length === 0) return <Empty search={hasSearchKeywords} />;+ if (!list || isStaleQuery || (isValidating && allItems.length === 0)) return <Loading />;- const hasReachedEnd = totalPages !== undefined && currentPage >= totalPages;+ if (allItems.length === 0) return <Empty search={hasSearchKeywords} />;const renderFooter = () => {- if (isLoading) return <VirtuosoLoading />;- if (hasReachedEnd) return <WantMoreSkills />;- return <div style={{ height: 16 }} />;+ switch (resolveMCPListFooter(list)) {+ case 'loading': {+ return <VirtuosoLoading />;+ }+ case 'error': {+ return (+ <Flexbox align={'center'} paddingBlock={12}>+ <AsyncError+ error={list.loadMoreError}+ variant={'inline'}+ onRetry={() => {+ void loadMoreMCPPlugins();+ }}+ />+ </Flexbox>+ );+ }+ case 'exhausted': {+ return <WantMoreSkills />;+ }+ default: {+ return <div style={{ height: 16 }} />;+ }+ }};return (<VirtuosoGridcomponents={{ Footer: renderFooter }}data={allItems}- endReached={loadMoreMCPPlugins}increaseViewportBy={typeof window !== 'undefined' ? window.innerHeight : 0}itemClassName={virtuosoGridStyles.item}itemContent={(_, item) => <Item {...item} />}listClassName={virtuosoGridStyles.list}overscan={24}style={{ height: '60vh', width: '100%' }}+ endReached={() => {+ // While a page is failing, paging waits for the explicit retry above+ // instead of hammering the endpoint on every scroll.+ if (!canAutoLoadMore(list)) return;+ void loadMoreMCPPlugins();+ }}/>);});diff --git a/src/features/SkillStore/SkillList/MCP/utils.test.ts b/src/features/SkillStore/SkillList/MCP/utils.test.tsnew file mode 100644index 00000000000..5c682419065--- /dev/null+++ b/src/features/SkillStore/SkillList/MCP/utils.test.ts@@ -0,0 +1,38 @@+import { describe, expect, it } from 'vitest';++import { canAutoLoadMore, resolveMCPListFooter } from './utils';++const list = (overrides: Partial<Parameters<typeof resolveMCPListFooter>[0]> = {}) => ({+ hasMore: true,+ isLoadingMore: false,+ ...overrides,+});++describe('resolveMCPListFooter', () => {+ it('surfaces a failed page instead of falling through to the idle spacer', () => {+ expect(resolveMCPListFooter(list({ loadMoreError: new Error('offline') }))).toBe('error');+ });++ it('shows the spinner while a page is in flight', () => {+ expect(resolveMCPListFooter(list({ isLoadingMore: true }))).toBe('loading');+ });++ it('marks the end of the list', () => {+ expect(resolveMCPListFooter(list({ hasMore: false }))).toBe('exhausted');+ });++ it('keeps a spacer while more pages are available', () => {+ expect(resolveMCPListFooter(list())).toBe('spacer');+ });+});++describe('canAutoLoadMore', () => {+ it('stands down while the last page failed', () => {+ expect(canAutoLoadMore(list({ loadMoreError: new Error('offline') }))).toBe(false);+ });++ it('pages when nothing is failing and more rows remain', () => {+ expect(canAutoLoadMore(list())).toBe(true);+ expect(canAutoLoadMore(list({ hasMore: false }))).toBe(false);+ });+});diff --git a/src/features/SkillStore/SkillList/MCP/utils.ts b/src/features/SkillStore/SkillList/MCP/utils.tsnew file mode 100644index 00000000000..f39775c3bf1--- /dev/null+++ b/src/features/SkillStore/SkillList/MCP/utils.ts@@ -0,0 +1,28 @@+/**+ * What the marketplace grid renders below its rows.+ *+ * `error` is its own state on purpose: a page that failed to load must not fall+ * through to the idle spacer, where a partially loaded list reads as complete.+ */+export type MCPListFooter = 'error' | 'exhausted' | 'loading' | 'spacer';++export interface MCPListPagingState {+ hasMore: boolean;+ isLoadingMore?: boolean;+ loadMoreError?: unknown;+}++export const resolveMCPListFooter = (list: MCPListPagingState): MCPListFooter => {+ if (list.isLoadingMore) return 'loading';+ if (list.loadMoreError) return 'error';+ if (!list.hasMore) return 'exhausted';+ return 'spacer';+};++/**+ * Whether reaching the end of the grid may request another page. While the last+ * page is failing, paging waits for the footer's explicit retry instead of+ * re-firing on every scroll.+ */+export const canAutoLoadMore = (list: MCPListPagingState): boolean =>+ list.hasMore && !list.loadMoreError;diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex bd0ef879bf0..4cf315787b7 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -910,11 +910,6 @@ export const toolKeys = {'tool:lobehubSkillTools',provider,]),- mcpPluginList: def('tool:mcpPluginList', (locale: string, params: unknown) => [- 'tool:mcpPluginList',- locale,- params,- ]),uninstalledBuiltins: def('tool:uninstalledBuiltins', (workspaceId: string | null | undefined) => ['tool:uninstalledBuiltins',workspaceId,diff --git a/src/store/tool/slices/mcpStore/action.test.ts b/src/store/tool/slices/mcpStore/action.test.tsindex f0e4aa12e06..a3e0a23bd0a 100644--- a/src/store/tool/slices/mcpStore/action.test.ts+++ b/src/store/tool/slices/mcpStore/action.test.ts@@ -13,6 +13,7 @@ import { MCPInstallStep } from '@/types/plugins';import type * as PlatformModule from '@/utils/platform';import { useToolStore } from '../../store';+import { type MCPPluginListData } from './initialState';vi.mock('@/utils/platform', async (importOriginal) => ({...(await importOriginal<typeof PlatformModule>()),@@ -57,6 +58,15 @@ vi.mock('@/utils/sleep', () => ({vi.mock('zustand/traditional');+/** Seed the `mcpPluginList` replica view with one loaded head page. */+const pagedPluginList = (items: PluginItem[]): MCPPluginListData => ({+ currentPage: 0,+ hasMore: false,+ items,+ pageSize: 20,+ total: items.length,+});+const bootstrapToolStoreWithDesktop = async (isDesktopEnv: boolean) => {vi.resetModules();@@ -99,15 +109,13 @@ beforeEach(() => {act(() => {useToolStore.setState({- mcpPluginItems: [],+ mcpPluginList: undefined,mcpInstallProgress: {},mcpInstallAbortControllers: {},mcpTestAbortControllers: {},mcpTestLoading: {},mcpTestErrors: {},- currentPage: 1,- totalCount: 0,- categories: [],+ mcpSearchKeywords: undefined,refreshPlugins: vi.fn(),updateInstallLoadingState: vi.fn(),},@@ -456,55 +464,93 @@ describe('mcpStore actions', () => {});describe('loadMoreMCPPlugins', () => {- it('should increment current page when more items available', () => {- const { result } = renderHook(() => useToolStore());+ it('appends the next page of the loaded query', async () => {+ const headItems = Array.from({ length: 20 }, (_, i) => ({+ identifier: `plugin-${i}`,+ name: `Plugin ${i}`,+ })) as PluginItem[];+ const nextItems = Array.from({ length: 20 }, (_, i) => ({+ identifier: `plugin-${i + 20}`,+ name: `Plugin ${i + 20}`,+ })) as PluginItem[];- act(() => {- useToolStore.setState({- mcpPluginItems: Array.from({ length: 10 }, (_, i) => ({- identifier: `plugin-${i}`,- })) as PluginItem[],- totalCount: 50,- currentPage: 1,- });+ vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');+ const fetchSpy = vi.spyOn(discoverService, 'getMCPPluginList').mockResolvedValue({+ categories: [],+ currentPage: 1,+ items: headItems,+ pageSize: 20,+ totalCount: 40,+ totalPages: 2,});- act(() => {- result.current.loadMoreMCPPlugins();+ const { result } = renderHook(() => ({+ loadMore: useToolStore((s) => s.loadMoreMCPPlugins),+ sync: useToolStore((s) => s.useFetchMCPPluginList)({ pageSize: 20 }),+ }));++ await waitFor(() => {+ expect(useToolStore.getState().mcpPluginList?.items).toHaveLength(20);+ });+ expect(useToolStore.getState().mcpPluginList).toMatchObject({ hasMore: true, total: 40 });++ fetchSpy.mockResolvedValue({+ categories: [],+ currentPage: 2,+ items: nextItems,+ pageSize: 20,+ totalCount: 40,+ totalPages: 2,});- expect(result.current.currentPage).toBe(2);+ await act(async () => {+ await result.current.loadMore();+ });++ const list = useToolStore.getState().mcpPluginList!;+ expect(list.items).toHaveLength(40);+ expect(list.items[20].identifier).toBe('plugin-20');+ expect(list.currentPage).toBe(1);+ expect(list.hasMore).toBe(false);+ expect(fetchSpy).toHaveBeenLastCalledWith(expect.objectContaining({ page: 2, pageSize: 20 }));});- it('should not increment page when all items loaded', () => {- const { result } = renderHook(() => useToolStore());+ it('does not fetch another page when the head page is the last one', async () => {+ vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');+ const fetchSpy = vi.spyOn(discoverService, 'getMCPPluginList').mockResolvedValue({+ categories: [],+ currentPage: 1,+ items: [{ identifier: 'only-plugin', name: 'Only Plugin' }] as PluginItem[],+ pageSize: 20,+ totalCount: 1,+ totalPages: 1,+ });- act(() => {- useToolStore.setState({- mcpPluginItems: Array.from({ length: 50 }, (_, i) => ({- identifier: `plugin-${i}`,- })) as PluginItem[],- totalCount: 50,- currentPage: 5,- });+ const { result } = renderHook(() => ({+ loadMore: useToolStore((s) => s.loadMoreMCPPlugins),+ sync: useToolStore((s) => s.useFetchMCPPluginList)({ pageSize: 20 }),+ }));++ await waitFor(() => {+ expect(useToolStore.getState().mcpPluginList?.items).toHaveLength(1);});+ expect(useToolStore.getState().mcpPluginList?.hasMore).toBe(false);- act(() => {- result.current.loadMoreMCPPlugins();+ await act(async () => {+ await result.current.loadMore();});- expect(result.current.currentPage).toBe(5);+ expect(fetchSpy).toHaveBeenCalledTimes(1);});});describe('resetMCPPluginList', () => {- it('should reset plugin list and page', () => {+ it('drops the painted page set and remembers the new keywords', () => {const { result } = renderHook(() => useToolStore());act(() => {useToolStore.setState({- mcpPluginItems: [{ identifier: 'plugin-1' }] as PluginItem[],- currentPage: 5,+ mcpPluginList: pagedPluginList([{ identifier: 'plugin-1' } as PluginItem]),mcpSearchKeywords: 'old-keyword',});});@@ -513,18 +559,16 @@ describe('mcpStore actions', () => {result.current.resetMCPPluginList('new-keyword');});- expect(result.current.mcpPluginItems).toEqual([]);- expect(result.current.currentPage).toBe(1);+ expect(result.current.mcpPluginList).toBeUndefined();expect(result.current.mcpSearchKeywords).toBe('new-keyword');});- it('should reset without keywords', () => {+ it('resets without keywords', () => {const { result } = renderHook(() => useToolStore());act(() => {useToolStore.setState({- mcpPluginItems: [{ identifier: 'plugin-1' }] as PluginItem[],- currentPage: 3,+ mcpPluginList: pagedPluginList([{ identifier: 'plugin-1' } as PluginItem]),});});@@ -532,14 +576,13 @@ describe('mcpStore actions', () => {result.current.resetMCPPluginList();});- expect(result.current.mcpPluginItems).toEqual([]);- expect(result.current.currentPage).toBe(1);+ expect(result.current.mcpPluginList).toBeUndefined();expect(result.current.mcpSearchKeywords).toBeUndefined();});});describe('useFetchMCPPluginList', () => {- it('should fetch MCP plugin list and update state', async () => {+ it('fetches the head page and folds it into the replica view', async () => {const mockData = {items: [{ identifier: 'plugin-1', name: 'Plugin 1' },@@ -555,78 +598,23 @@ describe('mcpStore actions', () => {vi.spyOn(discoverService, 'getMCPPluginList').mockResolvedValue(mockData);vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');- const { result } = renderHook(() =>- useToolStore.getState().useFetchMCPPluginList({ page: 1, pageSize: 20 }),- );+ renderHook(() => useToolStore((s) => s.useFetchMCPPluginList)({ pageSize: 20 }));await waitFor(() => {- expect(result.current.data).toEqual(mockData);+ expect(useToolStore.getState().mcpPluginList?.items).toEqual(mockData.items);});expect(discoverService.getMCPPluginList).toHaveBeenCalledWith(- expect.objectContaining({ page: 1, pageSize: 20, connectionType: 'http' }),+ expect.objectContaining({ connectionType: 'http', locale: 'en-US', page: 1, pageSize: 20 }),);- const state = useToolStore.getState();- expect(state.mcpPluginItems).toEqual(mockData.items);- expect(state.categories).toEqual(mockData.categories);- expect(state.totalCount).toBe(2);- expect(state.totalPages).toBe(1);- expect(state.searchLoading).toBe(false);+ const list = useToolStore.getState().mcpPluginList!;+ expect(list.total).toBe(2);+ expect(list.pageSize).toBe(20);+ expect(list.hasMore).toBe(false);});- it('should set active identifier on first init', async () => {- const mockData = {- items: [{ identifier: 'first-plugin', name: 'First Plugin' }] as PluginItem[],- categories: [],- totalCount: 1,- totalPages: 1,- currentPage: 1,- pageSize: 20,- };-- vi.spyOn(discoverService, 'getMCPPluginList').mockResolvedValue(mockData);- vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');-- act(() => {- useToolStore.setState({ isMcpListInit: false });- });-- const { result } = renderHook(() =>- useToolStore.getState().useFetchMCPPluginList({ page: 1 }),- );-- await waitFor(() => {- expect(result.current.data).toEqual(mockData);- });-- const state = useToolStore.getState();- expect(state.activeMCPIdentifier).toBe('first-plugin');- expect(state.isMcpListInit).toBe(true);- });-- it('should convert page to number', async () => {- vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');- vi.spyOn(discoverService, 'getMCPPluginList').mockResolvedValue({- items: [],- categories: [],- totalCount: 0,- totalPages: 0,- currentPage: 1,- pageSize: 20,- });-- const params = { page: 2, pageSize: 15 } as any;- renderHook(() => useToolStore.getState().useFetchMCPPluginList(params));-- await waitFor(() => {- expect(discoverService.getMCPPluginList).toHaveBeenCalledWith(- expect.objectContaining({ ...params, connectionType: 'http' }),- );- });- });-- it('should include locale and parameters in SWR key', async () => {+ it('sends the search term as the query `q`', async () => {vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('zh-CN');vi.spyOn(discoverService, 'getMCPPluginList').mockResolvedValue({items: [],@@ -634,20 +622,19 @@ describe('mcpStore actions', () => {totalCount: 0,totalPages: 0,currentPage: 1,- pageSize: 20,+ pageSize: 15,});- const params = { page: 3, pageSize: 15, q: 'test' } as any;- renderHook(() => useToolStore.getState().useFetchMCPPluginList(params));+ renderHook(() => useToolStore((s) => s.useFetchMCPPluginList)({ pageSize: 15, q: 'test' }));await waitFor(() => {expect(discoverService.getMCPPluginList).toHaveBeenCalledWith(- expect.objectContaining({ ...params, connectionType: 'http' }),+ expect.objectContaining({ locale: 'zh-CN', page: 1, pageSize: 15, q: 'test' }),);});});- it('should not append connectionType in desktop environment', async () => {+ it('does not pin a connection type in the desktop environment', async () => {const {useToolStore: desktopStore,discoverService: desktopDiscoverService,@@ -670,15 +657,12 @@ describe('mcpStore actions', () => {.spyOn(desktopDiscoverService, 'getMCPPluginList').mockResolvedValue(mockData);- const { result } = renderHook(() =>- desktopStore.getState().useFetchMCPPluginList({ page: 1, pageSize: 20 }),- );+ renderHook(() => desktopStore((s) => s.useFetchMCPPluginList)({ pageSize: 20 }));await waitFor(() => {- expect(result.current.data).toEqual(mockData);+ expect(fetchSpy).toHaveBeenCalledTimes(1);});- expect(fetchSpy).toHaveBeenCalledTimes(1);const [firstCallArgs] = fetchSpy.mock.calls[0];expect(firstCallArgs).toMatchObject({ page: 1, pageSize: 20 });expect(firstCallArgs.connectionType).toBeUndefined();@@ -748,7 +732,7 @@ describe('mcpStore actions', () => {act(() => {useToolStore.setState({- mcpPluginItems: [mockPlugin],+ mcpPluginList: pagedPluginList([mockPlugin]),});});@@ -772,7 +756,7 @@ describe('mcpStore actions', () => {act(() => {useToolStore.setState({- mcpPluginItems: [mockPlugin],+ mcpPluginList: pagedPluginList([mockPlugin]),});});@@ -812,7 +796,7 @@ describe('mcpStore actions', () => {act(() => {useToolStore.setState({- mcpPluginItems: [],+ mcpPluginList: pagedPluginList([]),});});@@ -830,7 +814,7 @@ describe('mcpStore actions', () => {act(() => {useToolStore.setState({- mcpPluginItems: [],+ mcpPluginList: pagedPluginList([]),});});@@ -862,7 +846,7 @@ describe('mcpStore actions', () => {act(() => {useToolStore.setState({- mcpPluginItems: [mockPlugin],+ mcpPluginList: pagedPluginList([mockPlugin]),});});@@ -885,7 +869,7 @@ describe('mcpStore actions', () => {act(() => {useToolStore.setState({- mcpPluginItems: [mockPlugin],+ mcpPluginList: pagedPluginList([mockPlugin]),});});@@ -918,7 +902,7 @@ describe('mcpStore actions', () => {act(() => {useToolStore.setState({- mcpPluginItems: [mockPlugin],+ mcpPluginList: pagedPluginList([mockPlugin]),});});@@ -990,7 +974,7 @@ describe('mcpStore actions', () => {act(() => {useToolStore.setState({- mcpPluginItems: [mockPluginWithCloudEndpoint],+ mcpPluginList: pagedPluginList([mockPluginWithCloudEndpoint]),});});@@ -1052,7 +1036,7 @@ describe('mcpStore actions', () => {act(() => {useToolStore.setState({- mcpPluginItems: [mockPlugin],+ mcpPluginList: pagedPluginList([mockPlugin]),});});@@ -1079,7 +1063,7 @@ describe('mcpStore actions', () => {act(() => {useToolStore.setState({- mcpPluginItems: [mockPlugin],+ mcpPluginList: pagedPluginList([mockPlugin]),mcpInstallProgress: {'test-plugin': {progress: 50,@@ -1114,7 +1098,7 @@ describe('mcpStore actions', () => {act(() => {useToolStore.setState({- mcpPluginItems: [mockPlugin],+ mcpPluginList: pagedPluginList([mockPlugin]),mcpInstallProgress: {},});});@@ -1146,7 +1130,7 @@ describe('mcpStore actions', () => {act(() => {useToolStore.setState({- mcpPluginItems: [mockPlugin],+ mcpPluginList: pagedPluginList([mockPlugin]),});});@@ -1195,7 +1179,7 @@ describe('mcpStore actions', () => {act(() => {useToolStore.setState({- mcpPluginItems: [mockPlugin],+ mcpPluginList: pagedPluginList([mockPlugin]),});});@@ -1219,7 +1203,7 @@ describe('mcpStore actions', () => {it('should handle cancellation during installation', async () => {const { result } = renderHook(() => useToolStore());- vi.spyOn(mcpService, 'checkInstallation').mockImplementation(async (manifest, signal) => {+ vi.spyOn(mcpService, 'checkInstallation').mockImplementation(async (_manifest, _signal) => {// Cancel after checksetTimeout(() => {result.current.cancelInstallMCPPlugin('test-plugin');@@ -1232,7 +1216,7 @@ describe('mcpStore actions', () => {act(() => {useToolStore.setState({- mcpPluginItems: [mockPlugin],+ mcpPluginList: pagedPluginList([mockPlugin]),});});@@ -1266,7 +1250,7 @@ describe('mcpStore actions', () => {act(() => {useToolStore.setState({- mcpPluginItems: [mockPlugin],+ mcpPluginList: pagedPluginList([mockPlugin]),});});@@ -1294,7 +1278,7 @@ describe('mcpStore actions', () => {act(() => {useToolStore.setState({- mcpPluginItems: [mockPlugin],+ mcpPluginList: pagedPluginList([mockPlugin]),});});@@ -1318,7 +1302,7 @@ describe('mcpStore actions', () => {act(() => {useToolStore.setState({- mcpPluginItems: [mockPlugin],+ mcpPluginList: pagedPluginList([mockPlugin]),});});@@ -1341,7 +1325,7 @@ describe('mcpStore actions', () => {act(() => {useToolStore.setState({- mcpPluginItems: [mockPlugin],+ mcpPluginList: pagedPluginList([mockPlugin]),});});@@ -1363,7 +1347,7 @@ describe('mcpStore actions', () => {act(() => {useToolStore.setState({- mcpPluginItems: [mockPlugin],+ mcpPluginList: pagedPluginList([mockPlugin]),});});@@ -1387,7 +1371,7 @@ describe('mcpStore actions', () => {act(() => {useToolStore.setState({- mcpPluginItems: [mockPlugin],+ mcpPluginList: pagedPluginList([mockPlugin]),});});@@ -1414,7 +1398,7 @@ describe('mcpStore actions', () => {act(() => {useToolStore.setState({- mcpPluginItems: [mockPlugin],+ mcpPluginList: pagedPluginList([mockPlugin]),});});diff --git a/src/store/tool/slices/mcpStore/action.ts b/src/store/tool/slices/mcpStore/action.tsindex 6d4b3b7f12e..b2fdf2455c0 100644--- a/src/store/tool/slices/mcpStore/action.ts+++ b/src/store/tool/slices/mcpStore/action.ts@@ -1,17 +1,19 @@import { CURRENT_VERSION, isDesktop } from '@lobechat/const';import { type ToolManifest } from '@lobechat/types';-import { type PluginItem, type PluginListResponse } from '@lobehub/market-sdk';+import { type PluginItem } from '@lobehub/market-sdk';import { type TRPCClientError } from '@trpc/client';import debug from 'debug';-import { uniqBy } from 'es-toolkit/compat';import { produce } from 'immer';import { gt, valid } from 'semver';-import { type SWRResponse } from 'swr';-import useSWR from 'swr';import { type MCPErrorData } from '@/libs/mcp/types';import { parseStdioErrorMessage } from '@/libs/mcp/types';-import { toolKeys } from '@/libs/swr/keys';+import {+ createReplicaSlice,+ type ReplicaLens,+ type ReplicaPageResult,+ type ReplicaSyncResult,+} from '@/libs/replica';import { discoverService } from '@/services/discover';import { mcpService } from '@/services/mcp';import { pluginService } from '@/services/plugin';@@ -24,7 +26,6 @@ import {type McpConnectionParams,type MCPErrorInfo,type MCPInstallProgress,- type MCPPluginListParams,} from '@/types/plugins';import { MCPInstallStep } from '@/types/plugins';import { getPlatform } from '@/utils/platform';@@ -32,7 +33,8 @@ import { sleep } from '@/utils/sleep';import { setNamespace } from '@/utils/storeDebug';import { type ToolStore } from '../../store';-import { type MCPStoreState } from './initialState';+import { type MCPPluginListData, type MCPStoreState } from './initialState';+import { MCP_PLUGIN_LIST_KEY, type MCPPluginListParams, mcpPluginListResource } from './projection';const log = debug('lobe-mcp:store:action');@@ -142,20 +144,69 @@ export interface TestMcpConnectionResult {success: boolean;}+/**+ * The marketplace list keeps a dedicated `mcpPluginList` field as the replica+ * view. It is `undefined` until the persisted row hydrates or the first network+ * page lands, so an un-loaded list never reads as an empty one β the gate is the+ * field's own default instead of a separate init flag.+ */+const mcpPluginListLens: ReplicaLens<ToolStore, MCPPluginListData> = {+ clear: () => ({ mcpPluginList: undefined }),+ get: (state) => state.mcpPluginList,+ set: (_state, _key, data) => ({ mcpPluginList: data }),+};+type Setter = StoreSetter<ToolStore>;export const createMCPPluginStoreSlice = (set: Setter, get: () => ToolStore, _api?: unknown) =>new PluginMCPStoreActionImpl(set, get, _api);export class PluginMCPStoreActionImpl {readonly #get: () => ToolStore;+ /**+ * The MCP marketplace list is a `@lobechat/replica` paged resource: the+ * persisted head page paints before the network answers, and "load more"+ * appends further pages through the engine instead of a hand-rolled+ * `currentPage` + accumulator.+ */+ readonly #mcpPluginList;readonly #set: Setter;constructor(set: Setter, get: () => ToolStore, _api?: unknown) {void _api;this.#set = set;this.#get = get;+ this.#mcpPluginList = createReplicaSlice(mcpPluginListResource, {+ actionPrefix: 'mcpPluginList',+ fetcher: (params, cursor) => this.#fetchMCPPluginListPage(params, cursor),+ get,+ set,+ stateKey: 'mcpPluginListReplica',+ view: mcpPluginListLens,+ viewFields: ({ connectionType, locale, pageSize, q }) => ({+ connectionType,+ locale,+ pageSize,+ q: q || undefined,+ }),+ });}+ /** One page of the marketplace list; `cursor` is the page index (0 = head). */+ #fetchMCPPluginListPage = async (+ params: MCPPluginListParams,+ cursor?: number,+ ): Promise<ReplicaPageResult<PluginItem, number>> => {+ const response = await discoverService.getMCPPluginList({+ connectionType: params.connectionType,+ locale: params.locale,+ page: (cursor ?? 0) + 1,+ pageSize: params.pageSize,+ q: params.q,+ });++ return { items: response.items, total: response.totalCount };+ };+cancelInstallMCPPlugin = async (identifier: string): Promise<void> => {// Get and cancel AbortControllerconst abortController = this.#get().mcpInstallAbortControllers[identifier];@@ -705,32 +756,22 @@ export class PluginMCPStoreActionImpl {}};- loadMoreMCPPlugins = (): void => {- const { mcpPluginItems, totalCount, currentPage } = this.#get();-- // Check if there's more data to load- if (mcpPluginItems.length < (totalCount || 0)) {- this.#set(- produce((draft: MCPStoreState) => {- draft.currentPage = currentPage + 1;- }),- false,- n('loadMoreMCPPlugins'),- );- }+ /**+ * Append the next page of the marketplace list. The engine reads the loaded+ * head params, dedupes by identifier and keeps `hasMore` honest.+ */+ loadMoreMCPPlugins = async (): Promise<void> => {+ await this.#mcpPluginList.loadMore(MCP_PLUGIN_LIST_KEY);};+ /**+ * The search term drives the resource query, so "reset" drops the painted page+ * set: the next (query-changed) fetch repaints from its own head page instead+ * of appending to the previous search. The persisted rows are left alone.+ */resetMCPPluginList = (keywords?: string): void => {- this.#set(- produce((draft: MCPStoreState) => {- draft.mcpPluginItems = [];- draft.currentPage = 1;- draft.mcpSearchKeywords = keywords;- draft.isMcpListInit = false;- }),- false,- n('resetMCPPluginList'),- );+ this.#set({ mcpSearchKeywords: keywords }, false, n('resetMCPPluginList'));+ this.#mcpPluginList.update(MCP_PLUGIN_LIST_KEY, () => undefined, { persist: false });};testMcpConnection = async (params: McpConnectionParams): Promise<TestMcpConnectionResult> => {@@ -860,57 +901,21 @@ export class PluginMCPStoreActionImpl {);};- useFetchMCPPluginList = (params: MCPPluginListParams): SWRResponse<PluginListResponse> => {- const locale = globalHelpers.getCurrentLanguage();- const requestParams = isDesktop- ? params- : { ...params, connectionType: McpConnectionType.http };- const page = requestParams.page ?? 1;-- return useSWR<PluginListResponse>(- toolKeys.mcpPluginList(locale, {- connectionType: requestParams.connectionType,- page: requestParams.page,- pageSize: requestParams.pageSize,- q: requestParams.q,- }),- () => discoverService.getMCPPluginList(requestParams),- {- onSuccess: (data) => {- this.#set(- produce((draft: MCPStoreState) => {- draft.searchLoading = false;-- // Set basic information- if (!draft.isMcpListInit) {- draft.activeMCPIdentifier = data.items?.[0]?.identifier;-- draft.isMcpListInit = true;- draft.categories = data.categories;- draft.totalCount = data.totalCount;- draft.totalPages = data.totalPages;- }-- // Accumulate data logic- if (page === 1) {- // First page, set directly- draft.mcpPluginItems = uniqBy(data.items, 'identifier');- } else {- // Subsequent pages, accumulate data- draft.mcpPluginItems = uniqBy(- [...draft.mcpPluginItems, ...data.items],- 'identifier',- );- }- }),- false,- n('useFetchMCPPluginList/onSuccess'),- );- },- revalidateOnFocus: false,- },- );- };+ /**+ * Fetch orchestration for the marketplace list. Hydrates the persisted head+ * page, then revalidates; the rows land in the `mcpPluginList` view β read them+ * from the store, never from this hook.+ */+ useFetchMCPPluginList = (+ params: { connectionType?: McpConnectionType; pageSize?: number; q?: string } = {},+ ): ReplicaSyncResult =>+ this.#mcpPluginList.useSync({+ // The web client can only reach http MCP endpoints; desktop may also use stdio.+ connectionType: isDesktop ? params.connectionType : McpConnectionType.http,+ locale: globalHelpers.getCurrentLanguage(),+ pageSize: params.pageSize ?? 20,+ q: params.q,+ });}export type PluginMCPStoreAction = Pick<PluginMCPStoreActionImpl, keyof PluginMCPStoreActionImpl>;diff --git a/src/store/tool/slices/mcpStore/index.ts b/src/store/tool/slices/mcpStore/index.tsindex 279e5868539..e80ec197b2c 100644--- a/src/store/tool/slices/mcpStore/index.ts+++ b/src/store/tool/slices/mcpStore/index.ts@@ -1,2 +1,3 @@export * from './action';export * from './initialState';+export * from './projection';diff --git a/src/store/tool/slices/mcpStore/initialState.ts b/src/store/tool/slices/mcpStore/initialState.tsindex ce8891d79dc..6aecdc12475 100644--- a/src/store/tool/slices/mcpStore/initialState.ts+++ b/src/store/tool/slices/mcpStore/initialState.ts@@ -1,37 +1,50 @@import { type PluginItem } from '@lobehub/market-sdk';+import { createReplicaState, type ReplicaPagedData, type ReplicaState } from '@/libs/replica';+import { type McpConnectionType } from '@/types/discover';import { type MCPInstallProgressMap } from '@/types/plugins';export type PluginStoreListType = 'installed' | 'mcp';+/**+ * The MCP marketplace list view: the generic local-first paged data plus the+ * query descriptors it was fetched with, so the surface can tell whether the+ * painted page set still answers the request on screen. Paging bookkeeping+ * (`currentPage` / `hasMore` / `isLoadingMore`) comes from `ReplicaPagedData`.+ */+export interface MCPPluginListData extends ReplicaPagedData<PluginItem, number> {+ connectionType?: McpConnectionType;+ locale?: string;+ q?: string;+}+export interface MCPStoreState {- activeMCPIdentifier?: string;- categories: string[];- currentPage: number;- isLoadingMore?: boolean;- isMcpListInit?: boolean;listType: PluginStoreListType;mcpInstallAbortControllers: Record<string, AbortController>;mcpInstallProgress: MCPInstallProgressMap;- mcpPluginItems: PluginItem[];+ /**+ * The MCP marketplace list of the active scope β the view of the+ * `mcpPluginList` replica. `undefined` until the persisted row hydrates or the+ * first network page lands, so an un-loaded list never reads as an empty one.+ */+ mcpPluginList?: MCPPluginListData;+ /** Replica bookkeeping for `mcpPluginList`. */+ mcpPluginListReplica: ReplicaState<MCPPluginListData>;mcpSearchKeywords?: string;// Test connection related statemcpTestAbortControllers: Record<string, AbortController>;mcpTestErrors: Record<string, string>;mcpTestLoading: Record<string, boolean>;- searchLoading?: boolean;- tags?: string[];- totalCount?: number;- totalPages?: number;}export const initialMCPStoreState: MCPStoreState = {- categories: [],- currentPage: 1,listType: 'mcp',mcpInstallAbortControllers: {},mcpInstallProgress: {},- mcpPluginItems: [],+ // Absent until the persisted row hydrates or the first network page lands.+ mcpPluginList: undefined,+ mcpPluginListReplica: createReplicaState(),+ mcpSearchKeywords: undefined,// Test connection related state initializationmcpTestAbortControllers: {},mcpTestErrors: {},diff --git a/src/store/tool/slices/mcpStore/projection.ts b/src/store/tool/slices/mcpStore/projection.tsnew file mode 100644index 00000000000..0081104892a--- /dev/null+++ b/src/store/tool/slices/mcpStore/projection.ts@@ -0,0 +1,54 @@+import { type PluginItem } from '@lobehub/market-sdk';++import { definePagedReplica } from '@/libs/replica';+import { type McpConnectionType } from '@/types/discover';++import { type MCPPluginListData } from './initialState';++/**+ * The MCP marketplace list is not partitioned per container: one entry per+ * scope, so every sync shares this key.+ */+export const MCP_PLUGIN_LIST_KEY = 'all';++/**+ * Query identity of one page set. `page` is NOT here β it is the paging cursor,+ * owned by the replica. `locale` and `connectionType` change the rows the+ * server returns, so a projection taken under other values never paints.+ */+export interface MCPPluginListParams {+ connectionType?: McpConnectionType;+ locale: string;+ pageSize: number;+ q?: string;+}++/**+ * The MCP marketplace list (`discoverService.getMCPPluginList`): a local-first+ * paged replica, so the skill store paints the persisted head page on the first+ * frame, the network confirms it, and "load more" appends further pages.+ */+export const mcpPluginListResource = definePagedReplica<+ MCPPluginListParams,+ PluginItem,+ number,+ MCPPluginListData+>({+ key: () => MCP_PLUGIN_LIST_KEY,+ name: 'mcpPluginList',+ paging: {+ direction: 'forward',+ getId: (item) => item.identifier,+ mode: 'offset',+ // A reload repaints what the first network page would show, never a stale tail.+ persist: { pages: 1 },+ },+ query: ({ connectionType, locale, pageSize, q }) => ({+ connectionType,+ locale,+ pageSize,+ q: q || undefined,+ }),+ storage: 'indexedDB',+ version: 1,+});diff --git a/src/store/tool/slices/mcpStore/replica.test.ts b/src/store/tool/slices/mcpStore/replica.test.tsnew file mode 100644index 00000000000..6db55b78546--- /dev/null+++ b/src/store/tool/slices/mcpStore/replica.test.ts@@ -0,0 +1,282 @@+/**+ * @vitest-environment happy-dom+ *+ * The MCP marketplace list is a `@lobechat/replica` paged resource: the+ * persisted head page paints before the network answers, the response confirms+ * and persists it, "load more" appends through the engine, and a query change+ * (search term) repaints from its own head page instead of appending to the+ * previous search.+ */+import { randomUUID } from 'node:crypto';++import type { PluginItem } from '@lobehub/market-sdk';+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';+import type { PropsWithChildren } from 'react';+import { createElement, useEffect } from 'react';+import { SWRConfig, useSWRConfig } from 'swr';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { cacheScope } from '@/libs/replica';+import { setScopedMutate } from '@/libs/swr/mutate';+import { discoverService } from '@/services/discover';+import { globalHelpers } from '@/store/global/helpers';+import { McpConnectionType, type McpListResponse } from '@/types/discover';++import { useToolStore } from '../../store';+import { initialMCPStoreState, type MCPPluginListData } from './initialState';+import { MCP_PLUGIN_LIST_KEY, type MCPPluginListParams, mcpPluginListResource } from './projection';++const BASE_PARAMS: MCPPluginListParams = {+ connectionType: McpConnectionType.http,+ locale: 'en-US',+ pageSize: 20,+};+const SEARCH_PARAMS: MCPPluginListParams = { ...BASE_PARAMS, q: 'foo' };+const BASE_KEY = mcpPluginListResource.storageKey(BASE_PARAMS);+const SEARCH_KEY = mcpPluginListResource.storageKey(SEARCH_PARAMS);++const plugin = (identifier: string): PluginItem => ({ identifier, name: identifier }) as PluginItem;++const ids = (data?: MCPPluginListData) => data?.items.map((item) => item.identifier);++const idsOf = (length: number, offset = 0) =>+ Array.from({ length }, (_, i) => `plugin-${i + offset}`).map(plugin);++const listPage = (items: PluginItem[], totalCount: number): McpListResponse => ({+ categories: [],+ currentPage: 1,+ items,+ pageSize: 20,+ totalCount,+ totalPages: Math.ceil(totalCount / 20),+});++/** Never-resolving fetch: the first frame can only come from storage. */+const pending = () => new Promise<never>(() => {});++const MutateBridge = () => {+ const { mutate } = useSWRConfig();+ useEffect(() => setScopedMutate(mutate), [mutate]);+ return null;+};++const wrapper = ({ children }: PropsWithChildren) =>+ createElement(+ SWRConfig,+ { value: { dedupingInterval: 0, provider: () => new Map() } },+ createElement(MutateBridge),+ children,+ );++describe('mcpPluginList replica', () => {+ const scopes = new Set<string>();+ let scope = '';+ let fetchSpy: ReturnType<typeof vi.spyOn>;++ const useScope = (next: string) => {+ scope = next;+ scopes.add(next);+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ };++ beforeEach(() => {+ useScope(`mcp-user-${randomUUID()}:personal`);+ vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');+ fetchSpy = vi.spyOn(discoverService, 'getMCPPluginList');+ act(() => useToolStore.setState(initialMCPStoreState));+ });++ afterEach(async () => {+ cleanup();+ await Promise.all(+ [...scopes].flatMap((value) =>+ [BASE_KEY, SEARCH_KEY].map((queryKey) =>+ mcpPluginListResource.storage!.remove({ queryKey, scope: value }),+ ),+ ),+ );+ scopes.clear();+ vi.restoreAllMocks();+ vi.clearAllMocks();+ });++ it('reads the list from a single scope entry', () => {+ expect(MCP_PLUGIN_LIST_KEY).toBe('all');+ });++ it('paints the persisted head page before the network answers', async () => {+ const cached: MCPPluginListData = {+ connectionType: McpConnectionType.http,+ currentPage: 0,+ hasMore: true,+ items: [plugin('cached-1')],+ locale: 'en-US',+ pageSize: 20,+ total: 40,+ };+ await mcpPluginListResource.storage!.set(+ { queryKey: BASE_KEY, scope },+ { data: cached, updatedAt: 1 },+ );+ fetchSpy.mockImplementation(pending);++ const hook = renderHook(+ () => ({+ list: useToolStore((s) => s.mcpPluginList),+ sync: useToolStore((s) => s.useFetchMCPPluginList)({ pageSize: 20 }),+ }),+ { wrapper },+ );++ await waitFor(() => expect(ids(useToolStore.getState().mcpPluginList)).toEqual(['cached-1']));+ expect(hook.result.current.sync.isHydrated).toBe(true);+ expect(hook.result.current.sync.isValidating).toBe(true);+ });++ it('replaces the head page with the server response and persists it', async () => {+ fetchSpy.mockResolvedValue(listPage([plugin('a'), plugin('b')], 40));++ renderHook(() => useToolStore((s) => s.useFetchMCPPluginList)({ pageSize: 20 }), { wrapper });++ await waitFor(() => expect(ids(useToolStore.getState().mcpPluginList)).toEqual(['a', 'b']));+ expect(useToolStore.getState().mcpPluginList).toMatchObject({ hasMore: true, total: 40 });++ await waitFor(async () => {+ const row = await mcpPluginListResource.storage!.get({ queryKey: BASE_KEY, scope });+ expect(ids(row?.data as MCPPluginListData)).toEqual(['a', 'b']);+ });+ });++ it('appends the next page with the loaded query params', async () => {+ fetchSpy+ .mockResolvedValueOnce(listPage(idsOf(20), 40))+ .mockResolvedValueOnce(listPage(idsOf(20, 20), 40));++ const hook = renderHook(+ () => ({+ loadMore: useToolStore((s) => s.loadMoreMCPPlugins),+ sync: useToolStore((s) => s.useFetchMCPPluginList)({ pageSize: 20 }),+ }),+ { wrapper },+ );++ await waitFor(() => expect(useToolStore.getState().mcpPluginList?.items).toHaveLength(20));++ await act(async () => {+ await hook.result.current.loadMore();+ });++ const list = useToolStore.getState().mcpPluginList!;+ expect(list.items).toHaveLength(40);+ expect(list.items[20].identifier).toBe('plugin-20');+ expect(list.currentPage).toBe(1);+ expect(list.hasMore).toBe(false);+ // The replica owns the cursor: page 2 of the loaded query.+ expect(fetchSpy).toHaveBeenLastCalledWith(expect.objectContaining({ page: 2, pageSize: 20 }));+ });++ it('repaints from its own head page when the query changes', async () => {+ fetchSpy+ .mockResolvedValueOnce(listPage(idsOf(20), 40))+ .mockResolvedValueOnce(listPage(idsOf(20, 20), 40))+ .mockResolvedValueOnce(listPage([plugin('foo-1')], 1));++ const hook = renderHook(+ (props: { q?: string }) =>+ useToolStore((s) => s.useFetchMCPPluginList)({ pageSize: 20, q: props.q }),+ { initialProps: {} as { q?: string }, wrapper },+ );++ await waitFor(() => expect(useToolStore.getState().mcpPluginList?.items).toHaveLength(20));+ await act(async () => {+ await useToolStore.getState().loadMoreMCPPlugins();+ });+ expect(useToolStore.getState().mcpPluginList?.items).toHaveLength(40);++ hook.rerender({ q: 'foo' });++ await waitFor(() => expect(ids(useToolStore.getState().mcpPluginList)).toEqual(['foo-1']));+ // A different query resets the loaded depth; it never merges into the previous search.+ expect(useToolStore.getState().mcpPluginList).toMatchObject({+ currentPage: 0,+ q: 'foo',+ total: 1,+ });+ });++ it('keeps the newest query when a superseded search resolves last', async () => {+ // Both queries share the `all` entry, so a response that resolves after the+ // search term changed must not repaint the list with the old query's rows β+ // that would leave the query-gated view showing the wrong search (or stuck).+ const pendingByQuery = new Map<string, (value: McpListResponse) => void>();+ fetchSpy.mockImplementation(+ ({ q }: { q?: string }) =>+ new Promise<McpListResponse>((resolve) => pendingByQuery.set(q ?? '', resolve)),+ );++ const hook = renderHook(+ (props: { q?: string }) =>+ useToolStore((s) => s.useFetchMCPPluginList)({ pageSize: 20, q: props.q }),+ { initialProps: {} as { q?: string }, wrapper },+ );++ hook.rerender({ q: 'foo' });+ await waitFor(() => expect(pendingByQuery.has('foo')).toBe(true));++ await act(async () => {+ pendingByQuery.get('foo')!(listPage([plugin('foo-1')], 1));+ });+ await waitFor(() => expect(ids(useToolStore.getState().mcpPluginList)).toEqual(['foo-1']));++ // The superseded head request settles late.+ await act(async () => {+ pendingByQuery.get('')!(listPage(idsOf(20), 40));+ });++ expect(useToolStore.getState().mcpPluginList).toMatchObject({ q: 'foo', total: 1 });+ expect(ids(useToolStore.getState().mcpPluginList)).toEqual(['foo-1']);+ });++ it('drops the painted page set on reset but keeps the persisted row', async () => {+ fetchSpy.mockResolvedValue(listPage([plugin('a')], 1));++ renderHook(() => useToolStore((s) => s.useFetchMCPPluginList)({ pageSize: 20 }), { wrapper });++ await waitFor(() => expect(ids(useToolStore.getState().mcpPluginList)).toEqual(['a']));+ await waitFor(async () =>+ expect(+ (await mcpPluginListResource.storage!.get({ queryKey: BASE_KEY, scope }))?.data,+ ).toBeDefined(),+ );++ act(() => useToolStore.getState().resetMCPPluginList('gone'));++ expect(useToolStore.getState().mcpPluginList).toBeUndefined();+ expect(useToolStore.getState().mcpSearchKeywords).toBe('gone');+ const row = await mcpPluginListResource.storage!.get({ queryKey: BASE_KEY, scope });+ expect(ids(row?.data as MCPPluginListData)).toEqual(['a']);+ });++ it('does not fetch another page when the head page is the last one', async () => {+ fetchSpy.mockResolvedValue(listPage([plugin('only')], 1));++ const hook = renderHook(+ () => ({+ loadMore: useToolStore((s) => s.loadMoreMCPPlugins),+ sync: useToolStore((s) => s.useFetchMCPPluginList)({ pageSize: 20 }),+ }),+ { wrapper },+ );++ await waitFor(() => expect(useToolStore.getState().mcpPluginList?.items).toHaveLength(1));+ expect(useToolStore.getState().mcpPluginList?.hasMore).toBe(false);++ await act(async () => {+ await hook.result.current.loadMore();+ });++ expect(fetchSpy).toHaveBeenCalledTimes(1);+ });+});diff --git a/src/store/tool/slices/mcpStore/selectors.test.ts b/src/store/tool/slices/mcpStore/selectors.test.tsindex 82521ca7dae..8b1719830f5 100644--- a/src/store/tool/slices/mcpStore/selectors.test.ts+++ b/src/store/tool/slices/mcpStore/selectors.test.ts@@ -5,6 +5,7 @@ import { MCPInstallStep } from '@/types/plugins';import { initialState } from '../../initialState';import { type ToolStoreState } from '../../initialState';+import { type MCPPluginListData } from './initialState';import { mcpStoreSelectors } from './selectors';const createMockPluginItem = (id: string, overrides: Partial<PluginItem> = {}): PluginItem =>@@ -44,9 +45,17 @@ const mockMcpPluginItems: PluginItem[] = [createMockPluginItem('plugin-c'),];+const mockPluginList = (items: PluginItem[]): MCPPluginListData => ({+ currentPage: 0,+ hasMore: false,+ items,+ pageSize: 20,+ total: items.length,+});+const baseState: ToolStoreState = {...initialState,- mcpPluginItems: mockMcpPluginItems,+ mcpPluginList: mockPluginList(mockMcpPluginItems),installedPlugins: [{identifier: 'plugin-a',@@ -105,8 +114,15 @@ describe('mcpStoreSelectors', () => {expect(result).toHaveLength(0);});- it('should return empty array when mcpPluginItems is empty', () => {- const state: ToolStoreState = { ...baseState, mcpPluginItems: [] };+ it('should return empty array when the list has not loaded', () => {+ const state: ToolStoreState = { ...baseState, mcpPluginList: undefined };+ const result = mcpStoreSelectors.mcpPluginList(state);++ expect(result).toHaveLength(0);+ });++ it('should return empty array when the loaded page set is empty', () => {+ const state: ToolStoreState = { ...baseState, mcpPluginList: mockPluginList([]) };const result = mcpStoreSelectors.mcpPluginList(state);expect(result).toHaveLength(0);@@ -241,30 +257,14 @@ describe('mcpStoreSelectors', () => {expect(result).toBeUndefined();});- it('should return undefined when mcpPluginItems is empty', () => {- const state: ToolStoreState = { ...baseState, mcpPluginItems: [] };+ it('should return undefined when the list has not loaded', () => {+ const state: ToolStoreState = { ...baseState, mcpPluginList: undefined };const result = mcpStoreSelectors.getPluginById('plugin-a')(state);expect(result).toBeUndefined();});});- describe('activeMCPPluginIdentifier', () => {- it('should return active MCP plugin identifier when set', () => {- const state: ToolStoreState = { ...baseState, activeMCPIdentifier: 'plugin-a' };- const result = mcpStoreSelectors.activeMCPPluginIdentifier(state);-- expect(result).toBe('plugin-a');- });-- it('should return undefined when no active plugin', () => {- const state: ToolStoreState = { ...baseState, activeMCPIdentifier: undefined };- const result = mcpStoreSelectors.activeMCPPluginIdentifier(state);-- expect(result).toBeUndefined();- });- });-describe('getMCPPluginRequiringConfig', () => {it('should return config schema when plugin requires config', () => {const configSchema = { type: 'object', properties: { apiKey: { type: 'string' } } };diff --git a/src/store/tool/slices/mcpStore/selectors.ts b/src/store/tool/slices/mcpStore/selectors.tsindex 2e32aae073a..7d76299d178 100644--- a/src/store/tool/slices/mcpStore/selectors.ts+++ b/src/store/tool/slices/mcpStore/selectors.ts@@ -2,12 +2,15 @@ import { type InstallPluginMeta } from '@/types/tool/plugin';import { type ToolStoreState } from '../../initialState';+/** The MCP marketplace rows of the loaded page set (empty while un-loaded). */+const loadedPluginItems = (s: ToolStoreState) => s.mcpPluginList?.items ?? [];+const mcpPluginList = (s: ToolStoreState) => {const installedPluginIds = new Set(s.installedPlugins.map((i) => i.identifier));const list =s.listType === 'mcp'- ? s.mcpPluginItems- : s.mcpPluginItems.filter((p) => installedPluginIds.has(p.identifier));+ ? loadedPluginItems(s)+ : loadedPluginItems(s).filter((p) => installedPluginIds.has(p.identifier));return list.map<InstallPluginMeta>((p) => ({author: p.author,@@ -31,11 +34,9 @@ const getMCPInstallProgress = (id: string) => (s: ToolStoreState) => s.mcpInstalconst isMCPInstalling = (id: string) => (s: ToolStoreState) => !!s.mcpInstallProgress[id];const getPluginById = (id: string) => (s: ToolStoreState) => {- return s.mcpPluginItems.find((i) => i.identifier === id);+ return loadedPluginItems(s).find((i) => i.identifier === id);};-const activeMCPPluginIdentifier = (s: ToolStoreState) => s.activeMCPIdentifier;-const getMCPPluginRequiringConfig = (id: string) => (s: ToolStoreState) =>s.mcpInstallProgress[id]?.configSchema;@@ -60,7 +61,6 @@ const getMCPConnectionTestState = (id: string) => (s: ToolStoreState) => ({});export const mcpStoreSelectors = {- activeMCPPluginIdentifier,getMCPConnectionTestError,getMCPConnectionTestState,getMCPInstallProgress,