Skip to content

🤯 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.

♻️ refactor(discover): move community and Skill Store market reads onto @lobechat/replica (#22878)

Arvin Xu09ca9e0a137b
diff --git a/src/features/AgentMarketSubmission/useAgentMarketSubmission.ts b/src/features/AgentMarketSubmission/useAgentMarketSubmission.ts
index d60dc9aade1..eae26f066fd 100644
--- a/src/features/AgentMarketSubmission/useAgentMarketSubmission.ts
+++ b/src/features/AgentMarketSubmission/useAgentMarketSubmission.ts
@@ -8,6 +8,7 @@ import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';
import { lambdaClient } from '@/libs/trpc/client';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
+import { useDiscoverStore } from '@/store/discover';
interface Options {
agentId?: string | null;
@@ -107,6 +108,11 @@ export const useAgentMarketSubmission = ({ agentId, canSubmit, getPrompt }: Opti
}
setSubmittedAgentId(agentId);
setRevision((value) => value + 1);
+ // The header's status / review tags read the Market status replica.
+ void useDiscoverStore
+ .getState()
+ .refreshMarketAgentStatus(result.identifier)
+ .catch(() => undefined);
toast.success(t('marketSubmission.success'));
} catch (error) {
console.error('Failed to submit agent for Market review:', error);
diff --git a/src/features/MCPPluginDetail/Agents.tsx b/src/features/MCPPluginDetail/Agents.tsx
index 4a8a5fee575..7c50fec9d93 100644
--- a/src/features/MCPPluginDetail/Agents.tsx
+++ b/src/features/MCPPluginDetail/Agents.tsx
@@ -2,75 +2,33 @@
import { Center, cssVar, Grid, Icon, Text } from '@lobehub/ui';
import { InboxIcon, ServerCrash } from 'lucide-react';
-import { memo, useCallback, useEffect, useRef, useState } from 'react';
+import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { VirtuosoGrid } from 'react-virtuoso';
import { ArticleSkeleton } from '@/components/Skeleton';
import AgentItem from '@/features/SkillStore/SkillDetail/AgentItem';
+import AgentsFooter, {
+ type AgentsFooterContext,
+} from '@/features/SkillStore/SkillDetail/AgentsFooter';
import { agentListStyles as styles } from '@/features/SkillStore/SkillDetail/style';
-import VirtuosoLoading from '@/features/SkillStore/SkillList/VirtuosoLoading';
-import { useClientDataSWR } from '@/libs/swr';
-import { discoverKeys } from '@/libs/swr/keys';
-import { discoverService } from '@/services/discover';
-import { type DiscoverAssistantItem } from '@/types/discover';
+import { usePluginAgentList } from '@/features/SkillStore/SkillDetail/usePluginAgentList';
import { useDetailContext } from './DetailProvider';
-const PAGE_SIZE = 12;
-
interface AgentsProps {
inModal?: boolean;
}
-const FooterSpacer = () => <div style={{ height: 16 }} />;
-
const Agents = memo<AgentsProps>(({ inModal }) => {
const { t } = useTranslation('discover');
const { identifier } = useDetailContext();
- // Local state for pagination
- const [items, setItems] = useState<DiscoverAssistantItem[]>([]);
- const [currentPage, setCurrentPage] = useState(1);
- const [totalCount, setTotalCount] = useState(0);
- const [isInitialized, setIsInitialized] = useState(false);
- const prevPageRef = useRef(currentPage);
-
- // SWR fetch data (lazy loading - only requests when component mounts)
- const { data, isLoading, error } = useClientDataSWR(
- identifier ? discoverKeys.mcpAgents(identifier, currentPage) : null,
- () =>
- discoverService.getAgentsByPlugin({
- page: currentPage,
- pageSize: PAGE_SIZE,
- pluginId: identifier!,
- }),
- );
-
- // Data accumulation logic
- useEffect(() => {
- if (data) {
- if (currentPage === 1) {
- setItems(data.items);
- } else if (currentPage > prevPageRef.current) {
- setItems((prev) => [...prev, ...data.items]);
- }
- setTotalCount(data.totalCount);
- setIsInitialized(true);
- prevPageRef.current = currentPage;
- }
- }, [data, currentPage]);
-
- const hasMore = items.length < totalCount;
-
- const loadMore = useCallback(() => {
- if (!isLoading && hasMore) {
- setCurrentPage((prev) => prev + 1);
- }
- }, [isLoading, hasMore]);
+ const { error, isEmpty, isInitialLoading, isLoadingMore, items, loadMore, pageError, retry } =
+ usePluginAgentList(identifier);
// Initial loading state
- if (!isInitialized && isLoading) {
+ if (isInitialLoading) {
return (
<Grid gap={12} rows={2} width={'100%'}>
{Array.from({ length: 4 }).map((_, index) => (
@@ -91,7 +49,7 @@ const Agents = memo<AgentsProps>(({ inModal }) => {
}
// Empty state
- if (isInitialized && items.length === 0) {
+ if (isEmpty) {
return (
<Center gap={12} padding={40}>
<Icon color={cssVar.colorTextDescription} icon={InboxIcon} size={80} />
@@ -102,7 +60,8 @@ const Agents = memo<AgentsProps>(({ inModal }) => {
// Use VirtuosoGrid for rendering
return (
- <VirtuosoGrid
+ <VirtuosoGrid<(typeof items)[number], AgentsFooterContext>
+ components={{ Footer: AgentsFooter }}
data={items}
endReached={loadMore}
increaseViewportBy={typeof window !== 'undefined' ? window.innerHeight : 0}
@@ -112,8 +71,11 @@ const Agents = memo<AgentsProps>(({ inModal }) => {
overscan={24}
style={inModal ? { height: '50vh', width: '100%' } : { width: '100%' }}
useWindowScroll={!inModal}
- components={{
- Footer: isLoading ? VirtuosoLoading : FooterSpacer,
+ context={{
+ isLoadingMore,
+ message: t('mcp.details.agents.networkError'),
+ onRetry: retry,
+ pageError,
}}
/>
);
diff --git a/src/features/MCPPluginDetail/Header.tsx b/src/features/MCPPluginDetail/Header.tsx
index d945e29aa68..6199b813473 100644
--- a/src/features/MCPPluginDetail/Header.tsx
+++ b/src/features/MCPPluginDetail/Header.tsx
@@ -31,15 +31,15 @@ import qs from 'query-string';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Link } from 'react-router';
-import useSWR from 'swr';
import OfficialIcon from '@/components/OfficialIcon';
import Scores from '@/features/MCP/Scores';
import { getLanguageColor, getRecommendedDeployment } from '@/features/MCP/utils';
import { useCategory } from '@/hooks/useMCPCategory';
import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';
-import { favoriteKeys } from '@/libs/swr/keys';
import { socialService } from '@/services/social';
+import { useDiscoverStore } from '@/store/discover';
+import { socialSelectors } from '@/store/discover/selectors';
import InstallationIcon from '../../components/MCPDepsIcon';
import PublishedTime from '../../components/PublishedTime';
@@ -93,12 +93,10 @@ const Header = memo<{ inModal?: boolean; mobile?: boolean }>(({ mobile: isMobile
socialService.setAccessToken(session.accessToken);
}
- // Fetch favorite status
- const { data: favoriteStatus, mutate: mutateFavorite } = useSWR(
- identifier && isAuthenticated ? favoriteKeys.status('plugin', identifier) : null,
- () => socialService.checkFavoriteStatus('plugin', identifier!),
- { revalidateOnFocus: false },
- );
+ const useFavoriteStatus = useDiscoverStore((s) => s.useFavoriteStatus);
+ const { queryKey: favoriteKey } = useFavoriteStatus('plugin', identifier, isAuthenticated);
+ const favoriteStatus = useDiscoverStore(socialSelectors.favoriteStatus(favoriteKey));
+ const setFavorite = useDiscoverStore((s) => s.setFavorite);
const isFavorited = favoriteStatus?.isFavorited ?? false;
@@ -112,14 +110,8 @@ const Header = memo<{ inModal?: boolean; mobile?: boolean }>(({ mobile: isMobile
setFavoriteLoading(true);
try {
- if (isFavorited) {
- await socialService.removeFavorite('plugin', identifier);
- toast.success(t('assistant.unfavoriteSuccess'));
- } else {
- await socialService.addFavorite('plugin', identifier);
- toast.success(t('assistant.favoriteSuccess'));
- }
- await mutateFavorite();
+ await setFavorite('plugin', identifier, !isFavorited);
+ toast.success(t(isFavorited ? 'assistant.unfavoriteSuccess' : 'assistant.favoriteSuccess'));
} catch (error) {
console.error('Favorite action failed:', error);
toast.error(t('assistant.favoriteFailed'));
diff --git a/src/features/SkillStore/SkillDetail/Agents.tsx b/src/features/SkillStore/SkillDetail/Agents.tsx
index 896cf75a95f..74c8f2dcb61 100644
--- a/src/features/SkillStore/SkillDetail/Agents.tsx
+++ b/src/features/SkillStore/SkillDetail/Agents.tsx
@@ -2,71 +2,27 @@
import { Center, cssVar, Grid, Icon, Text } from '@lobehub/ui';
import { InboxIcon, ServerCrash } from 'lucide-react';
-import { memo, useCallback, useEffect, useRef, useState } from 'react';
+import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { VirtuosoGrid } from 'react-virtuoso';
import { ArticleSkeleton } from '@/components/Skeleton';
-import { useClientDataSWR } from '@/libs/swr';
-import { discoverKeys } from '@/libs/swr/keys';
-import { discoverService } from '@/services/discover';
-import { type DiscoverAssistantItem } from '@/types/discover';
import AgentItem from './AgentItem';
+import AgentsFooter, { type AgentsFooterContext } from './AgentsFooter';
import { useDetailContext } from './DetailContext';
import { agentListStyles as styles } from './style';
-import VirtuosoLoading from './VirtuosoLoading';
-
-const PAGE_SIZE = 12;
-
-const FooterSpacer = () => <div style={{ height: 16 }} />;
+import { usePluginAgentList } from './usePluginAgentList';
const Agents = memo(() => {
const { t } = useTranslation('plugin');
const { identifier } = useDetailContext();
- // Local state for pagination
- const [items, setItems] = useState<DiscoverAssistantItem[]>([]);
- const [currentPage, setCurrentPage] = useState(1);
- const [totalCount, setTotalCount] = useState(0);
- const [isInitialized, setIsInitialized] = useState(false);
- const prevPageRef = useRef(currentPage);
-
- // SWR fetch data (lazy loading - only requests when component mounts)
- const { data, isLoading, error } = useClientDataSWR(
- identifier ? discoverKeys.skillAgents(identifier, currentPage) : null,
- () =>
- discoverService.getAgentsByPlugin({
- page: currentPage,
- pageSize: PAGE_SIZE,
- pluginId: identifier,
- }),
- );
-
- // Data accumulation logic
- useEffect(() => {
- if (data) {
- if (currentPage === 1) {
- setItems(data.items);
- } else if (currentPage > prevPageRef.current) {
- setItems((prev) => [...prev, ...data.items]);
- }
- setTotalCount(data.totalCount);
- setIsInitialized(true);
- prevPageRef.current = currentPage;
- }
- }, [data, currentPage]);
-
- const hasMore = items.length < totalCount;
-
- const loadMore = useCallback(() => {
- if (!isLoading && hasMore) {
- setCurrentPage((prev) => prev + 1);
- }
- }, [isLoading, hasMore]);
+ const { error, isEmpty, isInitialLoading, isLoadingMore, items, loadMore, pageError, retry } =
+ usePluginAgentList(identifier);
// Initial loading state
- if (!isInitialized && isLoading) {
+ if (isInitialLoading) {
return (
<Grid gap={12} rows={2} width={'100%'}>
{Array.from({ length: 4 }).map((_, index) => (
@@ -87,7 +43,7 @@ const Agents = memo(() => {
}
// Empty state
- if (isInitialized && items.length === 0) {
+ if (isEmpty) {
return (
<Center gap={12} padding={40}>
<Icon color={cssVar.colorTextDescription} icon={InboxIcon} size={80} />
@@ -98,7 +54,9 @@ const Agents = memo(() => {
// Use VirtuosoGrid for rendering
return (
- <VirtuosoGrid
+ <VirtuosoGrid<(typeof items)[number], AgentsFooterContext>
+ components={{ Footer: AgentsFooter }}
+ context={{ isLoadingMore, message: t('skillDetail.networkError'), onRetry: retry, pageError }}
data={items}
endReached={loadMore}
increaseViewportBy={typeof window !== 'undefined' ? window.innerHeight : 0}
@@ -107,9 +65,6 @@ const Agents = memo(() => {
listClassName={styles.list}
overscan={24}
style={{ height: '50vh', width: '100%' }}
- components={{
- Footer: isLoading ? VirtuosoLoading : FooterSpacer,
- }}
/>
);
});
diff --git a/src/features/SkillStore/SkillDetail/AgentsFooter.tsx b/src/features/SkillStore/SkillDetail/AgentsFooter.tsx
new file mode 100644
index 00000000000..61035dbd96d
--- /dev/null
+++ b/src/features/SkillStore/SkillDetail/AgentsFooter.tsx
@@ -0,0 +1,35 @@
+'use client';
+
+import { Button, Flexbox, Text } from '@lobehub/ui';
+import { useTranslation } from 'react-i18next';
+
+import VirtuosoLoading from './VirtuosoLoading';
+
+/** What the "agents using this plugin" grid footer needs, passed as Virtuoso `context`. */
+export interface AgentsFooterContext {
+ isLoadingMore: boolean;
+ /** Copy shown beside Retry when a later page failed. */
+ message: string;
+ onRetry: () => void;
+ pageError?: unknown;
+}
+
+/**
+ * Footer of the agents grids: a spinner while the next page loads, and an
+ * inline retry when a later page failed, so the loaded agents stay on screen.
+ */
+const AgentsFooter = ({ context }: { context?: AgentsFooterContext }) => {
+ const { t } = useTranslation('common');
+
+ if (context?.isLoadingMore) return <VirtuosoLoading />;
+ if (context?.pageError)
+ return (
+ <Flexbox horizontal align={'center'} gap={8} justify={'center'} padding={16}>
+ <Text type={'secondary'}>{context.message}</Text>
+ <Button onClick={context.onRetry}>{t('retry')}</Button>
+ </Flexbox>
+ );
+ return <div style={{ height: 16 }} />;
+};
+
+export default AgentsFooter;
diff --git a/src/features/SkillStore/SkillDetail/usePluginAgentList.test.ts b/src/features/SkillStore/SkillDetail/usePluginAgentList.test.ts
new file mode 100644
index 00000000000..166f0aec6c2
--- /dev/null
+++ b/src/features/SkillStore/SkillDetail/usePluginAgentList.test.ts
@@ -0,0 +1,166 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * "Agents using this plugin / skill" reads one replica entry per page,
+ * persisted to IndexedDB: reopening a detail paints the last confirmed first
+ * page before the network answers. A hydrated empty page is not proof of "no
+ * agents" until the server confirms it, and a failed refresh keeps the agents.
+ */
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { discoverService } from '@/services/discover';
+import {
+ deferred,
+ pending,
+ replicaWrapper as wrapper,
+ useReplicaHarness,
+} from '@/store/discover/__tests__/replicaHarness';
+import { pluginAgentsParams } from '@/store/discover/slices/market/action';
+import { pluginAgentsQueryKey } from '@/store/discover/slices/market/projection';
+import { globalHelpers } from '@/store/global/helpers';
+
+import { usePluginAgentList } from './usePluginAgentList';
+
+const page = (titles: string[], totalCount = titles.length) => ({
+ currentPage: 1,
+ items: titles.map((title) => ({ identifier: title, title })),
+ pageSize: 12,
+ totalCount,
+ totalPages: 1,
+});
+
+const pageKey = (pluginId: string, n = 1) => pluginAgentsQueryKey(pluginAgentsParams(pluginId, n));
+const titles = (items: { title?: string }[]) => items.map((item) => item.title);
+
+describe('usePluginAgentList', () => {
+ const { persist } = useReplicaHarness('plugin-agents');
+
+ it('paints the persisted first page before the network answers, then refreshes it', async () => {
+ await persist('discoverPluginAgents', pageKey('web-search'), page(['Cached agent']));
+ const next = deferred<unknown>();
+ vi.spyOn(discoverService, 'getAgentsByPlugin').mockImplementation(() => next.promise as never);
+
+ const { result } = renderHook(() => usePluginAgentList('web-search'), { wrapper });
+
+ await waitFor(() => expect(titles(result.current.items)).toEqual(['Cached agent']));
+ expect(result.current.isInitialLoading).toBe(false);
+
+ await act(async () => next.resolve(page(['Fresh agent'])));
+ await waitFor(() => expect(titles(result.current.items)).toEqual(['Fresh agent']));
+ });
+
+ it('keeps loading over a hydrated empty page until the server confirms it', async () => {
+ await persist('discoverPluginAgents', pageKey('web-search'), page([]));
+ const next = deferred<unknown>();
+ vi.spyOn(discoverService, 'getAgentsByPlugin').mockImplementation(() => next.promise as never);
+
+ const { result } = renderHook(() => usePluginAgentList('web-search'), { wrapper });
+
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(result.current.isEmpty).toBe(false);
+ expect(result.current.isInitialLoading).toBe(true);
+
+ await act(async () => next.resolve(page([])));
+ await waitFor(() => expect(result.current.isEmpty).toBe(true));
+ expect(result.current.isInitialLoading).toBe(false);
+ });
+
+ it('keeps the agents when a refresh fails', async () => {
+ await persist('discoverPluginAgents', pageKey('web-search'), page(['Cached agent']));
+ const fetch = vi
+ .spyOn(discoverService, 'getAgentsByPlugin')
+ .mockRejectedValue(new Error('network down'));
+
+ const { result } = renderHook(() => usePluginAgentList('web-search'), { wrapper });
+
+ await waitFor(() => expect(fetch).toHaveBeenCalled());
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(titles(result.current.items)).toEqual(['Cached agent']);
+ expect(result.current.error).toBeUndefined();
+ });
+
+ it('walks to the next page and appends it', async () => {
+ vi.spyOn(discoverService, 'getAgentsByPlugin').mockImplementation(
+ async ({ page: n }) => page([`Agent ${n}`], 2) as never,
+ );
+
+ const { result } = renderHook(() => usePluginAgentList('web-search'), { wrapper });
+ await waitFor(() => expect(titles(result.current.items)).toEqual(['Agent 1']));
+
+ act(() => result.current.loadMore());
+ await waitFor(() => expect(titles(result.current.items)).toEqual(['Agent 1', 'Agent 2']));
+ });
+
+ it('keeps the agents and offers a retry when a later page fails', async () => {
+ let fail = true;
+ vi.spyOn(discoverService, 'getAgentsByPlugin').mockImplementation(async ({ page: n }) => {
+ if (n === 2 && fail) throw new Error('rate limited');
+ return page([`Agent ${n}`], 2) as never;
+ });
+
+ const { result } = renderHook(() => usePluginAgentList('web-search'), { wrapper });
+ await waitFor(() => expect(titles(result.current.items)).toEqual(['Agent 1']));
+
+ act(() => result.current.loadMore());
+ await waitFor(() => expect(result.current.pageError).toBeInstanceOf(Error));
+ expect(titles(result.current.items)).toEqual(['Agent 1']);
+ expect(result.current.error).toBeUndefined();
+
+ fail = false;
+ act(() => result.current.retry());
+ await waitFor(() => expect(titles(result.current.items)).toEqual(['Agent 1', 'Agent 2']));
+ expect(result.current.pageError).toBeUndefined();
+ });
+
+ it('starts another plugin from its first page', async () => {
+ vi.spyOn(discoverService, 'getAgentsByPlugin').mockImplementation(
+ async ({ page: n, pluginId }) => page([`${pluginId} ${n}`], 2) as never,
+ );
+
+ const { rerender, result } = renderHook(({ id }) => usePluginAgentList(id), {
+ initialProps: { id: 'web-search' },
+ wrapper,
+ });
+ await waitFor(() => expect(result.current.items).toHaveLength(1));
+ act(() => result.current.loadMore());
+ await waitFor(() => expect(result.current.items).toHaveLength(2));
+
+ rerender({ id: 'calculator' });
+ await waitFor(() => expect(titles(result.current.items)).toEqual(['calculator 1']));
+ });
+
+ it('starts again from the first page when the UI language changes', async () => {
+ let locale = 'en-US';
+ vi.spyOn(globalHelpers, 'getCurrentLanguage').mockImplementation(() => locale as never);
+ vi.spyOn(discoverService, 'getAgentsByPlugin').mockImplementation(
+ async ({ page: n }) => page([`${locale} ${n}`], 2) as never,
+ );
+
+ const { rerender, result } = renderHook(() => usePluginAgentList('web-search'), { wrapper });
+ await waitFor(() => expect(result.current.items).toHaveLength(1));
+ act(() => result.current.loadMore());
+ await waitFor(() => expect(result.current.items).toHaveLength(2));
+
+ locale = 'zh-CN';
+ rerender();
+ await waitFor(() => expect(titles(result.current.items)).toEqual(['zh-CN 1']));
+ expect(result.current.isInitialLoading).toBe(false);
+ });
+
+ it("never paints another identity's agents", async () => {
+ await persist(
+ 'discoverPluginAgents',
+ pageKey('web-search'),
+ page(['Theirs']),
+ 'someone-else:personal',
+ );
+ vi.spyOn(discoverService, 'getAgentsByPlugin').mockImplementation(pending);
+
+ const { result } = renderHook(() => usePluginAgentList('web-search'), { wrapper });
+
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(result.current.items).toEqual([]);
+ expect(result.current.isInitialLoading).toBe(true);
+ });
+});
diff --git a/src/features/SkillStore/SkillDetail/usePluginAgentList.ts b/src/features/SkillStore/SkillDetail/usePluginAgentList.ts
new file mode 100644
index 00000000000..74f8f89d2f3
--- /dev/null
+++ b/src/features/SkillStore/SkillDetail/usePluginAgentList.ts
@@ -0,0 +1,81 @@
+import { useCallback, useMemo, useState } from 'react';
+
+import { useDiscoverStore } from '@/store/discover';
+import { marketSelectors } from '@/store/discover/selectors';
+import { pluginAgentsParams } from '@/store/discover/slices/market/action';
+import { pluginAgentsQueryKey } from '@/store/discover/slices/market/projection';
+import { globalHelpers } from '@/store/global/helpers';
+import { type DiscoverAssistantItem } from '@/types/discover';
+
+const pageKey = (pluginId: string, page: number) =>
+ pluginAgentsQueryKey(pluginAgentsParams(pluginId, page));
+
+/**
+ * The agents that use a plugin or skill, walked page by page. Every page is a
+ * replica entry, so reopening a detail paints the last confirmed first page
+ * before the network answers; later pages load as the grid scrolls.
+ */
+export const usePluginAgentList = (pluginId: string | undefined) => {
+ // Pages walked so far, owned by the plugin and UI language they were walked
+ // for: either changing starts again from the first page in the same render
+ // (each language is its own set of entries, so a later page alone would
+ // never paint).
+ const locale = globalHelpers.getCurrentLanguage();
+ const [walked, setWalked] = useState({ locale, pageCount: 1, pluginId });
+ const pageCount = walked.pluginId === pluginId && walked.locale === locale ? walked.pageCount : 1;
+
+ const usePluginAgents = useDiscoverStore((s) => s.usePluginAgents);
+ const { error, revalidate } = usePluginAgents(pluginId, pageCount);
+
+ // Rows of every loaded page in order, up to the first page without a value,
+ // so a gap never renders out of order.
+ const pluginAgentsMap = useDiscoverStore((s) => s.pluginAgentsMap);
+ const { items, loadedPages, totalCount } = useMemo(() => {
+ const rows: DiscoverAssistantItem[] = [];
+ let loaded = 0;
+ let total: number | undefined;
+ if (!pluginId) return { items: rows, loadedPages: loaded, totalCount: total };
+ for (let page = 1; page <= pageCount; page++) {
+ const entry = pluginAgentsMap[pageKey(pluginId, page)];
+ if (!entry) break;
+ rows.push(...entry.items);
+ loaded = page;
+ total = entry.totalCount;
+ }
+ return { items: rows, loadedPages: loaded, totalCount: total };
+ }, [pluginAgentsMap, pluginId, pageCount]);
+
+ const isConfirmed = useDiscoverStore(
+ marketSelectors.isPluginAgentsConfirmed(pluginId ? pageKey(pluginId, 1) : undefined),
+ );
+
+ const hasMore = totalCount !== undefined && items.length < totalCount;
+ const isPageLoading = loadedPages < pageCount && !error;
+
+ const loadMore = useCallback(() => {
+ // A failing page is retried explicitly, not by the scroll observer.
+ if (isPageLoading || error || !hasMore) return;
+ setWalked({ locale, pageCount: pageCount + 1, pluginId });
+ }, [error, hasMore, isPageLoading, locale, pageCount, pluginId]);
+
+ const retry = useCallback(() => {
+ void revalidate();
+ }, [revalidate]);
+
+ return {
+ /** Only a failure with nothing to show takes over the grid. */
+ error: items.length === 0 ? error : undefined,
+ isEmpty: items.length === 0 && isConfirmed && loadedPages > 0,
+ /**
+ * Nothing to paint yet. A hydrated empty first page is not proof of "no
+ * agents" until the server confirms it, so it stays in loading too.
+ */
+ isInitialLoading: items.length === 0 && !error && (!isConfirmed || loadedPages === 0),
+ isLoadingMore: items.length > 0 && isPageLoading,
+ items,
+ loadMore,
+ /** A page failed while rows are on screen: keep them and offer an inline retry. */
+ pageError: items.length > 0 ? error : undefined,
+ retry,
+ };
+};
diff --git a/src/features/SkillStore/SkillList/MarketSkills/MarketSkillDetail.tsx b/src/features/SkillStore/SkillList/MarketSkills/MarketSkillDetail.tsx
index c9132283671..511a982e689 100644
--- a/src/features/SkillStore/SkillList/MarketSkills/MarketSkillDetail.tsx
+++ b/src/features/SkillStore/SkillList/MarketSkills/MarketSkillDetail.tsx
@@ -3,18 +3,16 @@
import { type SkillResourceTreeNode } from '@lobechat/types';
import { Github } from '@lobehub/icons';
import { ActionIcon, Avatar, createStaticStyles, cssVar, Flexbox, Icon } from '@lobehub/ui';
-import { unzip } from 'fflate';
import { DotIcon, ExternalLinkIcon } from 'lucide-react';
-import { memo, useEffect, useMemo, useState } from 'react';
+import { memo, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import PublishedTime from '@/components/PublishedTime';
import { ArticleSkeleton } from '@/components/Skeleton';
import ContentViewer from '@/features/AgentSkillDetail/ContentViewer';
import FileTree from '@/features/FileTree';
-import { marketApiService } from '@/services/marketApi';
import { useDiscoverStore } from '@/store/discover';
-import { skillSelectors } from '@/store/discover/selectors';
+import { marketSelectors, skillSelectors } from '@/store/discover/selectors';
import { useToolStore } from '@/store/tool';
import { agentSkillsSelectors } from '@/store/tool/selectors';
import { type DiscoverSkillDetail as DiscoverSkillDetailType } from '@/types/discover';
@@ -92,47 +90,6 @@ const buildMarketResourceTree = (
}));
};
-/**
- * Fetch zip from downloadUrl and extract text file contents
- */
-const fetchZipContents = async (
- url: string,
-): Promise<{ contentMap: Record<string, string>; tree: SkillResourceTreeNode[] }> => {
- const res = await fetch(url);
- const buf = await res.arrayBuffer();
-
- return new Promise((resolve, reject) => {
- unzip(new Uint8Array(buf), (err, files) => {
- if (err) return reject(err);
-
- const contentMap: Record<string, string> = {};
- const tree: SkillResourceTreeNode[] = [];
- const decoder = new TextDecoder();
-
- for (const [rawPath, data] of Object.entries(files)) {
- if (rawPath.endsWith('/') || rawPath.includes('__MACOSX')) continue;
-
- // Strip the top-level directory prefix (e.g. "skill-name/")
- const slashIdx = rawPath.indexOf('/');
- const path = slashIdx >= 0 ? rawPath.slice(slashIdx + 1) : rawPath;
- if (!path || path === 'SKILL.md') continue;
-
- const content = decoder.decode(data);
- contentMap[path] = content;
- tree.push({
- content,
- name: path.split('/').pop() || path,
- path,
- type: 'file',
- });
- }
-
- tree.sort((a, b) => a.path.localeCompare(b.path));
- resolve({ contentMap, tree });
- });
- });
-};
-
const MarketSkillDetail = memo<MarketSkillDetailProps>(({ identifier }) => {
const { t } = useTranslation('setting');
const [selectedFile, setSelectedFile] = useState('SKILL.md');
@@ -148,24 +105,21 @@ const MarketSkillDetail = memo<MarketSkillDetailProps>(({ identifier }) => {
installedSkill?.id,
);
- // Zip-based content for uninstalled skills
- const [zipContentMap, setZipContentMap] = useState<Record<string, string>>({});
- const [zipTree, setZipTree] = useState<SkillResourceTreeNode[]>([]);
-
- const downloadUrl = marketApiService.getSkillDownloadUrl(encodeURIComponent(identifier));
-
- useEffect(() => {
- if (installedSkill) return;
-
- fetchZipContents(downloadUrl)
- .then(({ contentMap, tree }) => {
- setZipContentMap(contentMap);
- setZipTree(tree);
- })
- .catch(() => {
- // fall back to metadata-only view
- });
- }, [downloadUrl, installedSkill]);
+ // Package files of an uninstalled skill, kept in a replica so a reopened
+ // detail paints its file tree without downloading the zip again. A failed
+ // download falls back to the metadata-only view.
+ const useSkillPackageFiles = useDiscoverStore((s) => s.useSkillPackageFiles);
+ const { queryKey: packageFilesKey } = useSkillPackageFiles(identifier, !installedSkill);
+ const packageFiles = useDiscoverStore(marketSelectors.skillPackageFiles(packageFilesKey));
+ const { zipContentMap, zipTree } = useMemo(() => {
+ const contentMap: Record<string, string> = {};
+ const tree: SkillResourceTreeNode[] = [];
+ for (const { content, path } of packageFiles ?? []) {
+ contentMap[path] = content;
+ tree.push({ content, name: path.split('/').pop() || path, path, type: 'file' });
+ }
+ return { zipContentMap: contentMap, zipTree: tree };
+ }, [packageFiles]);
const installedResourceTree = useMemo(
() => installedData?.resourceTree ?? [],
diff --git a/src/features/SkillStore/SkillList/MarketSkills/index.tsx b/src/features/SkillStore/SkillList/MarketSkills/index.tsx
index a30faa7f00a..223b45c26e1 100644
--- a/src/features/SkillStore/SkillList/MarketSkills/index.tsx
+++ b/src/features/SkillStore/SkillList/MarketSkills/index.tsx
@@ -28,7 +28,7 @@ const MarketSkillList = memo<MarketSkillListProps>(({ keywords }) => {
const useFetchAgentSkills = useToolStore((s) => s.useFetchAgentSkills);
useFetchAgentSkills(true);
- const { error, isLoading, items, loadMore, page, retry, totalPages } =
+ const { error, isConfirmed, isLoading, items, loadMore, page, retry, totalPages } =
useMarketSkillList(keywords);
// A rate limit is not a network error, and saying so sends the user off
@@ -38,7 +38,8 @@ const MarketSkillList = memo<MarketSkillListProps>(({ keywords }) => {
? t('skillStore.rateLimited')
: t('skillStore.networkError');
- if (isLoading && items.length === 0) return <Loading />;
+ // A hydrated empty first page is not "no skills" until the server confirms it.
+ if (items.length === 0 && !error && (isLoading || !isConfirmed)) return <Loading />;
// Only take over the whole surface when there is nothing to show. Once pages
// have loaded, a failed *next* page must not wipe them.
diff --git a/src/features/SkillStore/SkillList/MarketSkills/useMarketSkillList.replica.test.ts b/src/features/SkillStore/SkillList/MarketSkills/useMarketSkillList.replica.test.ts
new file mode 100644
index 00000000000..9c35368583c
--- /dev/null
+++ b/src/features/SkillStore/SkillList/MarketSkills/useMarketSkillList.replica.test.ts
@@ -0,0 +1,107 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The Skill Store's market tab reads the discover `skillList` replica: a
+ * reopened store paints the last confirmed first page before the network
+ * answers, a hydrated empty page is not confirmed until the server answers,
+ * and a failed refresh keeps the skills on screen.
+ */
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { stableQueryKey } from '@/libs/replica';
+import { discoverService } from '@/services/discover';
+import {
+ deferred,
+ pending,
+ replicaWrapper as wrapper,
+ useReplicaHarness,
+} from '@/store/discover/__tests__/replicaHarness';
+import { SkillSorts } from '@/types/discover';
+
+import { useMarketSkillList } from './useMarketSkillList';
+
+vi.mock('@/store/global/helpers', () => ({
+ globalHelpers: { getCurrentLanguage: () => 'en-US' },
+}));
+
+const response = (identifiers: string[]) => ({
+ currentPage: 1,
+ items: identifiers.map((identifier) => ({ identifier })),
+ pageSize: 20,
+ totalCount: identifiers.length,
+ totalPages: 1,
+});
+
+// Entry key of the first page: the market query plus the UI language.
+const firstPageKey = (q?: string) =>
+ stableQueryKey({ locale: 'en-US', page: 1, pageSize: 20, q, sort: SkillSorts.InstallCount });
+
+describe('useMarketSkillList (replica)', () => {
+ const { persist } = useReplicaHarness('skill-store');
+
+ it('paints the persisted first page before the network answers, then refreshes it', async () => {
+ await persist('skillList', firstPageKey(), response(['cached-skill']));
+ const next = deferred<unknown>();
+ vi.spyOn(discoverService, 'getSkillList').mockImplementation(() => next.promise as never);
+
+ const { result } = renderHook(() => useMarketSkillList(), { wrapper });
+
+ await waitFor(() => expect(result.current.items[0]?.identifier).toBe('cached-skill'));
+ expect(result.current.isLoading).toBe(false);
+
+ await act(async () => next.resolve(response(['fresh-skill'])));
+ await waitFor(() => expect(result.current.items[0]?.identifier).toBe('fresh-skill'));
+ expect(result.current.isConfirmed).toBe(true);
+ });
+
+ it('treats a hydrated empty page as unconfirmed until the server answers', async () => {
+ await persist('skillList', firstPageKey(), response([]));
+ const next = deferred<unknown>();
+ vi.spyOn(discoverService, 'getSkillList').mockImplementation(() => next.promise as never);
+
+ const { result } = renderHook(() => useMarketSkillList(), { wrapper });
+
+ await waitFor(() => expect(result.current.page).toBe(1));
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(result.current.items).toEqual([]);
+ expect(result.current.isConfirmed).toBe(false);
+
+ await act(async () => next.resolve(response([])));
+ await waitFor(() => expect(result.current.isConfirmed).toBe(true));
+ });
+
+ it('keeps the persisted skills when a refresh fails', async () => {
+ await persist('skillList', firstPageKey(), response(['cached-skill']));
+ vi.spyOn(discoverService, 'getSkillList').mockRejectedValue(new Error('rate limited'));
+
+ const { result } = renderHook(() => useMarketSkillList(), { wrapper });
+
+ await waitFor(() => expect(result.current.error).toBeInstanceOf(Error));
+ expect(result.current.items[0]?.identifier).toBe('cached-skill');
+ });
+
+ it("never paints another identity's skills", async () => {
+ await persist('skillList', firstPageKey(), response(['theirs']), 'someone-else:personal');
+ vi.spyOn(discoverService, 'getSkillList').mockImplementation(pending);
+
+ const { result } = renderHook(() => useMarketSkillList(), { wrapper });
+
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(result.current.items).toEqual([]);
+ expect(result.current.isLoading).toBe(true);
+ });
+
+ it('sends one request when the store tabs read the same page', async () => {
+ const getSkillList = vi
+ .spyOn(discoverService, 'getSkillList')
+ .mockResolvedValue(response(['shared']) as never);
+
+ const { result } = renderHook(() => [useMarketSkillList(), useMarketSkillList()], {
+ wrapper,
+ });
+
+ await waitFor(() => expect(result.current[1].items[0]?.identifier).toBe('shared'));
+ expect(getSkillList).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/features/SkillStore/SkillList/MarketSkills/useMarketSkillList.test.ts b/src/features/SkillStore/SkillList/MarketSkills/useMarketSkillList.test.ts
index cb27b1c41e6..f8dd062f93e 100644
--- a/src/features/SkillStore/SkillList/MarketSkills/useMarketSkillList.test.ts
+++ b/src/features/SkillStore/SkillList/MarketSkills/useMarketSkillList.test.ts
@@ -10,7 +10,10 @@ import { useMarketSkillList } from './useMarketSkillList';
vi.mock('@/libs/swr', async () => ({ useClientDataSWR: (await import('swr')).default }));
vi.mock('@/services/discover', () => ({ discoverService: { getSkillList: vi.fn() } }));
-vi.mock('@/store/global/helpers', () => ({ globalHelpers: { getCurrentLanguage: () => 'en-US' } }));
+const ui = vi.hoisted(() => ({ locale: 'en-US' }));
+vi.mock('@/store/global/helpers', () => ({
+ globalHelpers: { getCurrentLanguage: () => ui.locale },
+}));
const response = (identifier: string, page = 1, totalPages = 1) => ({
currentPage: page,
@@ -33,6 +36,7 @@ const wrapper = () => {
describe('useMarketSkillList', () => {
beforeEach(() => {
+ ui.locale = 'en-US';
vi.mocked(discoverService.getSkillList).mockReset();
});
@@ -70,6 +74,25 @@ describe('useMarketSkillList', () => {
expect(result.current.page).toBe(1);
});
+ it('starts again from the first page when the UI language changes', async () => {
+ vi.mocked(discoverService.getSkillList).mockImplementation(
+ async (params) => response(`${ui.locale}-${params?.page}`, params?.page, 2) as any,
+ );
+ const { result, rerender } = renderHook(() => useMarketSkillList('meeting'), {
+ wrapper: wrapper(),
+ });
+ await waitFor(() => expect(result.current.items).toHaveLength(1));
+ act(() => result.current.loadMore());
+ await waitFor(() => expect(result.current.items).toHaveLength(2));
+
+ ui.locale = 'zh-CN';
+ rerender();
+ await waitFor(() =>
+ expect(result.current.items.map((item) => item.identifier)).toEqual(['zh-CN-1']),
+ );
+ expect(result.current.page).toBe(1);
+ });
+
it('keeps loaded items after a next-page failure and recovers through retry', async () => {
let fail = true;
vi.mocked(discoverService.getSkillList).mockImplementation(async (params) => {
diff --git a/src/features/SkillStore/SkillList/MarketSkills/useMarketSkillList.ts b/src/features/SkillStore/SkillList/MarketSkills/useMarketSkillList.ts
index 230a6adbaf4..01def938b05 100644
--- a/src/features/SkillStore/SkillList/MarketSkills/useMarketSkillList.ts
+++ b/src/features/SkillStore/SkillList/MarketSkills/useMarketSkillList.ts
@@ -1,71 +1,80 @@
import { uniqBy } from 'es-toolkit/compat';
-import { useCallback, useEffect, useRef, useState } from 'react';
+import { useCallback, useMemo, useState } from 'react';
-import { useClientDataSWR } from '@/libs/swr';
-import { discoverKeys } from '@/libs/swr/keys';
-import { discoverService } from '@/services/discover';
+import { useDiscoverStore } from '@/store/discover';
+import { normalizeSkillListParams } from '@/store/discover/slices/skill/action';
+import { skillListQueryKey } from '@/store/discover/slices/skill/projection';
import { globalHelpers } from '@/store/global/helpers';
-import { type DiscoverSkillItem, SkillSorts } from '@/types/discover';
+import { type DiscoverSkillItem, type SkillQueryParams, SkillSorts } from '@/types/discover';
// All store tabs stay mounted. Deduplicate reopening the modal to avoid rate limits.
const MARKET_SKILL_LIST_DEDUPING_INTERVAL = 60_000;
+const PAGE_SIZE = 20;
-export const useMarketSkillList = (keywords?: string) => {
- // Market skills pagination state
- const [page, setPage] = useState(1);
- const [items, setItems] = useState<DiscoverSkillItem[]>([]);
- const [totalPages, setTotalPages] = useState<number>();
+const pageParams = (q: string | undefined, page: number): SkillQueryParams => ({
+ page,
+ pageSize: PAGE_SIZE,
+ q,
+ sort: SkillSorts.InstallCount,
+});
+/**
+ * The Skill Store's market tab, read from the discover `skillList` replica.
+ * Each (search term · page) is one entry, so reopening the store paints the
+ * last confirmed first page before the network answers, and the community
+ * skill list and the store share one cache of the same endpoint.
+ */
+export const useMarketSkillList = (keywords?: string) => {
+ const q = keywords || undefined;
+ // Pages walked so far, owned by the search term and UI language they were
+ // walked for: either changing starts again from the first page in the same
+ // render (each language is its own set of entries).
const locale = globalHelpers.getCurrentLanguage();
- const { data, isLoading, error, mutate } = useClientDataSWR(
- discoverKeys.skillStoreMarketSkills(locale, keywords || '', page),
- () =>
- discoverService.getSkillList({
- page,
- pageSize: 20,
- q: keywords || undefined,
- sort: SkillSorts.InstallCount,
- }),
- {
- dedupingInterval: MARKET_SKILL_LIST_DEDUPING_INTERVAL,
- revalidateOnFocus: false,
- },
- );
+ const [walked, setWalked] = useState({ locale, page: 1, q });
+ const page = walked.q === q && walked.locale === locale ? walked.page : 1;
- const prevKeywordsRef = useRef(keywords);
- useEffect(() => {
- if (prevKeywordsRef.current !== keywords) {
- // A cached first page may never revalidate. Reset pagination and apply its
- // data together so a later reset cannot erase the cached search results.
- prevKeywordsRef.current = keywords;
- setPage(1);
- setItems(page === 1 ? data?.items || [] : []);
- setTotalPages(page === 1 ? data?.totalPages : undefined);
- return;
+ const useFetchSkillList = useDiscoverStore((s) => s.useFetchSkillList);
+ const { error, revalidate } = useFetchSkillList(pageParams(q, page), {
+ dedupingInterval: MARKET_SKILL_LIST_DEDUPING_INTERVAL,
+ revalidateOnFocus: false,
+ });
+
+ const skillListMap = useDiscoverStore((s) => s.skillListMap);
+ const { items, loadedPages, totalPages } = useMemo(() => {
+ let rows: DiscoverSkillItem[] = [];
+ let loaded = 0;
+ let total: number | undefined;
+ for (let p = 1; p <= page; p++) {
+ const entry = skillListMap[skillListQueryKey(normalizeSkillListParams(pageParams(q, p)))];
+ if (!entry) break;
+ rows = p === 1 ? entry.items : uniqBy([...rows, ...entry.items], (i) => i.identifier);
+ loaded = p;
+ total = entry.totalPages;
}
+ return { items: rows, loadedPages: loaded, totalPages: total };
+ }, [page, q, skillListMap]);
- if (!data) return;
- setTotalPages(data.totalPages);
+ const firstPageKey = skillListQueryKey(normalizeSkillListParams(pageParams(q, 1)));
+ // A hydrated first page may be stale or empty; "no skills" is only shown once
+ // the server has answered it in this session.
+ const isConfirmed = useDiscoverStore(
+ (s) => s.skillListReplica.entries[firstPageKey]?.source === 'server',
+ );
- if (page === 1) {
- setItems(data.items);
- } else {
- setItems((prev) => uniqBy([...prev, ...data.items], (i) => i.identifier));
- }
- }, [data, keywords, page]);
+ const isLoading = loadedPages < page && !error;
const loadMore = useCallback(() => {
// Don't let the scroll observer walk into the next page while the current
// one is still failing — that turns a rate limit into a silent retry loop.
if (error || isLoading) return;
- if (totalPages === undefined || page < totalPages) {
- setPage((p) => p + 1);
+ if (totalPages === undefined || loadedPages < totalPages) {
+ setWalked({ locale, page: loadedPages + 1, q });
}
- }, [error, isLoading, page, totalPages]);
+ }, [error, isLoading, loadedPages, locale, q, totalPages]);
const retry = useCallback(() => {
- void mutate();
- }, [mutate]);
+ void revalidate();
+ }, [revalidate]);
- return { error, isLoading, items, loadMore, page, retry, totalPages };
+ return { error, isConfirmed, isLoading, items, loadMore, page, retry, totalPages };
};
diff --git a/src/layout/AuthProvider/MarketAuth/MarketAuthProvider.tsx b/src/layout/AuthProvider/MarketAuth/MarketAuthProvider.tsx
index 9c122fedc46..d171e7d8825 100644
--- a/src/layout/AuthProvider/MarketAuth/MarketAuthProvider.tsx
+++ b/src/layout/AuthProvider/MarketAuth/MarketAuthProvider.tsx
@@ -4,11 +4,11 @@ import { toast } from '@lobehub/ui';
import { type ReactNode } from 'react';
import { createContext, lazy, Suspense, use, useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { mutate as globalMutate } from 'swr';
import { useSingleton } from '@/hooks/useSingleton';
import { lambdaClient } from '@/libs/trpc/client';
import { MARKET_OIDC_ENDPOINTS } from '@/services/_url';
+import { useDiscoverStore } from '@/store/discover';
import { useServerConfigStore } from '@/store/serverConfig';
import { serverConfigSelectors } from '@/store/serverConfig/selectors';
import { useUserStore } from '@/store/user';
@@ -601,10 +601,8 @@ export const MarketAuthProvider = ({ children, isDesktop }: MarketAuthProviderPr
setPendingClaimSuccessCallback(null);
}
- // Also refresh all user-profile related SWR cache as fallback
- globalMutate((key) => typeof key === 'string' && key.startsWith('user-profile'), undefined, {
- revalidate: true,
- });
+ // Also refresh the community profiles on screen as fallback
+ void useDiscoverStore.getState().refreshUserProfiles();
}, [pendingClaimSuccessCallback]);
/**
@@ -794,27 +792,18 @@ export const MarketAuthProvider = ({ children, isDesktop }: MarketAuthProviderPr
// Get current user's profile for the edit modal
const userInfo = session?.userInfo;
const username = userInfo?.sub;
- const { data: userProfile, mutate: mutateUserProfile } = useMarketUserProfile(username);
+ const { data: userProfile } = useMarketUserProfile(username);
// Handle profile update success - also refresh the cached profile
const handleProfileSuccess = useCallback(
(profile: MarketUserProfile) => {
handleProfileUpdateSuccess();
- // Update the SWR cache with the new profile
- mutateUserProfile(profile, false);
-
- // Also refresh the discover store's user profile cache
- // The discover store uses keys like 'user-profile-{locale}-{username}'
- if (profile.userName) {
- globalMutate(
- (key) =>
- typeof key === 'string' &&
- key.includes(`user-profile`) &&
- key.includes(profile.userName!),
- undefined,
- { revalidate: true },
- );
- }
+ const discover = useDiscoverStore.getState();
+ // The edit returned the saved profile: write it to the replica (memory
+ // and persisted row) instead of waiting for a refetch.
+ if (username) discover.setMarketUserProfile(username, profile);
+ // The community profile pages read their own replica; refetch them too.
+ if (profile.userName) void discover.refreshUserProfiles();
// Call the external success callback if provided
if (pendingProfileSuccessCallback) {
@@ -822,7 +811,7 @@ export const MarketAuthProvider = ({ children, isDesktop }: MarketAuthProviderPr
setPendingProfileSuccessCallback(null);
}
},
- [handleProfileUpdateSuccess, mutateUserProfile, pendingProfileSuccessCallback],
+ [handleProfileUpdateSuccess, pendingProfileSuccessCallback, username],
);
return (
diff --git a/src/layout/AuthProvider/MarketAuth/useMarketUserProfile.test.ts b/src/layout/AuthProvider/MarketAuth/useMarketUserProfile.test.ts
new file mode 100644
index 00000000000..538358e461d
--- /dev/null
+++ b/src/layout/AuthProvider/MarketAuth/useMarketUserProfile.test.ts
@@ -0,0 +1,109 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The viewer's Market profile is a replica persisted to IndexedDB: a reload
+ * paints the last confirmed profile before the network answers. Only public
+ * profile fields persist (the Market session and its tokens never enter it),
+ * and an account without a Market profile drops the persisted row.
+ */
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { lambdaClient } from '@/libs/trpc/client';
+import { useDiscoverStore } from '@/store/discover';
+import {
+ deferred,
+ pending,
+ replicaWrapper as wrapper,
+ useReplicaHarness,
+} from '@/store/discover/__tests__/replicaHarness';
+
+import { type MarketUserProfile } from './types';
+import { useMarketUserProfile } from './useMarketUserProfile';
+
+const profile = (displayName: string): MarketUserProfile => ({
+ avatarUrl: 'https://example.com/a.png',
+ bannerUrl: null,
+ createdAt: '2026-01-01T00:00:00.000Z',
+ description: null,
+ displayName,
+ id: 1,
+ namespace: 'alice',
+ socialLinks: null,
+ type: null,
+ userName: 'alice',
+});
+
+vi.mock('@/libs/trpc/client', () => ({
+ lambdaClient: { market: { user: { getUserByUsername: { query: vi.fn() } } } },
+}));
+
+const getUserByUsername = () => vi.mocked(lambdaClient.market.user.getUserByUsername.query);
+
+describe('useMarketUserProfile', () => {
+ const harness = useReplicaHarness('market-profile');
+
+ it('paints the persisted profile before the network answers, then refreshes it', async () => {
+ await harness.persist('discoverMarketUserProfile', 'alice', profile('Cached Alice'));
+ const next = deferred<MarketUserProfile>();
+ getUserByUsername().mockImplementation(() => next.promise as never);
+
+ const { result } = renderHook(() => useMarketUserProfile('alice'), { wrapper });
+
+ await waitFor(() => expect(result.current.data?.displayName).toBe('Cached Alice'));
+
+ await act(async () => next.resolve(profile('Fresh Alice')));
+ await waitFor(() => expect(result.current.data?.displayName).toBe('Fresh Alice'));
+ });
+
+ it('drops the persisted profile when the account has none any more', async () => {
+ await harness.persist('discoverMarketUserProfile', 'alice', profile('Cached Alice'));
+ getUserByUsername().mockRejectedValue({ data: { code: 'NOT_FOUND' } });
+
+ const { result } = renderHook(() => useMarketUserProfile('alice'), { wrapper });
+
+ await waitFor(() => expect(result.current.data).toBeUndefined());
+ await waitFor(async () =>
+ expect(await harness.stored('discoverMarketUserProfile', 'alice')).toBeUndefined(),
+ );
+ });
+
+ it('keeps the persisted profile when a refresh fails', async () => {
+ await harness.persist('discoverMarketUserProfile', 'alice', profile('Cached Alice'));
+ getUserByUsername().mockRejectedValue(new Error('network down'));
+
+ const { result } = renderHook(() => useMarketUserProfile('alice'), { wrapper });
+
+ await waitFor(() => expect(result.current.error).toBeInstanceOf(Error));
+ expect(result.current.data?.displayName).toBe('Cached Alice');
+ });
+
+ it("never paints another identity's profile", async () => {
+ await harness.persist(
+ 'discoverMarketUserProfile',
+ 'alice',
+ profile('Theirs'),
+ 'someone-else:personal',
+ );
+ getUserByUsername().mockImplementation(pending as never);
+
+ const { result } = renderHook(() => useMarketUserProfile('alice'), { wrapper });
+
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(result.current.data).toBeUndefined();
+ });
+
+ it('persists the profile an edit returned', async () => {
+ getUserByUsername().mockImplementation(pending as never);
+ const { result } = renderHook(() => useMarketUserProfile('alice'), { wrapper });
+
+ act(() => useDiscoverStore.getState().setMarketUserProfile('alice', profile('Edited')));
+
+ expect(result.current.data?.displayName).toBe('Edited');
+ await waitFor(async () =>
+ expect(await harness.stored('discoverMarketUserProfile', 'alice')).toMatchObject({
+ displayName: 'Edited',
+ }),
+ );
+ });
+});
diff --git a/src/layout/AuthProvider/MarketAuth/useMarketUserProfile.ts b/src/layout/AuthProvider/MarketAuth/useMarketUserProfile.ts
index 7c7bb978c86..d7e149d06f2 100644
--- a/src/layout/AuthProvider/MarketAuth/useMarketUserProfile.ts
+++ b/src/layout/AuthProvider/MarketAuth/useMarketUserProfile.ts
@@ -1,33 +1,19 @@
-import useSWR from 'swr';
-
-import { lambdaClient } from '@/libs/trpc/client';
-
-import { type MarketUserProfile } from './types';
+import { useDiscoverStore } from '@/store/discover';
+import { marketSelectors } from '@/store/discover/selectors';
/**
- * Fetcher function for user profile using tRPC
- */
-const fetchUserProfile = async (username: string): Promise<MarketUserProfile | null> => {
- const result = await lambdaClient.market.user.getUserByUsername.query({ username });
- return result as MarketUserProfile;
-};
-
-/**
- * Hook to fetch and cache Market user profile using SWR
+ * The Market profile of a username (typically `userInfo.sub`), read from the
+ * discover `marketUserProfile` replica: a reload paints the last confirmed
+ * profile before the network answers. Only public profile fields persist; the
+ * Market session and its tokens never enter the replica.
*
- * @param username - The username to fetch profile for (typically userInfo.sub)
- * @returns SWR response with user profile data
+ * `data` is `undefined` while unloaded and when the account has no Market
+ * profile yet (the server answers NOT_FOUND, which is not retried).
*/
export const useMarketUserProfile = (username: string | null | undefined) => {
- return useSWR<MarketUserProfile | null>(
- username ? ['market-user-profile', username] : null,
- () => fetchUserProfile(username!),
- {
- dedupingInterval: 60_000, // 1 minute deduplication
- revalidateOnFocus: false,
- revalidateOnReconnect: false,
- // NOT_FOUND means the user hasn't created a market username yet — no point retrying
- shouldRetryOnError: (error) => error?.data?.code !== 'NOT_FOUND',
- },
- );
+ const useSync = useDiscoverStore((s) => s.useMarketUserProfile);
+ const { queryKey, revalidate, ...sync } = useSync(username);
+ const data = useDiscoverStore(marketSelectors.userProfile(queryKey));
+
+ return { ...sync, data, mutate: revalidate, revalidate };
};
diff --git a/src/libs/swr/keys.frozen.test.ts b/src/libs/swr/keys.frozen.test.ts
index 3eb91b4a6ef..57770099c07 100644
--- a/src/libs/swr/keys.frozen.test.ts
+++ b/src/libs/swr/keys.frozen.test.ts
@@ -38,9 +38,6 @@ const LEGACY_SWR_KEYS = [
'deviceKeys.gitReviewPatches',
'deviceKeys.repoType',
'deviceKeys.systemInfo',
- 'discoverKeys.mcpAgents',
- 'discoverKeys.skillAgents',
- 'discoverKeys.skillStoreMarketSkills',
'documentCommentKeys.anchors',
'documentCommentKeys.detail',
'documentCommentKeys.replies',
@@ -63,10 +60,7 @@ const LEGACY_SWR_KEYS = [
'evalKeys.runs',
'evalKeys.testCaseDetail',
'evalKeys.testCases',
- 'favoriteKeys.status',
'fileKeys.ttsFile',
- 'forkKeys.groupSource',
- 'forkKeys.source',
'gatewayKeys.clientLlmWaits',
'gatewayKeys.reconnect',
'globalKeys.latestVersion',
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index cc07296787b..07790529e0c 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -313,34 +313,6 @@ export const serverConfigKeys = {
get: 'serverConfig:get' as const,
};
-// ---- discover (marketplace) ---------------------------------------------
-// NOTE: discover/eval/ragEval/knowledgeBase/device/userMemory/file prefixes
-// are deliberately kept OUT of `CACHE_TIERS`
-// (see localStorageProvider.ts) so this key-convergence introduces no new
-// persistence — they stay memory-only exactly as before.
-export const discoverKeys = {
- // -- marketplace detail "related agents" lists (UI) --
- mcpAgents: def('discover:mcpAgents', (identifier: string, page: number) => [
- 'discover:mcpAgents',
- identifier,
- page,
- ]),
- skillAgents: def('discover:skillAgents', (identifier: string, page: number) => [
- 'discover:skillAgents',
- identifier,
- page,
- ]),
- skillStoreMarketSkills: def(
- 'discover:skillStoreMarketSkills',
- (locale: string, keywords: string, page: number) => [
- 'discover:skillStoreMarketSkills',
- locale,
- keywords,
- page,
- ],
- ),
-};
-
// ---- agent eval ---------------------------------------------------------
export const evalKeys = {
benchmarkDetail: def('eval:benchmarkDetail', (id: string) => ['eval:benchmarkDetail', id]),
@@ -621,12 +593,6 @@ export const shareKeys = {
visitorTopics: def('share:visitorTopics', (shareId: string) => ['share:visitorTopics', shareId]),
};
-// ---- fork source (community detail) -------------------------------------
-export const forkKeys = {
- groupSource: def('fork:groupSource', (identifier: string) => ['fork:groupSource', identifier]),
- source: def('fork:source', (identifier: string) => ['fork:source', identifier]),
-};
-
// ---- local file ---------------------------------------------------------
export const localFileKeys = {
claudeCodeMemory: def(
@@ -679,15 +645,6 @@ export const localFileKeys = {
]),
};
-// ---- favorite status (marketplace detail headers) -----------------------
-export const favoriteKeys = {
- status: def('favorite:status', (targetType: string, identifier: string) => [
- 'favorite:status',
- targetType,
- identifier,
- ]),
-};
-
// ---- changelog ----------------------------------------------------------
export const canvasKeys = {
storage: def('canvas:storage', () => ['canvas:storage']),
@@ -836,12 +793,9 @@ export const swrKeys = {
changelog: changelogKeys,
cron: cronKeys,
device: deviceKeys,
- discover: discoverKeys,
electron: electronKeys,
eval: evalKeys,
- favorite: favoriteKeys,
file: fileKeys,
- fork: forkKeys,
gateway: gatewayKeys,
goal: goalKeys,
global: globalKeys,
diff --git a/src/routes/(main)/agent/profile/features/Header/AgentForkTag.tsx b/src/routes/(main)/agent/profile/features/Header/AgentForkTag.tsx
index 33cb3c02df7..a44789521f4 100644
--- a/src/routes/(main)/agent/profile/features/Header/AgentForkTag.tsx
+++ b/src/routes/(main)/agent/profile/features/Header/AgentForkTag.tsx
@@ -2,14 +2,12 @@
import { Icon, Tag } from '@lobehub/ui';
import { GitFork } from 'lucide-react';
-import { memo, useEffect, useState } from 'react';
+import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
-import { marketApiService } from '@/services/marketApi';
-import { useAgentStore } from '@/store/agent';
-import { agentSelectors } from '@/store/agent/selectors';
-import { type AgentForkSourceResponse } from '@/types/discover';
+
+import { useAgentMarketTags } from './useAgentMarketTags';
/**
* Agent Fork Tag Component
@@ -18,45 +16,9 @@ import { type AgentForkSourceResponse } from '@/types/discover';
const AgentForkTag = memo(() => {
const { t } = useTranslation('setting');
const navigate = useWorkspaceAwareNavigate();
- const [forkSource, setForkSource] = useState<AgentForkSourceResponse['source']>(null);
- const [loading, setLoading] = useState(false);
-
- const meta = useAgentStore(agentSelectors.currentAgentMeta);
- const marketIdentifier = meta?.marketIdentifier;
-
- useEffect(() => {
- if (!marketIdentifier) {
- setForkSource(null);
- return;
- }
-
- const fetchAgentAndForkInfo = async () => {
- try {
- setLoading(true);
-
- // Get agent detail to check if it's a fork
- const agentDetail = await marketApiService.getAgentDetail(marketIdentifier);
-
- // If forkedFromAgentId exists, get fork source info
- if (agentDetail.forkedFromAgentId) {
- const forkSourceResponse = await marketApiService.getAgentForkSource(marketIdentifier);
-
- setForkSource(forkSourceResponse.source);
- } else {
- setForkSource(null);
- }
- } catch (error) {
- console.error('Failed to fetch agent fork info:', error);
- setForkSource(null);
- } finally {
- setLoading(false);
- }
- };
-
- fetchAgentAndForkInfo();
- }, [marketIdentifier]);
+ const { forkSource } = useAgentMarketTags();
- if (loading || !forkSource) return null;
+ if (!forkSource) return null;
const handleClick = () => {
if (forkSource?.identifier) {
diff --git a/src/routes/(main)/agent/profile/features/Header/AgentStatusTag.tsx b/src/routes/(main)/agent/profile/features/Header/AgentStatusTag.tsx
index 59e78840ceb..534ef475856 100644
--- a/src/routes/(main)/agent/profile/features/Header/AgentStatusTag.tsx
+++ b/src/routes/(main)/agent/profile/features/Header/AgentStatusTag.tsx
@@ -1,47 +1,19 @@
'use client';
import { Tag } from '@lobehub/ui';
-import { memo, useEffect, useMemo, useState } from 'react';
+import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { marketApiService } from '@/services/marketApi';
-import { useAgentStore } from '@/store/agent';
-import { agentSelectors } from '@/store/agent/selectors';
-import { type AgentStatus } from '@/types/discover';
+import { useAgentMarketTags } from './useAgentMarketTags';
/**
* Agent Status Tag Component
- * Displays the market status of the agent (published/unpublished/archived/deprecated)
+ * Displays the market status of the agent (published/unpublished/archived/deprecated).
+ * Shares the header's one Market status read with the fork and review tags.
*/
const AgentStatusTag = memo(() => {
const { t } = useTranslation('setting');
- const [status, setStatus] = useState<AgentStatus | null>(null);
- const [loading, setLoading] = useState(false);
-
- const meta = useAgentStore(agentSelectors.currentAgentMeta);
- const marketIdentifier = meta?.marketIdentifier;
-
- useEffect(() => {
- if (!marketIdentifier) {
- setStatus(null);
- return;
- }
-
- const fetchAgentStatus = async () => {
- try {
- setLoading(true);
- const agentDetail = await marketApiService.getAgentDetail(marketIdentifier);
- setStatus(agentDetail.status as AgentStatus | null);
- } catch (error) {
- console.error('Failed to fetch agent status:', error);
- setStatus(null);
- } finally {
- setLoading(false);
- }
- };
-
- fetchAgentStatus();
- }, [marketIdentifier]);
+ const { status } = useAgentMarketTags();
const statusConfig = useMemo(() => {
if (!status) return null;
@@ -68,7 +40,7 @@ const AgentStatusTag = memo(() => {
return configs[status];
}, [status, t]);
- if (loading || !statusConfig) return null;
+ if (!statusConfig) return null;
return (
<Tag color={statusConfig.color} style={{ marginRight: 8 }}>
diff --git a/src/routes/(main)/agent/profile/features/Header/AgentVersionReviewTag.tsx b/src/routes/(main)/agent/profile/features/Header/AgentVersionReviewTag.tsx
index 6763a3ba764..ba05a0459b0 100644
--- a/src/routes/(main)/agent/profile/features/Header/AgentVersionReviewTag.tsx
+++ b/src/routes/(main)/agent/profile/features/Header/AgentVersionReviewTag.tsx
@@ -1,23 +1,11 @@
'use client';
import { Tag } from '@lobehub/ui';
-import { memo, useEffect, useMemo, useState } from 'react';
+import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { marketApiService } from '@/services/marketApi';
-import { useAgentStore } from '@/store/agent';
-import { agentSelectors } from '@/store/agent/selectors';
-
import AgentStatusTag from './AgentStatusTag';
-
-interface AgentVersion {
- isLatest: boolean;
- isValidated: boolean;
- status: string;
- updatedAt: string;
- version: string;
- versionNumber: number;
-}
+import { useAgentMarketTags } from './useAgentMarketTags';
/**
* Agent Version Review Tag Component
@@ -25,44 +13,11 @@ interface AgentVersion {
*/
const AgentVersionReviewTag = memo(({ submitted = false }: { submitted?: boolean }) => {
const { t } = useTranslation('setting');
- const [versions, setVersions] = useState<AgentVersion[] | null>(null);
- const [loading, setLoading] = useState(false);
-
- const meta = useAgentStore(agentSelectors.currentAgentMeta);
- const marketIdentifier = meta?.marketIdentifier;
-
- useEffect(() => {
- if (!marketIdentifier) {
- setVersions(null);
- return;
- }
-
- const fetchAgentVersions = async () => {
- try {
- setLoading(true);
- const agentDetail = await marketApiService.getAgentDetail(marketIdentifier);
- // @ts-ignore - versions field exists in the response
- setVersions(agentDetail.versions || null);
- } catch (error) {
- console.error('Failed to fetch agent versions:', error);
- setVersions(null);
- } finally {
- setLoading(false);
- }
- };
-
- fetchAgentVersions();
- }, [marketIdentifier]);
-
- const showReviewTag = useMemo(() => {
- if (!versions || versions.length === 0) return false;
- // Check the first version (latest version)
- return versions[0].isValidated === false;
- }, [versions]);
+ const { isUnderReview: showReviewTag } = useAgentMarketTags();
// A successful submission is authoritative even when the detail endpoint
// omits pending versions. Do not infer review status from "unpublished" alone.
- if (!submitted && (loading || !showReviewTag)) return <AgentStatusTag />;
+ if (!submitted && !showReviewTag) return <AgentStatusTag />;
return (
<Tag color="orange" style={{ marginRight: 8 }}>
@@ -74,42 +29,3 @@ const AgentVersionReviewTag = memo(({ submitted = false }: { submitted?: boolean
AgentVersionReviewTag.displayName = 'AgentVersionReviewTag';
export default AgentVersionReviewTag;
-
-/**
- * Hook to check if the latest version is under review
- * Can be used in other components to check review status
- */
-export const useVersionReviewStatus = () => {
- const [isUnderReview, setIsUnderReview] = useState(false);
- const [loading, setLoading] = useState(false);
-
- const meta = useAgentStore(agentSelectors.currentAgentMeta);
- const marketIdentifier = meta?.marketIdentifier;
-
- useEffect(() => {
- if (!marketIdentifier) {
- setIsUnderReview(false);
- return;
- }
-
- const checkReviewStatus = async () => {
- try {
- setLoading(true);
- const agentDetail = await marketApiService.getAgentDetail(marketIdentifier);
- // @ts-ignore - versions field exists in the response
- const versions = agentDetail.versions || [];
- // Check if the first version (latest) is not validated
- setIsUnderReview(versions.length > 0 && versions[0].isValidated === false);
- } catch (error) {
- console.error('Failed to check review status:', error);
- setIsUnderReview(false);
- } finally {
- setLoading(false);
- }
- };
-
- checkReviewStatus();
- }, [marketIdentifier]);
-
- return { isUnderReview, loading };
-};
diff --git a/src/routes/(main)/agent/profile/features/Header/useAgentMarketTags.test.ts b/src/routes/(main)/agent/profile/features/Header/useAgentMarketTags.test.ts
new file mode 100644
index 00000000000..e5f67f010cd
--- /dev/null
+++ b/src/routes/(main)/agent/profile/features/Header/useAgentMarketTags.test.ts
@@ -0,0 +1,137 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The status, review and fork tags of the agent profile header read one Market
+ * status replica persisted to IndexedDB: a reload paints the last confirmed
+ * tags before the network answers, and the header sends one detail request
+ * however many tags read it.
+ */
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { marketApiService } from '@/services/marketApi';
+import { useDiscoverStore } from '@/store/discover';
+import {
+ deferred,
+ pending,
+ replicaWrapper as wrapper,
+ useReplicaHarness,
+} from '@/store/discover/__tests__/replicaHarness';
+
+import { useAgentMarketTags } from './useAgentMarketTags';
+
+const meta = vi.hoisted(() => ({ current: { marketIdentifier: 'my-agent' } }));
+
+vi.mock('@/store/agent', () => ({
+ useAgentStore: (selector: (state: unknown) => unknown) => selector({}),
+}));
+vi.mock('@/store/agent/selectors', () => ({
+ agentSelectors: { currentAgentMeta: () => meta.current },
+}));
+
+const detail = (status: string, extra: Record<string, unknown> = {}) =>
+ ({ identifier: 'my-agent', status, versions: [{ isValidated: true }], ...extra }) as never;
+
+const PUBLISHED = { forkedFromAgentId: null, latestVersionUnderReview: false, status: 'published' };
+
+describe('useAgentMarketTags', () => {
+ const harness = useReplicaHarness('agent-market-tags');
+ const { persist } = harness;
+
+ beforeEach(() => {
+ meta.current = { marketIdentifier: 'my-agent' };
+ });
+
+ it('paints the persisted status and fork source before the network answers', async () => {
+ await persist('discoverMarketAgentStatus', 'my-agent', {
+ ...PUBLISHED,
+ forkedFromAgentId: '7',
+ });
+ await persist('discoverAgentForkSource', 'my-agent', {
+ source: { identifier: 'origin-agent', name: 'Origin Agent' },
+ });
+ vi.spyOn(marketApiService, 'getAgentDetail').mockImplementation(pending);
+ vi.spyOn(marketApiService, 'getAgentForkSource').mockImplementation(pending);
+
+ const { result } = renderHook(() => useAgentMarketTags(), { wrapper });
+
+ await waitFor(() => expect(result.current.status).toBe('published'));
+ await waitFor(() => expect(result.current.forkSource?.name).toBe('Origin Agent'));
+ });
+
+ it('replaces the persisted status with the server answer', async () => {
+ await persist('discoverMarketAgentStatus', 'my-agent', PUBLISHED);
+ const next = deferred<never>();
+ vi.spyOn(marketApiService, 'getAgentDetail').mockImplementation(() => next.promise);
+
+ const { result } = renderHook(() => useAgentMarketTags(), { wrapper });
+ await waitFor(() => expect(result.current.status).toBe('published'));
+
+ await act(async () => next.resolve(detail('archived')));
+ await waitFor(() => expect(result.current.status).toBe('archived'));
+ });
+
+ it('sends one detail request for the status, review and fork tags', async () => {
+ const getAgentDetail = vi
+ .spyOn(marketApiService, 'getAgentDetail')
+ .mockResolvedValue(detail('unpublished', { versions: [{ isValidated: false }] }));
+
+ const { result } = renderHook(
+ () => [useAgentMarketTags(), useAgentMarketTags(), useAgentMarketTags()],
+ { wrapper },
+ );
+
+ await waitFor(() => expect(result.current[2].isUnderReview).toBe(true));
+ expect(getAgentDetail).toHaveBeenCalledTimes(1);
+ });
+
+ it('asks for the fork source only once the agent is known to be a fork', async () => {
+ vi.spyOn(marketApiService, 'getAgentDetail').mockResolvedValue(detail('published'));
+ const getAgentForkSource = vi.spyOn(marketApiService, 'getAgentForkSource');
+
+ const { result } = renderHook(() => useAgentMarketTags(), { wrapper });
+
+ await waitFor(() => expect(result.current.status).toBe('published'));
+ expect(getAgentForkSource).not.toHaveBeenCalled();
+ });
+
+ it('keeps the last status when a refresh fails', async () => {
+ await persist('discoverMarketAgentStatus', 'my-agent', PUBLISHED);
+ const getAgentDetail = vi
+ .spyOn(marketApiService, 'getAgentDetail')
+ .mockRejectedValue(new Error('network down'));
+
+ const { result } = renderHook(() => useAgentMarketTags(), { wrapper });
+
+ await waitFor(() => expect(getAgentDetail).toHaveBeenCalled());
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(result.current.status).toBe('published');
+ });
+
+ it("never paints another identity's status", async () => {
+ await persist('discoverMarketAgentStatus', 'my-agent', PUBLISHED, `${harness.scope}-other`);
+ vi.spyOn(marketApiService, 'getAgentDetail').mockImplementation(pending);
+
+ const { result } = renderHook(() => useAgentMarketTags(), { wrapper });
+
+ await waitFor(() =>
+ expect(useDiscoverStore.getState().marketAgentStatusReplica.scope).toBe(harness.scope),
+ );
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(result.current.status).toBeNull();
+ });
+
+ it('drops the persisted status when the Market no longer has the agent', async () => {
+ await persist('discoverMarketAgentStatus', 'my-agent', PUBLISHED);
+ vi.spyOn(marketApiService, 'getAgentDetail').mockRejectedValue({
+ data: { code: 'NOT_FOUND' },
+ });
+
+ const { result } = renderHook(() => useAgentMarketTags(), { wrapper });
+
+ await waitFor(() => expect(result.current.status).toBeNull());
+ await waitFor(async () =>
+ expect(await harness.stored('discoverMarketAgentStatus', 'my-agent')).toBeUndefined(),
+ );
+ });
+});
diff --git a/src/routes/(main)/agent/profile/features/Header/useAgentMarketTags.ts b/src/routes/(main)/agent/profile/features/Header/useAgentMarketTags.ts
new file mode 100644
index 00000000000..94119a516d7
--- /dev/null
+++ b/src/routes/(main)/agent/profile/features/Header/useAgentMarketTags.ts
@@ -0,0 +1,31 @@
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
+import { useDiscoverStore } from '@/store/discover';
+import { marketSelectors } from '@/store/discover/selectors';
+
+/**
+ * What the status, review and fork tags of the agent profile header show for
+ * the current agent's Market listing. Every tag calls this hook; they share one
+ * Market status read (and one fork-source read, asked for only once the agent
+ * is known to be a fork), painted from the local replica first.
+ */
+export const useAgentMarketTags = () => {
+ const marketIdentifier = useAgentStore(agentSelectors.currentAgentMeta)?.marketIdentifier;
+
+ const useMarketAgentStatus = useDiscoverStore((s) => s.useMarketAgentStatus);
+ const { queryKey: statusKey } = useMarketAgentStatus(marketIdentifier);
+ const marketStatus = useDiscoverStore(marketSelectors.agentStatus(statusKey));
+
+ const useAgentForkSource = useDiscoverStore((s) => s.useAgentForkSource);
+ const { queryKey: forkKey } = useAgentForkSource(
+ marketIdentifier,
+ !!marketStatus?.forkedFromAgentId,
+ );
+ const forkSource = useDiscoverStore(marketSelectors.agentForkSource(forkKey));
+
+ return {
+ forkSource: forkSource ?? null,
+ isUnderReview: !!marketStatus?.latestVersionUnderReview,
+ status: marketStatus?.status ?? null,
+ };
+};
diff --git a/src/routes/(main)/community/(detail)/agent/features/AgentForkTag.tsx b/src/routes/(main)/community/(detail)/agent/features/AgentForkTag.tsx
index 4afe95c0a22..ce785eed05c 100644
--- a/src/routes/(main)/community/(detail)/agent/features/AgentForkTag.tsx
+++ b/src/routes/(main)/community/(detail)/agent/features/AgentForkTag.tsx
@@ -4,12 +4,11 @@ import { Icon, Tag } from '@lobehub/ui';
import { GitFork } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import useSWR from 'swr';
import urlJoin from 'url-join';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
-import { forkKeys } from '@/libs/swr/keys';
-import { marketApiService } from '@/services/marketApi';
+import { useDiscoverStore } from '@/store/discover';
+import { marketSelectors } from '@/store/discover/selectors';
import { useDetailContext } from './DetailProvider';
@@ -22,18 +21,15 @@ const AgentForkTag = memo(() => {
const navigate = useWorkspaceAwareNavigate();
const { identifier, forkedFromAgentId } = useDetailContext();
- // Fetch fork source info
- const { data: forkSource } = useSWR(
- identifier && forkedFromAgentId ? forkKeys.source(identifier) : null,
- () => marketApiService.getAgentForkSource(identifier!),
- { revalidateOnFocus: false },
- );
+ const useAgentForkSource = useDiscoverStore((s) => s.useAgentForkSource);
+ const { queryKey } = useAgentForkSource(identifier, !!forkedFromAgentId);
+ const source = useDiscoverStore(marketSelectors.agentForkSource(queryKey));
- if (!forkSource?.source) return null;
+ if (!source) return null;
const handleClick = () => {
- if (forkSource?.source?.identifier) {
- navigate(urlJoin('/community/agent', forkSource.source.identifier));
+ if (source?.identifier) {
+ navigate(urlJoin('/community/agent', source.identifier));
}
};
@@ -43,11 +39,11 @@ const AgentForkTag = memo(() => {
icon={<Icon icon={GitFork} />}
style={{ cursor: 'pointer' }}
title={t('fork.forkedFrom', {
- defaultValue: `Forked from ${forkSource.source.name}`,
+ defaultValue: `Forked from ${source.name}`,
})}
onClick={handleClick}
>
- {t('fork.forkedFrom')}: {forkSource.source.name}
+ {t('fork.forkedFrom')}: {source.name}
</Tag>
);
});
diff --git a/src/routes/(main)/community/(detail)/agent/features/Header.tsx b/src/routes/(main)/community/(detail)/agent/features/Header.tsx
index 944e9db6139..54a93c05e86 100644
--- a/src/routes/(main)/community/(detail)/agent/features/Header.tsx
+++ b/src/routes/(main)/community/(detail)/agent/features/Header.tsx
@@ -27,13 +27,13 @@ import {
import qs from 'query-string';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import useSWR from 'swr';
import PublishedTime from '@/components/PublishedTime';
import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';
-import { favoriteKeys } from '@/libs/swr/keys';
import { socialService } from '@/services/social';
+import { useDiscoverStore } from '@/store/discover';
+import { socialSelectors } from '@/store/discover/selectors';
import { formatIntergerNumber } from '@/utils/format';
import { useCategory } from '../../../(list)/agent/features/Category/useCategory';
@@ -69,12 +69,10 @@ const Header = memo<{ mobile?: boolean }>(({ mobile: isMobile }) => {
socialService.setAccessToken(session.accessToken);
}
- // Fetch favorite status
- const { data: favoriteStatus, mutate: mutateFavorite } = useSWR(
- identifier && isAuthenticated ? favoriteKeys.status('agent', identifier) : null,
- () => socialService.checkFavoriteStatus('agent', identifier!),
- { revalidateOnFocus: false },
- );
+ const useFavoriteStatus = useDiscoverStore((s) => s.useFavoriteStatus);
+ const { queryKey: favoriteKey } = useFavoriteStatus('agent', identifier, isAuthenticated);
+ const favoriteStatus = useDiscoverStore(socialSelectors.favoriteStatus(favoriteKey));
+ const setFavorite = useDiscoverStore((s) => s.setFavorite);
const isFavorited = favoriteStatus?.isFavorited ?? false;
@@ -88,14 +86,8 @@ const Header = memo<{ mobile?: boolean }>(({ mobile: isMobile }) => {
setFavoriteLoading(true);
try {
- if (isFavorited) {
- await socialService.removeFavorite('agent', identifier);
- toast.success(t('assistant.unfavoriteSuccess'));
- } else {
- await socialService.addFavorite('agent', identifier);
- toast.success(t('assistant.favoriteSuccess'));
- }
- await mutateFavorite();
+ await setFavorite('agent', identifier, !isFavorited);
+ toast.success(t(isFavorited ? 'assistant.unfavoriteSuccess' : 'assistant.favoriteSuccess'));
} catch (error) {
console.error('Favorite action failed:', error);
toast.error(t('assistant.favoriteFailed'));
diff --git a/src/routes/(main)/community/(detail)/group_agent/features/GroupAgentForkTag.tsx b/src/routes/(main)/community/(detail)/group_agent/features/GroupAgentForkTag.tsx
index 56c43acdc07..0b6907c8107 100644
--- a/src/routes/(main)/community/(detail)/group_agent/features/GroupAgentForkTag.tsx
+++ b/src/routes/(main)/community/(detail)/group_agent/features/GroupAgentForkTag.tsx
@@ -4,12 +4,11 @@ import { Icon, Tag } from '@lobehub/ui';
import { GitFork } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import useSWR from 'swr';
import urlJoin from 'url-join';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
-import { forkKeys } from '@/libs/swr/keys';
-import { marketApiService } from '@/services/marketApi';
+import { useDiscoverStore } from '@/store/discover';
+import { marketSelectors } from '@/store/discover/selectors';
import { useDetailContext } from './DetailProvider';
@@ -22,18 +21,15 @@ const GroupAgentForkTag = memo(() => {
const navigate = useWorkspaceAwareNavigate();
const { identifier, forkedFromGroupId } = useDetailContext();
- // Fetch fork source info
- const { data: forkSource } = useSWR(
- identifier && forkedFromGroupId ? forkKeys.groupSource(identifier) : null,
- () => marketApiService.getAgentGroupForkSource(identifier!),
- { revalidateOnFocus: false },
- );
+ const useAgentGroupForkSource = useDiscoverStore((s) => s.useAgentGroupForkSource);
+ const { queryKey } = useAgentGroupForkSource(identifier, !!forkedFromGroupId);
+ const source = useDiscoverStore(marketSelectors.agentGroupForkSource(queryKey));
- if (!forkSource?.source) return null;
+ if (!source) return null;
const handleClick = () => {
- if (forkSource?.source?.identifier) {
- navigate(urlJoin('/community/group_agent', forkSource.source.identifier));
+ if (source?.identifier) {
+ navigate(urlJoin('/community/group_agent', source.identifier));
}
};
@@ -43,11 +39,11 @@ const GroupAgentForkTag = memo(() => {
icon={<Icon icon={GitFork} />}
style={{ cursor: 'pointer' }}
title={t('fork.forkedFrom', {
- defaultValue: `Forked from ${forkSource.source.name}`,
+ defaultValue: `Forked from ${source.name}`,
})}
onClick={handleClick}
>
- {t('fork.forkedFrom')}: {forkSource.source.name}
+ {t('fork.forkedFrom')}: {source.name}
</Tag>
);
});
diff --git a/src/routes/(main)/community/(detail)/group_agent/features/Header.tsx b/src/routes/(main)/community/(detail)/group_agent/features/Header.tsx
index 4202109e473..e14582d4ad2 100644
--- a/src/routes/(main)/community/(detail)/group_agent/features/Header.tsx
+++ b/src/routes/(main)/community/(detail)/group_agent/features/Header.tsx
@@ -19,13 +19,13 @@ import { BookmarkCheckIcon, BookmarkIcon, DotIcon, GitBranchIcon, UsersIcon } fr
import qs from 'query-string';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import useSWR from 'swr';
import PublishedTime from '@/components/PublishedTime';
import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';
-import { favoriteKeys } from '@/libs/swr/keys';
import { socialService } from '@/services/social';
+import { useDiscoverStore } from '@/store/discover';
+import { socialSelectors } from '@/store/discover/selectors';
import { resolveCommunityProfileLink } from '../../utils/profileLink';
import { useDetailContext } from './DetailProvider';
@@ -62,13 +62,10 @@ const Header = memo<{ mobile?: boolean }>(({ mobile: isMobile }) => {
socialService.setAccessToken(session.accessToken);
}
- // TODO: Use 'group_agent' type when social service supports it
- // Fetch favorite status
- const { data: favoriteStatus, mutate: mutateFavorite } = useSWR(
- identifier && isAuthenticated ? favoriteKeys.status('agent', identifier) : null,
- () => socialService.checkFavoriteStatus('agent-group', identifier!),
- { revalidateOnFocus: false },
- );
+ const useFavoriteStatus = useDiscoverStore((s) => s.useFavoriteStatus);
+ const { queryKey: favoriteKey } = useFavoriteStatus('agent-group', identifier, isAuthenticated);
+ const favoriteStatus = useDiscoverStore(socialSelectors.favoriteStatus(favoriteKey));
+ const setFavorite = useDiscoverStore((s) => s.setFavorite);
const isFavorited = favoriteStatus?.isFavorited ?? false;
@@ -82,14 +79,8 @@ const Header = memo<{ mobile?: boolean }>(({ mobile: isMobile }) => {
setFavoriteLoading(true);
try {
- if (isFavorited) {
- await socialService.removeFavorite('agent-group', identifier);
- toast.success(t('assistant.unfavoriteSuccess'));
- } else {
- await socialService.addFavorite('agent-group', identifier);
- toast.success(t('assistant.favoriteSuccess'));
- }
- await mutateFavorite();
+ await setFavorite('agent-group', identifier, !isFavorited);
+ toast.success(t(isFavorited ? 'assistant.unfavoriteSuccess' : 'assistant.favoriteSuccess'));
} catch {
toast.error(t('assistant.favoriteFailed'));
} finally {
diff --git a/src/routes/(main)/group/profile/features/GroupProfile/GroupForkTag.tsx b/src/routes/(main)/group/profile/features/GroupProfile/GroupForkTag.tsx
index 3a622561c9e..3e0a5b62a7c 100644
--- a/src/routes/(main)/group/profile/features/GroupProfile/GroupForkTag.tsx
+++ b/src/routes/(main)/group/profile/features/GroupProfile/GroupForkTag.tsx
@@ -2,15 +2,12 @@
import { Icon, Tag } from '@lobehub/ui';
import { GitFork } from 'lucide-react';
-import { memo, useEffect, useState } from 'react';
+import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useParams } from 'react-router';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
-import { marketApiService } from '@/services/marketApi';
-import { useAgentGroupStore } from '@/store/agentGroup';
-import { agentGroupSelectors } from '@/store/agentGroup/selectors';
-import { type AgentGroupForkSourceResponse } from '@/types/discover';
+
+import { useGroupMarketTags } from './useGroupMarketTags';
/**
* Group Fork Tag Component
@@ -19,39 +16,9 @@ import { type AgentGroupForkSourceResponse } from '@/types/discover';
const GroupForkTag = memo(() => {
const { t } = useTranslation('setting');
const navigate = useWorkspaceAwareNavigate();
- const [forkSource, setForkSource] = useState<AgentGroupForkSourceResponse['source']>(null);
- const [loading, setLoading] = useState(false);
-
- const { gid } = useParams<{ gid: string }>();
- const groupMeta = useAgentGroupStore((s) => agentGroupSelectors.getGroupMeta(gid ?? '')(s));
- const marketIdentifier = groupMeta?.marketIdentifier;
-
- useEffect(() => {
- if (!marketIdentifier) {
- setForkSource(null);
- return;
- }
-
- const fetchGroupForkInfo = async () => {
- try {
- setLoading(true);
-
- // Get fork source info from market using the marketIdentifier
- const forkSourceResponse = await marketApiService.getAgentGroupForkSource(marketIdentifier);
-
- setForkSource(forkSourceResponse.source);
- } catch (error) {
- console.error('Failed to fetch group fork info:', error);
- setForkSource(null);
- } finally {
- setLoading(false);
- }
- };
-
- fetchGroupForkInfo();
- }, [marketIdentifier]);
+ const { forkSource } = useGroupMarketTags();
- if (loading || !forkSource) return null;
+ if (!forkSource) return null;
const handleClick = () => {
if (forkSource?.identifier) {
diff --git a/src/routes/(main)/group/profile/features/GroupProfile/GroupVersionReviewTag.tsx b/src/routes/(main)/group/profile/features/GroupProfile/GroupVersionReviewTag.tsx
index 011aab60a6a..ea6804403bd 100644
--- a/src/routes/(main)/group/profile/features/GroupProfile/GroupVersionReviewTag.tsx
+++ b/src/routes/(main)/group/profile/features/GroupProfile/GroupVersionReviewTag.tsx
@@ -1,22 +1,10 @@
'use client';
import { Tag } from '@lobehub/ui';
-import { memo, useEffect, useMemo, useState } from 'react';
+import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useParams } from 'react-router';
-import { marketApiService } from '@/services/marketApi';
-import { useAgentGroupStore } from '@/store/agentGroup';
-import { agentGroupSelectors } from '@/store/agentGroup/selectors';
-
-interface GroupVersion {
- isLatest: boolean;
- isValidated: boolean;
- status: string;
- updatedAt: string;
- version: string;
- versionNumber: number;
-}
+import { useGroupMarketTags } from './useGroupMarketTags';
/**
* Group Version Review Tag Component
@@ -24,42 +12,9 @@ interface GroupVersion {
*/
const GroupVersionReviewTag = memo(() => {
const { t } = useTranslation('setting');
- const [versions, setVersions] = useState<GroupVersion[] | null>(null);
- const [loading, setLoading] = useState(false);
-
- const { gid } = useParams<{ gid: string }>();
- const meta = useAgentGroupStore((s) => agentGroupSelectors.getGroupMeta(gid ?? '')(s));
- const marketIdentifier = meta?.marketIdentifier;
-
- useEffect(() => {
- if (!marketIdentifier) {
- setVersions(null);
- return;
- }
-
- const fetchGroupVersions = async () => {
- try {
- setLoading(true);
- const groupDetail = await marketApiService.getAgentGroupDetail(marketIdentifier);
- setVersions(groupDetail.versions || null);
- } catch (error) {
- console.error('Failed to fetch group versions:', error);
- setVersions(null);
- } finally {
- setLoading(false);
- }
- };
+ const { isUnderReview: showReviewTag } = useGroupMarketTags();
- fetchGroupVersions();
- }, [marketIdentifier]);
-
- const showReviewTag = useMemo(() => {
- if (!versions || versions.length === 0) return false;
- // Check the first version (latest version)
- return versions[0].isValidated === false;
- }, [versions]);
-
- if (loading || !showReviewTag) return null;
+ if (!showReviewTag) return null;
return (
<Tag color="orange">
@@ -71,42 +26,3 @@ const GroupVersionReviewTag = memo(() => {
GroupVersionReviewTag.displayName = 'GroupVersionReviewTag';
export default GroupVersionReviewTag;
-
-/**
- * Hook to check if the latest version is under review
- * Can be used in other components to check review status
- */
-export const useGroupVersionReviewStatus = () => {
- const [isUnderReview, setIsUnderReview] = useState(false);
- const [loading, setLoading] = useState(false);
-
- const { gid } = useParams<{ gid: string }>();
- const meta = useAgentGroupStore((s) => agentGroupSelectors.getGroupMeta(gid ?? '')(s));
- const marketIdentifier = meta?.marketIdentifier;
-
- useEffect(() => {
- if (!marketIdentifier) {
- setIsUnderReview(false);
- return;
- }
-
- const checkReviewStatus = async () => {
- try {
- setLoading(true);
- const groupDetail = await marketApiService.getAgentGroupDetail(marketIdentifier);
- const versions = groupDetail.versions || [];
- // Check if the first version (latest) is not validated
- setIsUnderReview(versions.length > 0 && versions[0].isValidated === false);
- } catch (error) {
- console.error('Failed to check review status:', error);
- setIsUnderReview(false);
- } finally {
- setLoading(false);
- }
- };
-
- checkReviewStatus();
- }, [marketIdentifier]);
-
- return { isUnderReview, loading };
-};
diff --git a/src/routes/(main)/group/profile/features/GroupProfile/useGroupMarketTags.test.ts b/src/routes/(main)/group/profile/features/GroupProfile/useGroupMarketTags.test.ts
new file mode 100644
index 00000000000..aa4b500e2f7
--- /dev/null
+++ b/src/routes/(main)/group/profile/features/GroupProfile/useGroupMarketTags.test.ts
@@ -0,0 +1,58 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The group profile's review and fork tags read Market replicas persisted to
+ * IndexedDB: a reload paints the last confirmed tags before the network
+ * answers, then the server answer replaces them.
+ */
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { marketApiService } from '@/services/marketApi';
+import {
+ deferred,
+ pending,
+ replicaWrapper as wrapper,
+ useReplicaHarness,
+} from '@/store/discover/__tests__/replicaHarness';
+
+import { useGroupMarketTags } from './useGroupMarketTags';
+
+vi.mock('react-router', () => ({ useParams: () => ({ gid: 'group-1' }) }));
+vi.mock('@/store/agentGroup', () => ({
+ useAgentGroupStore: (selector: (state: unknown) => unknown) => selector({}),
+}));
+vi.mock('@/store/agentGroup/selectors', () => ({
+ agentGroupSelectors: { getGroupMeta: () => () => ({ marketIdentifier: 'my-group' }) },
+}));
+
+describe('useGroupMarketTags', () => {
+ const { persist } = useReplicaHarness('group-market-tags');
+
+ it('paints the persisted review state and fork source before the network answers', async () => {
+ await persist('discoverMarketAgentGroupStatus', 'my-group', { latestVersionUnderReview: true });
+ await persist('discoverAgentGroupForkSource', 'my-group', {
+ source: { identifier: 'origin-group', name: 'Origin Group' },
+ });
+ vi.spyOn(marketApiService, 'getAgentGroupDetail').mockImplementation(pending);
+ vi.spyOn(marketApiService, 'getAgentGroupForkSource').mockImplementation(pending);
+
+ const { result } = renderHook(() => useGroupMarketTags(), { wrapper });
+
+ await waitFor(() => expect(result.current.isUnderReview).toBe(true));
+ await waitFor(() => expect(result.current.forkSource?.name).toBe('Origin Group'));
+ });
+
+ it('replaces the persisted review state with the server answer', async () => {
+ await persist('discoverMarketAgentGroupStatus', 'my-group', { latestVersionUnderReview: true });
+ const next = deferred<unknown>();
+ vi.spyOn(marketApiService, 'getAgentGroupDetail').mockImplementation(() => next.promise);
+ vi.spyOn(marketApiService, 'getAgentGroupForkSource').mockResolvedValue({ source: null });
+
+ const { result } = renderHook(() => useGroupMarketTags(), { wrapper });
+ await waitFor(() => expect(result.current.isUnderReview).toBe(true));
+
+ await act(async () => next.resolve({ versions: [{ isValidated: true }] }));
+ await waitFor(() => expect(result.current.isUnderReview).toBe(false));
+ });
+});
diff --git a/src/routes/(main)/group/profile/features/GroupProfile/useGroupMarketTags.ts b/src/routes/(main)/group/profile/features/GroupProfile/useGroupMarketTags.ts
new file mode 100644
index 00000000000..5a194878fed
--- /dev/null
+++ b/src/routes/(main)/group/profile/features/GroupProfile/useGroupMarketTags.ts
@@ -0,0 +1,30 @@
+import { useParams } from 'react-router';
+
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { agentGroupSelectors } from '@/store/agentGroup/selectors';
+import { useDiscoverStore } from '@/store/discover';
+import { marketSelectors } from '@/store/discover/selectors';
+
+/**
+ * What the review and fork tags of the group profile show for the current
+ * group's Market listing, painted from the local replicas first.
+ */
+export const useGroupMarketTags = () => {
+ const { gid } = useParams<{ gid: string }>();
+ const marketIdentifier = useAgentGroupStore((s) =>
+ agentGroupSelectors.getGroupMeta(gid ?? '')(s),
+ )?.marketIdentifier;
+
+ const useMarketAgentGroupStatus = useDiscoverStore((s) => s.useMarketAgentGroupStatus);
+ const { queryKey: statusKey } = useMarketAgentGroupStatus(marketIdentifier);
+ const marketStatus = useDiscoverStore(marketSelectors.agentGroupStatus(statusKey));
+
+ const useAgentGroupForkSource = useDiscoverStore((s) => s.useAgentGroupForkSource);
+ const { queryKey: forkKey } = useAgentGroupForkSource(marketIdentifier);
+ const forkSource = useDiscoverStore(marketSelectors.agentGroupForkSource(forkKey));
+
+ return {
+ forkSource: forkSource ?? null,
+ isUnderReview: !!marketStatus?.latestVersionUnderReview,
+ };
+};
diff --git a/src/services/marketApi.ts b/src/services/marketApi.ts
index 4bdb097cb73..5749d6061c6 100644
--- a/src/services/marketApi.ts
+++ b/src/services/marketApi.ts
@@ -4,6 +4,7 @@ import {
type AgentListResponse,
} from '@lobehub/market-sdk';
+import { type MarketUserProfile } from '@/layout/AuthProvider/MarketAuth/types';
import { lambdaClient } from '@/libs/trpc/client';
import { discoverService } from '@/services/discover';
import {
@@ -16,6 +17,13 @@ import {
type AgentGroupForksResponse,
type SkillSorts,
} from '@/types/discover';
+import { isTrpcErrorCode } from '@/utils/trpcError';
+
+/** One text file of a Market skill package, path relative to the package root. */
+export interface MarketSkillPackageFile {
+ content: string;
+ path: string;
+}
interface GetOwnAgentsParams {
page?: number;
@@ -202,6 +210,55 @@ export class MarketApiService {
const marketBaseUrl = process.env.NEXT_PUBLIC_MARKET_BASE_URL || 'https://market.lobehub.com';
return `${marketBaseUrl}/api/v1/skills/${identifier}/download`;
}
+
+ /**
+ * Download a skill package and return its text files, without the top-level
+ * directory prefix, `SKILL.md` (the detail endpoint serves it) and macOS
+ * metadata entries.
+ */
+ async getSkillPackageFiles(identifier: string): Promise<MarketSkillPackageFile[]> {
+ const res = await fetch(this.getSkillDownloadUrl(encodeURIComponent(identifier)));
+ if (!res.ok) throw new Error(`Skill package download failed: ${res.status}`);
+ const buf = await res.arrayBuffer();
+ const { unzip } = await import('fflate');
+
+ return new Promise((resolve, reject) => {
+ unzip(new Uint8Array(buf), (err, entries) => {
+ if (err) return reject(err);
+
+ const decoder = new TextDecoder();
+ const files: MarketSkillPackageFile[] = [];
+ for (const [rawPath, data] of Object.entries(entries)) {
+ if (rawPath.endsWith('/') || rawPath.includes('__MACOSX')) continue;
+
+ // Strip the top-level directory prefix (e.g. "skill-name/")
+ const slashIdx = rawPath.indexOf('/');
+ const path = slashIdx >= 0 ? rawPath.slice(slashIdx + 1) : rawPath;
+ if (!path || path === 'SKILL.md') continue;
+
+ files.push({ content: decoder.decode(data), path });
+ }
+
+ files.sort((a, b) => a.path.localeCompare(b.path));
+ resolve(files);
+ });
+ });
+ }
+
+ /**
+ * The Market profile of a username, or `null` when that account has not
+ * created a Market profile yet (the server answers NOT_FOUND).
+ */
+ async getUserProfile(username: string): Promise<MarketUserProfile | null> {
+ try {
+ return (await lambdaClient.market.user.getUserByUsername.query({
+ username,
+ })) as MarketUserProfile;
+ } catch (error) {
+ if (isTrpcErrorCode(error, 'NOT_FOUND')) return null;
+ throw error;
+ }
+ }
}
export const marketApiService = new MarketApiService();
diff --git a/src/store/discover/__tests__/replicaHarness.ts b/src/store/discover/__tests__/replicaHarness.ts
new file mode 100644
index 00000000000..6fe10b2152c
--- /dev/null
+++ b/src/store/discover/__tests__/replicaHarness.ts
@@ -0,0 +1,88 @@
+import { randomUUID } from 'node:crypto';
+
+import { act, cleanup } from '@testing-library/react';
+import type { PropsWithChildren } from 'react';
+import { createElement, useEffect } from 'react';
+import { SWRConfig, useSWRConfig } from 'swr';
+import { afterEach, beforeEach, vi } from 'vitest';
+
+import { AppIndexedDBStorage, cacheScope, REPLICA_INDEX_KEY } from '@/libs/replica';
+import { setScopedMutate } from '@/libs/swr/mutate';
+import { useDiscoverStore } from '@/store/discover';
+import { initialState } from '@/store/discover/initialState';
+
+/**
+ * Test harness for the discover replicas persisted to IndexedDB: a fresh
+ * identity scope per test, rows seeded through the storage namespace
+ * (`replica:<name>:v1`) and removed afterwards, and an SWR provider per render.
+ */
+
+const MutateBridge = () => {
+ const { mutate } = useSWRConfig();
+ useEffect(() => setScopedMutate(mutate), [mutate]);
+ return null;
+};
+
+export const replicaWrapper = ({ children }: PropsWithChildren) =>
+ createElement(
+ SWRConfig,
+ { value: { provider: () => new Map(), shouldRetryOnError: false } },
+ createElement(MutateBridge),
+ children,
+ );
+
+export const storageOf = (name: string) =>
+ new AppIndexedDBStorage<unknown>({ namespace: `replica:${name}:v1` });
+
+/** Never-resolving fetch: the first frame can only come from storage. */
+export const pending = () => new Promise<never>(() => {});
+
+export const deferred = <T>() => {
+ let resolve!: (value: T) => void;
+ let reject!: (error: unknown) => void;
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, reject, resolve };
+};
+
+/** Install the per-test scope and cleanup; call once at the top of a `describe`. */
+export const useReplicaHarness = (label: string) => {
+ const state = { scope: '' };
+ const seeded: { name: string; queryKey: string; scope: string }[] = [];
+
+ beforeEach(() => {
+ state.scope = `${label}-${randomUUID()}:personal`;
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => state.scope);
+ vi.spyOn(cacheScope, 'use').mockImplementation(() => state.scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ act(() => useDiscoverStore.setState(initialState, false));
+ });
+
+ afterEach(async () => {
+ cleanup();
+ for (const row of seeded.splice(0)) {
+ const storage = storageOf(row.name);
+ await storage.remove({ queryKey: row.queryKey, scope: row.scope });
+ await storage.remove({ queryKey: REPLICA_INDEX_KEY, scope: row.scope });
+ }
+ vi.restoreAllMocks();
+ });
+
+ return {
+ /** Seed one persisted row (in another scope with `at`). */
+ persist: async (name: string, queryKey: string, data: unknown, at = state.scope) => {
+ seeded.push({ name, queryKey, scope: at });
+ await storageOf(name).set({ queryKey, scope: at }, { data, updatedAt: 1 });
+ },
+ get scope() {
+ return state.scope;
+ },
+ /** Read one persisted row of the active scope. */
+ stored: async (name: string, queryKey: string) => {
+ seeded.push({ name, queryKey, scope: state.scope });
+ return (await storageOf(name).get({ queryKey, scope: state.scope }))?.data;
+ },
+ };
+};
diff --git a/src/store/discover/initialState.ts b/src/store/discover/initialState.ts
index 4a9dadbd8d9..c194ba52951 100644
--- a/src/store/discover/initialState.ts
+++ b/src/store/discover/initialState.ts
@@ -2,6 +2,8 @@ import type { AssistantSliceState } from './slices/assistant/initialState';
import { initialAssistantSliceState } from './slices/assistant/initialState';
import type { GroupAgentSliceState } from './slices/groupAgent/initialState';
import { initialGroupAgentSliceState } from './slices/groupAgent/initialState';
+import type { MarketSliceState } from './slices/market/initialState';
+import { initialMarketSliceState } from './slices/market/initialState';
import type { MCPSliceState } from './slices/mcp/initialState';
import { initialMCPSliceState } from './slices/mcp/initialState';
import type { ModelSliceState } from './slices/model/initialState';
@@ -23,6 +25,7 @@ import { initialUserSliceState } from './slices/user/initialState';
*/
export type DiscoverStoreState = AssistantSliceState &
GroupAgentSliceState &
+ MarketSliceState &
MCPSliceState &
ModelSliceState &
PluginSliceState &
@@ -34,6 +37,7 @@ export type DiscoverStoreState = AssistantSliceState &
export const initialState: DiscoverStoreState = {
...initialAssistantSliceState,
...initialGroupAgentSliceState,
+ ...initialMarketSliceState,
...initialMCPSliceState,
...initialModelSliceState,
...initialPluginSliceState,
diff --git a/src/store/discover/selectors/index.ts b/src/store/discover/selectors/index.ts
index 1f247cb8a61..60418d02b6b 100644
--- a/src/store/discover/selectors/index.ts
+++ b/src/store/discover/selectors/index.ts
@@ -1,5 +1,6 @@
export { assistantSelectors } from './assistantSelectors';
export { groupAgentSelectors } from './groupAgentSelectors';
+export { marketSelectors } from './marketSelectors';
export { mcpSelectors } from './mcpSelectors';
export { modelSelectors } from './modelSelectors';
export { pluginSelectors } from './pluginSelectors';
diff --git a/src/store/discover/selectors/marketSelectors.ts b/src/store/discover/selectors/marketSelectors.ts
new file mode 100644
index 00000000000..23667e9a599
--- /dev/null
+++ b/src/store/discover/selectors/marketSelectors.ts
@@ -0,0 +1,58 @@
+import type { MarketUserProfile } from '@/layout/AuthProvider/MarketAuth/types';
+import type { MarketSkillPackageFile } from '@/services/marketApi';
+import type { AgentForkSourceResponse, AgentGroupForkSourceResponse } from '@/types/discover';
+
+import type { MarketAgentGroupStatus, MarketAgentStatus } from '../slices/market/projection';
+import type { DiscoverStore } from '../store';
+
+/**
+ * Readers of the market replicas. Every helper takes the `queryKey` the
+ * matching fetch hook returned, so a surface never reads another entry.
+ */
+const agentStatus =
+ (queryKey?: string) =>
+ (s: DiscoverStore): MarketAgentStatus | undefined =>
+ queryKey ? s.marketAgentStatusMap[queryKey] : undefined;
+
+const agentGroupStatus =
+ (queryKey?: string) =>
+ (s: DiscoverStore): MarketAgentGroupStatus | undefined =>
+ queryKey ? s.marketAgentGroupStatusMap[queryKey] : undefined;
+
+const agentForkSource =
+ (queryKey?: string) =>
+ (s: DiscoverStore): AgentForkSourceResponse['source'] | undefined =>
+ queryKey ? s.agentForkSourceMap[queryKey]?.source : undefined;
+
+const agentGroupForkSource =
+ (queryKey?: string) =>
+ (s: DiscoverStore): AgentGroupForkSourceResponse['source'] | undefined =>
+ queryKey ? s.agentGroupForkSourceMap[queryKey]?.source : undefined;
+
+const skillPackageFiles =
+ (queryKey?: string) =>
+ (s: DiscoverStore): MarketSkillPackageFile[] | undefined =>
+ queryKey ? s.skillPackageFilesMap[queryKey] : undefined;
+
+const userProfile =
+ (queryKey?: string) =>
+ (s: DiscoverStore): MarketUserProfile | undefined =>
+ queryKey ? s.marketUserProfileMap[queryKey] : undefined;
+
+/**
+ * Whether the server answered this page of a plugin's agents in this session.
+ * A hydrated page may be stale or empty, so "no agents" is only rendered once
+ * the first page is confirmed.
+ */
+const isPluginAgentsConfirmed = (queryKey?: string) => (s: DiscoverStore) =>
+ !!queryKey && s.pluginAgentsReplica.entries[queryKey]?.source === 'server';
+
+export const marketSelectors = {
+ agentForkSource,
+ agentGroupForkSource,
+ agentGroupStatus,
+ agentStatus,
+ isPluginAgentsConfirmed,
+ skillPackageFiles,
+ userProfile,
+};
diff --git a/src/store/discover/selectors/socialSelectors.ts b/src/store/discover/selectors/socialSelectors.ts
index 86abe2771e6..a9d2ee460ea 100644
--- a/src/store/discover/selectors/socialSelectors.ts
+++ b/src/store/discover/selectors/socialSelectors.ts
@@ -1,6 +1,7 @@
import {
type FavoriteAgentItem,
type FavoritePluginItem,
+ type FavoriteStatus,
type FollowCounts,
type FollowStatus,
type FollowUserItem,
@@ -34,6 +35,11 @@ const following =
(s: DiscoverStore): PaginatedResponse<FollowUserItem> | undefined =>
queryKey ? s.followingMap[queryKey] : undefined;
+const favoriteStatus =
+ (queryKey?: string) =>
+ (s: DiscoverStore): FavoriteStatus | undefined =>
+ queryKey ? s.favoriteStatusMap[queryKey] : undefined;
+
const favoriteAgents =
(queryKey?: string) =>
(s: DiscoverStore): PaginatedResponse<FavoriteAgentItem> | undefined =>
@@ -47,6 +53,7 @@ const favoritePlugins =
export const socialSelectors = {
favoriteAgents,
favoritePlugins,
+ favoriteStatus,
followCounts,
followStatus,
followers,
diff --git a/src/store/discover/slices/market/action.ts b/src/store/discover/slices/market/action.ts
new file mode 100644
index 00000000000..1facd3c0a90
--- /dev/null
+++ b/src/store/discover/slices/market/action.ts
@@ -0,0 +1,298 @@
+import { type MarketUserProfile } from '@/layout/AuthProvider/MarketAuth/types';
+import { createReplicaSlice, recordLens, type ReplicaSyncResult } from '@/libs/replica';
+import { type MarketSkillPackageFile } from '@/services/marketApi';
+import { type DiscoverStore } from '@/store/discover';
+import { globalHelpers } from '@/store/global/helpers';
+import { type StoreSetter } from '@/store/types';
+import type {
+ AgentForkSourceResponse,
+ AgentGroupForkSourceResponse,
+ AssistantListResponse,
+} from '@/types/discover';
+import { setNamespace } from '@/utils/storeDebug';
+import { isTrpcErrorCode } from '@/utils/trpcError';
+
+import {
+ agentForkSourceResource,
+ agentGroupForkSourceResource,
+ type MarketAgentGroupStatus,
+ marketAgentGroupStatusResource,
+ type MarketAgentStatus,
+ marketAgentStatusResource,
+ marketIdentifierKey,
+ marketUserProfileKey,
+ marketUserProfileResource,
+ type PluginAgentsParams,
+ pluginAgentsQueryKey,
+ pluginAgentsResource,
+ skillPackageFilesResource,
+} from './projection';
+
+const n = setNamespace('discover/market');
+
+/**
+ * Several tags of one header (status, fork, review) and every mounted copy of
+ * a community header read the same entry. Collapse their mounts into one
+ * request; an explicit refresh still goes out.
+ */
+const SHARED_READ_DEDUPING_INTERVAL = 10_000;
+
+/** Sync flags of a market read, plus the entry key to read it by. */
+export interface MarketSyncResult extends ReplicaSyncResult {
+ /** A request is in flight and this entry has no value to show yet. */
+ isLoading: boolean;
+ /** Read the value with `marketSelectors.*(queryKey)`; undefined while disabled. */
+ queryKey?: string;
+}
+
+/** Page size of the "agents using this plugin" grids. */
+export const PLUGIN_AGENTS_PAGE_SIZE = 12;
+
+/** Params of one page of a plugin's agents, in the current UI language. */
+export const pluginAgentsParams = (pluginId: string, page: number): PluginAgentsParams => ({
+ locale: globalHelpers.getCurrentLanguage(),
+ page,
+ pageSize: PLUGIN_AGENTS_PAGE_SIZE,
+ pluginId,
+});
+
+type Setter = StoreSetter<DiscoverStore>;
+
+const toSyncResult = (
+ sync: ReplicaSyncResult,
+ queryKey: string,
+ hasValue: boolean,
+ active: boolean,
+): MarketSyncResult => ({
+ ...sync,
+ isLoading: active && !hasValue && (!sync.isHydrated || sync.isValidating),
+ queryKey: active ? queryKey : undefined,
+});
+
+export const createMarketSlice = (set: Setter, get: () => DiscoverStore, _api?: unknown) =>
+ new MarketActionImpl(set, get, _api);
+
+export class MarketActionImpl {
+ readonly #agentForkSource;
+ readonly #agentGroupForkSource;
+ readonly #agentGroupStatus;
+ readonly #agentStatus;
+ readonly #get: () => DiscoverStore;
+ readonly #pluginAgents;
+ readonly #skillPackageFiles;
+ readonly #userProfile;
+
+ constructor(set: Setter, get: () => DiscoverStore, _api?: unknown) {
+ void _api;
+ this.#get = get;
+ this.#agentStatus = createReplicaSlice(marketAgentStatusResource, {
+ actionPrefix: n('agentStatus'),
+ get,
+ set,
+ stateKey: 'marketAgentStatusReplica',
+ view: recordLens<DiscoverStore, MarketAgentStatus>('marketAgentStatusMap'),
+ });
+ this.#agentGroupStatus = createReplicaSlice(marketAgentGroupStatusResource, {
+ actionPrefix: n('agentGroupStatus'),
+ get,
+ set,
+ stateKey: 'marketAgentGroupStatusReplica',
+ view: recordLens<DiscoverStore, MarketAgentGroupStatus>('marketAgentGroupStatusMap'),
+ });
+ this.#agentForkSource = createReplicaSlice(agentForkSourceResource, {
+ actionPrefix: n('agentForkSource'),
+ get,
+ set,
+ stateKey: 'agentForkSourceReplica',
+ view: recordLens<DiscoverStore, AgentForkSourceResponse>('agentForkSourceMap'),
+ });
+ this.#agentGroupForkSource = createReplicaSlice(agentGroupForkSourceResource, {
+ actionPrefix: n('agentGroupForkSource'),
+ get,
+ set,
+ stateKey: 'agentGroupForkSourceReplica',
+ view: recordLens<DiscoverStore, AgentGroupForkSourceResponse>('agentGroupForkSourceMap'),
+ });
+ this.#pluginAgents = createReplicaSlice(pluginAgentsResource, {
+ actionPrefix: n('pluginAgents'),
+ get,
+ set,
+ stateKey: 'pluginAgentsReplica',
+ view: recordLens<DiscoverStore, AssistantListResponse>('pluginAgentsMap'),
+ });
+ this.#skillPackageFiles = createReplicaSlice(skillPackageFilesResource, {
+ actionPrefix: n('skillPackageFiles'),
+ get,
+ set,
+ stateKey: 'skillPackageFilesReplica',
+ view: recordLens<DiscoverStore, MarketSkillPackageFile[]>('skillPackageFilesMap'),
+ });
+ this.#userProfile = createReplicaSlice(marketUserProfileResource, {
+ actionPrefix: n('userProfile'),
+ get,
+ // No Market profile for this username (any more): drop the entry and its
+ // persisted row instead of painting the old profile.
+ isMissing: (profile) => profile === null,
+ set,
+ stateKey: 'marketUserProfileReplica',
+ view: recordLens<DiscoverStore, MarketUserProfile>('marketUserProfileMap'),
+ });
+ }
+
+ /**
+ * Publish status, fork marker and review state of the viewer's own Market
+ * agent. Read it with `marketSelectors.agentStatus(queryKey)`. An agent the
+ * Market no longer has (NOT_FOUND) drops its entry, memory and persisted row,
+ * so the header stops painting a status for it.
+ */
+ useMarketAgentStatus = (identifier?: string): MarketSyncResult => {
+ const active = !!identifier;
+ const params = { identifier: identifier ?? '' };
+ const queryKey = marketIdentifierKey(params);
+ const sync = this.#agentStatus.useSync(active ? params : null, {
+ dedupingInterval: SHARED_READ_DEDUPING_INTERVAL,
+ onError: (error, { key, scope }) => {
+ if (key && isTrpcErrorCode(error, 'NOT_FOUND')) this.#agentStatus.remove(key, scope);
+ },
+ revalidateOnFocus: false,
+ });
+ return toSyncResult(
+ sync,
+ queryKey,
+ active && this.#get().marketAgentStatusMap[queryKey] !== undefined,
+ active,
+ );
+ };
+
+ /** Refetch an agent's Market status after a submission changed it. */
+ refreshMarketAgentStatus = async (identifier: string): Promise<void> => {
+ await this.#agentStatus.fetch({ identifier }, { fresh: true });
+ };
+
+ /** Review state of the viewer's own Market group (`marketSelectors.agentGroupStatus`). */
+ useMarketAgentGroupStatus = (identifier?: string): MarketSyncResult => {
+ const active = !!identifier;
+ const params = { identifier: identifier ?? '' };
+ const queryKey = marketIdentifierKey(params);
+ const sync = this.#agentGroupStatus.useSync(active ? params : null, {
+ dedupingInterval: SHARED_READ_DEDUPING_INTERVAL,
+ onError: (error, { key, scope }) => {
+ if (key && isTrpcErrorCode(error, 'NOT_FOUND')) this.#agentGroupStatus.remove(key, scope);
+ },
+ revalidateOnFocus: false,
+ });
+ return toSyncResult(
+ sync,
+ queryKey,
+ active && this.#get().marketAgentGroupStatusMap[queryKey] !== undefined,
+ active,
+ );
+ };
+
+ /**
+ * Fork source of an agent (`marketSelectors.agentForkSource`). Pass
+ * `enabled: false` until the agent is known to be a fork.
+ */
+ useAgentForkSource = (identifier?: string, enabled = true): MarketSyncResult => {
+ const active = enabled && !!identifier;
+ const params = { identifier: identifier ?? '' };
+ const queryKey = marketIdentifierKey(params);
+ const sync = this.#agentForkSource.useSync(active ? params : null, {
+ dedupingInterval: SHARED_READ_DEDUPING_INTERVAL,
+ revalidateOnFocus: false,
+ });
+ return toSyncResult(
+ sync,
+ queryKey,
+ active && this.#get().agentForkSourceMap[queryKey] !== undefined,
+ active,
+ );
+ };
+
+ /** Fork source of a group (`marketSelectors.agentGroupForkSource`). */
+ useAgentGroupForkSource = (identifier?: string, enabled = true): MarketSyncResult => {
+ const active = enabled && !!identifier;
+ const params = { identifier: identifier ?? '' };
+ const queryKey = marketIdentifierKey(params);
+ const sync = this.#agentGroupForkSource.useSync(active ? params : null, {
+ dedupingInterval: SHARED_READ_DEDUPING_INTERVAL,
+ revalidateOnFocus: false,
+ });
+ return toSyncResult(
+ sync,
+ queryKey,
+ active && this.#get().agentGroupForkSourceMap[queryKey] !== undefined,
+ active,
+ );
+ };
+
+ /**
+ * One page of the agents that use a plugin or skill. The grid walks pages by
+ * mounting the next one; read the loaded pages with
+ * `marketSelectors.pluginAgentPages(pluginId, pageCount)`.
+ */
+ usePluginAgents = (pluginId: string | undefined, page: number): MarketSyncResult => {
+ const active = !!pluginId;
+ const params = pluginAgentsParams(pluginId ?? '', page);
+ const queryKey = pluginAgentsQueryKey(params);
+ const sync = this.#pluginAgents.useSync(active ? params : null, {
+ revalidateOnFocus: false,
+ });
+ return toSyncResult(
+ sync,
+ queryKey,
+ active && this.#get().pluginAgentsMap[queryKey] !== undefined,
+ active,
+ );
+ };
+
+ /**
+ * Text files of a Market skill package. Disabled for an installed skill,
+ * whose files come from the local copy. Read them with
+ * `marketSelectors.skillPackageFiles(queryKey)`.
+ */
+ useSkillPackageFiles = (identifier: string | undefined, enabled = true): MarketSyncResult => {
+ const active = enabled && !!identifier;
+ const params = { identifier: identifier ?? '' };
+ const queryKey = marketIdentifierKey(params);
+ const sync = this.#skillPackageFiles.useSync(active ? params : null, {
+ revalidateOnFocus: false,
+ revalidateOnReconnect: false,
+ });
+ return toSyncResult(
+ sync,
+ queryKey,
+ active && this.#get().skillPackageFilesMap[queryKey] !== undefined,
+ active,
+ );
+ };
+
+ /**
+ * The signed-in viewer's Market profile. Read it with
+ * `marketSelectors.userProfile(queryKey)`; `undefined` while unloaded or when
+ * the account has no Market profile yet.
+ */
+ useMarketUserProfile = (username: string | null | undefined): MarketSyncResult => {
+ const active = !!username;
+ const params = { username: username ?? '' };
+ const queryKey = marketUserProfileKey(params);
+ const sync = this.#userProfile.useSync(active ? params : null, {
+ dedupingInterval: 60_000,
+ revalidateOnFocus: false,
+ revalidateOnReconnect: false,
+ });
+ return toSyncResult(
+ sync,
+ queryKey,
+ active && this.#get().marketUserProfileMap[queryKey] !== undefined,
+ active,
+ );
+ };
+
+ /** Write a profile the server just returned from an edit, memory and persisted row. */
+ setMarketUserProfile = (username: string, profile: MarketUserProfile): void => {
+ this.#userProfile.update(marketUserProfileKey({ username }), () => profile);
+ };
+}
+
+export type MarketAction = Pick<MarketActionImpl, keyof MarketActionImpl>;
diff --git a/src/store/discover/slices/market/forkSource.replica.test.ts b/src/store/discover/slices/market/forkSource.replica.test.ts
new file mode 100644
index 00000000000..bebb8c65676
--- /dev/null
+++ b/src/store/discover/slices/market/forkSource.replica.test.ts
@@ -0,0 +1,49 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The community detail's "Forked from" tag reads the fork source replica
+ * persisted to IndexedDB, shared with the profile header: a reload paints the
+ * last confirmed source before the network answers, and an agent that is not
+ * a fork never asks for one.
+ */
+import { renderHook, waitFor } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { marketApiService } from '@/services/marketApi';
+import { useDiscoverStore } from '@/store/discover';
+import {
+ pending,
+ replicaWrapper as wrapper,
+ useReplicaHarness,
+} from '@/store/discover/__tests__/replicaHarness';
+import { marketSelectors } from '@/store/discover/selectors';
+
+const useForkSource = (identifier: string, isFork: boolean) => {
+ const { queryKey } = useDiscoverStore((s) => s.useAgentForkSource)(identifier, isFork);
+ return useDiscoverStore(marketSelectors.agentForkSource(queryKey));
+};
+
+describe('agent fork source replica', () => {
+ const { persist } = useReplicaHarness('fork-source');
+
+ it('paints the persisted fork source before the network answers', async () => {
+ await persist('discoverAgentForkSource', 'forked-agent', {
+ source: { identifier: 'origin-agent', name: 'Origin Agent' },
+ });
+ vi.spyOn(marketApiService, 'getAgentForkSource').mockImplementation(pending);
+
+ const { result } = renderHook(() => useForkSource('forked-agent', true), { wrapper });
+
+ await waitFor(() => expect(result.current?.name).toBe('Origin Agent'));
+ });
+
+ it('does not ask for the fork source of an agent that is not a fork', async () => {
+ const getAgentForkSource = vi.spyOn(marketApiService, 'getAgentForkSource');
+
+ const { result } = renderHook(() => useForkSource('plain-agent', false), { wrapper });
+
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(result.current).toBeUndefined();
+ expect(getAgentForkSource).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/store/discover/slices/market/index.ts b/src/store/discover/slices/market/index.ts
new file mode 100644
index 00000000000..2c0622fbb9c
--- /dev/null
+++ b/src/store/discover/slices/market/index.ts
@@ -0,0 +1 @@
+export * from './action';
diff --git a/src/store/discover/slices/market/initialState.ts b/src/store/discover/slices/market/initialState.ts
new file mode 100644
index 00000000000..4ddb5b9b283
--- /dev/null
+++ b/src/store/discover/slices/market/initialState.ts
@@ -0,0 +1,63 @@
+import { type MarketUserProfile } from '@/layout/AuthProvider/MarketAuth/types';
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
+import { type MarketSkillPackageFile } from '@/services/marketApi';
+import type {
+ AgentForkSourceResponse,
+ AgentGroupForkSourceResponse,
+ AssistantListResponse,
+} from '@/types/discover';
+
+import { type MarketAgentGroupStatus, type MarketAgentStatus } from './projection';
+
+/**
+ * Replica views of the market reads around one published agent, group or
+ * skill, each beside its bookkeeping slot. Components read them through
+ * `marketSelectors`, never through the fetch hook.
+ */
+export interface MarketSliceState {
+ /** Fork source per agent identifier. */
+ agentForkSourceMap: Record<string, AgentForkSourceResponse>;
+ /** Replica bookkeeping of `agentForkSourceMap`. */
+ agentForkSourceReplica: ReplicaState<AgentForkSourceResponse>;
+ /** Fork source per group identifier. */
+ agentGroupForkSourceMap: Record<string, AgentGroupForkSourceResponse>;
+ /** Replica bookkeeping of `agentGroupForkSourceMap`. */
+ agentGroupForkSourceReplica: ReplicaState<AgentGroupForkSourceResponse>;
+ /** Review status per group identifier. */
+ marketAgentGroupStatusMap: Record<string, MarketAgentGroupStatus>;
+ /** Replica bookkeeping of `marketAgentGroupStatusMap`. */
+ marketAgentGroupStatusReplica: ReplicaState<MarketAgentGroupStatus>;
+ /** Publish status per agent identifier. */
+ marketAgentStatusMap: Record<string, MarketAgentStatus>;
+ /** Replica bookkeeping of `marketAgentStatusMap`. */
+ marketAgentStatusReplica: ReplicaState<MarketAgentStatus>;
+ /** The viewer's Market profile per username. */
+ marketUserProfileMap: Record<string, MarketUserProfile>;
+ /** Replica bookkeeping of `marketUserProfileMap`. */
+ marketUserProfileReplica: ReplicaState<MarketUserProfile>;
+ /** Agents using a plugin, per page (`pluginAgentsQueryKey`). */
+ pluginAgentsMap: Record<string, AssistantListResponse>;
+ /** Replica bookkeeping of `pluginAgentsMap`. */
+ pluginAgentsReplica: ReplicaState<AssistantListResponse>;
+ /** Package text files per skill identifier. */
+ skillPackageFilesMap: Record<string, MarketSkillPackageFile[]>;
+ /** Replica bookkeeping of `skillPackageFilesMap`. */
+ skillPackageFilesReplica: ReplicaState<MarketSkillPackageFile[]>;
+}
+
+export const initialMarketSliceState: MarketSliceState = {
+ agentForkSourceMap: {},
+ agentForkSourceReplica: createReplicaState(),
+ agentGroupForkSourceMap: {},
+ agentGroupForkSourceReplica: createReplicaState(),
+ marketAgentGroupStatusMap: {},
+ marketAgentGroupStatusReplica: createReplicaState(),
+ marketAgentStatusMap: {},
+ marketAgentStatusReplica: createReplicaState(),
+ marketUserProfileMap: {},
+ marketUserProfileReplica: createReplicaState(),
+ pluginAgentsMap: {},
+ pluginAgentsReplica: createReplicaState(),
+ skillPackageFilesMap: {},
+ skillPackageFilesReplica: createReplicaState(),
+};
diff --git a/src/store/discover/slices/market/projection.ts b/src/store/discover/slices/market/projection.ts
new file mode 100644
index 00000000000..989b6c3a81f
--- /dev/null
+++ b/src/store/discover/slices/market/projection.ts
@@ -0,0 +1,206 @@
+import { type MarketUserProfile } from '@/layout/AuthProvider/MarketAuth/types';
+import { defineReplica, stableQueryKey } from '@/libs/replica';
+import { discoverService } from '@/services/discover';
+import { marketApiService, type MarketSkillPackageFile } from '@/services/marketApi';
+import type {
+ AgentForkSourceResponse,
+ AgentGroupForkSourceResponse,
+ AgentStatus,
+ AssistantListResponse,
+} from '@/types/discover';
+
+/**
+ * Market reads around one published agent, group or skill that the community
+ * detail pages and the agent / group profile headers paint: publish status,
+ * fork source, the agents using a plugin, a skill's package files and the
+ * viewer's own Market profile.
+ *
+ * All of them are per identity (`cacheScope`), so an account or workspace
+ * switch never paints the previous one's rows. Resource names stay clear of
+ * the `CACHE_TIERS` patterns so the SWR persistence layer never stores a second
+ * copy of a sync response.
+ */
+
+/** Read addressed by one Market identifier (agent, group or skill). */
+export interface MarketIdentifierParams {
+ identifier: string;
+}
+
+/** Entry key of an identifier-addressed read. */
+export const marketIdentifierKey = ({ identifier }: MarketIdentifierParams): string => identifier;
+
+/** Persisted entries kept per resource; older identifiers fall back to the network. */
+const MAX_PERSISTED_MARKET_ENTRIES = 50;
+
+// ============================== Agent publish status ==============================
+
+/**
+ * What the agent profile header needs from the owner's Market agent detail.
+ * The full detail carries every version's config; only these fields persist.
+ */
+export interface MarketAgentStatus {
+ /** Set when the agent is a fork; its fork source is a separate read. */
+ forkedFromAgentId: string | null;
+ /** The latest version is waiting for review (`isValidated === false`). */
+ latestVersionUnderReview: boolean;
+ status: AgentStatus | null;
+}
+
+interface MarketVersionLike {
+ isValidated?: boolean;
+}
+
+const isLatestVersionUnderReview = (versions: unknown): boolean =>
+ Array.isArray(versions) &&
+ versions.length > 0 &&
+ (versions[0] as MarketVersionLike).isValidated === false;
+
+/**
+ * One agent's Market status (`marketAgentStatusMap[identifier]`). The status,
+ * fork and review tags of the profile header all read this one entry, so the
+ * header costs a single detail request instead of one per tag.
+ */
+export const marketAgentStatusResource = defineReplica<MarketIdentifierParams, MarketAgentStatus>({
+ fetcher: async ({ identifier }) => {
+ const detail = await marketApiService.getAgentDetail(identifier);
+ return {
+ forkedFromAgentId: detail.forkedFromAgentId ? String(detail.forkedFromAgentId) : null,
+ latestVersionUnderReview: isLatestVersionUnderReview(
+ (detail as { versions?: unknown }).versions,
+ ),
+ status: (detail.status as AgentStatus | undefined) ?? null,
+ };
+ },
+ key: marketIdentifierKey,
+ name: 'discoverMarketAgentStatus',
+ persist: { maxEntries: MAX_PERSISTED_MARKET_ENTRIES },
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** What the group profile header needs from the owner's Market group detail. */
+export interface MarketAgentGroupStatus {
+ latestVersionUnderReview: boolean;
+}
+
+/** One group's Market review status (`marketAgentGroupStatusMap[identifier]`). */
+export const marketAgentGroupStatusResource = defineReplica<
+ MarketIdentifierParams,
+ MarketAgentGroupStatus
+>({
+ fetcher: async ({ identifier }) => {
+ const detail = await marketApiService.getAgentGroupDetail(identifier);
+ return { latestVersionUnderReview: isLatestVersionUnderReview(detail?.versions) };
+ },
+ key: marketIdentifierKey,
+ name: 'discoverMarketAgentGroupStatus',
+ persist: { maxEntries: MAX_PERSISTED_MARKET_ENTRIES },
+ storage: 'indexedDB',
+ version: 1,
+});
+
+// ============================== Fork source ==============================
+
+/**
+ * Where an agent was forked from (`agentForkSourceMap[identifier]`). The
+ * community detail tag and the profile header tag share the entry.
+ */
+export const agentForkSourceResource = defineReplica<
+ MarketIdentifierParams,
+ AgentForkSourceResponse
+>({
+ fetcher: ({ identifier }) => marketApiService.getAgentForkSource(identifier),
+ key: marketIdentifierKey,
+ name: 'discoverAgentForkSource',
+ persist: { maxEntries: MAX_PERSISTED_MARKET_ENTRIES },
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** Where a group was forked from (`agentGroupForkSourceMap[identifier]`). */
+export const agentGroupForkSourceResource = defineReplica<
+ MarketIdentifierParams,
+ AgentGroupForkSourceResponse
+>({
+ fetcher: ({ identifier }) => marketApiService.getAgentGroupForkSource(identifier),
+ key: marketIdentifierKey,
+ name: 'discoverAgentGroupForkSource',
+ persist: { maxEntries: MAX_PERSISTED_MARKET_ENTRIES },
+ storage: 'indexedDB',
+ version: 1,
+});
+
+// ============================== Agents using a plugin ==============================
+
+/** One page of the agents that use a plugin or skill. */
+export interface PluginAgentsParams {
+ /** Current UI language; the service localizes the agent copy. */
+ locale: string;
+ page: number;
+ pageSize: number;
+ pluginId: string;
+}
+
+/** Entry key of one page of a plugin's agents. */
+export const pluginAgentsQueryKey = (params: PluginAgentsParams): string => stableQueryKey(params);
+
+/**
+ * Agents that use a plugin (`pluginAgentsMap[queryKey]`), one entry per page.
+ * The MCP detail and the skill detail both list them from the same endpoint,
+ * so the same plugin shares its entries across both surfaces.
+ */
+export const pluginAgentsResource = defineReplica<PluginAgentsParams, AssistantListResponse>({
+ fetcher: ({ page, pageSize, pluginId }) =>
+ discoverService.getAgentsByPlugin({ page, pageSize, pluginId }),
+ key: pluginAgentsQueryKey,
+ name: 'discoverPluginAgents',
+ persist: { maxEntries: MAX_PERSISTED_MARKET_ENTRIES },
+ storage: 'indexedDB',
+ version: 1,
+});
+
+// ============================== Skill package files ==============================
+
+/**
+ * The text files of a Market skill package (`skillPackageFilesMap[identifier]`),
+ * so an uninstalled skill's file tree paints without downloading the zip
+ * again. Packages can be large, so fewer entries persist than for the other
+ * reads.
+ */
+export const skillPackageFilesResource = defineReplica<
+ MarketIdentifierParams,
+ MarketSkillPackageFile[]
+>({
+ fetcher: ({ identifier }) => marketApiService.getSkillPackageFiles(identifier),
+ key: marketIdentifierKey,
+ name: 'discoverSkillPackageFiles',
+ persist: { maxEntries: 20 },
+ storage: 'indexedDB',
+ version: 1,
+});
+
+// ============================== Market user profile ==============================
+
+export interface MarketUserProfileParams {
+ username: string;
+}
+
+/** Entry key of one Market profile. */
+export const marketUserProfileKey = ({ username }: MarketUserProfileParams): string => username;
+
+/**
+ * The signed-in viewer's Market profile (`marketUserProfileMap[username]`).
+ * Holds only the public profile fields; the Market session and its tokens stay
+ * in the auth provider. `null` (no profile created yet) drops the entry.
+ */
+export const marketUserProfileResource = defineReplica<
+ MarketUserProfileParams,
+ MarketUserProfile,
+ MarketUserProfile | null
+>({
+ fetcher: ({ username }) => marketApiService.getUserProfile(username),
+ key: marketUserProfileKey,
+ name: 'discoverMarketUserProfile',
+ storage: 'indexedDB',
+ version: 1,
+});
diff --git a/src/store/discover/slices/market/skillPackageFiles.replica.test.ts b/src/store/discover/slices/market/skillPackageFiles.replica.test.ts
new file mode 100644
index 00000000000..45b604e39f4
--- /dev/null
+++ b/src/store/discover/slices/market/skillPackageFiles.replica.test.ts
@@ -0,0 +1,48 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * An uninstalled Market skill's package files are a replica persisted to
+ * IndexedDB, so a reopened Skill Store detail paints its file tree without
+ * waiting for the zip download again; an installed skill never downloads it.
+ */
+import { renderHook, waitFor } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { marketApiService } from '@/services/marketApi';
+import { useDiscoverStore } from '@/store/discover';
+import {
+ pending,
+ replicaWrapper as wrapper,
+ useReplicaHarness,
+} from '@/store/discover/__tests__/replicaHarness';
+import { marketSelectors } from '@/store/discover/selectors';
+
+const usePackageFiles = (enabled: boolean) => {
+ const { queryKey } = useDiscoverStore((s) => s.useSkillPackageFiles)('pdf-tools', enabled);
+ return useDiscoverStore(marketSelectors.skillPackageFiles(queryKey));
+};
+
+describe('skill package files replica', () => {
+ const { persist } = useReplicaHarness('skill-files');
+
+ it('paints the persisted files before the download finishes', async () => {
+ await persist('discoverSkillPackageFiles', 'pdf-tools', [
+ { content: 'print("hi")', path: 'scripts/run.py' },
+ ]);
+ vi.spyOn(marketApiService, 'getSkillPackageFiles').mockImplementation(pending);
+
+ const { result } = renderHook(() => usePackageFiles(true), { wrapper });
+
+ await waitFor(() => expect(result.current?.[0]?.path).toBe('scripts/run.py'));
+ });
+
+ it('does not download the package of an installed skill', async () => {
+ const download = vi.spyOn(marketApiService, 'getSkillPackageFiles');
+
+ const { result } = renderHook(() => usePackageFiles(false), { wrapper });
+
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(result.current).toBeUndefined();
+ expect(download).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/store/discover/slices/skill/action.ts b/src/store/discover/slices/skill/action.ts
index e649c79da38..ccfb551ae02 100644
--- a/src/store/discover/slices/skill/action.ts
+++ b/src/store/discover/slices/skill/action.ts
@@ -54,6 +54,25 @@ export interface SkillSyncResult extends ReplicaSyncResult {
type Setter = StoreSetter<DiscoverStore>;
+export interface SkillListSyncOptions {
+ /** Collapse mounts of the same query within this window (ms). */
+ dedupingInterval?: number;
+ enabled?: boolean;
+ revalidateOnFocus?: boolean;
+}
+
+/**
+ * The params a skill list query is stored under: the UI language and the page
+ * / page size defaults the market endpoint applies. A reader that walks several
+ * pages builds each page's `skillListQueryKey` from this.
+ */
+export const normalizeSkillListParams = (params: SkillQueryParams = {}): SkillListParams => ({
+ ...params,
+ locale: globalHelpers.getCurrentLanguage(),
+ page: params.page ? Number(params.page) : 1,
+ pageSize: params.pageSize ? Number(params.pageSize) : 21,
+});
+
export const createSkillSlice = (set: Setter, get: () => DiscoverStore, _api?: unknown) =>
new SkillActionImpl(set, get, _api);
@@ -133,17 +152,12 @@ export class SkillActionImpl {
*/
useFetchSkillList = (
params: SkillQueryParams = {},
- options: { enabled?: boolean } = {},
+ options: SkillListSyncOptions = {},
): SkillSyncResult => {
- const { enabled = true } = options;
- const normalized: SkillListParams = {
- ...params,
- locale: globalHelpers.getCurrentLanguage(),
- page: params.page ? Number(params.page) : 1,
- pageSize: params.pageSize ? Number(params.pageSize) : 21,
- };
+ const { enabled = true, ...schedule } = options;
+ const normalized = normalizeSkillListParams(params);
const queryKey = skillListQueryKey(normalized);
- const sync = this.#list.useSync(normalized, { enabled });
+ const sync = this.#list.useSync(normalized, { enabled, ...schedule });
return this.#toSyncResult(sync, queryKey, !!this.#get().skillListMap[queryKey], enabled);
};
diff --git a/src/store/discover/slices/skill/projection.ts b/src/store/discover/slices/skill/projection.ts
index 2479af78d9d..f1511921d2f 100644
--- a/src/store/discover/slices/skill/projection.ts
+++ b/src/store/discover/slices/skill/projection.ts
@@ -51,6 +51,9 @@ export const skillListResource = defineReplica<SkillListParams, SkillListRespons
fetcher: (params) => discoverService.getSkillList(params),
key: skillListQueryKey,
name: 'skillList',
+ // Every search term and page of the community list and the Skill Store is
+ // its own entry; keep the most recently used ones.
+ persist: { maxEntries: 100 },
storage: 'indexedDB',
version: 1,
});
diff --git a/src/store/discover/slices/social/action.ts b/src/store/discover/slices/social/action.ts
index cd2f8b436a2..be29875e21b 100644
--- a/src/store/discover/slices/social/action.ts
+++ b/src/store/discover/slices/social/action.ts
@@ -2,6 +2,7 @@ import { createReplicaSlice, recordLens, type ReplicaSyncResult } from '@/libs/r
import {
type FavoriteAgentItem,
type FavoritePluginItem,
+ type FavoriteStatus,
type FollowCounts,
type FollowStatus,
type FollowUserItem,
@@ -16,6 +17,8 @@ import { setNamespace } from '@/utils/storeDebug';
import {
favoriteAgentsResource,
favoritePluginsResource,
+ favoriteStatusKey,
+ favoriteStatusResource,
followCountsResource,
followersResource,
followingResource,
@@ -82,6 +85,7 @@ export const createSocialSlice = (set: Setter, get: () => DiscoverStore, _api?:
export class SocialActionImpl {
readonly #favoriteAgents;
readonly #favoritePlugins;
+ readonly #favoriteStatus;
readonly #followCounts;
readonly #followStatus;
readonly #followers;
@@ -126,6 +130,13 @@ export class SocialActionImpl {
stateKey: 'favoriteAgentsReplica',
view: recordLens<DiscoverStore, PaginatedResponse<FavoriteAgentItem>>('favoriteAgentsMap'),
});
+ this.#favoriteStatus = createReplicaSlice(favoriteStatusResource, {
+ actionPrefix: n('favoriteStatus'),
+ get,
+ set,
+ stateKey: 'favoriteStatusReplica',
+ view: recordLens<DiscoverStore, FavoriteStatus>('favoriteStatusMap'),
+ });
this.#favoritePlugins = createReplicaSlice(favoritePluginsResource, {
actionPrefix: n('favoritePlugins'),
get,
@@ -255,6 +266,61 @@ export class SocialActionImpl {
);
};
+ /**
+ * Whether the signed-in Market viewer has favorited a target. Pass
+ * `enabled: false` while the viewer is signed out of the Market. Read it
+ * with `socialSelectors.favoriteStatus(queryKey)`.
+ */
+ useFavoriteStatus = (
+ targetType: SocialTargetType,
+ identifier: string | undefined,
+ enabled = true,
+ ): SocialSyncResult => {
+ const active = enabled && !!identifier;
+ const params = { identifier: identifier ?? '', targetType };
+ const queryKey = favoriteStatusKey(params);
+ const sync = this.#favoriteStatus.useSync(active ? params : null, {
+ revalidateOnFocus: false,
+ });
+ return toSyncResult(
+ sync,
+ queryKey,
+ active && this.#get().favoriteStatusMap[queryKey] !== undefined,
+ active,
+ );
+ };
+
+ /**
+ * Favorite or unfavorite a target by identifier. The status flips at once and
+ * the confirmed value lands in the replica, memory and persisted row, so a
+ * reload paints it; a rejected call rolls the status back and rethrows.
+ */
+ setFavorite = async (
+ targetType: SocialTargetType,
+ identifier: string,
+ isFavorited: boolean,
+ ): Promise<void> => {
+ const key = favoriteStatusKey({ identifier, targetType });
+ const token = this.#favoriteStatus.beginOptimistic(key, () => ({ isFavorited }));
+ try {
+ if (isFavorited) await socialService.addFavorite(targetType, identifier);
+ else await socialService.removeFavorite(targetType, identifier);
+ } catch (error) {
+ token.rollback();
+ throw error;
+ }
+ token.commit();
+ // A status never loaded (no view mounted) has nothing to confirm against.
+ if (this.#get().favoriteStatusMap[key] === undefined) {
+ this.#favoriteStatus.update(key, () => ({ isFavorited }));
+ }
+ // Pick up any other server change in the background: the button is done
+ // once the write is confirmed, and a failed refresh keeps the confirmed status.
+ void Promise.all([this.#favoriteStatus.revalidate(key), this.#refreshFavorites()]).catch(
+ () => undefined,
+ );
+ };
+
/** Refresh every loaded favorites page after a favorite mutation. */
#refreshFavorites = async (): Promise<void> => {
await Promise.all([this.#favoriteAgents.revalidate(), this.#favoritePlugins.revalidate()]);
diff --git a/src/store/discover/slices/social/favoriteStatus.replica.test.ts b/src/store/discover/slices/social/favoriteStatus.replica.test.ts
new file mode 100644
index 00000000000..9f382803e66
--- /dev/null
+++ b/src/store/discover/slices/social/favoriteStatus.replica.test.ts
@@ -0,0 +1,115 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The favorite button of the MCP, agent and group detail headers reads one
+ * favorite-status replica persisted to IndexedDB. A toggle lands in memory and
+ * in the persisted row, so a reload paints the confirmed state; a rejected
+ * toggle rolls back. Agents and groups that share an identifier keep separate
+ * entries.
+ */
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { socialService } from '@/services/social';
+import { useDiscoverStore } from '@/store/discover';
+import {
+ deferred,
+ pending,
+ replicaWrapper as wrapper,
+ useReplicaHarness,
+} from '@/store/discover/__tests__/replicaHarness';
+import { socialSelectors } from '@/store/discover/selectors';
+
+import { favoriteStatusKey } from './projection';
+
+const AGENT_KEY = favoriteStatusKey({ identifier: 'shared-id', targetType: 'agent' });
+const GROUP_KEY = favoriteStatusKey({ identifier: 'shared-id', targetType: 'agent-group' });
+
+const useStatus = (targetType: 'agent' | 'agent-group', enabled = true) => {
+ const { queryKey } = useDiscoverStore((s) => s.useFavoriteStatus)(
+ targetType,
+ 'shared-id',
+ enabled,
+ );
+ return useDiscoverStore(socialSelectors.favoriteStatus(queryKey));
+};
+
+describe('favorite status replica', () => {
+ const harness = useReplicaHarness('favorite-status');
+
+ it('paints the persisted status before the network answers, then refreshes it', async () => {
+ await harness.persist('discoverFavoriteStatus', AGENT_KEY, { isFavorited: true });
+ const next = deferred<{ isFavorited: boolean }>();
+ vi.spyOn(socialService, 'checkFavoriteStatus').mockImplementation(() => next.promise);
+
+ const { result } = renderHook(() => useStatus('agent'), { wrapper });
+
+ await waitFor(() => expect(result.current?.isFavorited).toBe(true));
+ await act(async () => next.resolve({ isFavorited: false }));
+ await waitFor(() => expect(result.current?.isFavorited).toBe(false));
+ });
+
+ it('keeps an agent and a group with the same identifier apart', async () => {
+ vi.spyOn(socialService, 'checkFavoriteStatus').mockImplementation(async (targetType) => ({
+ isFavorited: targetType === 'agent-group',
+ }));
+
+ const { result } = renderHook(() => [useStatus('agent'), useStatus('agent-group')], {
+ wrapper,
+ });
+
+ await waitFor(() => {
+ expect(result.current[0]?.isFavorited).toBe(false);
+ expect(result.current[1]?.isFavorited).toBe(true);
+ });
+ });
+
+ it('shows nothing while the viewer is signed out of the Market', async () => {
+ await harness.persist('discoverFavoriteStatus', AGENT_KEY, { isFavorited: true });
+ const check = vi.spyOn(socialService, 'checkFavoriteStatus');
+
+ const { result } = renderHook(() => useStatus('agent', false), { wrapper });
+
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(result.current).toBeUndefined();
+ expect(check).not.toHaveBeenCalled();
+ });
+
+ it('writes a toggle to the persisted row so a reload paints it', async () => {
+ vi.spyOn(socialService, 'checkFavoriteStatus')
+ .mockResolvedValueOnce({ isFavorited: false })
+ .mockImplementation(pending);
+ vi.spyOn(socialService, 'addFavorite').mockResolvedValue();
+
+ const { result } = renderHook(() => useStatus('agent'), { wrapper });
+ await waitFor(() => expect(result.current?.isFavorited).toBe(false));
+
+ await act(() => useDiscoverStore.getState().setFavorite('agent', 'shared-id', true));
+
+ expect(result.current?.isFavorited).toBe(true);
+ await waitFor(async () =>
+ expect(await harness.stored('discoverFavoriteStatus', AGENT_KEY)).toEqual({
+ isFavorited: true,
+ }),
+ );
+ });
+
+ it('rolls a rejected toggle back', async () => {
+ vi.spyOn(socialService, 'checkFavoriteStatus')
+ .mockResolvedValueOnce({ isFavorited: true })
+ .mockImplementation(pending);
+ vi.spyOn(socialService, 'removeFavorite').mockRejectedValue(new Error('offline'));
+
+ const { result } = renderHook(() => useStatus('agent'), { wrapper });
+ await waitFor(() => expect(result.current?.isFavorited).toBe(true));
+
+ await act(async () => {
+ await expect(
+ useDiscoverStore.getState().setFavorite('agent', 'shared-id', false),
+ ).rejects.toThrow('offline');
+ });
+
+ expect(result.current?.isFavorited).toBe(true);
+ expect(useDiscoverStore.getState().favoriteStatusMap[GROUP_KEY]).toBeUndefined();
+ });
+});
diff --git a/src/store/discover/slices/social/initialState.ts b/src/store/discover/slices/social/initialState.ts
index 1367d503bd9..ab87560f564 100644
--- a/src/store/discover/slices/social/initialState.ts
+++ b/src/store/discover/slices/social/initialState.ts
@@ -2,6 +2,7 @@ import { createReplicaState, type ReplicaState } from '@/libs/replica';
import {
type FavoriteAgentItem,
type FavoritePluginItem,
+ type FavoriteStatus,
type FollowCounts,
type FollowStatus,
type FollowUserItem,
@@ -23,6 +24,10 @@ export interface SocialSliceState {
favoritePluginsMap: Record<string, PaginatedResponse<FavoritePluginItem>>;
/** Replica bookkeeping of `favoritePluginsMap`. */
favoritePluginsReplica: ReplicaState<PaginatedResponse<FavoritePluginItem>>;
+ /** The viewer's favorite status per target (`favoriteStatusKey`). */
+ favoriteStatusMap: Record<string, FavoriteStatus>;
+ /** Replica bookkeeping of `favoriteStatusMap`. */
+ favoriteStatusReplica: ReplicaState<FavoriteStatus>;
/** Target user's follower / following counts (`socialUserKey`). */
followCountsMap: Record<string, FollowCounts>;
/** Replica bookkeeping of `followCountsMap`. */
@@ -45,6 +50,8 @@ export const initialSocialSliceState: SocialSliceState = {
favoriteAgentsMap: {},
favoriteAgentsReplica: createReplicaState(),
favoritePluginsMap: {},
+ favoriteStatusMap: {},
+ favoriteStatusReplica: createReplicaState(),
favoritePluginsReplica: createReplicaState(),
followCountsMap: {},
followCountsReplica: createReplicaState(),
diff --git a/src/store/discover/slices/social/projection.ts b/src/store/discover/slices/social/projection.ts
index bc83fbb3178..65e0ce8ae48 100644
--- a/src/store/discover/slices/social/projection.ts
+++ b/src/store/discover/slices/social/projection.ts
@@ -2,10 +2,12 @@ import { defineReplica, stableQueryKey } from '@/libs/replica';
import {
type FavoriteAgentItem,
type FavoritePluginItem,
+ type FavoriteStatus,
type FollowCounts,
type FollowStatus,
type FollowUserItem,
type PaginatedResponse,
+ type SocialTargetType,
} from '@/services/social';
import { socialService } from '@/services/social';
@@ -103,3 +105,26 @@ export const favoritePluginsResource = defineReplica<
storage: 'indexedDB',
version: 1,
});
+
+/** Whether the viewer has favorited one Market target (an MCP plugin, agent or group). */
+export interface FavoriteStatusParams {
+ identifier: string;
+ targetType: SocialTargetType;
+}
+
+/**
+ * Entry key of one favorite status. The target type is part of it: an agent
+ * and a group can share an identifier.
+ */
+export const favoriteStatusKey = (params: FavoriteStatusParams): string => stableQueryKey(params);
+
+/** The viewer's favorite status of one target (`favoriteStatusMap[key]`). */
+export const favoriteStatusResource = defineReplica<FavoriteStatusParams, FavoriteStatus>({
+ fetcher: ({ identifier, targetType }) =>
+ socialService.checkFavoriteStatus(targetType, identifier),
+ key: favoriteStatusKey,
+ name: 'discoverFavoriteStatus',
+ persist: { maxEntries: 100 },
+ storage: 'indexedDB',
+ version: 1,
+});
diff --git a/src/store/discover/slices/user/action.ts b/src/store/discover/slices/user/action.ts
index 1196f6af336..d0a858d4640 100644
--- a/src/store/discover/slices/user/action.ts
+++ b/src/store/discover/slices/user/action.ts
@@ -74,6 +74,14 @@ export class UserActionImpl {
queryKey: active ? queryKey : undefined,
};
};
+
+ /**
+ * Refetch every community profile on screen after the viewer edited their
+ * Market profile or claimed resources.
+ */
+ refreshUserProfiles = async (): Promise<void> => {
+ await this.#profile.revalidate();
+ };
}
export type UserAction = Pick<UserActionImpl, keyof UserActionImpl>;
diff --git a/src/store/discover/store.ts b/src/store/discover/store.ts
index 5b9cdaf9e8d..6fd2ceec4d1 100644
--- a/src/store/discover/store.ts
+++ b/src/store/discover/store.ts
@@ -11,6 +11,8 @@ import { type AssistantAction } from './slices/assistant/action';
import { createAssistantSlice } from './slices/assistant/action';
import { type GroupAgentAction } from './slices/groupAgent/action';
import { createGroupAgentSlice } from './slices/groupAgent/action';
+import { type MarketAction } from './slices/market';
+import { createMarketSlice } from './slices/market';
import { type MCPAction } from './slices/mcp';
import { createMCPSlice } from './slices/mcp';
import { type ModelAction } from './slices/model/action';
@@ -29,6 +31,7 @@ import { createUserSlice } from './slices/user';
// =============== Aggregate createStoreFn ============ //
export type DiscoverStore = MCPAction &
+ MarketAction &
AssistantAction &
GroupAgentAction &
ProviderAction &
@@ -41,6 +44,7 @@ export type DiscoverStore = MCPAction &
DiscoverStoreState;
type DiscoverStoreAction = MCPAction &
+ MarketAction &
AssistantAction &
GroupAgentAction &
ProviderAction &
@@ -61,6 +65,7 @@ const createStore: StateCreator<DiscoverStore, [['zustand/devtools', never]]> =
...initialState,
...flattenActions<DiscoverStoreAction>([
createMCPSlice(...parameters),
+ createMarketSlice(...parameters),
createAssistantSlice(...parameters),
createGroupAgentSlice(...parameters),
createProviderSlice(...parameters),