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 the remaining market slices onto @lobechat/replica (#20773)

Arvin Xu293d62da1460
diff --git a/.agents/skills/testing/references/zustand-store-action-test.md b/.agents/skills/testing/references/zustand-store-action-test.md
index 113ce4b5565..447f40b9155 100644
--- a/.agents/skills/testing/references/zustand-store-action-test.md
+++ b/.agents/skills/testing/references/zustand-store-action-test.md
@@ -119,14 +119,65 @@ it('should handle streaming chunks', async () => {
});
```
-## SWR Hook Testing
+## Fetch Hook Testing
+
+### Replica-backed hooks (`useFetch*` over `@lobechat/replica`)
+
+A replica hook returns sync flags plus a `queryKey`; the data lives in the store and is read through selectors. The engine is what the test exercises, so the SWR driver is a bare recorder: capture the registered sync, run its fetcher, fold the response through `onSuccess`, then read it back with the selector.
+
+```typescript
+vi.mock('@/services/discover', () => ({
+ discoverService: { getPluginCategories: vi.fn() },
+}));
+
+// The replica schedules its fetches through the app's SWR driver.
+vi.mock('@/libs/swr', () => ({
+ mutate: vi.fn(),
+ useClientDataSWR: vi.fn(() => ({ isValidating: false, mutate: vi.fn() })),
+}));
+
+const syncCalls = async (name: string) => {
+ const { useClientDataSWR } = await import('@/libs/swr');
+ return vi
+ .mocked(useClientDataSWR)
+ .mock.calls.filter(
+ ([key]) => Array.isArray(key) && key[0] === 'replica:sync' && key[1] === name,
+ )
+ .map(([, fetcher, config]) => ({
+ config: config as { onSuccess?: (data: unknown) => void },
+ fetcher: fetcher as () => Promise<any>,
+ }));
+};
+
+it('folds the categories into the replica view the selectors read', async () => {
+ const mockData = [{ category: 'tools', count: 1 }];
+ vi.mocked(discoverService.getPluginCategories).mockResolvedValue(mockData as any);
+
+ const { result } = renderHook(() => useStore.getState().useFetchPluginCategories({ q: 'x' }));
+ const [call] = await syncCalls('pluginCategories');
+ const fetched = await call.fetcher();
+ act(() => call.config.onSuccess!(fetched));
+
+ expect(pluginSelectors.pluginCategories(result.current.queryKey)(useStore.getState())).toEqual(
+ mockData,
+ );
+});
+```
+
+**Key points for replica hooks:**
+
+- Assert on the store through selectors, not on a hook-returned `data`
+- Assert the sync options that matter (e.g. `config.revalidateOnFocus`) on the recorded call
+- See `src/store/discover/slices/*/action.test.ts` for full examples
+
+### Plain SWR hooks
```typescript
it('should fetch data', async () => {
const mockData = [{ id: '1', name: 'Item 1' }];
- vi.spyOn(discoverService, 'getPluginCategories').mockResolvedValue(mockData);
+ vi.spyOn(someService, 'getItems').mockResolvedValue(mockData);
- const { result } = renderHook(() => useStore.getState().usePluginCategories(params));
+ const { result } = renderHook(() => useStore.getState().useFetchItems(params));
await waitFor(() => {
expect(result.current.data).toEqual(mockData);
diff --git a/src/components/CommentList/index.tsx b/src/components/CommentList/index.tsx
index e48560baaec..fcdd77fe9cc 100644
--- a/src/components/CommentList/index.tsx
+++ b/src/components/CommentList/index.tsx
@@ -3,51 +3,25 @@
import { Empty, Flexbox } from '@lobehub/ui';
import { Button } from '@lobehub/ui/base-ui';
import { MessageSquare } from 'lucide-react';
-import { memo, useCallback, useState, useTransition } from 'react';
+import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { ArticleSkeleton } from '@/components/Skeleton';
-import { type SkillCommentItem, type SkillCommentListResponse } from '@/types/discover';
+import { type SkillCommentListResponse } from '@/types/discover';
import CommentItem from './CommentItem';
+import { type FetchCommentPage, useCommentPages } from './useCommentPages';
export interface CommentListProps {
- fetchMore: (params: {
- order?: 'asc' | 'desc';
- page?: number;
- pageSize?: number;
- sort?: 'createdAt' | 'upvotes';
- }) => Promise<SkillCommentListResponse>;
+ fetchMore: FetchCommentPage;
initialData?: SkillCommentListResponse;
}
const CommentList = memo<CommentListProps>(({ initialData, fetchMore }) => {
const { t } = useTranslation('discover');
const { t: tc } = useTranslation('common');
- const [items, setItems] = useState<SkillCommentItem[]>(initialData?.items ?? []);
- const [currentPage, setCurrentPage] = useState(initialData?.currentPage ?? 1);
- const [totalPages, setTotalPages] = useState(initialData?.totalPages ?? 1);
- const [totalCount, setTotalCount] = useState(initialData?.totalCount ?? 0);
- const [loadMoreFailed, setLoadMoreFailed] = useState(false);
- const [isPending, startTransition] = useTransition();
-
- const handleLoadMore = useCallback(() => {
- const nextPage = currentPage + 1;
- startTransition(async () => {
- // Keep failures inside the transition: preserve loaded comments and
- // turn the button into a retry instead of surfacing to an error boundary
- try {
- const res = await fetchMore({ order: 'desc', page: nextPage, sort: 'createdAt' });
- setItems((prev) => [...prev, ...res.items]);
- setCurrentPage(res.currentPage);
- setTotalPages(res.totalPages);
- setTotalCount(res.totalCount);
- setLoadMoreFailed(false);
- } catch {
- setLoadMoreFailed(true);
- }
- });
- }, [currentPage, fetchMore]);
+ const { currentPage, isPending, items, loadMore, loadMoreFailed, totalCount, totalPages } =
+ useCommentPages(initialData, fetchMore);
let content;
if (totalCount === 0 && !isPending) {
@@ -67,7 +41,7 @@ const CommentList = memo<CommentListProps>(({ initialData, fetchMore }) => {
)}
</Flexbox>
{currentPage < totalPages && (
- <Button block loading={isPending} onClick={handleLoadMore}>
+ <Button block loading={isPending} onClick={loadMore}>
{loadMoreFailed ? tc('retry') : t('skills.details.comments.loadMore')}
</Button>
)}
diff --git a/src/components/CommentList/useCommentPages.test.ts b/src/components/CommentList/useCommentPages.test.ts
new file mode 100644
index 00000000000..6b35fcffe9a
--- /dev/null
+++ b/src/components/CommentList/useCommentPages.test.ts
@@ -0,0 +1,55 @@
+import { act, renderHook } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { type SkillCommentListResponse } from '@/types/discover';
+
+import { type FetchCommentPage, useCommentPages } from './useCommentPages';
+
+const page = (
+ ids: string[],
+ meta: Partial<SkillCommentListResponse> = {},
+): SkillCommentListResponse =>
+ ({
+ currentPage: 1,
+ items: ids.map((id) => ({ id })),
+ totalCount: ids.length,
+ totalPages: 1,
+ ...meta,
+ }) as unknown as SkillCommentListResponse;
+
+const ids = (items: { id: unknown }[]) => items.map((item) => item.id);
+
+describe('useCommentPages', () => {
+ it('reseeds from a refreshed first page that arrives after mount', () => {
+ const fetchMore = vi.fn() as unknown as FetchCommentPage;
+ const { result, rerender } = renderHook(({ data }) => useCommentPages(data, fetchMore), {
+ initialProps: { data: page(['cached']) },
+ });
+ expect(ids(result.current.items)).toEqual(['cached']);
+
+ // Revalidation replaces the persisted first page with fresh content.
+ rerender({ data: page(['new', 'cached']) });
+
+ expect(ids(result.current.items)).toEqual(['new', 'cached']);
+ expect(result.current.totalCount).toBe(2);
+ });
+
+ it('keeps later pages when the first page refreshes with identical content', async () => {
+ const fetchMore = vi
+ .fn()
+ .mockResolvedValue(page(['two'], { currentPage: 2, totalCount: 2, totalPages: 2 }));
+ const { result, rerender } = renderHook(({ data }) => useCommentPages(data, fetchMore), {
+ initialProps: { data: page(['one'], { totalCount: 2, totalPages: 2 }) },
+ });
+
+ await act(async () => {
+ result.current.loadMore();
+ });
+ expect(ids(result.current.items)).toEqual(['one', 'two']);
+
+ rerender({ data: page(['one'], { totalCount: 2, totalPages: 2 }) });
+
+ expect(ids(result.current.items)).toEqual(['one', 'two']);
+ expect(result.current.currentPage).toBe(2);
+ });
+});
diff --git a/src/components/CommentList/useCommentPages.ts b/src/components/CommentList/useCommentPages.ts
new file mode 100644
index 00000000000..f566be92ea6
--- /dev/null
+++ b/src/components/CommentList/useCommentPages.ts
@@ -0,0 +1,63 @@
+import isEqual from 'fast-deep-equal';
+import { useCallback, useState, useTransition } from 'react';
+
+import { type SkillCommentItem, type SkillCommentListResponse } from '@/types/discover';
+
+export type FetchCommentPage = (params: {
+ order?: 'asc' | 'desc';
+ page?: number;
+ pageSize?: number;
+ sort?: 'createdAt' | 'upvotes';
+}) => Promise<SkillCommentListResponse>;
+
+/**
+ * Paged comment state seeded from a first page, with "load more" appending
+ * later pages.
+ */
+export const useCommentPages = (
+ initialData: SkillCommentListResponse | undefined,
+ fetchMore: FetchCommentPage,
+) => {
+ const [items, setItems] = useState<SkillCommentItem[]>(initialData?.items ?? []);
+ const [currentPage, setCurrentPage] = useState(initialData?.currentPage ?? 1);
+ const [totalPages, setTotalPages] = useState(initialData?.totalPages ?? 1);
+ const [totalCount, setTotalCount] = useState(initialData?.totalCount ?? 0);
+ const [loadMoreFailed, setLoadMoreFailed] = useState(false);
+ const [isPending, startTransition] = useTransition();
+
+ // The first page can arrive after mount: a persisted copy seeds the list,
+ // then revalidation replaces it. Reseed from the refreshed first page when
+ // its content actually changes; an identical refresh keeps any later pages
+ // the user already loaded.
+ const [seed, setSeed] = useState(initialData);
+ if (initialData !== seed) {
+ setSeed(initialData);
+ if (initialData && !isEqual(initialData, seed)) {
+ setItems(initialData.items);
+ setCurrentPage(initialData.currentPage);
+ setTotalPages(initialData.totalPages);
+ setTotalCount(initialData.totalCount);
+ setLoadMoreFailed(false);
+ }
+ }
+
+ const loadMore = useCallback(() => {
+ const nextPage = currentPage + 1;
+ startTransition(async () => {
+ // Keep failures inside the transition: preserve loaded comments and
+ // turn the button into a retry instead of surfacing to an error boundary
+ try {
+ const res = await fetchMore({ order: 'desc', page: nextPage, sort: 'createdAt' });
+ setItems((prev) => [...prev, ...res.items]);
+ setCurrentPage(res.currentPage);
+ setTotalPages(res.totalPages);
+ setTotalCount(res.totalCount);
+ setLoadMoreFailed(false);
+ } catch {
+ setLoadMoreFailed(true);
+ }
+ });
+ }, [currentPage, fetchMore]);
+
+ return { currentPage, isPending, items, loadMore, loadMoreFailed, totalCount, totalPages };
+};
diff --git a/src/features/ChatInput/ActionBar/Tools/MarketAgentSkillPopoverContent.tsx b/src/features/ChatInput/ActionBar/Tools/MarketAgentSkillPopoverContent.tsx
index b727885b6fb..7f4d2823789 100644
--- a/src/features/ChatInput/ActionBar/Tools/MarketAgentSkillPopoverContent.tsx
+++ b/src/features/ChatInput/ActionBar/Tools/MarketAgentSkillPopoverContent.tsx
@@ -2,6 +2,7 @@ import { Avatar } from '@lobehub/ui/base-ui';
import { memo } from 'react';
import { useDiscoverStore } from '@/store/discover';
+import { skillSelectors } from '@/store/discover/selectors';
import ToolItemDetailPopover from './ToolItemDetailPopover';
@@ -22,7 +23,8 @@ interface MarketAgentSkillPopoverContentProps {
const MarketAgentSkillPopoverContent = memo<MarketAgentSkillPopoverContentProps>(
({ identifier, name, description, sourceLabel }) => {
const useFetchSkillDetail = useDiscoverStore((s) => s.useFetchSkillDetail);
- const { data } = useFetchSkillDetail({ identifier });
+ const { queryKey } = useFetchSkillDetail({ identifier });
+ const data = useDiscoverStore(skillSelectors.skillDetail(queryKey));
const iconSource = data?.icon || name;
diff --git a/src/features/ChatInput/ActionBar/Tools/MarketSkillIcon.tsx b/src/features/ChatInput/ActionBar/Tools/MarketSkillIcon.tsx
index 53799eb3c99..1a3ce21823f 100644
--- a/src/features/ChatInput/ActionBar/Tools/MarketSkillIcon.tsx
+++ b/src/features/ChatInput/ActionBar/Tools/MarketSkillIcon.tsx
@@ -2,6 +2,7 @@ import { Avatar } from '@lobehub/ui/base-ui';
import { memo } from 'react';
import { useDiscoverStore } from '@/store/discover';
+import { skillSelectors } from '@/store/discover/selectors';
export const SKILL_ICON_SIZE = 20;
@@ -22,7 +23,8 @@ interface MarketSkillIconProps {
const MarketSkillIcon = memo<MarketSkillIconProps>(
({ identifier, name, size = SKILL_ICON_SIZE }) => {
const useFetchSkillDetail = useDiscoverStore((s) => s.useFetchSkillDetail);
- const { data } = useFetchSkillDetail({ identifier });
+ const { queryKey } = useFetchSkillDetail({ identifier });
+ const data = useDiscoverStore(skillSelectors.skillDetail(queryKey));
return (
<Avatar
diff --git a/src/features/CommunitySkillDetail/Details/Overview/index.tsx b/src/features/CommunitySkillDetail/Details/Overview/index.tsx
index f6ec683be5d..36818697086 100644
--- a/src/features/CommunitySkillDetail/Details/Overview/index.tsx
+++ b/src/features/CommunitySkillDetail/Details/Overview/index.tsx
@@ -11,6 +11,7 @@ import { useTranslation } from 'react-i18next';
import PublishedTime from '@/components/PublishedTime';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useDiscoverStore } from '@/store/discover';
+import { skillSelectors } from '@/store/discover/selectors';
import { useDetailActionContext, useDetailContext } from '../../DetailProvider';
import RelatedSkillCard from './RelatedSkillCard';
@@ -83,7 +84,8 @@ const Overview = memo(() => {
const navigate = useWorkspaceAwareNavigate();
const useFetchRelatedSkills = useDiscoverStore((s) => s.useFetchRelatedSkills);
- const { data: related } = useFetchRelatedSkills({ category, identifier });
+ const { queryKey } = useFetchRelatedSkills({ category, identifier });
+ const related = useDiscoverStore(skillSelectors.skillRelated(queryKey));
// Honor the fetched (possibly deep-linked ?version=) version before falling
// back to the latest entry
diff --git a/src/features/CommunitySkillDetail/Details/Reviews/index.tsx b/src/features/CommunitySkillDetail/Details/Reviews/index.tsx
index 661eb3308f7..7c23ba862dc 100644
--- a/src/features/CommunitySkillDetail/Details/Reviews/index.tsx
+++ b/src/features/CommunitySkillDetail/Details/Reviews/index.tsx
@@ -9,6 +9,7 @@ import RatingOverview from '@/components/RatingOverview';
import { ArticleSkeleton } from '@/components/Skeleton';
import { discoverService } from '@/services/discover';
import { useDiscoverStore } from '@/store/discover';
+import { skillSelectors } from '@/store/discover/selectors';
import { FIRST_COMMENTS_PAGE_QUERY } from '../../const';
import { useDetailContext } from '../../DetailProvider';
@@ -21,17 +22,19 @@ const Reviews = memo(() => {
);
const useFetchSkillComments = useDiscoverStore((s) => s.useFetchSkillComments);
- const { data: distribution } = useFetchSkillRatingDistribution(identifier);
+ const { queryKey: distributionKey } = useFetchSkillRatingDistribution(identifier);
+ const distribution = useDiscoverStore(skillSelectors.skillRatingDistribution(distributionKey));
const {
- data: firstPage,
error,
isLoading,
isValidating,
mutate,
+ queryKey: commentsKey,
} = useFetchSkillComments({
identifier,
...FIRST_COMMENTS_PAGE_QUERY,
});
+ const firstPage = useDiscoverStore(skillSelectors.skillComments(commentsKey));
const fetchMore: CommentListProps['fetchMore'] = useCallback(
(params) => discoverService.getSkillComments({ identifier: identifier!, ...params }),
@@ -53,8 +56,7 @@ const Reviews = memo(() => {
</Flexbox>
) : error ? (
// A failed fetch is not "no reviews yet" β€” offer a retry. CommentList
- // only mounts on success, so retried data seeds it fresh (it snapshots
- // initialData at mount time).
+ // reseeds itself when a revalidated first page replaces the persisted one.
<AsyncError
error={error}
retrying={isValidating}
diff --git a/src/features/CommunitySkillDetail/Header.tsx b/src/features/CommunitySkillDetail/Header.tsx
index cc5e9d09259..1ec80dccdf3 100644
--- a/src/features/CommunitySkillDetail/Header.tsx
+++ b/src/features/CommunitySkillDetail/Header.tsx
@@ -13,6 +13,7 @@ import { usePermission } from '@/hooks/usePermission';
import { useSkillCategoryItem } from '@/hooks/useSkillCategory';
import { agentSkillService } from '@/services/skill';
import { useDiscoverStore } from '@/store/discover';
+import { skillSelectors } from '@/store/discover/selectors';
import { useToolStore } from '@/store/tool';
import { agentSkillsSelectors } from '@/store/tool/selectors';
import { formatShortenNumber } from '@/utils/format';
@@ -238,7 +239,11 @@ const Header = memo<{ mobile?: boolean }>(({ mobile: isMobile }) => {
// Same query as the Reviews tab β€” SWR dedupes them into one request, so the
// stat costs nothing extra and warms the tab
const useFetchSkillComments = useDiscoverStore((s) => s.useFetchSkillComments);
- const { data: comments } = useFetchSkillComments({ identifier, ...FIRST_COMMENTS_PAGE_QUERY });
+ const { queryKey: commentsKey } = useFetchSkillComments({
+ identifier,
+ ...FIRST_COMMENTS_PAGE_QUERY,
+ });
+ const comments = useDiscoverStore(skillSelectors.skillComments(commentsKey));
const displayRatingAverage =
typeof ratingAverage === 'number' ? Number(ratingAverage.toFixed(1)) : undefined;
diff --git a/src/features/CommunitySkillDetail/SkillDetailContent.tsx b/src/features/CommunitySkillDetail/SkillDetailContent.tsx
index 37341e218e1..51a08dc389e 100644
--- a/src/features/CommunitySkillDetail/SkillDetailContent.tsx
+++ b/src/features/CommunitySkillDetail/SkillDetailContent.tsx
@@ -8,6 +8,7 @@ import { useTranslation } from 'react-i18next';
import AsyncError from '@/components/AsyncError';
import { useDiscoverStore } from '@/store/discover';
+import { skillSelectors } from '@/store/discover/selectors';
import { type DiscoverSkillDetail } from '@/types/discover';
import { DetailActionContext, DetailProvider } from './DetailProvider';
@@ -53,7 +54,8 @@ export const SkillDetailContent = memo<SkillDetailContentProps>(
const { close } = useModalContext();
const useSkillDetail = useDiscoverStore((s) => s.useFetchSkillDetail);
- const { data, error, isLoading, isValidating, mutate } = useSkillDetail({ identifier });
+ const { error, isLoading, isValidating, mutate, queryKey } = useSkillDetail({ identifier });
+ const data = useDiscoverStore(skillSelectors.skillDetail(queryKey));
const actions = useMemo(() => ({ close, selectSkill: setIdentifier }), [close]);
diff --git a/src/features/ProfileEditor/PluginTag.test.tsx b/src/features/ProfileEditor/PluginTag.test.tsx
index 1bf9d9c8b8e..eb8fb911066 100644
--- a/src/features/ProfileEditor/PluginTag.test.tsx
+++ b/src/features/ProfileEditor/PluginTag.test.tsx
@@ -77,7 +77,7 @@ vi.mock('@/store/serverConfig', () => ({
}));
vi.mock('@/store/discover', () => ({
useDiscoverStore: (sel: (s: unknown) => unknown) =>
- sel({ usePluginDetail: () => ({ data: undefined, isLoading: false }) }),
+ sel({ useFetchPluginDetail: () => ({ isLoading: false, queryKey: undefined }) }),
}));
describe('PluginTag author attribution', () => {
diff --git a/src/features/ProfileEditor/PluginTag.tsx b/src/features/ProfileEditor/PluginTag.tsx
index 08aa06082c1..3baeae0882a 100644
--- a/src/features/ProfileEditor/PluginTag.tsx
+++ b/src/features/ProfileEditor/PluginTag.tsx
@@ -14,6 +14,7 @@ import { useTranslation } from 'react-i18next';
import PluginAvatar from '@/components/Plugins/PluginAvatar';
import { useIsDark } from '@/hooks/useIsDark';
import { useDiscoverStore } from '@/store/discover';
+import { pluginSelectors as discoverPluginSelectors } from '@/store/discover/selectors';
import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';
import { useToolStore } from '@/store/tool';
import {
@@ -314,11 +315,13 @@ const PluginTag = memo<PluginTagProps>(
]);
// Fetch from remote if not found locally
- const usePluginDetail = useDiscoverStore((s) => s.usePluginDetail);
- const { data: remoteData, isLoading } = usePluginDetail({
+ const usePluginDetail = useDiscoverStore((s) => s.useFetchPluginDetail);
+ const { isLoading, queryKey } = usePluginDetail({
identifier: !localMeta && !isInstalled ? identifier : undefined,
withManifest: false,
});
+ // The replica view of this identifier; the sync hook only reports the fetch flags.
+ const remoteData = useDiscoverStore(discoverPluginSelectors.pluginDetail(queryKey));
// Determine final metadata
const meta = localMeta || {
diff --git a/src/features/SkillStore/SkillList/MarketSkills/MarketSkillDetail.tsx b/src/features/SkillStore/SkillList/MarketSkills/MarketSkillDetail.tsx
index 4de821c23c4..d4cda6566d8 100644
--- a/src/features/SkillStore/SkillList/MarketSkills/MarketSkillDetail.tsx
+++ b/src/features/SkillStore/SkillList/MarketSkills/MarketSkillDetail.tsx
@@ -16,6 +16,7 @@ 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 { useToolStore } from '@/store/tool';
import { agentSkillsSelectors } from '@/store/tool/selectors';
import { type DiscoverSkillDetail as DiscoverSkillDetailType } from '@/types/discover';
@@ -140,7 +141,8 @@ const MarketSkillDetail = memo<MarketSkillDetailProps>(({ identifier }) => {
// Market data (always fetched for header info + icon)
const useFetchSkillDetail = useDiscoverStore((s) => s.useFetchSkillDetail);
- const { data, isLoading } = useFetchSkillDetail({ identifier });
+ const { isLoading, queryKey } = useFetchSkillDetail({ identifier });
+ const data = useDiscoverStore(skillSelectors.skillDetail(queryKey));
// Installed skill data (for full file content)
const installedSkill = useToolStore(agentSkillsSelectors.getAgentSkillByIdentifier(identifier));
diff --git a/src/features/ToolTag/index.tsx b/src/features/ToolTag/index.tsx
index f15ffc3cbd1..7060c58f39b 100644
--- a/src/features/ToolTag/index.tsx
+++ b/src/features/ToolTag/index.tsx
@@ -11,6 +11,7 @@ import { memo, useMemo } from 'react';
import PluginAvatar from '@/components/Plugins/PluginAvatar';
import { useIsDark } from '@/hooks/useIsDark';
import { useDiscoverStore } from '@/store/discover';
+import { pluginSelectors as discoverPluginSelectors } from '@/store/discover/selectors';
import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';
import { useToolStore } from '@/store/tool';
import {
@@ -117,11 +118,13 @@ const ToolTag = memo<ToolTagProps>(({ identifier, variant = 'default' }) => {
}, [identifier, builtinList, installedPluginList, isComposioEnabledInEnv, allComposioServers]);
// Fetch from remote if not found locally
- const usePluginDetail = useDiscoverStore((s) => s.usePluginDetail);
- const { data: remoteData, isLoading } = usePluginDetail({
+ const usePluginDetail = useDiscoverStore((s) => s.useFetchPluginDetail);
+ const { isLoading, queryKey } = usePluginDetail({
identifier: !localMeta && !isInstalled ? identifier : undefined,
withManifest: false,
});
+ // The replica view of this identifier; the sync hook only reports the fetch flags.
+ const remoteData = useDiscoverStore(discoverPluginSelectors.pluginDetail(queryKey));
// Determine final metadata
const meta = localMeta || {
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 6b6c8fe04f3..923e7804331 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -449,124 +449,6 @@ export const serverConfigKeys = {
// (see localStorageProvider.ts) so this key-convergence introduces no new
// persistence β€” they stay memory-only exactly as before.
export const discoverKeys = {
- assistantCategories: def('discover:assistantCategories', (locale: string, params: unknown) => [
- 'discover:assistantCategories',
- locale,
- params,
- ]),
- assistantDetail: def('discover:assistantDetail', (locale: string, params: unknown) => [
- 'discover:assistantDetail',
- locale,
- params,
- ]),
- assistantIdentifiers: def('discover:assistantIdentifiers', (source?: string) => [
- 'discover:assistantIdentifiers',
- source,
- ]),
- assistantList: def('discover:assistantList', (locale: string, params: unknown) => [
- 'discover:assistantList',
- locale,
- params,
- ]),
- favoriteAgents: def('discover:favoriteAgents', (userId: number, params?: unknown) => [
- 'discover:favoriteAgents',
- userId,
- params,
- ]),
- favoritePlugins: def('discover:favoritePlugins', (userId: number, params?: unknown) => [
- 'discover:favoritePlugins',
- userId,
- params,
- ]),
- followCounts: def('discover:followCounts', (userId: number) => ['discover:followCounts', userId]),
- followStatus: def('discover:followStatus', (userId: number) => ['discover:followStatus', userId]),
- followers: def('discover:followers', (userId: number, params?: unknown) => [
- 'discover:followers',
- userId,
- params,
- ]),
- following: def('discover:following', (userId: number, params?: unknown) => [
- 'discover:following',
- userId,
- params,
- ]),
- modelCategories: def('discover:modelCategories', (params: unknown) => [
- 'discover:modelCategories',
- params,
- ]),
- modelDetail: def('discover:modelDetail', (locale: string, identifier: string) => [
- 'discover:modelDetail',
- locale,
- identifier,
- ]),
- modelIdentifiers: def('discover:modelIdentifiers', () => ['discover:modelIdentifiers']),
- modelList: def('discover:modelList', (locale: string, params: unknown) => [
- 'discover:modelList',
- locale,
- params,
- ]),
- pluginCategories: def('discover:pluginCategories', (locale: string, params: unknown) => [
- 'discover:pluginCategories',
- locale,
- params,
- ]),
- pluginDetail: def(
- 'discover:pluginDetail',
- (locale: string, identifier: string, withManifest?: boolean) => [
- 'discover:pluginDetail',
- locale,
- identifier,
- withManifest,
- ],
- ),
- pluginIdentifiers: def('discover:pluginIdentifiers', () => ['discover:pluginIdentifiers']),
- pluginList: def('discover:pluginList', (locale: string, params: unknown) => [
- 'discover:pluginList',
- locale,
- params,
- ]),
- skillCategories: def('discover:skillCategories', (locale: string, params: unknown) => [
- 'discover:skillCategories',
- locale,
- params,
- ]),
- skillComments: def('discover:skillComments', (identifier: string, params: unknown) => [
- 'discover:skillComments',
- identifier,
- params,
- ]),
- skillDetail: def(
- 'discover:skillDetail',
- (locale: string, identifier: string, version?: string) => [
- 'discover:skillDetail',
- locale,
- identifier,
- version,
- ],
- ),
- skillList: def('discover:skillList', (locale: string, params: unknown) => [
- 'discover:skillList',
- locale,
- params,
- ]),
- skillRatingDistribution: def('discover:skillRatingDistribution', (identifier: string) => [
- 'discover:skillRatingDistribution',
- identifier,
- ]),
- skillRelated: def(
- 'discover:skillRelated',
- (locale: string, category: string, identifier: string) => [
- 'discover:skillRelated',
- locale,
- category,
- identifier,
- ],
- ),
- userProfile: def('discover:userProfile', (locale: string, username: string) => [
- 'discover:userProfile',
- locale,
- username,
- ]),
// -- marketplace detail "related agents" lists (UI) --
mcpAgents: def('discover:mcpAgents', (identifier: string, page: number) => [
'discover:mcpAgents',
diff --git a/src/routes/(main)/community/(detail)/_layout/Header.test.tsx b/src/routes/(main)/community/(detail)/_layout/Header.test.tsx
index 3267c25606b..5b3fbd8c307 100644
--- a/src/routes/(main)/community/(detail)/_layout/Header.test.tsx
+++ b/src/routes/(main)/community/(detail)/_layout/Header.test.tsx
@@ -8,6 +8,7 @@ import Header from './Header';
const mocks = vi.hoisted(() => ({
useUserProfile: vi.fn(),
+ userProfileMap: {} as Record<string, unknown>,
}));
vi.mock('@/features/NavHeader', () => ({
@@ -34,20 +35,16 @@ vi.mock('@/routes/(main)/community/features/UserAvatar', () => ({
}));
vi.mock('@/store/discover', () => ({
- useDiscoverStore: (
- selector: (state: { useUserProfile: typeof mocks.useUserProfile }) => unknown,
- ) => selector({ useUserProfile: mocks.useUserProfile }),
+ useDiscoverStore: (selector: (state: any) => unknown) =>
+ selector({ userProfileMap: mocks.userProfileMap, useUserProfile: mocks.useUserProfile }),
}));
describe('Community detail Header', () => {
it('shows the viewed organization avatar in the right corner', () => {
- mocks.useUserProfile.mockReturnValue({
- data: {
- user: {
- avatarUrl: 'sad-avatar',
- },
- },
- });
+ // The sync hook reports the fetch flags + the entry key; the profile itself
+ // is read from the replica view through the selector.
+ mocks.useUserProfile.mockReturnValue({ queryKey: 'org:sad' });
+ mocks.userProfileMap = { 'org:sad': { user: { avatarUrl: 'sad-avatar' } } };
render(
<MemoryRouter initialEntries={['/011/community/org/sad']}>
diff --git a/src/routes/(main)/community/(detail)/_layout/Header.tsx b/src/routes/(main)/community/(detail)/_layout/Header.tsx
index 88642b8a69e..01e372123a8 100644
--- a/src/routes/(main)/community/(detail)/_layout/Header.tsx
+++ b/src/routes/(main)/community/(detail)/_layout/Header.tsx
@@ -13,6 +13,7 @@ import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwar
import StoreSearchBar from '@/routes/(main)/community/features/Search';
import UserAvatar from '@/routes/(main)/community/features/UserAvatar';
import { useDiscoverStore } from '@/store/discover';
+import { userSelectors } from '@/store/discover/selectors';
import { styles } from './Header/style';
@@ -29,7 +30,9 @@ const Header = memo(() => {
: '';
const useUserProfile = useDiscoverStore((s) => s.useUserProfile);
- const { data: detailProfile } = useUserProfile({ username: profileUsername });
+ const { queryKey: detailProfileQueryKey } = useUserProfile({ username: profileUsername });
+ // The replica view of this profile; the sync hook only reports the fetch flags.
+ const detailProfile = useDiscoverStore(userSelectors.userProfile(detailProfileQueryKey));
const detailAvatar =
detailProfile?.user.avatarUrl || detailProfile?.user.userName || detailProfile?.user.namespace;
diff --git a/src/routes/(main)/community/(detail)/agent/features/Details/Capabilities/PluginItem.test.tsx b/src/routes/(main)/community/(detail)/agent/features/Details/Capabilities/PluginItem.test.tsx
new file mode 100644
index 00000000000..3462490306a
--- /dev/null
+++ b/src/routes/(main)/community/(detail)/agent/features/Details/Capabilities/PluginItem.test.tsx
@@ -0,0 +1,98 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useDiscoverStore } from '@/store/discover';
+import { pluginDetailQueryKey } from '@/store/discover/slices/plugin/projection';
+import { globalHelpers } from '@/store/global/helpers';
+
+import PluginItem from './PluginItem';
+
+// The marketplace read is the only thing faked: the store slice, its replica
+// and the component are the real ones. `getPluginDetail` rejects outright so a
+// rendered title can only come from the replica view, not the network.
+vi.mock('@/services/discover', () => ({
+ discoverService: {
+ getPluginCategories: vi.fn(),
+ getPluginDetail: vi.fn(() => Promise.reject(new Error('offline'))),
+ getPluginIdentifiers: vi.fn(),
+ getPluginList: vi.fn(),
+ },
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock('antd-style', () => ({
+ createStaticStyles: () => ({}),
+ cssVar: new Proxy({}, { get: () => 'var(--x)' }),
+ cx: (...args: unknown[]) => args.filter(Boolean).join(' '),
+}));
+
+vi.mock('@lobechat/builtin-tools', () => ({ builtinTools: [] }));
+
+vi.mock('@lobehub/ui', () => ({
+ Block: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
+ Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
+ Icon: () => null,
+ Image: () => null,
+}));
+
+vi.mock('@lobehub/ui/base-ui', () => ({
+ Avatar: () => null,
+ Skeleton: { Text: () => <div data-testid="skeleton" /> },
+ Tag: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
+ Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
+}));
+
+const IDENTIFIER = 'weather-plugin';
+
+const seedDetail = () =>
+ useDiscoverStore.setState({
+ pluginDetailMap: {
+ [pluginDetailQueryKey({ identifier: IDENTIFIER, locale: 'en-US', withManifest: false })]: {
+ author: 'LobeHub',
+ avatar: '',
+ createdAt: '',
+ description: 'Weather lookups for the agent',
+ homepage: 'https://lobehub.com',
+ identifier: IDENTIFIER,
+ manifest: undefined,
+ related: [],
+ schemaVersion: 1,
+ source: 'builtin',
+ tags: ['weather'],
+ title: 'Weather Plugin',
+ } as any,
+ },
+ });
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');
+ useDiscoverStore.setState({ pluginDetailMap: {} });
+});
+
+describe('PluginItem (replica-backed plugin detail)', () => {
+ it('paints the plugin title from the replica even though the network fetch fails', async () => {
+ seedDetail();
+
+ render(<PluginItem identifier={IDENTIFIER} />);
+
+ // The title can only come from the seeded replica view: the only faked
+ // dependency (getPluginDetail) rejects, so the network path yields nothing.
+ expect(await screen.findByText('Weather Plugin')).toBeTruthy();
+ expect(screen.queryByTestId('skeleton')).toBeNull();
+ expect(screen.getByText('Weather lookups for the agent')).toBeTruthy();
+ });
+
+ it('shows the loading skeleton while the entry is still empty', () => {
+ render(<PluginItem identifier={IDENTIFIER} />);
+
+ expect(screen.getByTestId('skeleton')).toBeTruthy();
+ });
+});
diff --git a/src/routes/(main)/community/(detail)/agent/features/Details/Capabilities/PluginItem.tsx b/src/routes/(main)/community/(detail)/agent/features/Details/Capabilities/PluginItem.tsx
index 76a4db3f4e7..0161ff8a950 100644
--- a/src/routes/(main)/community/(detail)/agent/features/Details/Capabilities/PluginItem.tsx
+++ b/src/routes/(main)/community/(detail)/agent/features/Details/Capabilities/PluginItem.tsx
@@ -16,6 +16,7 @@ import urlJoin from 'url-join';
import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useDiscoverStore } from '@/store/discover';
+import { pluginSelectors } from '@/store/discover/selectors';
/**
* Icon component for built-in tools (Composio & LobehubSkill)
@@ -77,8 +78,10 @@ interface PluginItemProps {
const PluginItem = memo<PluginItemProps>(({ identifier }) => {
const { t } = useTranslation('discover');
- const usePluginDetail = useDiscoverStore((s) => s.usePluginDetail);
- const { data: apiData, isLoading } = usePluginDetail({ identifier, withManifest: false });
+ const usePluginDetail = useDiscoverStore((s) => s.useFetchPluginDetail);
+ const { isLoading, queryKey } = usePluginDetail({ identifier, withManifest: false });
+ // The replica view of this identifier; the sync hook only reports the fetch flags.
+ const apiData = useDiscoverStore(pluginSelectors.pluginDetail(queryKey));
// Try to get Composio tool info if API returns no data
const composioTool = useMemo(() => {
diff --git a/src/routes/(main)/community/(detail)/agent/index.tsx b/src/routes/(main)/community/(detail)/agent/index.tsx
index f6551fb8ad0..2d5388807b4 100644
--- a/src/routes/(main)/community/(detail)/agent/index.tsx
+++ b/src/routes/(main)/community/(detail)/agent/index.tsx
@@ -8,6 +8,7 @@ import AsyncError from '@/components/AsyncError';
import { RouteLoading } from '@/components/Skeleton/RouteSegment';
import { useQuery } from '@/hooks/useQuery';
import { useDiscoverStore } from '@/store/discover';
+import { assistantSelectors } from '@/store/discover/selectors';
import { type AssistantMarketSource } from '@/types/discover';
import NotFound from '../components/NotFound';
@@ -26,8 +27,14 @@ const AssistantDetailPage = memo<AssistantDetailPageProps>(({ mobile }) => {
const identifier = decodeURIComponent(params.slug ?? '');
const { version, source } = useQuery() as { source?: AssistantMarketSource; version?: string };
- const useAssistantDetail = useDiscoverStore((s) => s.useAssistantDetail);
- const { data, error, isLoading, mutate } = useAssistantDetail({ identifier, source, version });
+ const useAssistantDetail = useDiscoverStore((s) => s.useFetchAssistantDetail);
+ const { error, isLoading, mutate, queryKey } = useAssistantDetail({
+ identifier,
+ source,
+ version,
+ });
+ const data = useDiscoverStore(assistantSelectors.assistantDetail(queryKey));
+
if (data === undefined) {
if (isLoading) return <RouteLoading />;
if (error) return <AsyncError error={error} variant={'page'} onRetry={() => void mutate()} />;
diff --git a/src/routes/(main)/community/(detail)/features/FollowButton.tsx b/src/routes/(main)/community/(detail)/features/FollowButton.tsx
index 5352ce18d22..61e788d10d4 100644
--- a/src/routes/(main)/community/(detail)/features/FollowButton.tsx
+++ b/src/routes/(main)/community/(detail)/features/FollowButton.tsx
@@ -7,6 +7,7 @@ import { useTranslation } from 'react-i18next';
import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';
import { socialService } from '@/services/social';
import { useDiscoverStore } from '@/store/discover';
+import { socialSelectors } from '@/store/discover/selectors';
interface FollowButtonProps {
userId: number;
@@ -25,7 +26,9 @@ const FollowButton = memo<FollowButtonProps>(({ userId }) => {
socialService.setAccessToken(session.accessToken);
}
- const { data: followStatus, mutate } = useFollowStatus(userId);
+ const { mutate, queryKey } = useFollowStatus(userId);
+ // The replica view of this entry; the sync hook only reports the fetch flags.
+ const followStatus = useDiscoverStore(socialSelectors.followStatus(queryKey));
const isFollowing = followStatus?.isFollowing ?? false;
const handleClick = async () => {
diff --git a/src/routes/(main)/community/(detail)/model/index.tsx b/src/routes/(main)/community/(detail)/model/index.tsx
index 18fec8cc908..a68f52e6bc3 100644
--- a/src/routes/(main)/community/(detail)/model/index.tsx
+++ b/src/routes/(main)/community/(detail)/model/index.tsx
@@ -7,6 +7,7 @@ import { useParams } from 'react-router';
import AsyncError from '@/components/AsyncError';
import { RouteLoading } from '@/components/Skeleton/RouteSegment';
import { useDiscoverStore } from '@/store/discover';
+import { modelSelectors } from '@/store/discover/selectors';
import NotFound from '../components/NotFound';
import { DetailProvider } from './features/DetailProvider';
@@ -21,8 +22,9 @@ const ModelDetailPage = memo<ModelDetailPageProps>(({ mobile }) => {
const params = useParams<{ slug: string }>();
const identifier = decodeURIComponent(params.slug ?? '');
- const useModelDetail = useDiscoverStore((s) => s.useModelDetail);
- const { data, error, isLoading, mutate } = useModelDetail({ identifier });
+ const useModelDetail = useDiscoverStore((s) => s.useFetchModelDetail);
+ const { error, isLoading, mutate, queryKey } = useModelDetail({ identifier });
+ const data = useDiscoverStore(modelSelectors.modelDetail(queryKey));
if (data === undefined) {
if (isLoading) return <RouteLoading />;
if (error) return <AsyncError error={error} variant={'page'} onRetry={() => void mutate()} />;
diff --git a/src/routes/(main)/community/(detail)/organization/features/FollowStats.tsx b/src/routes/(main)/community/(detail)/organization/features/FollowStats.tsx
index 85ce790bfb8..e6e949067b0 100644
--- a/src/routes/(main)/community/(detail)/organization/features/FollowStats.tsx
+++ b/src/routes/(main)/community/(detail)/organization/features/FollowStats.tsx
@@ -6,6 +6,7 @@ import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { useDiscoverStore } from '@/store/discover';
+import { socialSelectors } from '@/store/discover/selectors';
import { useOrganizationDetailContext } from './DetailProvider';
@@ -15,9 +16,11 @@ const FollowStats = memo(() => {
// Fall back to the static profile counts (sourced from the authoritative
// `accounts.*_count` columns) whenever the live count is missing or 0, so a
- // not-yet-populated live query never clobbers a real count.
+ // not-yet-populated live entry never clobbers a real count.
const useFollowCounts = useDiscoverStore((s) => s.useFollowCounts);
- const { data: followCounts } = useFollowCounts(user.id);
+ const { queryKey } = useFollowCounts(user.id);
+ // The replica view of this entry; the sync hook only reports the fetch flags.
+ const followCounts = useDiscoverStore(socialSelectors.followCounts(queryKey));
const followingCount = followCounts?.followingCount || user.followingCount || 0;
const followersCount = followCounts?.followersCount || user.followersCount || 0;
diff --git a/src/routes/(main)/community/(detail)/organization/index.tsx b/src/routes/(main)/community/(detail)/organization/index.tsx
index 3c17a98e82a..3bd5813e563 100644
--- a/src/routes/(main)/community/(detail)/organization/index.tsx
+++ b/src/routes/(main)/community/(detail)/organization/index.tsx
@@ -8,6 +8,7 @@ import AsyncError from '@/components/AsyncError';
import { RouteLoading } from '@/components/Skeleton/RouteSegment';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useDiscoverStore } from '@/store/discover';
+import { userSelectors } from '@/store/discover/selectors';
import NotFound from '../components/NotFound';
import { resolveWorkspaceCommunityProfileRedirect } from '../workspace/features/resolveWorkspaceProfileEdit';
@@ -27,7 +28,9 @@ const OrganizationDetailPage = memo<OrganizationDetailPageProps>(({ mobile }) =>
const { isWorkspaceScope } = useCommunityWorkspaceProfile();
const useUserProfile = useDiscoverStore((s) => s.useUserProfile);
- const { data, error, isLoading, mutate } = useUserProfile({ username });
+ const { error, isLoading, mutate, queryKey } = useUserProfile({ username });
+ // The replica view of this profile; the sync hook only reports the fetch flags.
+ const data = useDiscoverStore(userSelectors.userProfile(queryKey));
useEffect(() => {
const redirectTo = resolveWorkspaceCommunityProfileRedirect({
diff --git a/src/routes/(main)/community/(detail)/skill/index.tsx b/src/routes/(main)/community/(detail)/skill/index.tsx
index ef1429ce202..83593c528d0 100644
--- a/src/routes/(main)/community/(detail)/skill/index.tsx
+++ b/src/routes/(main)/community/(detail)/skill/index.tsx
@@ -9,6 +9,7 @@ import { RouteLoading } from '@/components/Skeleton/RouteSegment';
import { SkillDetailView, SkillNavKey } from '@/features/CommunitySkillDetail';
import { useQuery } from '@/hooks/useQuery';
import { useDiscoverStore } from '@/store/discover';
+import { skillSelectors } from '@/store/discover/selectors';
import NotFound from '../components/NotFound';
@@ -50,7 +51,8 @@ const SkillDetailPage = memo<SkillDetailPageProps>(({ mobile }) => {
);
const useSkillDetail = useDiscoverStore((s) => s.useFetchSkillDetail);
- const { data, error, isLoading, mutate } = useSkillDetail({ identifier, version });
+ const { error, isLoading, mutate, queryKey } = useSkillDetail({ identifier, version });
+ const data = useDiscoverStore(skillSelectors.skillDetail(queryKey));
if (data === undefined) {
if (isLoading) return <RouteLoading />;
if (error) return <AsyncError error={error} variant={'page'} onRetry={() => void mutate()} />;
diff --git a/src/routes/(main)/community/(detail)/user/features/FollowStats.tsx b/src/routes/(main)/community/(detail)/user/features/FollowStats.tsx
index db4cd42ef89..65945c26d55 100644
--- a/src/routes/(main)/community/(detail)/user/features/FollowStats.tsx
+++ b/src/routes/(main)/community/(detail)/user/features/FollowStats.tsx
@@ -6,6 +6,7 @@ import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { useDiscoverStore } from '@/store/discover';
+import { socialSelectors } from '@/store/discover/selectors';
import { useUserDetailContext } from './DetailProvider';
@@ -13,13 +14,16 @@ const FollowStats = memo(() => {
const { t } = useTranslation('discover');
const { user } = useUserDetailContext();
- // Live follow counts: the `follow-counts-{userId}` cache is invalidated by
- // follow()/unfollow(), so the numbers update immediately after toggling follow.
- // Fall back to the static profile counts (which come straight from the
- // authoritative `accounts.*_count` columns) whenever the live count is missing
- // or 0 β€” so a not-yet-populated live query never clobbers a real count.
+ // Live follow counts: `follow()` / `unfollow()` optimistically patch the
+ // `followCounts` replica entry for this user, so the numbers update immediately
+ // after toggling follow. Fall back to the static profile counts (which come
+ // straight from the authoritative `accounts.*_count` columns) whenever the
+ // live count is missing or 0 β€” so a not-yet-populated live entry never
+ // clobbers a real count.
const useFollowCounts = useDiscoverStore((s) => s.useFollowCounts);
- const { data: followCounts } = useFollowCounts(user.id);
+ const { queryKey } = useFollowCounts(user.id);
+ // The replica view of this entry; the sync hook only reports the fetch flags.
+ const followCounts = useDiscoverStore(socialSelectors.followCounts(queryKey));
const followingCount = followCounts?.followingCount || user.followingCount || 0;
const followersCount = followCounts?.followersCount || user.followersCount || 0;
diff --git a/src/routes/(main)/community/(detail)/user/index.tsx b/src/routes/(main)/community/(detail)/user/index.tsx
index 6a679770d67..b9c7db7319c 100644
--- a/src/routes/(main)/community/(detail)/user/index.tsx
+++ b/src/routes/(main)/community/(detail)/user/index.tsx
@@ -10,6 +10,7 @@ import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwar
import { useMarketAuth, useMarketUserProfile } from '@/layout/AuthProvider/MarketAuth';
import { type MarketUserProfile } from '@/layout/AuthProvider/MarketAuth/types';
import { useDiscoverStore } from '@/store/discover';
+import { userSelectors } from '@/store/discover/selectors';
import NotFound from '../components/NotFound';
import { resolveWorkspaceCommunityProfileRedirect } from '../workspace/features/resolveWorkspaceProfileEdit';
@@ -33,7 +34,9 @@ const UserDetailPage = memo<UserDetailPageProps>(({ mobile }) => {
useMarketAuth();
const useUserProfile = useDiscoverStore((s) => s.useUserProfile);
- const { data, error, isLoading, mutate } = useUserProfile({ username });
+ const { error, isLoading, mutate, queryKey } = useUserProfile({ username });
+ // The replica view of this profile; the sync hook only reports the fetch flags.
+ const data = useDiscoverStore(userSelectors.userProfile(queryKey));
// When inside a workspace scope, /community/user/:slug and /community/org/:slug are not the
// right surface β€” redirect to the dedicated workspace community page.
diff --git a/src/routes/(main)/community/(detail)/workspace/index.tsx b/src/routes/(main)/community/(detail)/workspace/index.tsx
index 34bd4383f47..853579a4bd3 100644
--- a/src/routes/(main)/community/(detail)/workspace/index.tsx
+++ b/src/routes/(main)/community/(detail)/workspace/index.tsx
@@ -8,6 +8,7 @@ import AsyncError from '@/components/AsyncError';
import { RouteLoading } from '@/components/Skeleton/RouteSegment';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useDiscoverStore } from '@/store/discover';
+import { userSelectors } from '@/store/discover/selectors';
import type { DiscoverUserProfile } from '@/types/discover';
import NotFound from '../components/NotFound';
@@ -40,13 +41,15 @@ const WorkspaceDetailPage = memo<WorkspaceDetailPageProps>(({ mobile }) => {
const useUserProfile = useDiscoverStore((s) => s.useUserProfile);
const {
- data,
error: userProfileError,
isLoading: isUserProfileLoading,
mutate,
+ queryKey: userProfileQueryKey,
} = useUserProfile({
username: workspaceUsername ?? '',
});
+ // The replica view of this profile; the sync hook only reports the fetch flags.
+ const data = useDiscoverStore(userSelectors.userProfile(userProfileQueryKey));
// Fallback profile so the page header renders even before the market profile is materialized
const fallbackProfile = useMemo<DiscoverUserProfile | null>(() => {
diff --git a/src/routes/(main)/community/(list)/(home)/index.tsx b/src/routes/(main)/community/(list)/(home)/index.tsx
index 707d539fe18..426f48c7bb0 100644
--- a/src/routes/(main)/community/(list)/(home)/index.tsx
+++ b/src/routes/(main)/community/(list)/(home)/index.tsx
@@ -5,7 +5,7 @@ import { useTranslation } from 'react-i18next';
import AsyncBoundary from '@/components/AsyncBoundary';
import { useDiscoverStore } from '@/store/discover';
-import { mcpSelectors } from '@/store/discover/selectors';
+import { assistantSelectors, mcpSelectors } from '@/store/discover/selectors';
import { AssistantSorts, McpSorts } from '@/types/discover';
import ListLoading from '../../components/ListLoading';
@@ -16,19 +16,20 @@ import CreatorRewardBanner from './features/CreatorRewardBanner';
const HomePage = memo(() => {
const { t } = useTranslation('discover');
- const useAssistantList = useDiscoverStore((s) => s.useAssistantList);
+ const useAssistantList = useDiscoverStore((s) => s.useFetchAssistantList);
const useMcpList = useDiscoverStore((s) => s.useFetchMcpList);
const {
- data: assistantList,
- isLoading: assistantLoading,
error: assistantError,
+ isLoading: assistantLoading,
mutate: refetchAssistants,
+ queryKey: assistantQueryKey,
} = useAssistantList({
page: 1,
pageSize: 12,
sort: AssistantSorts.Recommended,
});
+ const assistantList = useDiscoverStore(assistantSelectors.assistantList(assistantQueryKey));
const {
error: mcpError,
diff --git a/src/routes/(main)/community/(list)/agent/features/Category/index.tsx b/src/routes/(main)/community/(list)/agent/features/Category/index.tsx
index b426bf0317e..ab2bf9d48f1 100644
--- a/src/routes/(main)/community/(list)/agent/features/Category/index.tsx
+++ b/src/routes/(main)/community/(list)/agent/features/Category/index.tsx
@@ -12,22 +12,30 @@ import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useQuery } from '@/hooks/useQuery';
import { SCROLL_PARENT_ID } from '@/routes/(main)/community/features/const';
import { useDiscoverStore } from '@/store/discover';
+import { assistantSelectors } from '@/store/discover/selectors';
import { AssistantCategory, type AssistantQueryParams, AssistantSorts } from '@/types/discover';
import CategoryMenu from '../../../../components/CategoryMenu';
import { useCategory } from './useCategory';
const Category = memo(() => {
- const useAssistantCategories = useDiscoverStore((s) => s.useAssistantCategories);
- const useAssistantList = useDiscoverStore((s) => s.useAssistantList);
+ const useAssistantCategories = useDiscoverStore((s) => s.useFetchAssistantCategories);
+ const useAssistantList = useDiscoverStore((s) => s.useFetchAssistantList);
const query = useQuery() as AssistantQueryParams;
const { category = AssistantCategory.Discover, q, source } = query;
- const { data } = useAssistantList(buildAssistantListQuery(query), { keepPreviousData: true });
- const shouldLoadFallbackCategories = data !== undefined && data.categoryCounts === undefined;
- const { data: fallbackItems = [] } = useAssistantCategories(
+ const { queryKey } = useAssistantList(buildAssistantListQuery(query));
+ const data = useDiscoverStore(assistantSelectors.assistantList(queryKey));
+ // Fallback counts while the list entry converges: the categories query is
+ // keyed by `q` + `source` only, so switching category keeps its rows on screen
+ // (the replica replacement for the old SWR `keepPreviousData`).
+ const shouldLoadFallbackCategories = data?.categoryCounts === undefined;
+ const { queryKey: categoriesQueryKey } = useAssistantCategories(
{ q, source },
{ enabled: shouldLoadFallbackCategories },
);
+ const fallbackItems = useDiscoverStore(
+ assistantSelectors.assistantCategories(categoriesQueryKey),
+ );
const items = data?.categoryCounts ?? fallbackItems;
const navigate = useWorkspaceAwareNavigate();
const cates = useCategory();
diff --git a/src/routes/(main)/community/(list)/agent/index.tsx b/src/routes/(main)/community/(list)/agent/index.tsx
index e60c7344d14..dee57f43a46 100644
--- a/src/routes/(main)/community/(list)/agent/index.tsx
+++ b/src/routes/(main)/community/(list)/agent/index.tsx
@@ -8,6 +8,7 @@ import { RouteLoading } from '@/components/Skeleton/RouteSegment';
import { buildAssistantListQuery } from '@/features/CommunityAgentList/assistantListQuery';
import { useQuery } from '@/hooks/useQuery';
import { useDiscoverStore } from '@/store/discover';
+import { assistantSelectors } from '@/store/discover/selectors';
import { type AssistantQueryParams } from '@/types/discover';
import { DiscoverTab } from '@/types/discover';
@@ -17,8 +18,10 @@ import List from './features/List';
const AssistantPage = memo(() => {
const query = useQuery() as AssistantQueryParams;
- const useAssistantList = useDiscoverStore((s) => s.useAssistantList);
- const { data, error, isLoading, mutate } = useAssistantList(buildAssistantListQuery(query));
+ const useAssistantList = useDiscoverStore((s) => s.useFetchAssistantList);
+ const { error, isLoading, mutate, queryKey } = useAssistantList(buildAssistantListQuery(query));
+ // The replica view of this query; the sync hook only reports the fetch flags.
+ const data = useDiscoverStore(assistantSelectors.assistantList(queryKey));
const items = data?.items ?? [];
diff --git a/src/routes/(main)/community/(list)/model/features/Category/index.tsx b/src/routes/(main)/community/(list)/model/features/Category/index.tsx
index 4bb5b33fdca..ed1ff8a3d47 100644
--- a/src/routes/(main)/community/(list)/model/features/Category/index.tsx
+++ b/src/routes/(main)/community/(list)/model/features/Category/index.tsx
@@ -11,14 +11,16 @@ import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useQuery } from '@/hooks/useQuery';
import { SCROLL_PARENT_ID } from '@/routes/(main)/community/features/const';
import { useDiscoverStore } from '@/store/discover';
+import { modelSelectors } from '@/store/discover/selectors';
import CategoryMenu from '../../../../components/CategoryMenu';
import { useCategory } from './useCategory';
const Category = memo(() => {
- const useModelCategories = useDiscoverStore((s) => s.useModelCategories);
+ const useModelCategories = useDiscoverStore((s) => s.useFetchModelCategories);
const { category = 'all', q } = useQuery() as { category?: string; q?: string };
- const { data: items = [] } = useModelCategories({ q });
+ const { queryKey } = useModelCategories({ q });
+ const items = useDiscoverStore(modelSelectors.modelCategories(queryKey));
const navigate = useWorkspaceAwareNavigate();
const cates = useCategory();
diff --git a/src/routes/(main)/community/(list)/model/index.tsx b/src/routes/(main)/community/(list)/model/index.tsx
index 9bc3ae1fb4b..815ef80e335 100644
--- a/src/routes/(main)/community/(list)/model/index.tsx
+++ b/src/routes/(main)/community/(list)/model/index.tsx
@@ -7,6 +7,7 @@ import AsyncBoundary from '@/components/AsyncBoundary';
import { RouteLoading } from '@/components/Skeleton/RouteSegment';
import { useQuery } from '@/hooks/useQuery';
import { useDiscoverStore } from '@/store/discover';
+import { modelSelectors } from '@/store/discover/selectors';
import { type ModelQueryParams } from '@/types/discover';
import { DiscoverTab } from '@/types/discover';
@@ -16,8 +17,8 @@ import List from './features/List';
const ModelPage = memo<{ mobile?: boolean }>(() => {
const { q, page, category, sort, order } = useQuery() as ModelQueryParams;
- const useModelList = useDiscoverStore((s) => s.useModelList);
- const { data, error, isLoading, mutate } = useModelList({
+ const useModelList = useDiscoverStore((s) => s.useFetchModelList);
+ const { error, isLoading, mutate, queryKey } = useModelList({
category,
order,
page,
@@ -25,6 +26,8 @@ const ModelPage = memo<{ mobile?: boolean }>(() => {
q,
sort,
});
+ // The replica view of this query; the sync hook only reports the fetch flags.
+ const data = useDiscoverStore(modelSelectors.modelList(queryKey));
const items = data?.items ?? [];
diff --git a/src/routes/(main)/community/(list)/skill/features/Category/index.tsx b/src/routes/(main)/community/(list)/skill/features/Category/index.tsx
index d5456cef441..7c7a4b83b50 100644
--- a/src/routes/(main)/community/(list)/skill/features/Category/index.tsx
+++ b/src/routes/(main)/community/(list)/skill/features/Category/index.tsx
@@ -12,6 +12,7 @@ import { useQuery } from '@/hooks/useQuery';
import { useSkillCategory } from '@/hooks/useSkillCategory';
import { SCROLL_PARENT_ID } from '@/routes/(main)/community/features/const';
import { useDiscoverStore } from '@/store/discover';
+import { skillSelectors } from '@/store/discover/selectors';
import { SkillCategory, SkillSorts } from '@/types/discover';
import CategoryMenu from '../../../../components/CategoryMenu';
@@ -22,7 +23,8 @@ const Category = memo(() => {
category?: SkillCategory;
q?: string;
};
- const { data: items = [] } = useSkillCategories({ q });
+ const { queryKey } = useSkillCategories({ q });
+ const items = useDiscoverStore(skillSelectors.skillCategories(queryKey));
const navigate = useWorkspaceAwareNavigate();
const cates = useSkillCategory();
diff --git a/src/routes/(main)/community/(list)/skill/index.tsx b/src/routes/(main)/community/(list)/skill/index.tsx
index 7c8a55ced11..a1732769eef 100644
--- a/src/routes/(main)/community/(list)/skill/index.tsx
+++ b/src/routes/(main)/community/(list)/skill/index.tsx
@@ -7,6 +7,7 @@ import AsyncBoundary from '@/components/AsyncBoundary';
import { RouteLoading } from '@/components/Skeleton/RouteSegment';
import { useQuery } from '@/hooks/useQuery';
import { useDiscoverStore } from '@/store/discover';
+import { skillSelectors } from '@/store/discover/selectors';
import { type SkillQueryParams } from '@/types/discover';
import { DiscoverTab, SkillSorts } from '@/types/discover';
@@ -17,7 +18,7 @@ import List from './features/List';
const SkillPage = memo(() => {
const { q, page, category, sort, order } = useQuery() as SkillQueryParams;
const useSkillList = useDiscoverStore((s) => s.useFetchSkillList);
- const { data, error, isLoading, mutate } = useSkillList({
+ const { error, isLoading, mutate, queryKey } = useSkillList({
category,
order,
page,
@@ -25,6 +26,8 @@ const SkillPage = memo(() => {
q,
sort: sort ?? SkillSorts.InstallCount,
});
+ // The replica view of this query; the sync hook only reports the fetch flags.
+ const data = useDiscoverStore(skillSelectors.skillList(queryKey));
const items = data?.items ?? [];
diff --git a/src/store/discover/initialState.ts b/src/store/discover/initialState.ts
index 9784c210566..4a9dadbd8d9 100644
--- a/src/store/discover/initialState.ts
+++ b/src/store/discover/initialState.ts
@@ -1,18 +1,44 @@
+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 { MCPSliceState } from './slices/mcp/initialState';
import { initialMCPSliceState } from './slices/mcp/initialState';
+import type { ModelSliceState } from './slices/model/initialState';
+import { initialModelSliceState } from './slices/model/initialState';
+import type { PluginSliceState } from './slices/plugin/initialState';
+import { initialPluginSliceState } from './slices/plugin/initialState';
import type { ProviderSliceState } from './slices/provider/initialState';
import { initialProviderSliceState } from './slices/provider/initialState';
+import type { SkillSliceState } from './slices/skill/initialState';
+import { initialSkillSliceState } from './slices/skill/initialState';
+import type { SocialSliceState } from './slices/social/initialState';
+import { initialSocialSliceState } from './slices/social/initialState';
+import type { UserSliceState } from './slices/user/initialState';
+import { initialUserSliceState } from './slices/user/initialState';
/**
* State of the discover (marketplace) store: the replica views of its slices,
* plus each slice's bookkeeping. Slices add their own actions on top.
*/
-export type DiscoverStoreState = GroupAgentSliceState & MCPSliceState & ProviderSliceState;
+export type DiscoverStoreState = AssistantSliceState &
+ GroupAgentSliceState &
+ MCPSliceState &
+ ModelSliceState &
+ PluginSliceState &
+ ProviderSliceState &
+ SkillSliceState &
+ SocialSliceState &
+ UserSliceState;
export const initialState: DiscoverStoreState = {
+ ...initialAssistantSliceState,
...initialGroupAgentSliceState,
...initialMCPSliceState,
+ ...initialModelSliceState,
+ ...initialPluginSliceState,
...initialProviderSliceState,
+ ...initialSkillSliceState,
+ ...initialSocialSliceState,
+ ...initialUserSliceState,
};
diff --git a/src/store/discover/selectors/assistantSelectors.ts b/src/store/discover/selectors/assistantSelectors.ts
new file mode 100644
index 00000000000..fbe280f1d5e
--- /dev/null
+++ b/src/store/discover/selectors/assistantSelectors.ts
@@ -0,0 +1,43 @@
+import type { CategoryItem } from '@lobehub/market-sdk';
+
+import type {
+ AssistantListResponse,
+ DiscoverAssistantDetail,
+ IdentifiersResponse,
+} from '@/types/discover';
+
+import type { DiscoverStore } from '../store';
+
+const EMPTY_CATEGORIES: CategoryItem[] = [];
+
+/**
+ * Readers of the assistant market replicas. Every helper takes the `queryKey`
+ * the matching fetch hook returned, so a surface that asks for one query never
+ * reads another's rows.
+ */
+const assistantList =
+ (queryKey?: string) =>
+ (s: DiscoverStore): AssistantListResponse | undefined =>
+ queryKey ? s.assistantListMap[queryKey] : undefined;
+
+const assistantDetail =
+ (queryKey?: string) =>
+ (s: DiscoverStore): DiscoverAssistantDetail | undefined =>
+ queryKey ? s.assistantDetailMap[queryKey] : undefined;
+
+const assistantCategories =
+ (queryKey?: string) =>
+ (s: DiscoverStore): CategoryItem[] =>
+ (queryKey && s.assistantCategoriesMap[queryKey]) || EMPTY_CATEGORIES;
+
+const assistantIdentifiers =
+ (queryKey?: string) =>
+ (s: DiscoverStore): IdentifiersResponse | undefined =>
+ queryKey ? s.assistantIdentifiersMap[queryKey] : undefined;
+
+export const assistantSelectors = {
+ assistantCategories,
+ assistantDetail,
+ assistantIdentifiers,
+ assistantList,
+};
diff --git a/src/store/discover/selectors/index.ts b/src/store/discover/selectors/index.ts
index 536803c2abb..1f247cb8a61 100644
--- a/src/store/discover/selectors/index.ts
+++ b/src/store/discover/selectors/index.ts
@@ -1,3 +1,9 @@
+export { assistantSelectors } from './assistantSelectors';
export { groupAgentSelectors } from './groupAgentSelectors';
export { mcpSelectors } from './mcpSelectors';
+export { modelSelectors } from './modelSelectors';
+export { pluginSelectors } from './pluginSelectors';
export { providerSelectors } from './providerSelectors';
+export { skillSelectors } from './skillSelectors';
+export { socialSelectors } from './socialSelectors';
+export { userSelectors } from './userSelectors';
diff --git a/src/store/discover/selectors/modelSelectors.ts b/src/store/discover/selectors/modelSelectors.ts
new file mode 100644
index 00000000000..9a55d3ecdf6
--- /dev/null
+++ b/src/store/discover/selectors/modelSelectors.ts
@@ -0,0 +1,39 @@
+import type { CategoryItem } from '@lobehub/market-sdk';
+
+import type { DiscoverModelDetail, IdentifiersResponse, ModelListResponse } from '@/types/discover';
+
+import type { DiscoverStore } from '../store';
+
+const EMPTY_CATEGORIES: CategoryItem[] = [];
+
+/**
+ * Readers of the model market replicas. Every helper takes the `queryKey` the
+ * matching fetch hook returned, so a surface that asks for one query never
+ * reads another's rows.
+ */
+const modelList =
+ (queryKey?: string) =>
+ (s: DiscoverStore): ModelListResponse | undefined =>
+ queryKey ? s.modelListMap[queryKey] : undefined;
+
+const modelDetail =
+ (queryKey?: string) =>
+ (s: DiscoverStore): DiscoverModelDetail | undefined =>
+ queryKey ? s.modelDetailMap[queryKey] : undefined;
+
+const modelCategories =
+ (queryKey?: string) =>
+ (s: DiscoverStore): CategoryItem[] =>
+ (queryKey && s.modelCategoriesMap[queryKey]) || EMPTY_CATEGORIES;
+
+const modelIdentifiers =
+ (queryKey?: string) =>
+ (s: DiscoverStore): IdentifiersResponse | undefined =>
+ queryKey ? s.modelIdentifiersMap[queryKey] : undefined;
+
+export const modelSelectors = {
+ modelCategories,
+ modelDetail,
+ modelIdentifiers,
+ modelList,
+};
diff --git a/src/store/discover/selectors/pluginSelectors.ts b/src/store/discover/selectors/pluginSelectors.ts
new file mode 100644
index 00000000000..6172449512e
--- /dev/null
+++ b/src/store/discover/selectors/pluginSelectors.ts
@@ -0,0 +1,43 @@
+import type { CategoryItem } from '@lobehub/market-sdk';
+
+import type {
+ DiscoverPluginDetail,
+ IdentifiersResponse,
+ PluginListResponse,
+} from '@/types/discover';
+
+import type { DiscoverStore } from '../store';
+
+const EMPTY_CATEGORIES: CategoryItem[] = [];
+
+/**
+ * Readers of the plugin market replicas. Every helper takes the `queryKey` the
+ * matching fetch hook returned, so a surface that asks for one query never
+ * reads another's rows.
+ */
+const pluginList =
+ (queryKey?: string) =>
+ (s: DiscoverStore): PluginListResponse | undefined =>
+ queryKey ? s.pluginListMap[queryKey] : undefined;
+
+const pluginDetail =
+ (queryKey?: string) =>
+ (s: DiscoverStore): DiscoverPluginDetail | undefined =>
+ queryKey ? s.pluginDetailMap[queryKey] : undefined;
+
+const pluginCategories =
+ (queryKey?: string) =>
+ (s: DiscoverStore): CategoryItem[] =>
+ (queryKey && s.pluginCategoriesMap[queryKey]) || EMPTY_CATEGORIES;
+
+const pluginIdentifiers =
+ (queryKey?: string) =>
+ (s: DiscoverStore): IdentifiersResponse | undefined =>
+ queryKey ? s.pluginIdentifiersMap[queryKey] : undefined;
+
+export const pluginSelectors = {
+ pluginCategories,
+ pluginDetail,
+ pluginIdentifiers,
+ pluginList,
+};
diff --git a/src/store/discover/selectors/skillSelectors.ts b/src/store/discover/selectors/skillSelectors.ts
new file mode 100644
index 00000000000..38fbc8847ef
--- /dev/null
+++ b/src/store/discover/selectors/skillSelectors.ts
@@ -0,0 +1,57 @@
+import type {
+ DiscoverSkillDetail,
+ DiscoverSkillItem,
+ SkillCategoryItem,
+ SkillCommentListResponse,
+ SkillListResponse,
+ SkillRatingDistribution,
+} from '@/types/discover';
+
+import type { DiscoverStore } from '../store';
+
+const EMPTY_CATEGORIES: SkillCategoryItem[] = [];
+const EMPTY_RELATED: DiscoverSkillItem[] = [];
+
+/**
+ * Readers of the skill market replicas. Every helper takes the `queryKey` the
+ * matching fetch hook returned, so a surface that asks for one query never
+ * reads another's rows.
+ */
+const skillList =
+ (queryKey?: string) =>
+ (s: DiscoverStore): SkillListResponse | undefined =>
+ queryKey ? s.skillListMap[queryKey] : undefined;
+
+const skillDetail =
+ (queryKey?: string) =>
+ (s: DiscoverStore): DiscoverSkillDetail | undefined =>
+ queryKey ? s.skillDetailMap[queryKey] : undefined;
+
+const skillCategories =
+ (queryKey?: string) =>
+ (s: DiscoverStore): SkillCategoryItem[] =>
+ (queryKey && s.skillCategoriesMap[queryKey]) || EMPTY_CATEGORIES;
+
+const skillComments =
+ (queryKey?: string) =>
+ (s: DiscoverStore): SkillCommentListResponse | undefined =>
+ queryKey ? s.skillCommentsMap[queryKey] : undefined;
+
+const skillRatingDistribution =
+ (queryKey?: string) =>
+ (s: DiscoverStore): SkillRatingDistribution | undefined =>
+ queryKey ? s.skillRatingDistributionMap[queryKey] : undefined;
+
+const skillRelated =
+ (queryKey?: string) =>
+ (s: DiscoverStore): DiscoverSkillItem[] =>
+ (queryKey && s.skillRelatedMap[queryKey]) || EMPTY_RELATED;
+
+export const skillSelectors = {
+ skillCategories,
+ skillComments,
+ skillDetail,
+ skillList,
+ skillRatingDistribution,
+ skillRelated,
+};
diff --git a/src/store/discover/selectors/socialSelectors.ts b/src/store/discover/selectors/socialSelectors.ts
new file mode 100644
index 00000000000..86abe2771e6
--- /dev/null
+++ b/src/store/discover/selectors/socialSelectors.ts
@@ -0,0 +1,54 @@
+import {
+ type FavoriteAgentItem,
+ type FavoritePluginItem,
+ type FollowCounts,
+ type FollowStatus,
+ type FollowUserItem,
+ type PaginatedResponse,
+} from '@/services/social';
+
+import type { DiscoverStore } from '../store';
+
+/**
+ * Readers of the social replicas. Every helper takes the `queryKey` the
+ * matching fetch hook returned, so a surface that asks for one entry never
+ * reads another's value.
+ */
+const followStatus =
+ (queryKey?: string) =>
+ (s: DiscoverStore): FollowStatus | undefined =>
+ queryKey ? s.followStatusMap[queryKey] : undefined;
+
+const followCounts =
+ (queryKey?: string) =>
+ (s: DiscoverStore): FollowCounts | undefined =>
+ queryKey ? s.followCountsMap[queryKey] : undefined;
+
+const followers =
+ (queryKey?: string) =>
+ (s: DiscoverStore): PaginatedResponse<FollowUserItem> | undefined =>
+ queryKey ? s.followersMap[queryKey] : undefined;
+
+const following =
+ (queryKey?: string) =>
+ (s: DiscoverStore): PaginatedResponse<FollowUserItem> | undefined =>
+ queryKey ? s.followingMap[queryKey] : undefined;
+
+const favoriteAgents =
+ (queryKey?: string) =>
+ (s: DiscoverStore): PaginatedResponse<FavoriteAgentItem> | undefined =>
+ queryKey ? s.favoriteAgentsMap[queryKey] : undefined;
+
+const favoritePlugins =
+ (queryKey?: string) =>
+ (s: DiscoverStore): PaginatedResponse<FavoritePluginItem> | undefined =>
+ queryKey ? s.favoritePluginsMap[queryKey] : undefined;
+
+export const socialSelectors = {
+ favoriteAgents,
+ favoritePlugins,
+ followCounts,
+ followStatus,
+ followers,
+ following,
+};
diff --git a/src/store/discover/selectors/userSelectors.ts b/src/store/discover/selectors/userSelectors.ts
new file mode 100644
index 00000000000..2e6e6e6f02b
--- /dev/null
+++ b/src/store/discover/selectors/userSelectors.ts
@@ -0,0 +1,15 @@
+import { type DiscoverUserProfile } from '@/types/discover';
+
+import type { DiscoverStore } from '../store';
+
+/**
+ * Reader of the community profile replica. Takes the `queryKey` the profile
+ * fetch hook returned, so a surface that asks for one profile never reads
+ * another's value.
+ */
+const userProfile =
+ (queryKey?: string) =>
+ (s: DiscoverStore): DiscoverUserProfile | undefined =>
+ queryKey ? s.userProfileMap[queryKey] : undefined;
+
+export const userSelectors = { userProfile };
diff --git a/src/store/discover/slices/assistant/action.test.ts b/src/store/discover/slices/assistant/action.test.ts
index b6cc2dae8ae..9a217defe5b 100644
--- a/src/store/discover/slices/assistant/action.test.ts
+++ b/src/store/discover/slices/assistant/action.test.ts
@@ -1,297 +1,295 @@
-import { act, renderHook, waitFor } from '@testing-library/react';
+import { act, renderHook } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { discoverService } from '@/services/discover';
+import { createReplicaState } from '@/libs/replica';
import { globalHelpers } from '@/store/global/helpers';
+import type { AssistantListResponse } from '@/types/discover';
+import { assistantSelectors } from '../../selectors';
import { useDiscoverStore as useStore } from '../../store';
+import {
+ assistantCategoriesQueryKey,
+ assistantDetailQueryKey,
+ assistantIdentifiersQueryKey,
+ assistantListQueryKey,
+} from './projection';
+
+vi.mock('@/services/discover', () => ({
+ discoverService: {
+ getAssistantCategories: vi.fn(),
+ getAssistantDetail: vi.fn(),
+ getAssistantIdentifiers: vi.fn(),
+ getAssistantList: vi.fn(),
+ },
+}));
+
+// The replica schedules its fetches through the app's SWR driver; the engine
+// itself is what these tests exercise, so the driver is a bare recorder.
+vi.mock('@/libs/swr', () => ({
+ mutate: vi.fn(),
+ useClientDataSWR: vi.fn(() => ({ isValidating: false, mutate: vi.fn() })),
+}));
+
+const makeList = (identifier = 'assistant-1'): AssistantListResponse => ({
+ currentPage: 1,
+ items: [{ identifier } as any],
+ pageSize: 21,
+ totalCount: 1,
+ totalPages: 1,
+});
+
+const emptyAssistantState = () => ({
+ assistantCategoriesMap: {},
+ assistantCategoriesReplica: createReplicaState(),
+ assistantDetailMap: {},
+ assistantDetailReplica: createReplicaState(),
+ assistantIdentifiersMap: {},
+ assistantIdentifiersReplica: createReplicaState(),
+ assistantListMap: {},
+ assistantListReplica: createReplicaState(),
+});
beforeEach(() => {
vi.clearAllMocks();
+ vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');
+ useStore.setState(emptyAssistantState());
});
-describe('AssistantAction', () => {
- describe('useAssistantCategories', () => {
- it('should fetch assistant categories with correct parameters', async () => {
- const mockCategories = [
- { id: 'cat-1', name: 'Category 1' },
- { id: 'cat-2', name: 'Category 2' },
- ];
-
- vi.spyOn(discoverService, 'getAssistantCategories').mockResolvedValue(mockCategories as any);
- vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');
-
- const params = {} as any;
- const { result } = renderHook(() => useStore.getState().useAssistantCategories(params));
-
- await waitFor(() => {
- expect(result.current.data).toEqual(mockCategories);
- });
-
- expect(discoverService.getAssistantCategories).toHaveBeenCalledWith(params);
+/** The replica network syncs registered with the SWR driver, per resource name. */
+const syncCalls = async (
+ name: 'assistantCategories' | 'assistantDetail' | 'assistantIdentifiers' | 'assistantList',
+) => {
+ const { useClientDataSWR } = await import('@/libs/swr');
+ return vi
+ .mocked(useClientDataSWR)
+ .mock.calls.filter(
+ ([key]) => Array.isArray(key) && key[0] === 'replica:sync' && key[1] === name,
+ )
+ .map(([key, fetcher, config]) => ({
+ config: config as { onSuccess?: (data: unknown) => void; revalidateOnFocus?: boolean },
+ fetcher: fetcher as () => Promise<any>,
+ key: key as unknown[],
+ }));
+};
+
+describe('AssistantSlice (replica)', () => {
+ it('does not revalidate any assistant read on window focus', async () => {
+ renderHook(() => {
+ const state = useStore.getState();
+ state.useFetchAssistantList();
+ state.useFetchAssistantDetail({ identifier: 'lobe-chat' });
+ state.useFetchAssistantCategories();
+ state.useFetchAssistantIdentifiers();
});
- it('should fetch assistant categories with custom parameters', async () => {
- const mockCategories = [{ id: 'cat-1', name: 'Custom Category' }];
-
- vi.spyOn(discoverService, 'getAssistantCategories').mockResolvedValue(mockCategories as any);
- vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('zh-CN');
-
- const params = { filter: 'popular' } as any;
- const { result } = renderHook(() => useStore.getState().useAssistantCategories(params));
-
- await waitFor(() => {
- expect(result.current.data).toEqual(mockCategories);
- });
-
- expect(discoverService.getAssistantCategories).toHaveBeenCalledWith(params);
- });
-
- it('should skip the compatibility request when category counts come from the list', async () => {
- const getAssistantCategories = vi.spyOn(discoverService, 'getAssistantCategories');
-
- const { result } = renderHook(() =>
- useStore.getState().useAssistantCategories({}, { enabled: false }),
- );
-
- expect(result.current.data).toBeUndefined();
- expect(getAssistantCategories).not.toHaveBeenCalled();
- });
+ for (const name of [
+ 'assistantList',
+ 'assistantDetail',
+ 'assistantCategories',
+ 'assistantIdentifiers',
+ ] as const) {
+ const calls = await syncCalls(name);
+ expect(calls.length).toBeGreaterThan(0);
+ for (const call of calls) expect(call.config.revalidateOnFocus).toBe(false);
+ }
});
- describe('useAssistantDetail', () => {
- it('should fetch assistant detail when identifier is provided', async () => {
- const mockDetail = {
- identifier: 'test-assistant',
- name: 'Test Assistant',
- description: 'A test assistant',
- };
+ describe('useFetchAssistantList', () => {
+ it('requests the list with normalized page / pageSize and the locale', async () => {
+ const { discoverService } = await import('@/services/discover');
- vi.spyOn(discoverService, 'getAssistantDetail').mockResolvedValue(mockDetail as any);
- vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');
+ renderHook(() => useStore.getState().useFetchAssistantList({ q: 'coding' }));
- const params = { identifier: 'test-assistant' };
- const { result } = renderHook(() => useStore.getState().useAssistantDetail(params));
+ const [call] = await syncCalls('assistantList');
+ await call.fetcher();
- await waitFor(() => {
- expect(result.current.data).toEqual(mockDetail);
+ expect(discoverService.getAssistantList).toHaveBeenCalledWith({
+ locale: 'en-US',
+ page: 1,
+ pageSize: 21,
+ q: 'coding',
});
-
- expect(discoverService.getAssistantDetail).toHaveBeenCalledWith(params);
});
- it('should respect locale changes', async () => {
- const mockDetail = {
- identifier: 'test-assistant',
- name: 'ζ΅‹θ―•εŠ©η†',
- description: 'δΈ€δΈͺζ΅‹θ―•εŠ©η†',
- };
-
- vi.spyOn(discoverService, 'getAssistantDetail').mockResolvedValue(mockDetail as any);
- vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('zh-CN');
+ it('keys each page and filter set as its own replica entry', () => {
+ const { result } = renderHook(() => [
+ useStore.getState().useFetchAssistantList({ page: 1 }),
+ useStore.getState().useFetchAssistantList({ page: 2 }),
+ useStore.getState().useFetchAssistantList({ category: 'programming' }),
+ ]);
- const params = { identifier: 'test-assistant' };
- const { result } = renderHook(() => useStore.getState().useAssistantDetail(params));
-
- await waitFor(() => {
- expect(result.current.data).toEqual(mockDetail);
- });
-
- expect(globalHelpers.getCurrentLanguage).toHaveBeenCalled();
+ const [first, second, third] = result.current;
+ expect(new Set([first.queryKey, second.queryKey, third.queryKey]).size).toBe(3);
});
- it('should drop previous detail data when the identifier changes', async () => {
- const first = { identifier: 'assistant-a', name: 'A' };
- const second = { identifier: 'assistant-b', name: 'B' };
- let resolveSecond!: (value: typeof second) => void;
- const secondRequest = new Promise<typeof second>((resolve) => {
- resolveSecond = resolve;
- });
- vi.spyOn(discoverService, 'getAssistantDetail').mockImplementation(async (params) =>
- params?.identifier === 'assistant-b' ? secondRequest : (first as any),
+ it('does not register a sync β€” and reports no loading β€” when disabled', async () => {
+ const { result } = renderHook(() =>
+ useStore.getState().useFetchAssistantList({ page: 1 }, { enabled: false }),
);
- vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');
- const { result, rerender } = renderHook(
- ({ identifier }) => useStore.getState().useAssistantDetail({ identifier }),
- { initialProps: { identifier: 'assistant-a' } },
- );
+ expect(result.current.queryKey).toBeUndefined();
+ expect(result.current.isLoading).toBe(false);
+ expect(await syncCalls('assistantList')).toHaveLength(0);
+ });
- await waitFor(() => {
- expect(result.current.data).toEqual(first);
- });
+ it('reports loading until the entry has a value to show', () => {
+ const { result } = renderHook(() => useStore.getState().useFetchAssistantList({ page: 1 }));
- rerender({ identifier: 'assistant-b' });
+ expect(result.current.isLoading).toBe(true);
+ });
- await waitFor(() => {
- expect(result.current.data).toBeUndefined();
- });
+ it('does not report loading when the entry already has a (hydrated) value', () => {
+ const key = assistantListQueryKey({ locale: 'en-US', page: 1, pageSize: 21 });
+ useStore.setState({ assistantListMap: { [key]: makeList() } });
- resolveSecond(second);
+ const { result } = renderHook(() => useStore.getState().useFetchAssistantList({ page: 1 }));
- await waitFor(() => {
- expect(result.current.data).toEqual(second);
- });
+ expect(result.current.queryKey).toBe(key);
+ expect(result.current.isLoading).toBe(false);
});
- });
-
- describe('useAssistantIdentifiers', () => {
- it('should fetch assistant identifiers', async () => {
- const mockIdentifiers = [
- { identifier: 'assistant-1', lastModified: '2024-01-01' },
- { identifier: 'assistant-2', lastModified: '2024-01-02' },
- ];
- vi.spyOn(discoverService, 'getAssistantIdentifiers').mockResolvedValue(mockIdentifiers);
+ it('folds the response into the replica view the selectors read', async () => {
+ const response = makeList();
- const { result } = renderHook(() => useStore.getState().useAssistantIdentifiers());
-
- await waitFor(() => {
- expect(result.current.data).toEqual(mockIdentifiers);
- });
+ renderHook(() => useStore.getState().useFetchAssistantList({ page: 1 }));
+ const [call] = await syncCalls('assistantList');
+ act(() => call.config.onSuccess!(response));
- expect(discoverService.getAssistantIdentifiers).toHaveBeenCalled();
+ const key = assistantListQueryKey({ locale: 'en-US', page: 1, pageSize: 21 });
+ expect(assistantSelectors.assistantList(key)(useStore.getState())).toEqual(response);
});
});
- describe('useAssistantList', () => {
- it('should keep previous list data while a paginated request is loading', async () => {
- const firstPage = { items: [{ identifier: 'first-page' }], total: 1 };
- const secondPage = { items: [{ identifier: 'second-page' }], total: 1 };
- let resolveSecondPage!: (value: typeof secondPage) => void;
- const secondPageRequest = new Promise<typeof secondPage>((resolve) => {
- resolveSecondPage = resolve;
- });
- vi.spyOn(discoverService, 'getAssistantList').mockImplementation(async (params) =>
- params?.page === 2 ? secondPageRequest : (firstPage as any),
- );
- vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');
+ describe('useFetchAssistantDetail', () => {
+ it('requests the detail with identifier / source / version / locale', async () => {
+ const { discoverService } = await import('@/services/discover');
- const q = `keep-previous-${Date.now()}`;
- const { rerender, result } = renderHook(
- ({ page }) => useStore.getState().useAssistantList({ page, q }, { keepPreviousData: true }),
- { initialProps: { page: 1 } },
+ renderHook(() =>
+ useStore
+ .getState()
+ .useFetchAssistantDetail({ identifier: 'lobe-chat', source: 'new', version: '1.0.0' }),
);
- await waitFor(() => expect(result.current.data).toEqual(firstPage));
- rerender({ page: 2 });
- expect(result.current.data).toEqual(firstPage);
+ const [call] = await syncCalls('assistantDetail');
+ await call.fetcher();
- await act(async () => resolveSecondPage(secondPage));
- await waitFor(() => expect(result.current.data).toEqual(secondPage));
+ expect(discoverService.getAssistantDetail).toHaveBeenCalledWith({
+ identifier: 'lobe-chat',
+ locale: 'en-US',
+ source: 'new',
+ version: '1.0.0',
+ });
});
- it('should fetch assistant list with default parameters', async () => {
- const mockList = {
- items: [{ identifier: 'assistant-1' }, { identifier: 'assistant-2' }],
- total: 2,
- };
+ it('keys the detail by identifier, source and version', () => {
+ const { result } = renderHook(() => [
+ useStore.getState().useFetchAssistantDetail({ identifier: 'lobe-chat' }),
+ useStore.getState().useFetchAssistantDetail({ identifier: 'lobe-chat', source: 'new' }),
+ useStore.getState().useFetchAssistantDetail({ identifier: 'lobe-chat', version: '1.0.0' }),
+ ]);
- vi.spyOn(discoverService, 'getAssistantList').mockResolvedValue(mockList as any);
- vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');
+ expect(new Set(result.current.map((sync) => sync.queryKey)).size).toBe(3);
+ });
- const { result } = renderHook(() => useStore.getState().useAssistantList());
+ it('drops a cached detail once the market reports the assistant gone', async () => {
+ const { discoverService } = await import('@/services/discover');
- await waitFor(() => {
- expect(result.current.data).toEqual(mockList);
+ const { result } = renderHook(() =>
+ useStore.getState().useFetchAssistantDetail({ identifier: 'lobe-chat' }),
+ );
+ const key = result.current.queryKey!;
+ const [call] = await syncCalls('assistantDetail');
+
+ vi.mocked(discoverService.getAssistantDetail).mockResolvedValueOnce({
+ identifier: 'lobe-chat',
+ } as any);
+ const cached = await call.fetcher();
+ act(() => call.config.onSuccess!(cached));
+ expect(assistantSelectors.assistantDetail(key)(useStore.getState())).toEqual({
+ identifier: 'lobe-chat',
});
- expect(discoverService.getAssistantList).toHaveBeenCalledWith({
- page: 1,
- pageSize: 21,
- });
+ // The market removed the assistant: the service answers `undefined`.
+ vi.mocked(discoverService.getAssistantDetail).mockResolvedValueOnce(undefined);
+ const missing = await call.fetcher();
+ act(() => call.config.onSuccess!(missing));
+
+ expect(assistantSelectors.assistantDetail(key)(useStore.getState())).toBeUndefined();
+ expect(useStore.getState().assistantDetailMap[key]).toBeUndefined();
});
- it('should fetch assistant list with custom parameters', async () => {
- const mockList = {
- items: [{ identifier: 'assistant-1' }],
- total: 1,
- };
+ it('keys the detail by the locale, so a language switch refetches', () => {
+ const { result, rerender } = renderHook(() =>
+ useStore.getState().useFetchAssistantDetail({ identifier: 'lobe-chat' }),
+ );
+ const first = result.current.queryKey;
- vi.spyOn(discoverService, 'getAssistantList').mockResolvedValue(mockList as any);
vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('zh-CN');
+ rerender();
- const params = { page: 2, pageSize: 10, category: 'productivity' } as any;
- const { result } = renderHook(() => useStore.getState().useAssistantList(params));
-
- await waitFor(() => {
- expect(result.current.data).toEqual(mockList);
- });
-
- expect(discoverService.getAssistantList).toHaveBeenCalledWith({
- page: 2,
- pageSize: 10,
- category: 'productivity',
- });
+ expect(result.current.queryKey).not.toBe(first);
});
+ });
- it('should convert page and pageSize to numbers', async () => {
- vi.spyOn(discoverService, 'getAssistantList').mockResolvedValue({ items: [] } as any);
- vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');
+ describe('useFetchAssistantCategories', () => {
+ it('requests category counts with the search term and locale', async () => {
+ const { discoverService } = await import('@/services/discover');
- const params = { page: 3, pageSize: 15 } as any;
- const { result } = renderHook(() => useStore.getState().useAssistantList(params));
+ renderHook(() =>
+ useStore.getState().useFetchAssistantCategories({ q: 'coding', source: 'new' }),
+ );
- await waitFor(() => {
- expect(result.current.data).toBeDefined();
- });
+ const [call] = await syncCalls('assistantCategories');
+ await call.fetcher();
- expect(discoverService.getAssistantList).toHaveBeenCalledWith({
- page: 3,
- pageSize: 15,
+ expect(discoverService.getAssistantCategories).toHaveBeenCalledWith({
+ locale: 'en-US',
+ q: 'coding',
+ source: 'new',
});
});
- it('should work with search query parameter', async () => {
- const mockList = {
- items: [{ identifier: 'search-result-1' }],
- total: 1,
- };
-
- vi.spyOn(discoverService, 'getAssistantList').mockResolvedValue(mockList as any);
- vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');
-
- const params = { search: 'coding', page: 1, pageSize: 21 } as any;
- const { result } = renderHook(() => useStore.getState().useAssistantList(params));
+ it('skips the request when disabled (the list already carries the counts)', async () => {
+ const { result } = renderHook(() =>
+ useStore.getState().useFetchAssistantCategories({}, { enabled: false }),
+ );
- await waitFor(() => {
- expect(result.current.data).toEqual(mockList);
- });
+ expect(result.current.queryKey).toBeUndefined();
+ expect(await syncCalls('assistantCategories')).toHaveLength(0);
+ });
- expect(discoverService.getAssistantList).toHaveBeenCalledWith({
- search: 'coding',
- page: 1,
- pageSize: 21,
- });
+ it('falls back to an empty list when no category entry is loaded', () => {
+ expect(assistantSelectors.assistantCategories(undefined)(useStore.getState())).toEqual([]);
+ expect(assistantSelectors.assistantList(undefined)(useStore.getState())).toBeUndefined();
+ expect(assistantSelectors.assistantDetail(undefined)(useStore.getState())).toBeUndefined();
});
+ });
- it('should work with multiple filter parameters', async () => {
- const mockList = {
- items: [{ identifier: 'filtered-assistant' }],
- total: 1,
- };
+ describe('useFetchAssistantIdentifiers', () => {
+ it('requests the identifier index of a source', async () => {
+ const { discoverService } = await import('@/services/discover');
- vi.spyOn(discoverService, 'getAssistantList').mockResolvedValue(mockList as any);
- vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');
+ renderHook(() => useStore.getState().useFetchAssistantIdentifiers({ source: 'new' }));
- const params = {
- category: 'development',
- search: 'code',
- page: 1,
- pageSize: 10,
- } as any;
- const { result } = renderHook(() => useStore.getState().useAssistantList(params));
+ const [call] = await syncCalls('assistantIdentifiers');
+ await call.fetcher();
- await waitFor(() => {
- expect(result.current.data).toEqual(mockList);
- });
+ expect(discoverService.getAssistantIdentifiers).toHaveBeenCalledWith({ source: 'new' });
+ });
+ });
- expect(discoverService.getAssistantList).toHaveBeenCalledWith({
- category: 'development',
- search: 'code',
- page: 1,
- pageSize: 10,
- });
+ describe('replica key helpers', () => {
+ it('produces stable, distinct keys per query dimension', () => {
+ expect(assistantListQueryKey({ locale: 'en-US', page: 1, pageSize: 21 })).toBe(
+ assistantListQueryKey({ locale: 'en-US', page: 1, pageSize: 21 }),
+ );
+ expect(assistantDetailQueryKey({ identifier: 'a' })).not.toBe(
+ assistantDetailQueryKey({ identifier: 'b' }),
+ );
+ expect(assistantCategoriesQueryKey({ q: 'a' })).not.toBe(assistantCategoriesQueryKey({}));
+ expect(assistantIdentifiersQueryKey({ source: 'new' })).not.toBe(
+ assistantIdentifiersQueryKey({}),
+ );
});
});
});
diff --git a/src/store/discover/slices/assistant/action.ts b/src/store/discover/slices/assistant/action.ts
index ea39f07f867..b5848a572b1 100644
--- a/src/store/discover/slices/assistant/action.ts
+++ b/src/store/discover/slices/assistant/action.ts
@@ -1,89 +1,193 @@
-import { type CategoryItem, type CategoryListQuery } from '@lobehub/market-sdk';
-import { type SWRResponse } from 'swr';
-import useSWR from 'swr';
+import type { CategoryItem } from '@lobehub/market-sdk';
-import { discoverKeys } from '@/libs/swr/keys';
-import { discoverService } from '@/services/discover';
-import { type DiscoverStore } from '@/store/discover';
+import { createReplicaSlice, recordLens, type ReplicaSyncResult } from '@/libs/replica';
+import type { DiscoverStore } from '@/store/discover';
import { globalHelpers } from '@/store/global/helpers';
-import { type StoreSetter } from '@/store/types';
-import {
- type AssistantListResponse,
- type AssistantMarketSource,
- type AssistantQueryParams,
- type DiscoverAssistantDetail,
- type IdentifiersResponse,
+import type { StoreSetter } from '@/store/types';
+import type {
+ AssistantListResponse,
+ AssistantQueryParams,
+ DiscoverAssistantDetail,
+ IdentifiersResponse,
} from '@/types/discover';
+import { setNamespace } from '@/utils/storeDebug';
+
+import {
+ type AssistantCategoriesParams,
+ assistantCategoriesQueryKey,
+ assistantCategoriesResource,
+ type AssistantDetailParams,
+ assistantDetailQueryKey,
+ assistantDetailResource,
+ type AssistantIdentifiersParams,
+ assistantIdentifiersQueryKey,
+ assistantIdentifiersResource,
+ type AssistantListParams,
+ assistantListQueryKey,
+ assistantListResource,
+} from './projection';
+
+const n = setNamespace('discover/assistant');
+
+/**
+ * Sync flags of a market read, plus the aliases the old SWR hooks returned
+ * (`isLoading` / `mutate`) so a call site only has to move its `data` read to
+ * the matching `assistantSelectors` entry.
+ */
+export interface AssistantSyncResult extends ReplicaSyncResult {
+ /** A request is in flight and this entry has no value to show yet. */
+ isLoading: boolean;
+ /** Alias of `revalidate`. */
+ mutate: () => Promise<unknown>;
+ /** Read the value with `assistantSelectors.*(queryKey)`; undefined while disabled. */
+ queryKey?: string;
+}
type Setter = StoreSetter<DiscoverStore>;
+
export const createAssistantSlice = (set: Setter, get: () => DiscoverStore, _api?: unknown) =>
new AssistantActionImpl(set, get, _api);
export class AssistantActionImpl {
+ readonly #categories;
+ readonly #detail;
+ readonly #get: () => DiscoverStore;
+ readonly #identifiers;
+ readonly #list;
+
constructor(set: Setter, get: () => DiscoverStore, _api?: unknown) {
void _api;
- void set;
- void get;
+ this.#get = get;
+ this.#list = createReplicaSlice(assistantListResource, {
+ actionPrefix: n('list'),
+ get,
+ set,
+ stateKey: 'assistantListReplica',
+ view: recordLens<DiscoverStore, AssistantListResponse>('assistantListMap'),
+ });
+ this.#detail = createReplicaSlice(assistantDetailResource, {
+ actionPrefix: n('detail'),
+ get,
+ // The market no longer has this assistant: drop the entry and its
+ // persisted row rather than keep serving the cached copy.
+ isMissing: (detail) => detail === null,
+ set,
+ stateKey: 'assistantDetailReplica',
+ view: recordLens<DiscoverStore, DiscoverAssistantDetail>('assistantDetailMap'),
+ });
+ this.#categories = createReplicaSlice(assistantCategoriesResource, {
+ actionPrefix: n('categories'),
+ get,
+ set,
+ stateKey: 'assistantCategoriesReplica',
+ view: recordLens<DiscoverStore, CategoryItem[]>('assistantCategoriesMap'),
+ });
+ this.#identifiers = createReplicaSlice(assistantIdentifiersResource, {
+ actionPrefix: n('identifiers'),
+ get,
+ set,
+ stateKey: 'assistantIdentifiersReplica',
+ view: recordLens<DiscoverStore, IdentifiersResponse>('assistantIdentifiersMap'),
+ });
}
- useAssistantCategories = (
- params: CategoryListQuery & { source?: AssistantMarketSource },
+ #toSyncResult = (
+ sync: ReplicaSyncResult,
+ queryKey: string | undefined,
+ hasValue: boolean,
+ active: boolean,
+ ): AssistantSyncResult => ({
+ ...sync,
+ // A disabled hook never loads; a settled entry with a value never flashes.
+ isLoading: active && !hasValue && (!sync.isHydrated || sync.isValidating),
+ mutate: sync.revalidate,
+ queryKey: active ? queryKey : undefined,
+ });
+
+ /**
+ * The assistant market list of one query. Each (filters Β· page) pair is its
+ * own entry, so the URL-driven pager walks entries instead of appending
+ * pages. Read the rows with `assistantSelectors.assistantList(queryKey)`.
+ */
+ useFetchAssistantList = (
+ params: AssistantQueryParams = {},
options: { enabled?: boolean } = {},
- ): SWRResponse<CategoryItem[]> => {
- const locale = globalHelpers.getCurrentLanguage();
- return useSWR(
- options.enabled === false ? null : discoverKeys.assistantCategories(locale, params),
- async () => discoverService.getAssistantCategories(params),
- {
- revalidateOnFocus: false,
- },
- );
+ ): AssistantSyncResult => {
+ const { enabled = true } = options;
+ const normalized: AssistantListParams = {
+ ...params,
+ locale: globalHelpers.getCurrentLanguage(),
+ page: params.page ? Number(params.page) : 1,
+ pageSize: params.pageSize ? Number(params.pageSize) : 21,
+ };
+ const queryKey = assistantListQueryKey(normalized);
+ const sync = this.#list.useSync(normalized, { enabled, revalidateOnFocus: false });
+ return this.#toSyncResult(sync, queryKey, !!this.#get().assistantListMap[queryKey], enabled);
};
- useAssistantDetail = (params: {
- identifier: string;
- source?: AssistantMarketSource;
- version?: string;
- }): SWRResponse<DiscoverAssistantDetail | undefined> => {
- const locale = globalHelpers.getCurrentLanguage();
- return useSWR(
- discoverKeys.assistantDetail(locale, params),
- async () => discoverService.getAssistantDetail(params),
- {
- revalidateOnFocus: false,
- },
+ /**
+ * One assistant detail (identifier Β· source Β· version). Read it with
+ * `assistantSelectors.assistantDetail(queryKey)`; `undefined` after the sync
+ * settles means the market has no such identifier.
+ */
+ useFetchAssistantDetail = (
+ params: AssistantDetailParams,
+ options: { enabled?: boolean } = {},
+ ): AssistantSyncResult => {
+ const { enabled = true } = options;
+ const normalized: AssistantDetailParams = {
+ identifier: params.identifier,
+ locale: globalHelpers.getCurrentLanguage(),
+ source: params.source,
+ version: params.version,
+ };
+ const queryKey = assistantDetailQueryKey(normalized);
+ const sync = this.#detail.useSync(normalized, { enabled, revalidateOnFocus: false });
+ return this.#toSyncResult(
+ sync,
+ queryKey,
+ this.#get().assistantDetailMap[queryKey] !== undefined,
+ enabled,
);
};
- useAssistantIdentifiers = (params?: {
- source?: AssistantMarketSource;
- }): SWRResponse<IdentifiersResponse> => {
- return useSWR(
- discoverKeys.assistantIdentifiers(params?.source),
- async () => discoverService.getAssistantIdentifiers(params),
- {
- revalidateOnFocus: false,
- },
+ /**
+ * Category counts of one query (the search term + source). The community
+ * sidebar reads `assistantSelectors.assistantCategories(queryKey)`; it is the
+ * fallback when a list response carries no `categoryCounts`.
+ */
+ useFetchAssistantCategories = (
+ params: AssistantCategoriesParams = {},
+ options: { enabled?: boolean } = {},
+ ): AssistantSyncResult => {
+ const { enabled = true } = options;
+ const normalized: AssistantCategoriesParams = {
+ ...params,
+ locale: globalHelpers.getCurrentLanguage(),
+ };
+ const queryKey = assistantCategoriesQueryKey(normalized);
+ const sync = this.#categories.useSync(normalized, { enabled, revalidateOnFocus: false });
+ return this.#toSyncResult(
+ sync,
+ queryKey,
+ !!this.#get().assistantCategoriesMap[queryKey],
+ enabled,
);
};
- useAssistantList = (
- params: AssistantQueryParams = {},
- options: { keepPreviousData?: boolean } = {},
- ): SWRResponse<AssistantListResponse> => {
- const locale = globalHelpers.getCurrentLanguage();
- return useSWR(
- discoverKeys.assistantList(locale, params),
- async () =>
- discoverService.getAssistantList({
- ...params,
- page: params.page ? Number(params.page) : 1,
- pageSize: params.pageSize ? Number(params.pageSize) : 21,
- }),
- {
- keepPreviousData: options.keepPreviousData,
- revalidateOnFocus: false,
- },
+ /** The identifier index of one market source. */
+ useFetchAssistantIdentifiers = (
+ params: AssistantIdentifiersParams = {},
+ options: { enabled?: boolean } = {},
+ ): AssistantSyncResult => {
+ const { enabled = true } = options;
+ const queryKey = assistantIdentifiersQueryKey(params);
+ const sync = this.#identifiers.useSync(params, { enabled, revalidateOnFocus: false });
+ return this.#toSyncResult(
+ sync,
+ queryKey,
+ !!this.#get().assistantIdentifiersMap[queryKey],
+ enabled,
);
};
}
diff --git a/src/store/discover/slices/assistant/initialState.ts b/src/store/discover/slices/assistant/initialState.ts
new file mode 100644
index 00000000000..7778c459a6f
--- /dev/null
+++ b/src/store/discover/slices/assistant/initialState.ts
@@ -0,0 +1,44 @@
+import type { CategoryItem } from '@lobehub/market-sdk';
+
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
+import type {
+ AssistantListResponse,
+ DiscoverAssistantDetail,
+ IdentifiersResponse,
+} from '@/types/discover';
+
+/**
+ * Replica views of the assistant market reads, each beside its bookkeeping
+ * slot. The views are plain records keyed by the entry key of the matching
+ * resource (`projection.ts`); components read them through
+ * `assistantSelectors`, never through the fetch hook.
+ */
+export interface AssistantSliceState {
+ /** Category counts per query (`assistantCategoriesQueryKey`). */
+ assistantCategoriesMap: Record<string, CategoryItem[]>;
+ /** Replica bookkeeping of `assistantCategoriesMap`. */
+ assistantCategoriesReplica: ReplicaState<CategoryItem[]>;
+ /** Assistant detail per identifier / source / version (`assistantDetailQueryKey`). */
+ assistantDetailMap: Record<string, DiscoverAssistantDetail>;
+ /** Replica bookkeeping of `assistantDetailMap`. */
+ assistantDetailReplica: ReplicaState<DiscoverAssistantDetail>;
+ /** Identifier index per source (`assistantIdentifiersQueryKey`). */
+ assistantIdentifiersMap: Record<string, IdentifiersResponse>;
+ /** Replica bookkeeping of `assistantIdentifiersMap`. */
+ assistantIdentifiersReplica: ReplicaState<IdentifiersResponse>;
+ /** Assistant list per query (`assistantListQueryKey`). */
+ assistantListMap: Record<string, AssistantListResponse>;
+ /** Replica bookkeeping of `assistantListMap`. */
+ assistantListReplica: ReplicaState<AssistantListResponse>;
+}
+
+export const initialAssistantSliceState: AssistantSliceState = {
+ assistantCategoriesMap: {},
+ assistantCategoriesReplica: createReplicaState(),
+ assistantDetailMap: {},
+ assistantDetailReplica: createReplicaState(),
+ assistantIdentifiersMap: {},
+ assistantIdentifiersReplica: createReplicaState(),
+ assistantListMap: {},
+ assistantListReplica: createReplicaState(),
+};
diff --git a/src/store/discover/slices/assistant/projection.ts b/src/store/discover/slices/assistant/projection.ts
new file mode 100644
index 00000000000..07a9f12f573
--- /dev/null
+++ b/src/store/discover/slices/assistant/projection.ts
@@ -0,0 +1,129 @@
+import type { CategoryItem, CategoryListQuery } from '@lobehub/market-sdk';
+
+import { defineReplica, stableQueryKey } from '@/libs/replica';
+import { discoverService } from '@/services/discover';
+import type {
+ AssistantListResponse,
+ AssistantMarketSource,
+ AssistantQueryParams,
+ DiscoverAssistantDetail,
+ IdentifiersResponse,
+} from '@/types/discover';
+
+/**
+ * The marketplace assistant reads are **read-only**: no optimistic write, no
+ * cross-copy entity link. What the replica buys here is the first frame β€” the
+ * last confirmed page paints before the network answers β€” and one cache
+ * partition per identity (the `cacheScope`), so switching account or workspace
+ * never serves the previous one's rows.
+ *
+ * Each distinct query is its own entry (`key`), exactly like the SWR key it
+ * replaces: the community list paginates by URL (`?page=N`), so a page flip is
+ * a different entry rather than a `loadMore` of the same one.
+ */
+
+/** Normalized `assistantList` params β€” the shape actually sent to the market endpoint. */
+export interface AssistantListParams extends Omit<AssistantQueryParams, 'page' | 'pageSize'> {
+ /** Current UI language; part of the entry so a locale switch refetches. */
+ locale?: string;
+ page: number;
+ pageSize: number;
+}
+
+/**
+ * Entry key of one assistant list query. Includes the page, because the list
+ * pages through the URL instead of appending pages to one entry.
+ */
+export const assistantListQueryKey = (params: AssistantListParams): string =>
+ stableQueryKey(params);
+
+export interface AssistantDetailParams {
+ identifier: string;
+ /** Current UI language; the market resolves localized copy server-side. */
+ locale?: string;
+ source?: AssistantMarketSource;
+ version?: string;
+}
+
+/** Entry key of one assistant detail (`identifier` + source + version). */
+export const assistantDetailQueryKey = (params: AssistantDetailParams): string =>
+ stableQueryKey(params);
+
+export interface AssistantCategoriesParams extends CategoryListQuery {
+ /** Current UI language; the market resolves localized category labels. */
+ locale?: string;
+ source?: AssistantMarketSource;
+}
+
+/** Entry key of one category-counts query (the search term + source). */
+export const assistantCategoriesQueryKey = (params: AssistantCategoriesParams): string =>
+ stableQueryKey(params);
+
+export interface AssistantIdentifiersParams {
+ source?: AssistantMarketSource;
+}
+
+/** Entry key of the identifiers lookup of one source. */
+export const assistantIdentifiersQueryKey = (params: AssistantIdentifiersParams): string =>
+ stableQueryKey(params);
+
+/**
+ * Assistant market list, one entry per query (`assistantListMap[queryKey]`).
+ * The response already carries everything a row reader needs (`items`,
+ * `currentPage`, `pageSize`, `totalCount`, and the optional `categoryCounts`),
+ * so it is stored as-is.
+ */
+export const assistantListResource = defineReplica<AssistantListParams, AssistantListResponse>({
+ fetcher: (params) => discoverService.getAssistantList(params),
+ key: assistantListQueryKey,
+ name: 'assistantList',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/**
+ * One assistant detail by identifier / source / version (`assistantDetailMap[key]`).
+ * The service answers `undefined` for an identifier the market no longer has;
+ * the fetcher turns that into `null` so the slice's `isMissing` drops the entry
+ * (memory and persisted row) instead of letting the engine skip the write and
+ * keep painting a stale cached copy. The page then reaches "not found" once the
+ * sync settles.
+ */
+export const assistantDetailResource = defineReplica<
+ AssistantDetailParams,
+ DiscoverAssistantDetail,
+ DiscoverAssistantDetail | null
+>({
+ fetcher: async (params) => (await discoverService.getAssistantDetail(params)) ?? null,
+ key: assistantDetailQueryKey,
+ name: 'assistantDetail',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/**
+ * Category counts of one query (`assistantCategoriesMap[queryKey]`). Small and
+ * read on almost every community screen, so localStorage keeps the first frame
+ * populated instead of flashing an empty sidebar.
+ */
+export const assistantCategoriesResource = defineReplica<AssistantCategoriesParams, CategoryItem[]>(
+ {
+ fetcher: (params) => discoverService.getAssistantCategories(params),
+ key: assistantCategoriesQueryKey,
+ name: 'assistantCategories',
+ storage: 'localStorage',
+ version: 1,
+ },
+);
+
+/** The identifier index of one market source (`assistantIdentifiersMap[queryKey]`). */
+export const assistantIdentifiersResource = defineReplica<
+ AssistantIdentifiersParams,
+ IdentifiersResponse
+>({
+ fetcher: (params) => discoverService.getAssistantIdentifiers(params),
+ key: assistantIdentifiersQueryKey,
+ name: 'assistantIdentifiers',
+ storage: 'localStorage',
+ version: 1,
+});
diff --git a/src/store/discover/slices/model/action.test.ts b/src/store/discover/slices/model/action.test.ts
index 5c02c63914c..521c054c161 100644
--- a/src/store/discover/slices/model/action.test.ts
+++ b/src/store/discover/slices/model/action.test.ts
@@ -1,251 +1,276 @@
-import { renderHook, waitFor } from '@testing-library/react';
+import { act, renderHook } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { discoverService } from '@/services/discover';
+import { createReplicaState } from '@/libs/replica';
import { globalHelpers } from '@/store/global/helpers';
+import type { ModelListResponse } from '@/types/discover';
+import { modelSelectors } from '../../selectors';
import { useDiscoverStore as useStore } from '../../store';
+import {
+ modelCategoriesQueryKey,
+ modelDetailQueryKey,
+ modelIdentifiersQueryKey,
+ modelListQueryKey,
+} from './projection';
+
+vi.mock('@/services/discover', () => ({
+ discoverService: {
+ getModelCategories: vi.fn(),
+ getModelDetail: vi.fn(),
+ getModelIdentifiers: vi.fn(),
+ getModelList: vi.fn(),
+ },
+}));
+
+// The replica schedules its fetches through the app's SWR driver; the engine
+// itself is what these tests exercise, so the driver is a bare recorder.
+vi.mock('@/libs/swr', () => ({
+ mutate: vi.fn(),
+ useClientDataSWR: vi.fn(() => ({ isValidating: false, mutate: vi.fn() })),
+}));
+
+const makeList = (identifier = 'model-1'): ModelListResponse => ({
+ currentPage: 1,
+ items: [{ identifier } as any],
+ pageSize: 21,
+ totalCount: 1,
+ totalPages: 1,
+});
+
+const emptyModelState = () => ({
+ modelCategoriesMap: {},
+ modelCategoriesReplica: createReplicaState(),
+ modelDetailMap: {},
+ modelDetailReplica: createReplicaState(),
+ modelIdentifiersMap: {},
+ modelIdentifiersReplica: createReplicaState(),
+ modelListMap: {},
+ modelListReplica: createReplicaState(),
+});
beforeEach(() => {
vi.clearAllMocks();
+ vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');
+ useStore.setState(emptyModelState());
});
-describe('ModelAction', () => {
- describe('useModelCategories', () => {
- it('should fetch model categories with correct parameters', async () => {
- const mockCategories = [
- { id: 'cat-1', name: 'Category 1' },
- { id: 'cat-2', name: 'Category 2' },
- ];
-
- vi.spyOn(discoverService, 'getModelCategories').mockResolvedValue(mockCategories as any);
-
- const params = {} as any;
- const { result } = renderHook(() => useStore.getState().useModelCategories(params));
-
- await waitFor(() => {
- expect(result.current.data).toEqual(mockCategories);
- });
-
- expect(discoverService.getModelCategories).toHaveBeenCalledWith(params);
+/** The replica network syncs registered with the SWR driver, per resource name. */
+const syncCalls = async (
+ name: 'modelCategories' | 'modelDetail' | 'modelIdentifiers' | 'modelList',
+) => {
+ const { useClientDataSWR } = await import('@/libs/swr');
+ return vi
+ .mocked(useClientDataSWR)
+ .mock.calls.filter(
+ ([key]) => Array.isArray(key) && key[0] === 'replica:sync' && key[1] === name,
+ )
+ .map(([key, fetcher, config]) => ({
+ config: config as { onSuccess?: (data: unknown) => void; revalidateOnFocus?: boolean },
+ fetcher: fetcher as () => Promise<any>,
+ key: key as unknown[],
+ }));
+};
+
+describe('ModelSlice (replica)', () => {
+ it('does not revalidate any model read on window focus', async () => {
+ renderHook(() => {
+ const state = useStore.getState();
+ state.useFetchModelList();
+ state.useFetchModelDetail({ identifier: 'gpt-4' });
+ state.useFetchModelCategories();
+ state.useFetchModelIdentifiers();
});
- it('should fetch model categories with custom parameters', async () => {
- const mockCategories = [{ id: 'cat-1', name: 'AI Models' }];
+ for (const name of [
+ 'modelList',
+ 'modelDetail',
+ 'modelCategories',
+ 'modelIdentifiers',
+ ] as const) {
+ const calls = await syncCalls(name);
+ expect(calls.length).toBeGreaterThan(0);
+ for (const call of calls) expect(call.config.revalidateOnFocus).toBe(false);
+ }
+ });
- vi.spyOn(discoverService, 'getModelCategories').mockResolvedValue(mockCategories as any);
+ describe('useFetchModelList', () => {
+ it('requests the list with normalized page / pageSize and the locale', async () => {
+ const { discoverService } = await import('@/services/discover');
- const params = { category: 'llm', limit: 10 } as any;
- const { result } = renderHook(() => useStore.getState().useModelCategories(params));
+ renderHook(() => useStore.getState().useFetchModelList({ q: 'gpt' }));
- await waitFor(() => {
- expect(result.current.data).toEqual(mockCategories);
- });
+ const [call] = await syncCalls('modelList');
+ await call.fetcher();
- expect(discoverService.getModelCategories).toHaveBeenCalledWith(params);
+ expect(discoverService.getModelList).toHaveBeenCalledWith({
+ locale: 'en-US',
+ page: 1,
+ pageSize: 21,
+ q: 'gpt',
+ });
});
- });
-
- describe('useModelDetail', () => {
- it('should fetch model detail when identifier is provided', async () => {
- const mockDetail = {
- identifier: 'gpt-4',
- name: 'GPT-4',
- description: 'A powerful language model',
- provider: 'openai',
- };
- vi.spyOn(discoverService, 'getModelDetail').mockResolvedValue(mockDetail as any);
- vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');
+ it('keys each page and filter set as its own replica entry', () => {
+ const { result } = renderHook(() => [
+ useStore.getState().useFetchModelList({ page: 1 }),
+ useStore.getState().useFetchModelList({ page: 2 }),
+ useStore.getState().useFetchModelList({ category: 'llm' }),
+ ]);
- const params = { identifier: 'gpt-4' };
- const { result } = renderHook(() => useStore.getState().useModelDetail(params));
+ const [first, second, third] = result.current;
+ expect(new Set([first.queryKey, second.queryKey, third.queryKey]).size).toBe(3);
+ });
- await waitFor(() => {
- expect(result.current.data).toEqual(mockDetail);
- });
+ it('does not register a sync β€” and reports no loading β€” when disabled', async () => {
+ const { result } = renderHook(() =>
+ useStore.getState().useFetchModelList({ page: 1 }, { enabled: false }),
+ );
- expect(discoverService.getModelDetail).toHaveBeenCalledWith(params);
+ expect(result.current.queryKey).toBeUndefined();
+ expect(result.current.isLoading).toBe(false);
+ expect(await syncCalls('modelList')).toHaveLength(0);
});
- it('should include locale in SWR key', async () => {
- const mockDetail = {
- identifier: 'gpt-4',
- name: 'GPT-4',
- };
+ it('reports loading until the entry has a value to show', () => {
+ const { result } = renderHook(() => useStore.getState().useFetchModelList({ page: 1 }));
- vi.spyOn(discoverService, 'getModelDetail').mockResolvedValue(mockDetail as any);
- vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('zh-CN');
+ expect(result.current.isLoading).toBe(true);
+ });
- const params = { identifier: 'gpt-4' };
- const { result } = renderHook(() => useStore.getState().useModelDetail(params));
+ it('does not report loading when the entry already has a (hydrated) value', () => {
+ const key = modelListQueryKey({ locale: 'en-US', page: 1, pageSize: 21 });
+ useStore.setState({ modelListMap: { [key]: makeList() } });
- await waitFor(() => {
- expect(result.current.data).toEqual(mockDetail);
- });
+ const { result } = renderHook(() => useStore.getState().useFetchModelList({ page: 1 }));
- expect(globalHelpers.getCurrentLanguage).toHaveBeenCalled();
- expect(discoverService.getModelDetail).toHaveBeenCalledWith(params);
+ expect(result.current.queryKey).toBe(key);
+ expect(result.current.isLoading).toBe(false);
});
- it('should return undefined when model is not found', async () => {
- vi.spyOn(discoverService, 'getModelDetail').mockResolvedValue(undefined);
- vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');
-
- const params = { identifier: 'non-existent-model' };
- const { result } = renderHook(() => useStore.getState().useModelDetail(params));
+ it('folds the response into the replica view the selectors read', async () => {
+ const response = makeList();
- await waitFor(() => {
- expect(result.current.data).toBeUndefined();
- });
+ renderHook(() => useStore.getState().useFetchModelList({ page: 1 }));
+ const [call] = await syncCalls('modelList');
+ act(() => call.config.onSuccess!(response));
- expect(discoverService.getModelDetail).toHaveBeenCalledWith(params);
+ const key = modelListQueryKey({ locale: 'en-US', page: 1, pageSize: 21 });
+ expect(modelSelectors.modelList(key)(useStore.getState())).toEqual(response);
});
});
- describe('useModelIdentifiers', () => {
- it('should fetch model identifiers', async () => {
- const mockIdentifiers = [
- { identifier: 'gpt-4', lastModified: '2024-01-01' },
- { identifier: 'claude-3', lastModified: '2024-01-02' },
- ];
+ describe('useFetchModelDetail', () => {
+ it('requests the detail with identifier and locale', async () => {
+ const { discoverService } = await import('@/services/discover');
- vi.spyOn(discoverService, 'getModelIdentifiers').mockResolvedValue(mockIdentifiers);
+ renderHook(() => useStore.getState().useFetchModelDetail({ identifier: 'gpt-4' }));
- const { result } = renderHook(() => useStore.getState().useModelIdentifiers());
+ const [call] = await syncCalls('modelDetail');
+ await call.fetcher();
- await waitFor(() => {
- expect(result.current.data).toEqual(mockIdentifiers);
+ expect(discoverService.getModelDetail).toHaveBeenCalledWith({
+ identifier: 'gpt-4',
+ locale: 'en-US',
});
-
- expect(discoverService.getModelIdentifiers).toHaveBeenCalled();
});
- });
-
- describe('useModelList', () => {
- it('should fetch model list with default parameters', async () => {
- const mockList = {
- items: [{ identifier: 'gpt-4' }, { identifier: 'claude-3' }],
- total: 2,
- };
- vi.spyOn(discoverService, 'getModelList').mockResolvedValue(mockList as any);
- vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');
+ it('keys the detail by identifier, so a different identifier is a different entry', () => {
+ const { result } = renderHook(() => [
+ useStore.getState().useFetchModelDetail({ identifier: 'gpt-4' }),
+ useStore.getState().useFetchModelDetail({ identifier: 'claude-3' }),
+ ]);
- const { result } = renderHook(() => useStore.getState().useModelList());
-
- await waitFor(() => {
- expect(result.current.data).toEqual(mockList);
- });
-
- expect(discoverService.getModelList).toHaveBeenCalledWith({
- page: 1,
- pageSize: 21,
- });
+ expect(new Set(result.current.map((sync) => sync.queryKey)).size).toBe(2);
});
- it('should fetch model list with custom parameters', async () => {
- const mockList = {
- items: [{ identifier: 'gpt-4' }],
- total: 1,
- };
-
- vi.spyOn(discoverService, 'getModelList').mockResolvedValue(mockList as any);
- vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('zh-CN');
+ it('clears a cached detail once the market answers the identifier no longer exists', async () => {
+ const { discoverService } = await import('@/services/discover');
+ const key = modelDetailQueryKey({ identifier: 'gone', locale: 'en-US' });
+ useStore.setState({
+ modelDetailMap: { [key]: { identifier: 'gone' } as any },
+ });
+ vi.mocked(discoverService.getModelDetail).mockResolvedValue(undefined as any);
- const params = { page: 2, pageSize: 10, category: 'llm' } as any;
- const { result } = renderHook(() => useStore.getState().useModelList(params));
+ const { result } = renderHook(() =>
+ useStore.getState().useFetchModelDetail({ identifier: 'gone' }),
+ );
+ expect(modelSelectors.modelDetail(key)(useStore.getState())).toBeDefined();
- await waitFor(() => {
- expect(result.current.data).toEqual(mockList);
- });
+ const [call] = await syncCalls('modelDetail');
+ const fetched = await call.fetcher();
+ act(() => call.config.onSuccess!(fetched));
- expect(discoverService.getModelList).toHaveBeenCalledWith({
- page: 2,
- pageSize: 10,
- category: 'llm',
- });
+ // The stale copy is gone and the entry is settled, so the page renders NotFound.
+ expect(modelSelectors.modelDetail(key)(useStore.getState())).toBeUndefined();
+ expect(useStore.getState().modelDetailMap[key]).toBeUndefined();
+ expect(result.current.isLoading).toBe(false);
});
- it('should convert page and pageSize to numbers', async () => {
- vi.spyOn(discoverService, 'getModelList').mockResolvedValue({ items: [] } as any);
- vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');
+ it('keys the detail by the locale, so a language switch refetches', () => {
+ const { result, rerender } = renderHook(() =>
+ useStore.getState().useFetchModelDetail({ identifier: 'gpt-4' }),
+ );
+ const first = result.current.queryKey;
- const params = { page: 3, pageSize: 15 } as any;
- const { result } = renderHook(() => useStore.getState().useModelList(params));
-
- await waitFor(() => {
- expect(result.current.data).toBeDefined();
- });
+ vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('zh-CN');
+ rerender();
- expect(discoverService.getModelList).toHaveBeenCalledWith({
- page: 3,
- pageSize: 15,
- });
+ expect(result.current.queryKey).not.toBe(first);
});
+ });
- it('should use default page and pageSize when not provided in params', async () => {
- const mockList = {
- items: [{ identifier: 'model-1' }],
- total: 1,
- };
-
- vi.spyOn(discoverService, 'getModelList').mockResolvedValue(mockList as any);
- vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');
+ describe('useFetchModelCategories', () => {
+ it('requests category counts with the search term', async () => {
+ const { discoverService } = await import('@/services/discover');
- const params = { category: 'vision' } as any;
- const { result } = renderHook(() => useStore.getState().useModelList(params));
+ renderHook(() => useStore.getState().useFetchModelCategories({ q: 'gpt' }));
- await waitFor(() => {
- expect(result.current.data).toEqual(mockList);
- });
+ const [call] = await syncCalls('modelCategories');
+ await call.fetcher();
- expect(discoverService.getModelList).toHaveBeenCalledWith({
- page: 1,
- pageSize: 21,
- category: 'vision',
- });
+ expect(discoverService.getModelCategories).toHaveBeenCalledWith({ q: 'gpt' });
});
- it('should include locale in SWR key', async () => {
- const mockList = {
- items: [{ identifier: 'model-1' }],
- total: 1,
- };
+ it('skips the request when disabled', async () => {
+ const { result } = renderHook(() =>
+ useStore.getState().useFetchModelCategories({}, { enabled: false }),
+ );
- vi.spyOn(discoverService, 'getModelList').mockResolvedValue(mockList as any);
- vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('ja-JP');
-
- const { result } = renderHook(() => useStore.getState().useModelList());
-
- await waitFor(() => {
- expect(result.current.data).toEqual(mockList);
- });
+ expect(result.current.queryKey).toBeUndefined();
+ expect(await syncCalls('modelCategories')).toHaveLength(0);
+ });
- expect(globalHelpers.getCurrentLanguage).toHaveBeenCalled();
+ it('falls back to an empty list when no category entry is loaded', () => {
+ expect(modelSelectors.modelCategories(undefined)(useStore.getState())).toEqual([]);
+ expect(modelSelectors.modelList(undefined)(useStore.getState())).toBeUndefined();
+ expect(modelSelectors.modelDetail(undefined)(useStore.getState())).toBeUndefined();
});
+ });
- it('should handle search query parameter', async () => {
- const mockList = {
- items: [{ identifier: 'gpt-4' }],
- total: 1,
- };
+ describe('useFetchModelIdentifiers', () => {
+ it('requests the identifier index', async () => {
+ const { discoverService } = await import('@/services/discover');
- vi.spyOn(discoverService, 'getModelList').mockResolvedValue(mockList as any);
- vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');
+ renderHook(() => useStore.getState().useFetchModelIdentifiers());
- const params = { search: 'gpt', page: 1, pageSize: 10 } as any;
- const { result } = renderHook(() => useStore.getState().useModelList(params));
+ const [call] = await syncCalls('modelIdentifiers');
+ await call.fetcher();
- await waitFor(() => {
- expect(result.current.data).toEqual(mockList);
- });
+ expect(discoverService.getModelIdentifiers).toHaveBeenCalled();
+ });
+ });
- expect(discoverService.getModelList).toHaveBeenCalledWith({
- search: 'gpt',
- page: 1,
- pageSize: 10,
- });
+ describe('replica key helpers', () => {
+ it('produces stable, distinct keys per query dimension', () => {
+ expect(modelListQueryKey({ locale: 'en-US', page: 1, pageSize: 21 })).toBe(
+ modelListQueryKey({ locale: 'en-US', page: 1, pageSize: 21 }),
+ );
+ expect(modelDetailQueryKey({ identifier: 'a' })).not.toBe(
+ modelDetailQueryKey({ identifier: 'b' }),
+ );
+ expect(modelCategoriesQueryKey({ q: 'a' })).not.toBe(modelCategoriesQueryKey({}));
+ expect(modelIdentifiersQueryKey()).toBe(modelIdentifiersQueryKey({}));
});
});
});
diff --git a/src/store/discover/slices/model/action.ts b/src/store/discover/slices/model/action.ts
index 461dafdca64..4fc249ed39a 100644
--- a/src/store/discover/slices/model/action.ts
+++ b/src/store/discover/slices/model/action.ts
@@ -1,77 +1,175 @@
-import { type CategoryItem, type CategoryListQuery } from '@lobehub/market-sdk';
-import { type SWRResponse } from 'swr';
-import useSWR from 'swr';
+import type { CategoryItem } from '@lobehub/market-sdk';
-import { discoverKeys } from '@/libs/swr/keys';
-import { discoverService } from '@/services/discover';
-import { type DiscoverStore } from '@/store/discover';
+import { createReplicaSlice, recordLens, type ReplicaSyncResult } from '@/libs/replica';
+import type { DiscoverStore } from '@/store/discover';
import { globalHelpers } from '@/store/global/helpers';
-import { type StoreSetter } from '@/store/types';
-import {
- type DiscoverModelDetail,
- type IdentifiersResponse,
- type ModelListResponse,
- type ModelQueryParams,
+import type { StoreSetter } from '@/store/types';
+import type {
+ DiscoverModelDetail,
+ IdentifiersResponse,
+ ModelListResponse,
+ ModelQueryParams,
} from '@/types/discover';
+import { setNamespace } from '@/utils/storeDebug';
+
+import {
+ type ModelCategoriesParams,
+ modelCategoriesQueryKey,
+ modelCategoriesResource,
+ type ModelDetailParams,
+ modelDetailQueryKey,
+ modelDetailResource,
+ type ModelIdentifiersParams,
+ modelIdentifiersQueryKey,
+ modelIdentifiersResource,
+ type ModelListParams,
+ modelListQueryKey,
+ modelListResource,
+} from './projection';
+
+const n = setNamespace('discover/model');
+
+/**
+ * Sync flags of a market read, plus the aliases the old SWR hooks returned
+ * (`isLoading` / `mutate`) so a call site only has to move its `data` read to
+ * the matching `modelSelectors` entry.
+ */
+export interface ModelSyncResult extends ReplicaSyncResult {
+ /** A request is in flight and this entry has no value to show yet. */
+ isLoading: boolean;
+ /** Alias of `revalidate`. */
+ mutate: () => Promise<unknown>;
+ /** Read the value with `modelSelectors.*(queryKey)`; undefined while disabled. */
+ queryKey?: string;
+}
type Setter = StoreSetter<DiscoverStore>;
+
export const createModelSlice = (set: Setter, get: () => DiscoverStore, _api?: unknown) =>
new ModelActionImpl(set, get, _api);
export class ModelActionImpl {
+ readonly #categories;
+ readonly #detail;
+ readonly #get: () => DiscoverStore;
+ readonly #identifiers;
+ readonly #list;
+
constructor(set: Setter, get: () => DiscoverStore, _api?: unknown) {
void _api;
- void set;
- void get;
+ this.#get = get;
+ this.#list = createReplicaSlice(modelListResource, {
+ actionPrefix: n('list'),
+ get,
+ set,
+ stateKey: 'modelListReplica',
+ view: recordLens<DiscoverStore, ModelListResponse>('modelListMap'),
+ });
+ this.#detail = createReplicaSlice(modelDetailResource, {
+ actionPrefix: n('detail'),
+ get,
+ // The market no longer has this model: drop the entry and its persisted
+ // row rather than keep serving the cached copy.
+ isMissing: (detail) => detail === null,
+ set,
+ stateKey: 'modelDetailReplica',
+ view: recordLens<DiscoverStore, DiscoverModelDetail>('modelDetailMap'),
+ });
+ this.#categories = createReplicaSlice(modelCategoriesResource, {
+ actionPrefix: n('categories'),
+ get,
+ set,
+ stateKey: 'modelCategoriesReplica',
+ view: recordLens<DiscoverStore, CategoryItem[]>('modelCategoriesMap'),
+ });
+ this.#identifiers = createReplicaSlice(modelIdentifiersResource, {
+ actionPrefix: n('identifiers'),
+ get,
+ set,
+ stateKey: 'modelIdentifiersReplica',
+ view: recordLens<DiscoverStore, IdentifiersResponse>('modelIdentifiersMap'),
+ });
}
- useModelCategories = (params: CategoryListQuery): SWRResponse<CategoryItem[]> => {
- return useSWR(
- discoverKeys.modelCategories(params),
- async () => discoverService.getModelCategories(params),
- {
- revalidateOnFocus: false,
- },
- );
+ #toSyncResult = (
+ sync: ReplicaSyncResult,
+ queryKey: string | undefined,
+ hasValue: boolean,
+ active: boolean,
+ ): ModelSyncResult => ({
+ ...sync,
+ // A disabled hook never loads; a settled entry with a value never flashes.
+ isLoading: active && !hasValue && (!sync.isHydrated || sync.isValidating),
+ mutate: sync.revalidate,
+ queryKey: active ? queryKey : undefined,
+ });
+
+ /**
+ * The model market list of one query. Each (filters Β· page) pair is its own
+ * entry, so the URL-driven pager walks entries instead of appending pages.
+ * Read the rows with `modelSelectors.modelList(queryKey)`.
+ */
+ useFetchModelList = (
+ params: ModelQueryParams = {},
+ options: { enabled?: boolean } = {},
+ ): ModelSyncResult => {
+ const { enabled = true } = options;
+ const normalized: ModelListParams = {
+ ...params,
+ locale: globalHelpers.getCurrentLanguage(),
+ page: params.page ? Number(params.page) : 1,
+ pageSize: params.pageSize ? Number(params.pageSize) : 21,
+ };
+ const queryKey = modelListQueryKey(normalized);
+ const sync = this.#list.useSync(normalized, { enabled, revalidateOnFocus: false });
+ return this.#toSyncResult(sync, queryKey, !!this.#get().modelListMap[queryKey], enabled);
};
- useModelDetail = (params: {
- identifier: string;
- }): SWRResponse<DiscoverModelDetail | undefined> => {
- const locale = globalHelpers.getCurrentLanguage();
- return useSWR(
- discoverKeys.modelDetail(locale, params.identifier),
- async () => discoverService.getModelDetail(params),
- {
- revalidateOnFocus: false,
- },
+ /**
+ * One model detail by identifier. Read it with
+ * `modelSelectors.modelDetail(queryKey)`; `undefined` after the sync settles
+ * means the market has no such identifier.
+ */
+ useFetchModelDetail = (
+ params: ModelDetailParams,
+ options: { enabled?: boolean } = {},
+ ): ModelSyncResult => {
+ const { enabled = true } = options;
+ const normalized: ModelDetailParams = {
+ identifier: params.identifier,
+ locale: globalHelpers.getCurrentLanguage(),
+ };
+ const queryKey = modelDetailQueryKey(normalized);
+ const sync = this.#detail.useSync(normalized, { enabled, revalidateOnFocus: false });
+ return this.#toSyncResult(
+ sync,
+ queryKey,
+ this.#get().modelDetailMap[queryKey] !== undefined,
+ enabled,
);
};
- useModelIdentifiers = (): SWRResponse<IdentifiersResponse> => {
- return useSWR(
- discoverKeys.modelIdentifiers(),
- async () => discoverService.getModelIdentifiers(),
- {
- revalidateOnFocus: false,
- },
- );
+ /**
+ * Category counts of one query (the search term). The community sidebar reads
+ * `modelSelectors.modelCategories(queryKey)`.
+ */
+ useFetchModelCategories = (
+ params: ModelCategoriesParams = {},
+ options: { enabled?: boolean } = {},
+ ): ModelSyncResult => {
+ const { enabled = true } = options;
+ const queryKey = modelCategoriesQueryKey(params);
+ const sync = this.#categories.useSync(params, { enabled, revalidateOnFocus: false });
+ return this.#toSyncResult(sync, queryKey, !!this.#get().modelCategoriesMap[queryKey], enabled);
};
- useModelList = (params: ModelQueryParams = {}): SWRResponse<ModelListResponse> => {
- const locale = globalHelpers.getCurrentLanguage();
- return useSWR(
- discoverKeys.modelList(locale, params),
- async () =>
- discoverService.getModelList({
- ...params,
- page: params.page ? Number(params.page) : 1,
- pageSize: params.pageSize ? Number(params.pageSize) : 21,
- }),
- {
- revalidateOnFocus: false,
- },
- );
+ /** The model identifier index. */
+ useFetchModelIdentifiers = (options: { enabled?: boolean } = {}): ModelSyncResult => {
+ const { enabled = true } = options;
+ const params: ModelIdentifiersParams = {};
+ const queryKey = modelIdentifiersQueryKey(params);
+ const sync = this.#identifiers.useSync(params, { enabled, revalidateOnFocus: false });
+ return this.#toSyncResult(sync, queryKey, !!this.#get().modelIdentifiersMap[queryKey], enabled);
};
}
diff --git a/src/store/discover/slices/model/initialState.ts b/src/store/discover/slices/model/initialState.ts
new file mode 100644
index 00000000000..af01e5e2933
--- /dev/null
+++ b/src/store/discover/slices/model/initialState.ts
@@ -0,0 +1,40 @@
+import type { CategoryItem } from '@lobehub/market-sdk';
+
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
+import type { DiscoverModelDetail, IdentifiersResponse, ModelListResponse } from '@/types/discover';
+
+/**
+ * Replica views of the model market reads, each beside its bookkeeping slot.
+ * The views are plain records keyed by the entry key of the matching resource
+ * (`projection.ts`); components read them through `modelSelectors`, never
+ * through the fetch hook.
+ */
+export interface ModelSliceState {
+ /** Category counts per query (`modelCategoriesQueryKey`). */
+ modelCategoriesMap: Record<string, CategoryItem[]>;
+ /** Replica bookkeeping of `modelCategoriesMap`. */
+ modelCategoriesReplica: ReplicaState<CategoryItem[]>;
+ /** Model detail per identifier (`modelDetailQueryKey`). */
+ modelDetailMap: Record<string, DiscoverModelDetail>;
+ /** Replica bookkeeping of `modelDetailMap`. */
+ modelDetailReplica: ReplicaState<DiscoverModelDetail>;
+ /** Identifier index (`modelIdentifiersQueryKey`). */
+ modelIdentifiersMap: Record<string, IdentifiersResponse>;
+ /** Replica bookkeeping of `modelIdentifiersMap`. */
+ modelIdentifiersReplica: ReplicaState<IdentifiersResponse>;
+ /** Model list per query (`modelListQueryKey`). */
+ modelListMap: Record<string, ModelListResponse>;
+ /** Replica bookkeeping of `modelListMap`. */
+ modelListReplica: ReplicaState<ModelListResponse>;
+}
+
+export const initialModelSliceState: ModelSliceState = {
+ modelCategoriesMap: {},
+ modelCategoriesReplica: createReplicaState(),
+ modelDetailMap: {},
+ modelDetailReplica: createReplicaState(),
+ modelIdentifiersMap: {},
+ modelIdentifiersReplica: createReplicaState(),
+ modelListMap: {},
+ modelListReplica: createReplicaState(),
+};
diff --git a/src/store/discover/slices/model/projection.ts b/src/store/discover/slices/model/projection.ts
new file mode 100644
index 00000000000..5ca65a131bc
--- /dev/null
+++ b/src/store/discover/slices/model/projection.ts
@@ -0,0 +1,113 @@
+import type { CategoryItem, CategoryListQuery } from '@lobehub/market-sdk';
+
+import { defineReplica, stableQueryKey } from '@/libs/replica';
+import { discoverService } from '@/services/discover';
+import type {
+ DiscoverModelDetail,
+ IdentifiersResponse,
+ ModelListResponse,
+ ModelQueryParams,
+} from '@/types/discover';
+
+/**
+ * The marketplace model reads are **read-only**: no optimistic write, no
+ * cross-copy entity link. What the replica buys here is the first frame β€” the
+ * last confirmed page paints before the network answers β€” and one cache
+ * partition per identity (the `cacheScope`), so switching account or workspace
+ * never serves the previous one's rows.
+ *
+ * Each distinct query is its own entry (`key`), exactly like the SWR key it
+ * replaces: the community list paginates by URL (`?page=N`), so a page flip is
+ * a different entry rather than a `loadMore` of the same one.
+ */
+
+/** Normalized `modelList` params β€” the shape actually sent to the market endpoint. */
+export interface ModelListParams extends Omit<ModelQueryParams, 'page' | 'pageSize'> {
+ /** Current UI language; part of the entry so a locale switch refetches. */
+ locale?: string;
+ page: number;
+ pageSize: number;
+}
+
+/**
+ * Entry key of one model list query. Includes the page, because the list pages
+ * through the URL instead of appending pages to one entry.
+ */
+export const modelListQueryKey = (params: ModelListParams): string => stableQueryKey(params);
+
+export interface ModelDetailParams {
+ identifier: string;
+ /** Current UI language; the market resolves localized copy server-side. */
+ locale?: string;
+}
+
+/** Entry key of one model detail (`identifier`, localized). */
+export const modelDetailQueryKey = (params: ModelDetailParams): string => stableQueryKey(params);
+
+/** Category counts query of the community model sidebar (the search term). */
+export type ModelCategoriesParams = CategoryListQuery;
+
+/** Entry key of one category-counts query (the search term). */
+export const modelCategoriesQueryKey = (params: ModelCategoriesParams): string =>
+ stableQueryKey(params);
+
+/** The model identifier index takes no query β€” one entry for the whole index. */
+export type ModelIdentifiersParams = Record<string, never>;
+
+/** Entry key of the model identifier index. */
+export const modelIdentifiersQueryKey = (params: ModelIdentifiersParams = {}): string =>
+ stableQueryKey(params);
+
+/**
+ * Model market list, one entry per query (`modelListMap[queryKey]`). The
+ * response already carries everything a row reader needs (`items`,
+ * `currentPage`, `pageSize`, `totalCount`), so it is stored as-is.
+ */
+export const modelListResource = defineReplica<ModelListParams, ModelListResponse>({
+ fetcher: (params) => discoverService.getModelList(params),
+ key: modelListQueryKey,
+ name: 'modelList',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/**
+ * One model detail by identifier (`modelDetailMap[key]`). The service answers
+ * `undefined` for an identifier the market no longer has; the fetcher turns
+ * that into `null` so the slice's `isMissing` drops the entry (memory and
+ * persisted row) instead of letting the engine skip the write and keep painting
+ * a stale cached copy. The page then reaches "not found" once the sync settles.
+ */
+export const modelDetailResource = defineReplica<
+ ModelDetailParams,
+ DiscoverModelDetail,
+ DiscoverModelDetail | null
+>({
+ fetcher: async (params) => (await discoverService.getModelDetail(params)) ?? null,
+ key: modelDetailQueryKey,
+ name: 'modelDetail',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/**
+ * Category counts of one query (`modelCategoriesMap[queryKey]`). Small and read
+ * on almost every community model screen, so localStorage keeps the first frame
+ * populated instead of flashing an empty sidebar.
+ */
+export const modelCategoriesResource = defineReplica<ModelCategoriesParams, CategoryItem[]>({
+ fetcher: (params) => discoverService.getModelCategories(params),
+ key: modelCategoriesQueryKey,
+ name: 'modelCategories',
+ storage: 'localStorage',
+ version: 1,
+});
+
+/** The model identifier index (`modelIdentifiersMap[queryKey]`). */
+export const modelIdentifiersResource = defineReplica<ModelIdentifiersParams, IdentifiersResponse>({
+ fetcher: () => discoverService.getModelIdentifiers(),
+ key: modelIdentifiersQueryKey,
+ name: 'modelIdentifiers',
+ storage: 'localStorage',
+ version: 1,
+});
diff --git a/src/store/discover/slices/plugin/action.test.ts b/src/store/discover/slices/plugin/action.test.ts
index b7acf9584a6..d754183ee55 100644
--- a/src/store/discover/slices/plugin/action.test.ts
+++ b/src/store/discover/slices/plugin/action.test.ts
@@ -1,147 +1,311 @@
-import { renderHook, waitFor } from '@testing-library/react';
+import { act, renderHook } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { discoverService } from '@/services/discover';
+import { createReplicaState } from '@/libs/replica';
import { globalHelpers } from '@/store/global/helpers';
+import type { PluginListResponse } from '@/types/discover';
+import { pluginSelectors } from '../../selectors';
import { useDiscoverStore as useStore } from '../../store';
+import {
+ pluginCategoriesQueryKey,
+ pluginDetailQueryKey,
+ pluginIdentifiersQueryKey,
+ pluginListQueryKey,
+} from './projection';
+
+vi.mock('@/services/discover', () => ({
+ discoverService: {
+ getPluginCategories: vi.fn(),
+ getPluginDetail: vi.fn(),
+ getPluginIdentifiers: vi.fn(),
+ getPluginList: vi.fn(),
+ },
+}));
+
+// The replica schedules its fetches through the app's SWR driver; the engine
+// itself is what these tests exercise, so the driver is a bare recorder.
+vi.mock('@/libs/swr', () => ({
+ mutate: vi.fn(),
+ useClientDataSWR: vi.fn(() => ({ isValidating: false, mutate: vi.fn() })),
+}));
+
+const makeList = (identifier = 'plugin-1'): PluginListResponse => ({
+ currentPage: 1,
+ items: [{ identifier } as any],
+ pageSize: 21,
+ totalCount: 1,
+ totalPages: 1,
+});
+
+const emptyPluginState = () => ({
+ pluginCategoriesMap: {},
+ pluginCategoriesReplica: createReplicaState(),
+ pluginDetailMap: {},
+ pluginDetailReplica: createReplicaState(),
+ pluginIdentifiersMap: {},
+ pluginIdentifiersReplica: createReplicaState(),
+ pluginListMap: {},
+ pluginListReplica: createReplicaState(),
+});
beforeEach(() => {
vi.clearAllMocks();
+ vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');
+ useStore.setState(emptyPluginState());
});
-describe('PluginAction', () => {
- describe('usePluginCategories', () => {
- it('should fetch plugin categories with correct parameters', async () => {
- const mockCategories = [
- { id: 'cat-1', name: 'Category 1' },
- { id: 'cat-2', name: 'Category 2' },
- ];
+/** The replica network syncs registered with the SWR driver, per resource name. */
+const syncCalls = async (
+ name: 'pluginCategories' | 'pluginDetail' | 'pluginIdentifiers' | 'pluginList',
+) => {
+ const { useClientDataSWR } = await import('@/libs/swr');
+ return vi
+ .mocked(useClientDataSWR)
+ .mock.calls.filter(
+ ([key]) => Array.isArray(key) && key[0] === 'replica:sync' && key[1] === name,
+ )
+ .map(([key, fetcher, config]) => ({
+ config: config as { onSuccess?: (data: unknown) => void; revalidateOnFocus?: boolean },
+ fetcher: fetcher as () => Promise<any>,
+ key: key as unknown[],
+ }));
+};
+
+describe('PluginSlice (replica)', () => {
+ it('does not revalidate any plugin read on window focus', async () => {
+ renderHook(() => {
+ const state = useStore.getState();
+ state.useFetchPluginList();
+ state.useFetchPluginDetail({ identifier: 'plugin-1' });
+ state.useFetchPluginCategories();
+ state.useFetchPluginIdentifiers();
+ });
- vi.spyOn(discoverService, 'getPluginCategories').mockResolvedValue(mockCategories as any);
- vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');
+ for (const name of [
+ 'pluginList',
+ 'pluginDetail',
+ 'pluginCategories',
+ 'pluginIdentifiers',
+ ] as const) {
+ const calls = await syncCalls(name);
+ expect(calls.length).toBeGreaterThan(0);
+ for (const call of calls) expect(call.config.revalidateOnFocus).toBe(false);
+ }
+ });
- const params = {} as any;
- const { result } = renderHook(() => useStore.getState().usePluginCategories(params));
+ describe('useFetchPluginList', () => {
+ it('requests the list with normalized page / pageSize and the locale', async () => {
+ const { discoverService } = await import('@/services/discover');
- await waitFor(() => {
- expect(result.current.data).toEqual(mockCategories);
+ renderHook(() => useStore.getState().useFetchPluginList({ q: 'weather' }));
+
+ const [call] = await syncCalls('pluginList');
+ await call.fetcher();
+
+ expect(discoverService.getPluginList).toHaveBeenCalledWith({
+ locale: 'en-US',
+ page: 1,
+ pageSize: 21,
+ q: 'weather',
});
+ });
+
+ it('keys each page and filter set as its own replica entry', () => {
+ const { result } = renderHook(() => [
+ useStore.getState().useFetchPluginList({ page: 1 }),
+ useStore.getState().useFetchPluginList({ page: 2 }),
+ useStore.getState().useFetchPluginList({ category: 'tools' }),
+ ]);
- expect(discoverService.getPluginCategories).toHaveBeenCalledWith(params);
+ const [first, second, third] = result.current;
+ expect(new Set([first.queryKey, second.queryKey, third.queryKey]).size).toBe(3);
});
- });
- describe('usePluginDetail', () => {
- it('should fetch plugin detail when identifier is provided', async () => {
- const mockDetail = {
- identifier: 'test-plugin',
- name: 'Test Plugin',
- description: 'A test plugin',
- };
+ it('does not register a sync β€” and reports no loading β€” when disabled', async () => {
+ const { result } = renderHook(() =>
+ useStore.getState().useFetchPluginList({ page: 1 }, { enabled: false }),
+ );
- vi.spyOn(discoverService, 'getPluginDetail').mockResolvedValue(mockDetail as any);
- vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');
+ expect(result.current.queryKey).toBeUndefined();
+ expect(result.current.isLoading).toBe(false);
+ expect(await syncCalls('pluginList')).toHaveLength(0);
+ });
- const params = { identifier: 'test-plugin', withManifest: true };
- const { result } = renderHook(() => useStore.getState().usePluginDetail(params));
+ it('reports loading until the entry has a value to show', () => {
+ const { result } = renderHook(() => useStore.getState().useFetchPluginList({ page: 1 }));
- await waitFor(() => {
- expect(result.current.data).toEqual(mockDetail);
- });
+ expect(result.current.isLoading).toBe(true);
+ });
- expect(discoverService.getPluginDetail).toHaveBeenCalledWith(params);
+ it('does not report loading when the entry already has a (hydrated) value', () => {
+ const key = pluginListQueryKey({ locale: 'en-US', page: 1, pageSize: 21 });
+ useStore.setState({ pluginListMap: { [key]: makeList() } });
+
+ const { result } = renderHook(() => useStore.getState().useFetchPluginList({ page: 1 }));
+
+ expect(result.current.queryKey).toBe(key);
+ expect(result.current.isLoading).toBe(false);
});
- it('should not fetch when identifier is undefined', () => {
- const { result } = renderHook(() =>
- useStore.getState().usePluginDetail({ identifier: undefined }),
- );
+ it('folds the response into the replica view the selectors read', async () => {
+ const response = makeList();
+
+ renderHook(() => useStore.getState().useFetchPluginList({ page: 1 }));
+ const [call] = await syncCalls('pluginList');
+ act(() => call.config.onSuccess!(response));
- expect(result.current.data).toBeUndefined();
- expect(discoverService.getPluginDetail).not.toHaveBeenCalled();
+ const key = pluginListQueryKey({ locale: 'en-US', page: 1, pageSize: 21 });
+ expect(pluginSelectors.pluginList(key)(useStore.getState())).toEqual(response);
});
});
- describe('usePluginIdentifiers', () => {
- it('should fetch plugin identifiers', async () => {
- const mockIdentifiers = [
- { identifier: 'plugin-1', lastModified: '2024-01-01' },
- { identifier: 'plugin-2', lastModified: '2024-01-02' },
- ];
+ describe('useFetchPluginDetail', () => {
+ it('requests the detail with identifier, locale and the manifest flag', async () => {
+ const { discoverService } = await import('@/services/discover');
- vi.spyOn(discoverService, 'getPluginIdentifiers').mockResolvedValue(mockIdentifiers);
+ renderHook(() =>
+ useStore.getState().useFetchPluginDetail({ identifier: 'plugin-1', withManifest: false }),
+ );
- const { result } = renderHook(() => useStore.getState().usePluginIdentifiers());
+ const [call] = await syncCalls('pluginDetail');
+ await call.fetcher();
- await waitFor(() => {
- expect(result.current.data).toEqual(mockIdentifiers);
+ expect(discoverService.getPluginDetail).toHaveBeenCalledWith({
+ identifier: 'plugin-1',
+ locale: 'en-US',
+ withManifest: false,
});
+ });
- expect(discoverService.getPluginIdentifiers).toHaveBeenCalled();
+ it('keys the detail by identifier, so a different identifier is a different entry', () => {
+ const { result } = renderHook(() => [
+ useStore.getState().useFetchPluginDetail({ identifier: 'plugin-1', withManifest: false }),
+ useStore.getState().useFetchPluginDetail({ identifier: 'plugin-2', withManifest: false }),
+ ]);
+
+ expect(new Set(result.current.map((sync) => sync.queryKey)).size).toBe(2);
});
- });
- describe('usePluginList', () => {
- it('should fetch plugin list with default parameters', async () => {
- const mockList = {
- items: [{ identifier: 'plugin-1' }, { identifier: 'plugin-2' }],
- total: 2,
- };
+ it('keys the detail by the locale, so a language switch refetches', () => {
+ const { result, rerender } = renderHook(() =>
+ useStore.getState().useFetchPluginDetail({ identifier: 'plugin-1', withManifest: false }),
+ );
+ const first = result.current.queryKey;
+
+ vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('zh-CN');
+ rerender();
- vi.spyOn(discoverService, 'getPluginList').mockResolvedValue(mockList as any);
- vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');
+ expect(result.current.queryKey).not.toBe(first);
+ });
- const { result } = renderHook(() => useStore.getState().usePluginList());
+ it('drops a cached detail once the market reports the plugin gone', async () => {
+ const { discoverService } = await import('@/services/discover');
- await waitFor(() => {
- expect(result.current.data).toEqual(mockList);
+ const { result } = renderHook(() =>
+ useStore.getState().useFetchPluginDetail({ identifier: 'plugin-1' }),
+ );
+ const key = result.current.queryKey!;
+ const [call] = await syncCalls('pluginDetail');
+
+ vi.mocked(discoverService.getPluginDetail).mockResolvedValueOnce({
+ identifier: 'plugin-1',
+ } as any);
+ const cached = await call.fetcher();
+ act(() => call.config.onSuccess!(cached));
+ expect(pluginSelectors.pluginDetail(key)(useStore.getState())).toEqual({
+ identifier: 'plugin-1',
});
- expect(discoverService.getPluginList).toHaveBeenCalledWith({
- page: 1,
- pageSize: 21,
+ // The market removed the plugin: the service answers `undefined`.
+ vi.mocked(discoverService.getPluginDetail).mockResolvedValueOnce(undefined as any);
+ const missing = await call.fetcher();
+ act(() => call.config.onSuccess!(missing));
+
+ expect(pluginSelectors.pluginDetail(key)(useStore.getState())).toBeUndefined();
+ expect(useStore.getState().pluginDetailMap[key]).toBeUndefined();
+ });
+
+ it('does not register a sync β€” and exposes no queryKey β€” when the identifier is absent', async () => {
+ const { result } = renderHook(() =>
+ useStore.getState().useFetchPluginDetail({ identifier: undefined, withManifest: false }),
+ );
+
+ expect(result.current.queryKey).toBeUndefined();
+ expect(result.current.isLoading).toBe(false);
+ expect(await syncCalls('pluginDetail')).toHaveLength(0);
+ });
+ });
+
+ describe('useFetchPluginCategories', () => {
+ it('requests category counts with the search term', async () => {
+ const { discoverService } = await import('@/services/discover');
+
+ renderHook(() => useStore.getState().useFetchPluginCategories({ q: 'weather' }));
+
+ const [call] = await syncCalls('pluginCategories');
+ await call.fetcher();
+
+ expect(discoverService.getPluginCategories).toHaveBeenCalledWith({
+ locale: 'en-US',
+ q: 'weather',
});
});
- it('should fetch plugin list with custom parameters', async () => {
- const mockList = {
- items: [{ identifier: 'plugin-1' }],
- total: 1,
- };
+ it('keys the categories by the locale, so a language switch refetches', () => {
+ const { result, rerender } = renderHook(() =>
+ useStore.getState().useFetchPluginCategories({ q: 'weather' }),
+ );
+ const first = result.current.queryKey;
- vi.spyOn(discoverService, 'getPluginList').mockResolvedValue(mockList as any);
vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('zh-CN');
+ rerender();
- const params = { page: 2, pageSize: 10, category: 'development' } as any;
- const { result } = renderHook(() => useStore.getState().usePluginList(params));
+ expect(result.current.queryKey).not.toBe(first);
+ });
- await waitFor(() => {
- expect(result.current.data).toEqual(mockList);
- });
+ it('skips the request when disabled', async () => {
+ const { result } = renderHook(() =>
+ useStore.getState().useFetchPluginCategories({}, { enabled: false }),
+ );
- expect(discoverService.getPluginList).toHaveBeenCalledWith({
- page: 2,
- pageSize: 10,
- category: 'development',
- });
+ expect(result.current.queryKey).toBeUndefined();
+ expect(await syncCalls('pluginCategories')).toHaveLength(0);
});
- it('should convert page and pageSize to numbers', async () => {
- vi.spyOn(discoverService, 'getPluginList').mockResolvedValue({ items: [] } as any);
- vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');
+ it('falls back to an empty list when no category entry is loaded', () => {
+ expect(pluginSelectors.pluginCategories(undefined)(useStore.getState())).toEqual([]);
+ expect(pluginSelectors.pluginList(undefined)(useStore.getState())).toBeUndefined();
+ expect(pluginSelectors.pluginDetail(undefined)(useStore.getState())).toBeUndefined();
+ });
+ });
- const params = { page: 3, pageSize: 15 } as any;
- const { result } = renderHook(() => useStore.getState().usePluginList(params));
+ describe('useFetchPluginIdentifiers', () => {
+ it('requests the identifier index', async () => {
+ const { discoverService } = await import('@/services/discover');
- await waitFor(() => {
- expect(result.current.data).toBeDefined();
- });
+ renderHook(() => useStore.getState().useFetchPluginIdentifiers());
- expect(discoverService.getPluginList).toHaveBeenCalledWith({
- page: 3,
- pageSize: 15,
- });
+ const [call] = await syncCalls('pluginIdentifiers');
+ await call.fetcher();
+
+ expect(discoverService.getPluginIdentifiers).toHaveBeenCalled();
+ });
+ });
+
+ describe('replica key helpers', () => {
+ it('produces stable, distinct keys per query dimension', () => {
+ expect(pluginListQueryKey({ locale: 'en-US', page: 1, pageSize: 21 })).toBe(
+ pluginListQueryKey({ locale: 'en-US', page: 1, pageSize: 21 }),
+ );
+ expect(pluginDetailQueryKey({ identifier: 'a', withManifest: false })).not.toBe(
+ pluginDetailQueryKey({ identifier: 'b', withManifest: false }),
+ );
+ expect(pluginDetailQueryKey({ identifier: 'a', withManifest: false })).not.toBe(
+ pluginDetailQueryKey({ identifier: 'a', withManifest: true }),
+ );
+ expect(pluginCategoriesQueryKey({ q: 'a' })).not.toBe(pluginCategoriesQueryKey({}));
+ expect(pluginIdentifiersQueryKey()).toBe(pluginIdentifiersQueryKey({}));
});
});
});
diff --git a/src/store/discover/slices/plugin/action.ts b/src/store/discover/slices/plugin/action.ts
index ca7c6bec07f..c20abc4bdec 100644
--- a/src/store/discover/slices/plugin/action.ts
+++ b/src/store/discover/slices/plugin/action.ts
@@ -1,81 +1,186 @@
-import {
- type DiscoverPluginDetail,
- type IdentifiersResponse,
- type PluginListResponse,
- type PluginQueryParams,
-} from '@lobechat/types';
-import { type CategoryItem, type CategoryListQuery } from '@lobehub/market-sdk';
-import { type SWRResponse } from 'swr';
-import useSWR from 'swr';
+import type { CategoryItem } from '@lobehub/market-sdk';
-import { discoverKeys } from '@/libs/swr/keys';
-import { discoverService } from '@/services/discover';
-import { type DiscoverStore } from '@/store/discover';
+import { createReplicaSlice, recordLens, type ReplicaSyncResult } from '@/libs/replica';
+import type { DiscoverStore } from '@/store/discover';
import { globalHelpers } from '@/store/global/helpers';
-import { type StoreSetter } from '@/store/types';
+import type { StoreSetter } from '@/store/types';
+import type {
+ DiscoverPluginDetail,
+ IdentifiersResponse,
+ PluginListResponse,
+ PluginQueryParams,
+} from '@/types/discover';
+import { setNamespace } from '@/utils/storeDebug';
+
+import {
+ type PluginCategoriesParams,
+ pluginCategoriesQueryKey,
+ pluginCategoriesResource,
+ type PluginDetailParams,
+ pluginDetailQueryKey,
+ pluginDetailResource,
+ type PluginIdentifiersParams,
+ pluginIdentifiersQueryKey,
+ pluginIdentifiersResource,
+ type PluginListParams,
+ pluginListQueryKey,
+ pluginListResource,
+} from './projection';
+
+const n = setNamespace('discover/plugin');
+
+/**
+ * Sync flags of a market read, plus the aliases the old SWR hooks returned
+ * (`isLoading` / `mutate`) so a call site only has to move its `data` read to
+ * the matching `pluginSelectors` entry.
+ */
+export interface PluginSyncResult extends ReplicaSyncResult {
+ /** A request is in flight and this entry has no value to show yet. */
+ isLoading: boolean;
+ /** Alias of `revalidate`. */
+ mutate: () => Promise<unknown>;
+ /** Read the value with `pluginSelectors.*(queryKey)`; undefined while disabled. */
+ queryKey?: string;
+}
type Setter = StoreSetter<DiscoverStore>;
+
export const createPluginSlice = (set: Setter, get: () => DiscoverStore, _api?: unknown) =>
new PluginActionImpl(set, get, _api);
export class PluginActionImpl {
+ readonly #categories;
+ readonly #detail;
+ readonly #get: () => DiscoverStore;
+ readonly #identifiers;
+ readonly #list;
+
constructor(set: Setter, get: () => DiscoverStore, _api?: unknown) {
void _api;
- void set;
- void get;
+ this.#get = get;
+ this.#list = createReplicaSlice(pluginListResource, {
+ actionPrefix: n('list'),
+ get,
+ set,
+ stateKey: 'pluginListReplica',
+ view: recordLens<DiscoverStore, PluginListResponse>('pluginListMap'),
+ });
+ this.#detail = createReplicaSlice(pluginDetailResource, {
+ actionPrefix: n('detail'),
+ get,
+ // The market no longer has this plugin: drop the entry and its persisted
+ // row rather than keep serving the cached copy.
+ isMissing: (detail) => detail === null,
+ set,
+ stateKey: 'pluginDetailReplica',
+ view: recordLens<DiscoverStore, DiscoverPluginDetail>('pluginDetailMap'),
+ });
+ this.#categories = createReplicaSlice(pluginCategoriesResource, {
+ actionPrefix: n('categories'),
+ get,
+ set,
+ stateKey: 'pluginCategoriesReplica',
+ view: recordLens<DiscoverStore, CategoryItem[]>('pluginCategoriesMap'),
+ });
+ this.#identifiers = createReplicaSlice(pluginIdentifiersResource, {
+ actionPrefix: n('identifiers'),
+ get,
+ set,
+ stateKey: 'pluginIdentifiersReplica',
+ view: recordLens<DiscoverStore, IdentifiersResponse>('pluginIdentifiersMap'),
+ });
}
- usePluginCategories = (params: CategoryListQuery): SWRResponse<CategoryItem[]> => {
- const locale = globalHelpers.getCurrentLanguage();
- return useSWR(
- discoverKeys.pluginCategories(locale, params),
- async () => discoverService.getPluginCategories(params),
- {
- revalidateOnFocus: false,
- },
- );
+ #toSyncResult = (
+ sync: ReplicaSyncResult,
+ queryKey: string | undefined,
+ hasValue: boolean,
+ active: boolean,
+ ): PluginSyncResult => ({
+ ...sync,
+ // A disabled hook never loads; a settled entry with a value never flashes.
+ isLoading: active && !hasValue && (!sync.isHydrated || sync.isValidating),
+ mutate: sync.revalidate,
+ queryKey: active ? queryKey : undefined,
+ });
+
+ /**
+ * The plugin market list of one query. Each (filters Β· page) pair is its own
+ * entry, so the URL-driven pager walks entries instead of appending pages.
+ * Read the rows with `pluginSelectors.pluginList(queryKey)`.
+ */
+ useFetchPluginList = (
+ params: PluginQueryParams = {},
+ options: { enabled?: boolean } = {},
+ ): PluginSyncResult => {
+ const { enabled = true } = options;
+ const normalized: PluginListParams = {
+ ...params,
+ locale: globalHelpers.getCurrentLanguage(),
+ page: params.page ? Number(params.page) : 1,
+ pageSize: params.pageSize ? Number(params.pageSize) : 21,
+ };
+ const queryKey = pluginListQueryKey(normalized);
+ const sync = this.#list.useSync(normalized, { enabled, revalidateOnFocus: false });
+ return this.#toSyncResult(sync, queryKey, !!this.#get().pluginListMap[queryKey], enabled);
};
- usePluginDetail = ({
- identifier,
- withManifest,
- }: {
- identifier?: string;
- withManifest?: boolean;
- }): SWRResponse<DiscoverPluginDetail | undefined> => {
- const locale = globalHelpers.getCurrentLanguage();
- return useSWR(
- !identifier ? null : discoverKeys.pluginDetail(locale, identifier, withManifest),
- async () => discoverService.getPluginDetail({ identifier: identifier!, withManifest }),
- {
- revalidateOnFocus: false,
- },
+ /**
+ * One plugin detail by identifier. Read it with
+ * `pluginSelectors.pluginDetail(queryKey)`; `undefined` while disabled or
+ * after the sync settles means the market has no such identifier (the caller
+ * then falls back to its builtin / composio metadata).
+ */
+ useFetchPluginDetail = (
+ params: { identifier?: string; withManifest?: boolean },
+ options: { enabled?: boolean } = {},
+ ): PluginSyncResult => {
+ const { enabled = true } = options;
+ const active = enabled && !!params.identifier;
+ const normalized: PluginDetailParams = {
+ identifier: params.identifier ?? '',
+ locale: globalHelpers.getCurrentLanguage(),
+ withManifest: params.withManifest,
+ };
+ const queryKey = pluginDetailQueryKey(normalized);
+ const sync = this.#detail.useSync(normalized, { enabled: active, revalidateOnFocus: false });
+ return this.#toSyncResult(
+ sync,
+ queryKey,
+ this.#get().pluginDetailMap[queryKey] !== undefined,
+ active,
);
};
- usePluginIdentifiers = (): SWRResponse<IdentifiersResponse> => {
- return useSWR(
- discoverKeys.pluginIdentifiers(),
- async () => discoverService.getPluginIdentifiers(),
- {
- revalidateOnFocus: false,
- },
- );
+ /**
+ * Category counts of one query (the search term). The community sidebar reads
+ * `pluginSelectors.pluginCategories(queryKey)`.
+ */
+ useFetchPluginCategories = (
+ params: PluginCategoriesParams = {},
+ options: { enabled?: boolean } = {},
+ ): PluginSyncResult => {
+ const { enabled = true } = options;
+ const normalized: PluginCategoriesParams = {
+ ...params,
+ locale: globalHelpers.getCurrentLanguage(),
+ };
+ const queryKey = pluginCategoriesQueryKey(normalized);
+ const sync = this.#categories.useSync(normalized, { enabled, revalidateOnFocus: false });
+ return this.#toSyncResult(sync, queryKey, !!this.#get().pluginCategoriesMap[queryKey], enabled);
};
- usePluginList = (params: PluginQueryParams = {}): SWRResponse<PluginListResponse> => {
- const locale = globalHelpers.getCurrentLanguage();
- return useSWR(
- discoverKeys.pluginList(locale, params),
- async () =>
- discoverService.getPluginList({
- ...params,
- page: params.page ? Number(params.page) : 1,
- pageSize: params.pageSize ? Number(params.pageSize) : 21,
- }),
- {
- revalidateOnFocus: false,
- },
+ /** The plugin identifier index. */
+ useFetchPluginIdentifiers = (options: { enabled?: boolean } = {}): PluginSyncResult => {
+ const { enabled = true } = options;
+ const params: PluginIdentifiersParams = {};
+ const queryKey = pluginIdentifiersQueryKey(params);
+ const sync = this.#identifiers.useSync(params, { enabled, revalidateOnFocus: false });
+ return this.#toSyncResult(
+ sync,
+ queryKey,
+ !!this.#get().pluginIdentifiersMap[queryKey],
+ enabled,
);
};
}
diff --git a/src/store/discover/slices/plugin/initialState.ts b/src/store/discover/slices/plugin/initialState.ts
new file mode 100644
index 00000000000..f253f758e1d
--- /dev/null
+++ b/src/store/discover/slices/plugin/initialState.ts
@@ -0,0 +1,44 @@
+import type { CategoryItem } from '@lobehub/market-sdk';
+
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
+import type {
+ DiscoverPluginDetail,
+ IdentifiersResponse,
+ PluginListResponse,
+} from '@/types/discover';
+
+/**
+ * Replica views of the plugin market reads, each beside its bookkeeping slot.
+ * The views are plain records keyed by the entry key of the matching resource
+ * (`projection.ts`); components read them through `pluginSelectors`, never
+ * through the fetch hook.
+ */
+export interface PluginSliceState {
+ /** Category counts per query (`pluginCategoriesQueryKey`). */
+ pluginCategoriesMap: Record<string, CategoryItem[]>;
+ /** Replica bookkeeping of `pluginCategoriesMap`. */
+ pluginCategoriesReplica: ReplicaState<CategoryItem[]>;
+ /** Plugin detail per identifier (`pluginDetailQueryKey`). */
+ pluginDetailMap: Record<string, DiscoverPluginDetail>;
+ /** Replica bookkeeping of `pluginDetailMap`. */
+ pluginDetailReplica: ReplicaState<DiscoverPluginDetail>;
+ /** Identifier index (`pluginIdentifiersQueryKey`). */
+ pluginIdentifiersMap: Record<string, IdentifiersResponse>;
+ /** Replica bookkeeping of `pluginIdentifiersMap`. */
+ pluginIdentifiersReplica: ReplicaState<IdentifiersResponse>;
+ /** Plugin list per query (`pluginListQueryKey`). */
+ pluginListMap: Record<string, PluginListResponse>;
+ /** Replica bookkeeping of `pluginListMap`. */
+ pluginListReplica: ReplicaState<PluginListResponse>;
+}
+
+export const initialPluginSliceState: PluginSliceState = {
+ pluginCategoriesMap: {},
+ pluginCategoriesReplica: createReplicaState(),
+ pluginDetailMap: {},
+ pluginDetailReplica: createReplicaState(),
+ pluginIdentifiersMap: {},
+ pluginIdentifiersReplica: createReplicaState(),
+ pluginListMap: {},
+ pluginListReplica: createReplicaState(),
+};
diff --git a/src/store/discover/slices/plugin/projection.ts b/src/store/discover/slices/plugin/projection.ts
new file mode 100644
index 00000000000..496be46f2ee
--- /dev/null
+++ b/src/store/discover/slices/plugin/projection.ts
@@ -0,0 +1,125 @@
+import type { CategoryItem, CategoryListQuery } from '@lobehub/market-sdk';
+
+import { defineReplica, stableQueryKey } from '@/libs/replica';
+import { discoverService } from '@/services/discover';
+import type {
+ DiscoverPluginDetail,
+ IdentifiersResponse,
+ PluginListResponse,
+ PluginQueryParams,
+} from '@/types/discover';
+
+/**
+ * The marketplace plugin reads are **read-only**: no optimistic write, no
+ * cross-copy entity link. What the replica buys here is the first frame β€” the
+ * last confirmed page / detail paints before the network answers β€” and one
+ * cache partition per identity (the `cacheScope`), so switching account or
+ * workspace never serves the previous one's rows.
+ *
+ * Each distinct query is its own entry (`key`), exactly like the SWR key it
+ * replaces: the plugin list paginates by URL (`?page=N`), so a page flip is a
+ * different entry rather than a `loadMore` of the same one.
+ */
+
+/** Normalized `pluginList` params β€” the shape actually sent to the market endpoint. */
+export interface PluginListParams extends Omit<PluginQueryParams, 'page' | 'pageSize'> {
+ /** Current UI language; part of the entry so a locale switch refetches. */
+ locale?: string;
+ page: number;
+ pageSize: number;
+}
+
+/**
+ * Entry key of one plugin list query. Includes the page, because the list pages
+ * through the URL instead of appending pages to one entry.
+ */
+export const pluginListQueryKey = (params: PluginListParams): string => stableQueryKey(params);
+
+export interface PluginDetailParams {
+ identifier: string;
+ /** Current UI language; the market resolves localized copy server-side. */
+ locale?: string;
+ /** Whether the entry carries the compiled manifest; a distinct entry per value. */
+ withManifest?: boolean;
+}
+
+/** Entry key of one plugin detail (`identifier`, localized, manifest or not). */
+export const pluginDetailQueryKey = (params: PluginDetailParams): string => stableQueryKey(params);
+
+/** Category counts query of the community plugin sidebar (the search term). */
+export type PluginCategoriesParams = CategoryListQuery & {
+ /**
+ * Current UI language. The service resolves localized category labels, so a
+ * language switch is a different entry (the old SWR key carried it too).
+ */
+ locale?: string;
+};
+
+/** Entry key of one category-counts query (the search term + locale). */
+export const pluginCategoriesQueryKey = (params: PluginCategoriesParams): string =>
+ stableQueryKey(params);
+
+/** The plugin identifier index takes no query β€” one entry for the whole index. */
+export type PluginIdentifiersParams = Record<string, never>;
+
+/** Entry key of the plugin identifier index. */
+export const pluginIdentifiersQueryKey = (params: PluginIdentifiersParams = {}): string =>
+ stableQueryKey(params);
+
+/**
+ * Plugin market list, one entry per query (`pluginListMap[queryKey]`). The
+ * response already carries everything a row reader needs (`items`,
+ * `currentPage`, `pageSize`, `totalCount`), so it is stored as-is.
+ */
+export const pluginListResource = defineReplica<PluginListParams, PluginListResponse>({
+ fetcher: (params) => discoverService.getPluginList(params),
+ key: pluginListQueryKey,
+ name: 'pluginList',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/**
+ * One plugin detail by identifier (`pluginDetailMap[key]`). The service answers
+ * `undefined` for an identifier the market no longer has; the fetcher turns
+ * that into `null` so the slice's `isMissing` drops the entry (memory and
+ * persisted row) instead of letting the engine skip the write and keep painting
+ * a stale cached copy. The surface then falls back to its builtin / composio
+ * metadata once the sync settles.
+ */
+export const pluginDetailResource = defineReplica<
+ PluginDetailParams,
+ DiscoverPluginDetail,
+ DiscoverPluginDetail | null
+>({
+ fetcher: async (params) => (await discoverService.getPluginDetail(params)) ?? null,
+ key: pluginDetailQueryKey,
+ name: 'pluginDetail',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/**
+ * Category counts of one query (`pluginCategoriesMap[queryKey]`). Small and read
+ * on almost every community plugin screen, so localStorage keeps the first frame
+ * populated instead of flashing an empty sidebar.
+ */
+export const pluginCategoriesResource = defineReplica<PluginCategoriesParams, CategoryItem[]>({
+ fetcher: (params) => discoverService.getPluginCategories(params),
+ key: pluginCategoriesQueryKey,
+ name: 'pluginCategories',
+ storage: 'localStorage',
+ version: 1,
+});
+
+/** The plugin identifier index (`pluginIdentifiersMap[queryKey]`). */
+export const pluginIdentifiersResource = defineReplica<
+ PluginIdentifiersParams,
+ IdentifiersResponse
+>({
+ fetcher: () => discoverService.getPluginIdentifiers(),
+ key: pluginIdentifiersQueryKey,
+ name: 'pluginIdentifiers',
+ storage: 'localStorage',
+ version: 1,
+});
diff --git a/src/store/discover/slices/skill/action.test.ts b/src/store/discover/slices/skill/action.test.ts
index 545e626c61a..f708502f965 100644
--- a/src/store/discover/slices/skill/action.test.ts
+++ b/src/store/discover/slices/skill/action.test.ts
@@ -1,39 +1,357 @@
-import { renderHook, waitFor } from '@testing-library/react';
+import { act, renderHook } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { discoverService } from '@/services/discover';
+import { createReplicaState } from '@/libs/replica';
import { globalHelpers } from '@/store/global/helpers';
+import type { SkillListResponse } from '@/types/discover';
import { SkillSorts } from '@/types/discover';
+import { skillSelectors } from '../../selectors';
import { useDiscoverStore as useStore } from '../../store';
+import {
+ skillCategoriesQueryKey,
+ skillCommentsQueryKey,
+ skillDetailQueryKey,
+ skillListQueryKey,
+ skillRatingDistributionQueryKey,
+ skillRelatedQueryKey,
+} from './projection';
+
+vi.mock('@/services/discover', () => ({
+ discoverService: {
+ getSkillCategories: vi.fn(),
+ getSkillComments: vi.fn(),
+ getSkillDetail: vi.fn(),
+ getSkillList: vi.fn(),
+ getSkillRatingDistribution: vi.fn(),
+ },
+}));
+
+// The replica schedules its fetches through the app's SWR driver; the engine
+// itself is what these tests exercise, so the driver is a bare recorder.
+vi.mock('@/libs/swr', () => ({
+ mutate: vi.fn(),
+ useClientDataSWR: vi.fn(() => ({ isValidating: false, mutate: vi.fn() })),
+}));
+
+const listItem = (identifier: string) => ({ identifier, name: identifier }) as any;
+
+const makeList = (identifier = 'skill-1'): SkillListResponse =>
+ ({
+ currentPage: 1,
+ items: [listItem(identifier)],
+ pageSize: 21,
+ totalCount: 1,
+ totalPages: 1,
+ }) as any;
+
+const emptySkillState = () => ({
+ skillCategoriesMap: {},
+ skillCategoriesReplica: createReplicaState(),
+ skillCommentsMap: {},
+ skillCommentsReplica: createReplicaState(),
+ skillDetailMap: {},
+ skillDetailReplica: createReplicaState(),
+ skillListMap: {},
+ skillListReplica: createReplicaState(),
+ skillRatingDistributionMap: {},
+ skillRatingDistributionReplica: createReplicaState(),
+ skillRelatedMap: {},
+ skillRelatedReplica: createReplicaState(),
+});
beforeEach(() => {
vi.clearAllMocks();
+ vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');
+ useStore.setState(emptySkillState());
});
-const listItem = (identifier: string) => ({ identifier, name: identifier }) as any;
+/** The replica network syncs registered with the SWR driver, per resource name. */
+const syncCalls = async (
+ name:
+ | 'skillCategories'
+ | 'skillComments'
+ | 'skillDetail'
+ | 'skillList'
+ | 'skillRatingDistribution'
+ | 'skillRelated',
+) => {
+ const { useClientDataSWR } = await import('@/libs/swr');
+ return vi
+ .mocked(useClientDataSWR)
+ .mock.calls.filter(
+ ([key]) => Array.isArray(key) && key[0] === 'replica:sync' && key[1] === name,
+ )
+ .map(([key, fetcher, config]) => ({
+ config: config as {
+ onError?: (error: unknown) => void;
+ onSuccess?: (data: unknown) => void;
+ },
+ fetcher: fetcher as () => Promise<any>,
+ key: key as unknown[],
+ }));
+};
+
+describe('SkillSlice (replica)', () => {
+ describe('useFetchSkillList', () => {
+ it('requests the list with normalized page / pageSize and the locale', async () => {
+ const { discoverService } = await import('@/services/discover');
+
+ renderHook(() => useStore.getState().useFetchSkillList({ q: 'gpt' }));
+
+ const [call] = await syncCalls('skillList');
+ await call.fetcher();
+
+ expect(discoverService.getSkillList).toHaveBeenCalledWith({
+ locale: 'en-US',
+ page: 1,
+ pageSize: 21,
+ q: 'gpt',
+ });
+ });
+
+ it('keys each page and filter set as its own replica entry', () => {
+ const { result } = renderHook(() => [
+ useStore.getState().useFetchSkillList({ page: 1 }),
+ useStore.getState().useFetchSkillList({ page: 2 }),
+ useStore.getState().useFetchSkillList({ category: 'git-github' }),
+ ]);
+
+ const [first, second, third] = result.current;
+ expect(new Set([first.queryKey, second.queryKey, third.queryKey]).size).toBe(3);
+ });
+
+ it('does not register a sync β€” and reports no loading β€” when disabled', async () => {
+ const { result } = renderHook(() =>
+ useStore.getState().useFetchSkillList({ page: 1 }, { enabled: false }),
+ );
+
+ expect(result.current.queryKey).toBeUndefined();
+ expect(result.current.isLoading).toBe(false);
+ expect(await syncCalls('skillList')).toHaveLength(0);
+ });
+
+ it('reports loading until the entry has a value to show', () => {
+ const { result } = renderHook(() => useStore.getState().useFetchSkillList({ page: 1 }));
+
+ expect(result.current.isLoading).toBe(true);
+ });
+
+ it('does not report loading when the entry already has a (hydrated) value', () => {
+ const key = skillListQueryKey({ locale: 'en-US', page: 1, pageSize: 21 });
+ useStore.setState({ skillListMap: { [key]: makeList() } });
+
+ const { result } = renderHook(() => useStore.getState().useFetchSkillList({ page: 1 }));
+
+ expect(result.current.queryKey).toBe(key);
+ expect(result.current.isLoading).toBe(false);
+ });
+
+ it('folds the response into the replica view the selectors read', async () => {
+ const response = makeList();
+
+ renderHook(() => useStore.getState().useFetchSkillList({ page: 1 }));
+ const [call] = await syncCalls('skillList');
+ act(() => call.config.onSuccess!(response));
+
+ const key = skillListQueryKey({ locale: 'en-US', page: 1, pageSize: 21 });
+ expect(skillSelectors.skillList(key)(useStore.getState())).toEqual(response);
+ });
+ });
+
+ describe('useFetchSkillDetail', () => {
+ it('requests the detail with identifier and locale', async () => {
+ const { discoverService } = await import('@/services/discover');
+
+ renderHook(() => useStore.getState().useFetchSkillDetail({ identifier: 'github.acme.a' }));
+
+ const [call] = await syncCalls('skillDetail');
+ await call.fetcher();
+
+ expect(discoverService.getSkillDetail).toHaveBeenCalledWith(
+ expect.objectContaining({ identifier: 'github.acme.a' }),
+ );
+ });
+
+ it('passes the pinned version through to the detail request', async () => {
+ const { discoverService } = await import('@/services/discover');
+
+ renderHook(() =>
+ useStore.getState().useFetchSkillDetail({ identifier: 'github.acme.a', version: '1.2.0' }),
+ );
+
+ const [call] = await syncCalls('skillDetail');
+ await call.fetcher();
+
+ expect(discoverService.getSkillDetail).toHaveBeenCalledWith({
+ identifier: 'github.acme.a',
+ version: '1.2.0',
+ });
+ });
+
+ it('keys the detail by identifier, so a different identifier is a different entry', () => {
+ const { result } = renderHook(() => [
+ useStore.getState().useFetchSkillDetail({ identifier: 'github.acme.a' }),
+ useStore.getState().useFetchSkillDetail({ identifier: 'github.acme.b' }),
+ ]);
+
+ expect(new Set(result.current.map((sync) => sync.queryKey)).size).toBe(2);
+ });
+
+ it('disables the sync for a raw-URL identifier and reports no loading', async () => {
+ const { result } = renderHook(() =>
+ useStore.getState().useFetchSkillDetail({ identifier: 'url.example.com.foo' }),
+ );
+
+ expect(result.current.queryKey).toBeUndefined();
+ expect(result.current.isLoading).toBe(false);
+ expect(await syncCalls('skillDetail')).toHaveLength(0);
+ });
+
+ it('keys the detail by the locale, so a language switch refetches', () => {
+ const { result, rerender } = renderHook(() =>
+ useStore.getState().useFetchSkillDetail({ identifier: 'github.acme.a' }),
+ );
+ const first = result.current.queryKey;
+
+ vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('zh-CN');
+ rerender();
+
+ expect(result.current.queryKey).not.toBe(first);
+ });
+
+ it('evicts a hydrated detail when revalidation answers NOT_FOUND', async () => {
+ const key = skillDetailQueryKey({ identifier: 'github.acme.a', locale: 'en-US' });
+ // The persisted detail the detail route would keep painting: it only
+ // falls back to its error state once the map entry is gone.
+ useStore.setState({ skillDetailMap: { [key]: { identifier: 'github.acme.a' } as any } });
+
+ const { result } = renderHook(() =>
+ useStore.getState().useFetchSkillDetail({ identifier: 'github.acme.a' }),
+ );
+ expect(result.current.isLoading).toBe(false);
+ expect(skillSelectors.skillDetail(key)(useStore.getState())).toBeDefined();
+
+ const [call] = await syncCalls('skillDetail');
+ act(() => call.config.onError!({ data: { code: 'NOT_FOUND' } }));
+
+ expect(skillSelectors.skillDetail(key)(useStore.getState())).toBeUndefined();
+ });
+
+ it('keeps the cached detail when revalidation fails transiently', async () => {
+ const key = skillDetailQueryKey({ identifier: 'github.acme.a', locale: 'en-US' });
+ const detail = { identifier: 'github.acme.a' } as any;
+ useStore.setState({ skillDetailMap: { [key]: detail } });
+
+ renderHook(() => useStore.getState().useFetchSkillDetail({ identifier: 'github.acme.a' }));
+
+ const [call] = await syncCalls('skillDetail');
+ act(() => call.config.onError!({ data: { code: 'INTERNAL_SERVER_ERROR' } }));
+
+ expect(skillSelectors.skillDetail(key)(useStore.getState())).toBe(detail);
+ });
+ });
+
+ describe('useSkillCategories', () => {
+ it('requests category counts with the search term and the locale', async () => {
+ const { discoverService } = await import('@/services/discover');
+
+ renderHook(() => useStore.getState().useSkillCategories({ q: 'gpt' }));
+
+ const [call] = await syncCalls('skillCategories');
+ await call.fetcher();
+
+ expect(discoverService.getSkillCategories).toHaveBeenCalledWith({
+ locale: 'en-US',
+ q: 'gpt',
+ });
+ });
+
+ it('skips the request when disabled', async () => {
+ const { result } = renderHook(() =>
+ useStore.getState().useSkillCategories({}, { enabled: false }),
+ );
+
+ expect(result.current.queryKey).toBeUndefined();
+ expect(await syncCalls('skillCategories')).toHaveLength(0);
+ });
+
+ it('falls back to an empty list when no category entry is loaded', () => {
+ expect(skillSelectors.skillCategories(undefined)(useStore.getState())).toEqual([]);
+ expect(skillSelectors.skillRelated(undefined)(useStore.getState())).toEqual([]);
+ expect(skillSelectors.skillList(undefined)(useStore.getState())).toBeUndefined();
+ expect(skillSelectors.skillDetail(undefined)(useStore.getState())).toBeUndefined();
+ expect(skillSelectors.skillComments(undefined)(useStore.getState())).toBeUndefined();
+ expect(
+ skillSelectors.skillRatingDistribution(undefined)(useStore.getState()),
+ ).toBeUndefined();
+ });
+ });
+
+ describe('useFetchSkillComments', () => {
+ it('requests the first comment page with the identifier and paging params', async () => {
+ const { discoverService } = await import('@/services/discover');
+
+ renderHook(() =>
+ useStore.getState().useFetchSkillComments({
+ identifier: 'github.acme.a',
+ order: 'desc',
+ page: 1,
+ sort: 'createdAt',
+ }),
+ );
+
+ const [call] = await syncCalls('skillComments');
+ await call.fetcher();
+
+ expect(discoverService.getSkillComments).toHaveBeenCalledWith({
+ identifier: 'github.acme.a',
+ order: 'desc',
+ page: 1,
+ sort: 'createdAt',
+ });
+ });
+
+ it('disables the sync without an identifier', async () => {
+ const { result } = renderHook(() => useStore.getState().useFetchSkillComments({ page: 1 }));
+
+ expect(result.current.queryKey).toBeUndefined();
+ expect(await syncCalls('skillComments')).toHaveLength(0);
+ });
+ });
+
+ describe('useFetchSkillRatingDistribution', () => {
+ it('requests the rating distribution for the identifier', async () => {
+ const { discoverService } = await import('@/services/discover');
+
+ renderHook(() => useStore.getState().useFetchSkillRatingDistribution('github.acme.a'));
+
+ const [call] = await syncCalls('skillRatingDistribution');
+ await call.fetcher();
+
+ expect(discoverService.getSkillRatingDistribution).toHaveBeenCalledWith('github.acme.a');
+ });
+ });
-describe('SkillAction', () => {
describe('useFetchRelatedSkills', () => {
it('fetches same-category recommended skills, dropping the skill itself and capping at 6', async () => {
- vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');
- vi.spyOn(discoverService, 'getSkillList').mockResolvedValue({
+ const { discoverService } = await import('@/services/discover');
+ vi.mocked(discoverService.getSkillList).mockResolvedValue({
items: [
listItem('github.acme.skill-a'),
...Array.from({ length: 6 }, (_, i) => listItem(`github.acme.other-${i}`)),
],
} as any);
- const { result } = renderHook(() =>
+ renderHook(() =>
useStore.getState().useFetchRelatedSkills({
category: 'productivity-tasks',
identifier: 'github.acme.skill-a',
}),
);
- await waitFor(() => {
- expect(result.current.data).toHaveLength(6);
- });
+ const [call] = await syncCalls('skillRelated');
+ const related = await call.fetcher();
expect(discoverService.getSkillList).toHaveBeenCalledWith({
category: 'productivity-tasks',
@@ -41,47 +359,68 @@ describe('SkillAction', () => {
pageSize: 7,
sort: SkillSorts.Recommended,
});
- expect(result.current.data?.map((i) => i.identifier)).not.toContain('github.acme.skill-a');
+ expect(related).toHaveLength(6);
+ expect(related.map((i: any) => i.identifier)).not.toContain('github.acme.skill-a');
});
it('caps at 6 even when the skill itself is not in the page', async () => {
- vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');
- vi.spyOn(discoverService, 'getSkillList').mockResolvedValue({
+ const { discoverService } = await import('@/services/discover');
+ vi.mocked(discoverService.getSkillList).mockResolvedValue({
items: Array.from({ length: 7 }, (_, i) => listItem(`github.acme.other-${i}`)),
} as any);
- const { result } = renderHook(() =>
+ renderHook(() =>
useStore.getState().useFetchRelatedSkills({
category: 'productivity-tasks',
identifier: 'github.acme.skill-a',
}),
);
- await waitFor(() => {
- expect(result.current.data).toHaveLength(6);
- });
+ const [call] = await syncCalls('skillRelated');
+ expect(await call.fetcher()).toHaveLength(6);
});
it('does not fetch without a category', async () => {
- const getSkillList = vi.spyOn(discoverService, 'getSkillList');
+ const { discoverService } = await import('@/services/discover');
renderHook(() =>
useStore.getState().useFetchRelatedSkills({ identifier: 'github.acme.skill-a' }),
);
- await new Promise((resolve) => setTimeout(resolve, 50));
- expect(getSkillList).not.toHaveBeenCalled();
+ expect(await syncCalls('skillRelated')).toHaveLength(0);
+ expect(discoverService.getSkillList).not.toHaveBeenCalled();
});
it('does not fetch without an identifier', async () => {
- const getSkillList = vi.spyOn(discoverService, 'getSkillList');
+ const { discoverService } = await import('@/services/discover');
renderHook(() =>
useStore.getState().useFetchRelatedSkills({ category: 'productivity-tasks' }),
);
- await new Promise((resolve) => setTimeout(resolve, 50));
- expect(getSkillList).not.toHaveBeenCalled();
+ expect(await syncCalls('skillRelated')).toHaveLength(0);
+ expect(discoverService.getSkillList).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('replica key helpers', () => {
+ it('produces stable, distinct keys per query dimension', () => {
+ expect(skillListQueryKey({ locale: 'en-US', page: 1, pageSize: 21 })).toBe(
+ skillListQueryKey({ locale: 'en-US', page: 1, pageSize: 21 }),
+ );
+ expect(skillDetailQueryKey({ identifier: 'a' })).not.toBe(
+ skillDetailQueryKey({ identifier: 'b' }),
+ );
+ expect(skillCategoriesQueryKey({ q: 'a' })).not.toBe(skillCategoriesQueryKey({}));
+ expect(skillCommentsQueryKey({ identifier: 'a', page: 1 })).not.toBe(
+ skillCommentsQueryKey({ identifier: 'a', page: 2 }),
+ );
+ expect(skillRatingDistributionQueryKey({ identifier: 'a' })).not.toBe(
+ skillRatingDistributionQueryKey({ identifier: 'b' }),
+ );
+ expect(skillRelatedQueryKey({ category: 'a', identifier: 'b' })).not.toBe(
+ skillRelatedQueryKey({ category: 'a', identifier: 'c' }),
+ );
});
});
});
diff --git a/src/store/discover/slices/skill/action.ts b/src/store/discover/slices/skill/action.ts
index 04769c1d59c..e649c79da38 100644
--- a/src/store/discover/slices/skill/action.ts
+++ b/src/store/discover/slices/skill/action.ts
@@ -1,9 +1,4 @@
-import { type CategoryListQuery } from '@lobehub/market-sdk';
-import { type SWRResponse } from 'swr';
-
-import { useClientDataSWR } from '@/libs/swr';
-import { discoverKeys } from '@/libs/swr/keys';
-import { discoverService } from '@/services/discover';
+import { createReplicaSlice, recordLens, type ReplicaSyncResult } from '@/libs/replica';
import { type DiscoverStore } from '@/store/discover';
import { globalHelpers } from '@/store/global/helpers';
import { type StoreSetter } from '@/store/types';
@@ -16,113 +11,278 @@ import {
type SkillListResponse,
type SkillQueryParams,
type SkillRatingDistribution,
- SkillSorts,
} from '@/types/discover';
+import { setNamespace } from '@/utils/storeDebug';
+import { isTrpcErrorCode } from '@/utils/trpcError';
-type Setter = StoreSetter<DiscoverStore>;
+import {
+ type SkillCategoriesParams,
+ skillCategoriesQueryKey,
+ skillCategoriesResource,
+ type SkillCommentsParams,
+ skillCommentsQueryKey,
+ skillCommentsResource,
+ type SkillDetailParams,
+ skillDetailQueryKey,
+ skillDetailResource,
+ type SkillListParams,
+ skillListQueryKey,
+ skillListResource,
+ type SkillRatingDistributionParams,
+ skillRatingDistributionQueryKey,
+ skillRatingDistributionResource,
+ type SkillRelatedParams,
+ skillRelatedQueryKey,
+ skillRelatedResource,
+} from './projection';
+
+const n = setNamespace('discover/skill');
+
+/**
+ * Sync flags of a market read, plus the aliases the old SWR hooks returned
+ * (`isLoading` / `mutate`) so a call site only has to move its `data` read to
+ * the matching `skillSelectors` entry.
+ */
+export interface SkillSyncResult extends ReplicaSyncResult {
+ /** A request is in flight and this entry has no value to show yet. */
+ isLoading: boolean;
+ /** Alias of `revalidate`. */
+ mutate: () => Promise<unknown>;
+ /** Read the value with `skillSelectors.*(queryKey)`; undefined while disabled. */
+ queryKey?: string;
+}
-/** How many related skills the detail view shows alongside the skill itself */
-const RELATED_SKILLS_COUNT = 6;
+type Setter = StoreSetter<DiscoverStore>;
export const createSkillSlice = (set: Setter, get: () => DiscoverStore, _api?: unknown) =>
new SkillActionImpl(set, get, _api);
export class SkillActionImpl {
+ readonly #categories;
+ readonly #comments;
+ readonly #detail;
+ readonly #get: () => DiscoverStore;
+ readonly #list;
+ readonly #ratingDistribution;
+ readonly #related;
+
constructor(set: Setter, get: () => DiscoverStore, _api?: unknown) {
void _api;
- void set;
- void get;
+ this.#get = get;
+ this.#list = createReplicaSlice(skillListResource, {
+ actionPrefix: n('list'),
+ get,
+ set,
+ stateKey: 'skillListReplica',
+ view: recordLens<DiscoverStore, SkillListResponse>('skillListMap'),
+ });
+ this.#detail = createReplicaSlice(skillDetailResource, {
+ actionPrefix: n('detail'),
+ get,
+ set,
+ stateKey: 'skillDetailReplica',
+ view: recordLens<DiscoverStore, DiscoverSkillDetail>('skillDetailMap'),
+ });
+ this.#categories = createReplicaSlice(skillCategoriesResource, {
+ actionPrefix: n('categories'),
+ get,
+ set,
+ stateKey: 'skillCategoriesReplica',
+ view: recordLens<DiscoverStore, SkillCategoryItem[]>('skillCategoriesMap'),
+ });
+ this.#comments = createReplicaSlice(skillCommentsResource, {
+ actionPrefix: n('comments'),
+ get,
+ set,
+ stateKey: 'skillCommentsReplica',
+ view: recordLens<DiscoverStore, SkillCommentListResponse>('skillCommentsMap'),
+ });
+ this.#ratingDistribution = createReplicaSlice(skillRatingDistributionResource, {
+ actionPrefix: n('ratingDistribution'),
+ get,
+ set,
+ stateKey: 'skillRatingDistributionReplica',
+ view: recordLens<DiscoverStore, SkillRatingDistribution>('skillRatingDistributionMap'),
+ });
+ this.#related = createReplicaSlice(skillRelatedResource, {
+ actionPrefix: n('related'),
+ get,
+ set,
+ stateKey: 'skillRelatedReplica',
+ view: recordLens<DiscoverStore, DiscoverSkillItem[]>('skillRelatedMap'),
+ });
}
- useFetchSkillDetail = ({
- identifier,
- version,
- }: {
- identifier?: string;
- version?: string;
- }): SWRResponse<DiscoverSkillDetail> => {
- const locale = globalHelpers.getCurrentLanguage();
-
- // Skills imported from a raw URL get a synthetic `url.<host>.<path>`
- // identifier (see server skill importer `url.${host}.${pathPart}`), not a
- // marketplace slug β€” the market detail lookup can only 404 for them and
- // would otherwise spam the console with 500s + SWR retries. Skip the request
- // and let callers fall back to the locally stored name/description/icon.
- const isMarketIdentifier = !!identifier && !identifier.startsWith('url.');
+ #toSyncResult = (
+ sync: ReplicaSyncResult,
+ queryKey: string | undefined,
+ hasValue: boolean,
+ active: boolean,
+ ): SkillSyncResult => ({
+ ...sync,
+ // A disabled hook never loads; a settled entry with a value never flashes.
+ isLoading: active && !hasValue && (!sync.isHydrated || sync.isValidating),
+ mutate: sync.revalidate,
+ queryKey: active ? queryKey : undefined,
+ });
- return useClientDataSWR(
- !isMarketIdentifier ? null : discoverKeys.skillDetail(locale, identifier, version),
- async () => discoverService.getSkillDetail({ identifier: identifier!, version }),
- );
+ /**
+ * The skill market list of one query. Each (filters Β· page) pair is its own
+ * entry, so the URL-driven pager walks entries instead of appending pages.
+ * Read the rows with `skillSelectors.skillList(queryKey)`.
+ */
+ useFetchSkillList = (
+ params: SkillQueryParams = {},
+ options: { enabled?: boolean } = {},
+ ): 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 queryKey = skillListQueryKey(normalized);
+ const sync = this.#list.useSync(normalized, { enabled });
+ return this.#toSyncResult(sync, queryKey, !!this.#get().skillListMap[queryKey], enabled);
};
/**
- * Related skills for the detail view, composed client-side from the list
- * endpoint. Kept out of `getSkillDetail` on purpose: that query also backs
- * per-skill icon/metadata lookups (one per installed skill in the chat tools
- * panel), which must not pay for an extra upstream list request.
+ * One skill detail by identifier (optionally pinned to a version). Read it
+ * with `skillSelectors.skillDetail(queryKey)`; `undefined` after the sync
+ * settles means the market has no such identifier.
+ *
+ * Skills imported from a raw URL carry a synthetic `url.<host>.<path>`
+ * identifier that the market detail endpoint can only 404 β€” the sync is
+ * disabled for those and callers fall back to the locally stored metadata.
*/
- useFetchRelatedSkills = ({
- category,
- identifier,
- }: {
- category?: string;
- identifier?: string;
- }): SWRResponse<DiscoverSkillItem[]> => {
- const locale = globalHelpers.getCurrentLanguage();
- return useClientDataSWR(
- category && identifier ? discoverKeys.skillRelated(locale, category, identifier) : null,
- async (): Promise<DiscoverSkillItem[]> => {
- const list = await discoverService.getSkillList({
- category,
- page: 1,
- // Fetch one extra so the cap still holds after dropping the skill itself
- pageSize: RELATED_SKILLS_COUNT + 1,
- sort: SkillSorts.Recommended,
- });
- return list.items
- .filter((item) => item.identifier !== identifier)
- .slice(0, RELATED_SKILLS_COUNT);
+ useFetchSkillDetail = (
+ params: { identifier?: string; version?: string },
+ options: { enabled?: boolean } = {},
+ ): SkillSyncResult => {
+ const { enabled = true } = options;
+ const identifier = params.identifier;
+ const isMarketIdentifier = !!identifier && !identifier.startsWith('url.');
+ const normalized: SkillDetailParams = {
+ identifier: identifier ?? '',
+ locale: globalHelpers.getCurrentLanguage(),
+ version: params.version,
+ };
+ const queryKey = skillDetailQueryKey(normalized);
+ const active = enabled && isMarketIdentifier;
+ const sync = this.#detail.useSync(active ? normalized : null, {
+ enabled: active,
+ // A skill (or a pinned version) later removed from the market answers
+ // NOT_FOUND on every read, yet the hydrated IndexedDB row would keep the
+ // detail route painting it: that route only renders its error state once
+ // the map entry is gone (`skillDetail(queryKey) === undefined`), so the
+ // obsolete copy would survive reloads. NOT_FOUND is definitive β€” drop the
+ // entry (memory plus its persisted rows) and let the route settle on its
+ // 404. Any transient failure keeps the cached detail on screen. Bind the
+ // removal to the scope the failing request was captured under: an
+ // identity / workspace switch in flight must not delete the same
+ // identifier out of the scope that is active when the callback runs.
+ onError: (error, { key, scope }) => {
+ if (key && isTrpcErrorCode(error, 'NOT_FOUND')) this.#detail.remove(key, scope);
},
+ });
+ return this.#toSyncResult(
+ sync,
+ queryKey,
+ this.#get().skillDetailMap[queryKey] !== undefined,
+ active,
);
};
- useFetchSkillComments = ({
- identifier,
- ...params
- }: Partial<SkillCommentsQueryParams>): SWRResponse<SkillCommentListResponse> => {
- return useClientDataSWR(
- identifier ? discoverKeys.skillComments(identifier, params) : null,
- async () => discoverService.getSkillComments({ identifier: identifier!, ...params }),
- );
+ /**
+ * Category counts of one query (the search term). The community sidebar reads
+ * `skillSelectors.skillCategories(queryKey)`.
+ */
+ useSkillCategories = (
+ params: SkillCategoriesParams = {},
+ options: { enabled?: boolean } = {},
+ ): SkillSyncResult => {
+ const { enabled = true } = options;
+ const normalized: SkillCategoriesParams = {
+ ...params,
+ locale: globalHelpers.getCurrentLanguage(),
+ };
+ const queryKey = skillCategoriesQueryKey(normalized);
+ const sync = this.#categories.useSync(normalized, { enabled, revalidateOnFocus: false });
+ return this.#toSyncResult(sync, queryKey, !!this.#get().skillCategoriesMap[queryKey], enabled);
};
- useFetchSkillList = (params: SkillQueryParams): SWRResponse<SkillListResponse> => {
- const locale = globalHelpers.getCurrentLanguage();
- return useClientDataSWR(discoverKeys.skillList(locale, params), async () =>
- discoverService.getSkillList({
- ...params,
- page: params.page ? Number(params.page) : 1,
- pageSize: params.pageSize ? Number(params.pageSize) : 21,
- }),
+ /**
+ * Comments of one skill. The header stat and the Reviews tab pass the same
+ * params, so they share one entry. Read them with
+ * `skillSelectors.skillComments(queryKey)`.
+ */
+ useFetchSkillComments = (
+ params: Partial<SkillCommentsQueryParams>,
+ options: { enabled?: boolean } = {},
+ ): SkillSyncResult => {
+ const { enabled = true } = options;
+ const identifier = params.identifier;
+ const normalized: SkillCommentsParams = {
+ ...params,
+ identifier: identifier ?? '',
+ } as SkillCommentsParams;
+ const queryKey = skillCommentsQueryKey(normalized);
+ const active = enabled && !!identifier;
+ const sync = this.#comments.useSync(active ? normalized : null, { enabled: active });
+ return this.#toSyncResult(
+ sync,
+ queryKey,
+ this.#get().skillCommentsMap[queryKey] !== undefined,
+ active,
);
};
- useFetchSkillRatingDistribution = (identifier?: string): SWRResponse<SkillRatingDistribution> => {
- return useClientDataSWR(
- identifier ? discoverKeys.skillRatingDistribution(identifier) : null,
- async () => discoverService.getSkillRatingDistribution(identifier!),
+ /**
+ * Rating distribution of one skill. Read it with
+ * `skillSelectors.skillRatingDistribution(queryKey)`.
+ */
+ useFetchSkillRatingDistribution = (
+ identifier?: string,
+ options: { enabled?: boolean } = {},
+ ): SkillSyncResult => {
+ const { enabled = true } = options;
+ const normalized: SkillRatingDistributionParams = { identifier: identifier ?? '' };
+ const queryKey = skillRatingDistributionQueryKey(normalized);
+ const active = enabled && !!identifier;
+ const sync = this.#ratingDistribution.useSync(active ? normalized : null, { enabled: active });
+ return this.#toSyncResult(
+ sync,
+ queryKey,
+ this.#get().skillRatingDistributionMap[queryKey] !== undefined,
+ active,
);
};
- useSkillCategories = (params: CategoryListQuery = {}): SWRResponse<SkillCategoryItem[]> => {
- const locale = globalHelpers.getCurrentLanguage();
- return useClientDataSWR(
- discoverKeys.skillCategories(locale, params),
- async () => discoverService.getSkillCategories(params),
- {
- revalidateOnFocus: false,
- },
+ /**
+ * Related skills for the detail view. Needs both the category and the
+ * identifier; without them the sync is disabled and the selector is empty.
+ * Read them with `skillSelectors.skillRelated(queryKey)`.
+ */
+ useFetchRelatedSkills = (
+ params: { category?: string; identifier?: string },
+ options: { enabled?: boolean } = {},
+ ): SkillSyncResult => {
+ const { enabled = true } = options;
+ const { category, identifier } = params;
+ const normalized: SkillRelatedParams = {
+ category: category ?? '',
+ identifier: identifier ?? '',
+ locale: globalHelpers.getCurrentLanguage(),
+ };
+ const queryKey = skillRelatedQueryKey(normalized);
+ const active = enabled && !!category && !!identifier;
+ const sync = this.#related.useSync(active ? normalized : null, { enabled: active });
+ return this.#toSyncResult(
+ sync,
+ queryKey,
+ this.#get().skillRelatedMap[queryKey] !== undefined,
+ active,
);
};
}
diff --git a/src/store/discover/slices/skill/initialState.ts b/src/store/discover/slices/skill/initialState.ts
new file mode 100644
index 00000000000..c5162c4bdb3
--- /dev/null
+++ b/src/store/discover/slices/skill/initialState.ts
@@ -0,0 +1,57 @@
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
+import type {
+ DiscoverSkillDetail,
+ DiscoverSkillItem,
+ SkillCategoryItem,
+ SkillCommentListResponse,
+ SkillListResponse,
+ SkillRatingDistribution,
+} from '@/types/discover';
+
+/**
+ * Replica views of the skill market reads, each beside its bookkeeping slot.
+ * The views are plain records keyed by the entry key of the matching resource
+ * (`projection.ts`); components read them through `skillSelectors`, never
+ * through the fetch hook.
+ */
+export interface SkillSliceState {
+ /** Category counts per query (`skillCategoriesQueryKey`). */
+ skillCategoriesMap: Record<string, SkillCategoryItem[]>;
+ /** Replica bookkeeping of `skillCategoriesMap`. */
+ skillCategoriesReplica: ReplicaState<SkillCategoryItem[]>;
+ /** Comments per query (`skillCommentsQueryKey`). */
+ skillCommentsMap: Record<string, SkillCommentListResponse>;
+ /** Replica bookkeeping of `skillCommentsMap`. */
+ skillCommentsReplica: ReplicaState<SkillCommentListResponse>;
+ /** Skill detail per identifier (`skillDetailQueryKey`). */
+ skillDetailMap: Record<string, DiscoverSkillDetail>;
+ /** Replica bookkeeping of `skillDetailMap`. */
+ skillDetailReplica: ReplicaState<DiscoverSkillDetail>;
+ /** Skill list per query (`skillListQueryKey`). */
+ skillListMap: Record<string, SkillListResponse>;
+ /** Replica bookkeeping of `skillListMap`. */
+ skillListReplica: ReplicaState<SkillListResponse>;
+ /** Rating distribution per skill (`skillRatingDistributionQueryKey`). */
+ skillRatingDistributionMap: Record<string, SkillRatingDistribution>;
+ /** Replica bookkeeping of `skillRatingDistributionMap`. */
+ skillRatingDistributionReplica: ReplicaState<SkillRatingDistribution>;
+ /** Related skills per query (`skillRelatedQueryKey`). */
+ skillRelatedMap: Record<string, DiscoverSkillItem[]>;
+ /** Replica bookkeeping of `skillRelatedMap`. */
+ skillRelatedReplica: ReplicaState<DiscoverSkillItem[]>;
+}
+
+export const initialSkillSliceState: SkillSliceState = {
+ skillCategoriesMap: {},
+ skillCategoriesReplica: createReplicaState(),
+ skillCommentsMap: {},
+ skillCommentsReplica: createReplicaState(),
+ skillDetailMap: {},
+ skillDetailReplica: createReplicaState(),
+ skillListMap: {},
+ skillListReplica: createReplicaState(),
+ skillRatingDistributionMap: {},
+ skillRatingDistributionReplica: createReplicaState(),
+ skillRelatedMap: {},
+ skillRelatedReplica: createReplicaState(),
+};
diff --git a/src/store/discover/slices/skill/projection.ts b/src/store/discover/slices/skill/projection.ts
new file mode 100644
index 00000000000..2479af78d9d
--- /dev/null
+++ b/src/store/discover/slices/skill/projection.ts
@@ -0,0 +1,187 @@
+import type { CategoryListQuery } from '@lobehub/market-sdk';
+
+import { defineReplica, stableQueryKey } from '@/libs/replica';
+import { discoverService } from '@/services/discover';
+import type {
+ DiscoverSkillDetail,
+ DiscoverSkillItem,
+ SkillCategoryItem,
+ SkillCommentListResponse,
+ SkillCommentsQueryParams,
+ SkillListResponse,
+ SkillQueryParams,
+ SkillRatingDistribution,
+} from '@/types/discover';
+import { SkillSorts } from '@/types/discover';
+
+/**
+ * The marketplace skill reads are **read-only**: no optimistic write, no
+ * cross-copy entity link. What the replica buys here is the first frame β€” the
+ * last confirmed page paints before the network answers β€” and one cache
+ * partition per identity (the `cacheScope`), so switching account or workspace
+ * never serves the previous one's rows.
+ *
+ * Each distinct query is its own entry (`key`), exactly like the SWR key it
+ * replaces: the community list paginates by URL (`?page=N`), so a page flip is
+ * a different entry rather than a `loadMore` of the same one.
+ */
+
+/** How many related skills the detail view shows alongside the skill itself */
+export const RELATED_SKILLS_COUNT = 6;
+
+// ============================== List ==============================
+
+/** Normalized `skillList` params β€” the shape actually sent to the market endpoint. */
+export interface SkillListParams extends Omit<SkillQueryParams, 'page' | 'pageSize'> {
+ /** Current UI language; part of the entry so a locale switch refetches. */
+ locale?: string;
+ page: number;
+ pageSize: number;
+}
+
+/** Entry key of one skill list query (page / filters / locale). */
+export const skillListQueryKey = (params: SkillListParams): string => stableQueryKey(params);
+
+/**
+ * Skill market list, one entry per query (`skillListMap[key]`). The response
+ * already carries everything a row reader needs (`items`, `currentPage`,
+ * `pageSize`, `totalCount`), so it is stored as-is.
+ */
+export const skillListResource = defineReplica<SkillListParams, SkillListResponse>({
+ fetcher: (params) => discoverService.getSkillList(params),
+ key: skillListQueryKey,
+ name: 'skillList',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+// ============================== Detail ==============================
+
+export interface SkillDetailParams {
+ identifier: string;
+ /** Current UI language; the market resolves localized copy server-side. */
+ locale?: string;
+ version?: string;
+}
+
+/** Entry key of one skill detail (`identifier`, localized, optional version). */
+export const skillDetailQueryKey = (params: SkillDetailParams): string => stableQueryKey(params);
+
+/**
+ * One skill detail by identifier (`skillDetailMap[key]`). Skills imported from
+ * a raw URL get a synthetic `url.<host>.<path>` identifier (see the server
+ * skill importer), not a marketplace slug β€” the caller disables the sync for
+ * those instead of letting the market detail lookup 404 and retry.
+ */
+export const skillDetailResource = defineReplica<SkillDetailParams, DiscoverSkillDetail>({
+ fetcher: (params) =>
+ discoverService.getSkillDetail({ identifier: params.identifier, version: params.version }),
+ key: skillDetailQueryKey,
+ name: 'skillDetail',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+// ============================== Categories ==============================
+
+/** Category counts of the community skill sidebar (the search term). */
+export type SkillCategoriesParams = CategoryListQuery;
+
+/** Entry key of one category-counts query (search term + locale). */
+export const skillCategoriesQueryKey = (params: SkillCategoriesParams): string =>
+ stableQueryKey(params);
+
+/**
+ * Category counts of one query (`skillCategoriesMap[key]`). Small and read on
+ * almost every community skill screen, so localStorage keeps the first frame
+ * populated instead of flashing an empty sidebar.
+ */
+export const skillCategoriesResource = defineReplica<SkillCategoriesParams, SkillCategoryItem[]>({
+ fetcher: (params) => discoverService.getSkillCategories(params),
+ key: skillCategoriesQueryKey,
+ name: 'skillCategories',
+ storage: 'localStorage',
+ version: 1,
+});
+
+// ============================== Comments ==============================
+
+/** Comment list query of one skill (`identifier` + paging / sort). */
+export type SkillCommentsParams = SkillCommentsQueryParams;
+
+/** Entry key of one comment page (`identifier`, sort, page). */
+export const skillCommentsQueryKey = (params: SkillCommentsParams): string =>
+ stableQueryKey(params);
+
+/**
+ * Comments of one skill, one entry per page (`skillCommentsMap[key]`). The
+ * detail header reads the first page and the Reviews tab reuses the same entry,
+ * so the stat and the list cost one request.
+ */
+export const skillCommentsResource = defineReplica<SkillCommentsParams, SkillCommentListResponse>({
+ fetcher: (params) => discoverService.getSkillComments(params),
+ key: skillCommentsQueryKey,
+ name: 'skillComments',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+// ============================== Rating distribution ==============================
+
+export interface SkillRatingDistributionParams {
+ identifier: string;
+}
+
+/** Entry key of one skill's rating distribution. */
+export const skillRatingDistributionQueryKey = (params: SkillRatingDistributionParams): string =>
+ stableQueryKey(params);
+
+/** Rating distribution of one skill (`skillRatingDistributionMap[key]`). */
+export const skillRatingDistributionResource = defineReplica<
+ SkillRatingDistributionParams,
+ SkillRatingDistribution
+>({
+ fetcher: (params) => discoverService.getSkillRatingDistribution(params.identifier),
+ key: skillRatingDistributionQueryKey,
+ name: 'skillRatingDistribution',
+ storage: 'localStorage',
+ version: 1,
+});
+
+// ============================== Related ==============================
+
+export interface SkillRelatedParams {
+ category: string;
+ identifier: string;
+ /** Current UI language; part of the entry so a locale switch refetches. */
+ locale?: string;
+}
+
+/** Entry key of one related-skills query (`category`, identifier, locale). */
+export const skillRelatedQueryKey = (params: SkillRelatedParams): string => stableQueryKey(params);
+
+/**
+ * Related skills for the detail view (`skillRelatedMap[key]`), composed
+ * client-side from the list endpoint. Kept out of `getSkillDetail` on purpose:
+ * that query also backs per-skill icon/metadata lookups (one per installed
+ * skill in the chat tools panel), which must not pay for an extra upstream list
+ * request. One extra row is fetched so the cap still holds after dropping the
+ * skill itself.
+ */
+export const skillRelatedResource = defineReplica<SkillRelatedParams, DiscoverSkillItem[]>({
+ fetcher: async (params) => {
+ const list = await discoverService.getSkillList({
+ category: params.category,
+ page: 1,
+ pageSize: RELATED_SKILLS_COUNT + 1,
+ sort: SkillSorts.Recommended,
+ });
+ return list.items
+ .filter((item) => item.identifier !== params.identifier)
+ .slice(0, RELATED_SKILLS_COUNT);
+ },
+ key: skillRelatedQueryKey,
+ name: 'skillRelated',
+ storage: 'localStorage',
+ version: 1,
+});
diff --git a/src/store/discover/slices/social/action.test.ts b/src/store/discover/slices/social/action.test.ts
index 5e23f6ba647..42abfc0cb09 100644
--- a/src/store/discover/slices/social/action.test.ts
+++ b/src/store/discover/slices/social/action.test.ts
@@ -1,85 +1,317 @@
+import { act, renderHook } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { replicaKeys } from '@/libs/replica';
import { mutate } from '@/libs/swr';
-import { discoverKeys } from '@/libs/swr/keys';
-import type { FollowCounts } from '@/services/social';
import { socialService } from '@/services/social';
-import { SocialActionImpl } from './action';
+import { socialSelectors } from '../../selectors';
+import { useDiscoverStore as useStore } from '../../store';
+import { initialSocialSliceState } from './initialState';
+import { followersResource, socialListKey, socialUserKey } from './projection';
-vi.mock('swr', () => ({
- default: vi.fn(),
+vi.mock('@/services/social', () => ({
+ socialService: {
+ addFavorite: vi.fn(),
+ checkFollowStatus: vi.fn(),
+ follow: vi.fn(),
+ getFollowCounts: vi.fn(),
+ getFollowers: vi.fn(),
+ getFollowing: vi.fn(),
+ getUserFavoriteAgents: vi.fn(),
+ getUserFavoritePlugins: vi.fn(),
+ removeFavorite: vi.fn(),
+ toggleLike: vi.fn(),
+ unfollow: vi.fn(),
+ },
}));
+// The replica schedules its fetches through the app's SWR driver; the engine
+// itself is what these tests exercise, so the driver is a bare recorder.
vi.mock('@/libs/swr', () => ({
mutate: vi.fn(),
+ useClientDataSWR: vi.fn(() => ({ isValidating: false, mutate: vi.fn() })),
}));
const mutateMock = vi.mocked(mutate);
+const makePage = <T>(item: T) => ({
+ currentPage: 1,
+ items: [item],
+ pageSize: 20,
+ totalCount: 1,
+ totalPages: 1,
+});
+
beforeEach(() => {
vi.clearAllMocks();
+ useStore.setState({ ...initialSocialSliceState });
});
-describe('SocialActionImpl', () => {
+/** The replica network syncs registered with the SWR driver, per resource name. */
+const syncCalls = async (name: string) => {
+ const { useClientDataSWR } = await import('@/libs/swr');
+ return vi
+ .mocked(useClientDataSWR)
+ .mock.calls.filter(
+ ([key]) => Array.isArray(key) && key[0] === 'replica:sync' && key[1] === name,
+ )
+ .map(([key, fetcher, config]) => ({
+ config: config as { onSuccess?: (data: unknown) => void; revalidateOnFocus?: boolean },
+ fetcher: fetcher as () => Promise<any>,
+ key: key as unknown[],
+ }));
+};
+
+const fold = async (name: string, data: unknown) => {
+ const [call] = await syncCalls(name);
+ act(() => call.config.onSuccess!(data));
+};
+
+describe('SocialSlice (replica)', () => {
+ it('does not revalidate any social read on window focus', async () => {
+ renderHook(() => {
+ const state = useStore.getState();
+ state.useFollowStatus(1);
+ state.useFollowCounts(1);
+ state.useFollowers(1);
+ state.useFollowing(1);
+ state.useFavoriteAgents(1);
+ state.useFavoritePlugins(1);
+ });
+
+ for (const name of [
+ 'discoverFollowStatus',
+ 'discoverFollowCounts',
+ 'discoverFollowers',
+ 'discoverFollowing',
+ 'discoverFavoriteAgents',
+ 'discoverFavoritePlugins',
+ ]) {
+ const calls = await syncCalls(name);
+ expect(calls.length).toBeGreaterThan(0);
+ for (const call of calls) expect(call.config.revalidateOnFocus).toBe(false);
+ }
+ });
+
+ describe('useFollowStatus', () => {
+ it('requests the viewer-relative status for the target user', async () => {
+ renderHook(() => useStore.getState().useFollowStatus(42));
+
+ const [call] = await syncCalls('discoverFollowStatus');
+ await call.fetcher();
+
+ expect(socialService.checkFollowStatus).toHaveBeenCalledWith(42);
+ });
+
+ it('keys each target user as its own entry', () => {
+ const { result } = renderHook(() => [
+ useStore.getState().useFollowStatus(1),
+ useStore.getState().useFollowStatus(2),
+ ]);
+
+ expect(new Set(result.current.map((sync) => sync.queryKey)).size).toBe(2);
+ });
+
+ it('does not register a sync β€” and reports no loading β€” without a user id', async () => {
+ const { result } = renderHook(() => useStore.getState().useFollowStatus(undefined));
+
+ expect(result.current.queryKey).toBeUndefined();
+ expect(result.current.isLoading).toBe(false);
+ expect(await syncCalls('discoverFollowStatus')).toHaveLength(0);
+ });
+
+ it('reports loading until the entry has a value to show', () => {
+ const { result } = renderHook(() => useStore.getState().useFollowStatus(42));
+
+ expect(result.current.isLoading).toBe(true);
+ });
+
+ it('does not report loading when the entry already has a value', () => {
+ const key = socialUserKey({ userId: 42 });
+ useStore.setState({ followStatusMap: { [key]: { isFollowing: true, isMutual: false } } });
+
+ const { result } = renderHook(() => useStore.getState().useFollowStatus(42));
+
+ expect(result.current.queryKey).toBe(key);
+ expect(result.current.isLoading).toBe(false);
+ });
+
+ it('folds the response into the replica view the selector reads', async () => {
+ renderHook(() => useStore.getState().useFollowStatus(42));
+ await fold('discoverFollowStatus', { isFollowing: true, isMutual: true });
+
+ const key = socialUserKey({ userId: 42 });
+ expect(socialSelectors.followStatus(key)(useStore.getState())).toEqual({
+ isFollowing: true,
+ isMutual: true,
+ });
+ });
+ });
+
+ describe('useFollowCounts', () => {
+ it('requests the target user counts and folds them into the view', async () => {
+ renderHook(() => useStore.getState().useFollowCounts(7));
+
+ const [call] = await syncCalls('discoverFollowCounts');
+ await call.fetcher();
+ expect(socialService.getFollowCounts).toHaveBeenCalledWith(7);
+
+ await fold('discoverFollowCounts', { followersCount: 3, followingCount: 9 });
+ expect(
+ socialSelectors.followCounts(socialUserKey({ userId: 7 }))(useStore.getState()),
+ ).toEqual({ followersCount: 3, followingCount: 9 });
+ });
+ });
+
+ describe('paged lists', () => {
+ it('requests a followers page with the page and page size', async () => {
+ renderHook(() => useStore.getState().useFollowers(5, { page: 2, pageSize: 20 }));
+
+ const [call] = await syncCalls('discoverFollowers');
+ await call.fetcher();
+
+ expect(socialService.getFollowers).toHaveBeenCalledWith(5, { page: 2, pageSize: 20 });
+ });
+
+ it('keys each page as its own entry', () => {
+ const { result } = renderHook(() => [
+ useStore.getState().useFollowers(5, { page: 1 }),
+ useStore.getState().useFollowers(5, { page: 2 }),
+ ]);
+
+ expect(new Set(result.current.map((sync) => sync.queryKey)).size).toBe(2);
+ });
+
+ it('folds a favorites page into the view the selector reads', async () => {
+ renderHook(() => useStore.getState().useFavoriteAgents(5, { page: 1, pageSize: 20 }));
+
+ const [call] = await syncCalls('discoverFavoriteAgents');
+ await call.fetcher();
+ expect(socialService.getUserFavoriteAgents).toHaveBeenCalledWith(5, {
+ page: 1,
+ pageSize: 20,
+ });
+
+ const page = makePage({ identifier: 'agent-1' });
+ await fold('discoverFavoriteAgents', page);
+
+ const key = socialListKey({ page: 1, pageSize: 20, userId: 5 });
+ expect(socialSelectors.favoriteAgents(key)(useStore.getState())).toEqual(page);
+ });
+
+ it('reports no value for a disabled list entry', () => {
+ expect(socialSelectors.followers(undefined)(useStore.getState())).toBeUndefined();
+ expect(socialSelectors.following(undefined)(useStore.getState())).toBeUndefined();
+ expect(socialSelectors.favoritePlugins(undefined)(useStore.getState())).toBeUndefined();
+ });
+ });
+
describe('follow', () => {
- it('optimistically increments target follower count after following', async () => {
- vi.spyOn(socialService, 'follow').mockResolvedValue();
- const action = new SocialActionImpl(vi.fn(), vi.fn());
+ const seedTarget = (followersCount = 2, followingCount = 7) => {
+ const key = socialUserKey({ userId: 42 });
+ useStore.setState({
+ followCountsMap: { [key]: { followersCount, followingCount } },
+ followStatusMap: { [key]: { isFollowing: false, isMutual: false } },
+ });
+ return key;
+ };
- await action.follow(42);
+ it('optimistically follows, commits, and refreshes the lists', async () => {
+ const key = seedTarget();
+ vi.mocked(socialService.follow).mockResolvedValue(undefined);
+
+ await useStore.getState().follow(42);
expect(socialService.follow).toHaveBeenCalledWith(42);
- expect(mutateMock).toHaveBeenCalledWith(
- discoverKeys.followStatus(42),
- { isFollowing: true, isMutual: false },
- { revalidate: false },
- );
-
- const countsCall = mutateMock.mock.calls.find(
- ([key]) => Array.isArray(key) && key[0] === discoverKeys.followCounts.root && key[1] === 42,
- );
- const updateCounts = countsCall?.[1] as
- | ((current?: FollowCounts) => FollowCounts)
- | undefined;
-
- expect(updateCounts?.({ followersCount: 2, followingCount: 7 })).toEqual({
- followersCount: 3,
- followingCount: 7,
- });
- expect(updateCounts?.()).toEqual({ followersCount: 1, followingCount: 0 });
+ expect(useStore.getState().followStatusMap[key]?.isFollowing).toBe(true);
+ expect(useStore.getState().followCountsMap[key]?.followersCount).toBe(3);
+ // The follower / following lists are refreshed after the toggle.
+ const matchers = mutateMock.mock.calls
+ .map(([matcher]) => matcher)
+ .filter((matcher) => typeof matcher === 'function');
+ const scope = followersResource.scope.get();
+ expect(
+ matchers.some((matcher) =>
+ matcher(replicaKeys.sync('discoverFollowers', 1, scope, '42', {})),
+ ),
+ ).toBe(true);
+ expect(
+ matchers.some((matcher) =>
+ matcher(replicaKeys.sync('discoverFollowing', 1, scope, '42', {})),
+ ),
+ ).toBe(true);
+ });
+
+ it('rolls the optimistic follow back when the server rejects it', async () => {
+ const key = seedTarget();
+ vi.mocked(socialService.follow).mockRejectedValue(new Error('nope'));
+
+ await expect(useStore.getState().follow(42)).rejects.toThrow('nope');
+
+ expect(useStore.getState().followStatusMap[key]?.isFollowing).toBe(false);
+ expect(useStore.getState().followCountsMap[key]?.followersCount).toBe(2);
});
});
describe('unfollow', () => {
- it('optimistically decrements target follower count after unfollowing', async () => {
- vi.spyOn(socialService, 'unfollow').mockResolvedValue();
- const action = new SocialActionImpl(vi.fn(), vi.fn());
+ it('optimistically unfollows and floors the follower count at zero', async () => {
+ const key = socialUserKey({ userId: 42 });
+ useStore.setState({
+ followCountsMap: { [key]: { followersCount: 0, followingCount: 7 } },
+ followStatusMap: { [key]: { isFollowing: true, isMutual: false } },
+ });
+ vi.mocked(socialService.unfollow).mockResolvedValue(undefined);
- await action.unfollow(42);
+ await useStore.getState().unfollow(42);
expect(socialService.unfollow).toHaveBeenCalledWith(42);
- expect(mutateMock).toHaveBeenCalledWith(
- discoverKeys.followStatus(42),
- { isFollowing: false, isMutual: false },
- { revalidate: false },
- );
-
- const countsCall = mutateMock.mock.calls.find(
- ([key]) => Array.isArray(key) && key[0] === discoverKeys.followCounts.root && key[1] === 42,
- );
- const updateCounts = countsCall?.[1] as
- | ((current?: FollowCounts) => FollowCounts)
- | undefined;
-
- expect(updateCounts?.({ followersCount: 2, followingCount: 7 })).toEqual({
- followersCount: 1,
- followingCount: 7,
- });
- expect(updateCounts?.({ followersCount: 0, followingCount: 7 })).toEqual({
- followersCount: 0,
- followingCount: 7,
- });
+ expect(useStore.getState().followStatusMap[key]?.isFollowing).toBe(false);
+ expect(useStore.getState().followCountsMap[key]?.followersCount).toBe(0);
+ });
+ });
+
+ describe('favorites', () => {
+ it('refreshes the favorite replicas after adding a favorite', async () => {
+ vi.mocked(socialService.addFavorite).mockResolvedValue(undefined);
+
+ await useStore.getState().addFavorite('agent', 42);
+
+ expect(socialService.addFavorite).toHaveBeenCalledWith('agent', 42);
+ const matchers = mutateMock.mock.calls
+ .map(([matcher]) => matcher)
+ .filter((matcher) => typeof matcher === 'function');
+ const scope = followersResource.scope.get();
+ expect(
+ matchers.some((matcher) =>
+ matcher(replicaKeys.sync('discoverFavoriteAgents', 1, scope, 'key', {})),
+ ),
+ ).toBe(true);
+ expect(
+ matchers.some((matcher) =>
+ matcher(replicaKeys.sync('discoverFavoritePlugins', 1, scope, 'key', {})),
+ ),
+ ).toBe(true);
+ });
+ });
+
+ describe('toggleLike', () => {
+ it('returns the server result', async () => {
+ vi.mocked(socialService.toggleLike).mockResolvedValue({ liked: true });
+
+ await expect(useStore.getState().toggleLike('plugin', 42)).resolves.toEqual({ liked: true });
+ expect(socialService.toggleLike).toHaveBeenCalledWith('plugin', 42);
+ });
+ });
+
+ describe('replica key helpers', () => {
+ it('produces stable, distinct keys per query dimension', () => {
+ expect(socialUserKey({ userId: 1 })).toBe(socialUserKey({ userId: 1 }));
+ expect(socialUserKey({ userId: 1 })).not.toBe(socialUserKey({ userId: 2 }));
+
+ expect(socialListKey({ page: 1, userId: 1 })).toBe(socialListKey({ page: 1, userId: 1 }));
+ expect(socialListKey({ page: 1, userId: 1 })).not.toBe(socialListKey({ page: 2, userId: 1 }));
+ expect(socialListKey({ page: 1, userId: 1 })).not.toBe(socialListKey({ page: 1, userId: 2 }));
});
});
});
diff --git a/src/store/discover/slices/social/action.ts b/src/store/discover/slices/social/action.ts
index c68edf2cbf4..cd2f8b436a2 100644
--- a/src/store/discover/slices/social/action.ts
+++ b/src/store/discover/slices/social/action.ts
@@ -1,8 +1,4 @@
-import { type SWRResponse } from 'swr';
-import useSWR from 'swr';
-
-import { mutate } from '@/libs/swr';
-import { discoverKeys } from '@/libs/swr/keys';
+import { createReplicaSlice, recordLens, type ReplicaSyncResult } from '@/libs/replica';
import {
type FavoriteAgentItem,
type FavoritePluginItem,
@@ -15,165 +11,312 @@ import {
import { socialService } from '@/services/social';
import { type DiscoverStore } from '@/store/discover';
import { type StoreSetter } from '@/store/types';
+import { setNamespace } from '@/utils/storeDebug';
+
+import {
+ favoriteAgentsResource,
+ favoritePluginsResource,
+ followCountsResource,
+ followersResource,
+ followingResource,
+ followStatusResource,
+ socialListKey,
+ type SocialListParams,
+ socialUserKey,
+ type SocialUserParams,
+} from './projection';
+
+const n = setNamespace('discover/social');
+
+/**
+ * Sync flags of a social read, plus the aliases the old SWR hooks returned
+ * (`isLoading` / `mutate`) so a call site only has to move its `data` read to
+ * the matching `socialSelectors` entry.
+ */
+export interface SocialSyncResult extends ReplicaSyncResult {
+ /** A request is in flight and this entry has no value to show yet. */
+ isLoading: boolean;
+ /** Alias of `revalidate`. */
+ mutate: () => Promise<unknown>;
+ /** Read the value with `socialSelectors.*(queryKey)`; undefined while disabled. */
+ queryKey?: string;
+}
type Setter = StoreSetter<DiscoverStore>;
-export const createSocialSlice = (set: Setter, get: () => DiscoverStore, _api?: unknown) =>
- new SocialActionImpl(set, get, _api);
+/** The follower-count delta a viewer's follow toggle applies to the target. */
const optimisticFollowCounts =
(isFollowing: boolean) =>
- (current?: FollowCounts): FollowCounts => {
- const followersCount = current?.followersCount ?? 0;
+ (current: FollowCounts): FollowCounts => ({
+ followersCount: isFollowing
+ ? current.followersCount + 1
+ : Math.max(0, current.followersCount - 1),
+ followingCount: current.followingCount,
+ });
- return {
- followersCount: isFollowing ? followersCount + 1 : Math.max(0, followersCount - 1),
- followingCount: current?.followingCount ?? 0,
- };
- };
+/** Normalized params of a `socialUserKey` read (status / counts). */
+const userParams = (userId: number): SocialUserParams => ({ userId });
+
+/** Normalized params of a `socialListKey` read (followers / following / favorites). */
+const listParams = (
+ userId: number,
+ params?: { page?: number; pageSize?: number },
+): SocialListParams => ({ page: params?.page, pageSize: params?.pageSize, userId });
-const updateFollowCaches = async (followingId: number, isFollowing: boolean) => {
- await Promise.all([
- mutate(
- discoverKeys.followStatus(followingId),
- {
- isFollowing,
- isMutual: false,
- } satisfies FollowStatus,
- { revalidate: false },
- ),
- mutate(discoverKeys.followCounts(followingId), optimisticFollowCounts(isFollowing), {
- revalidate: false,
- }),
- mutate(
- (key) =>
- Array.isArray(key) &&
- (key[0] === discoverKeys.followers.root || key[0] === discoverKeys.following.root),
- undefined,
- {
- revalidate: true,
- },
- ),
- ]);
-};
+/** A disabled hook never loads; a settled entry with a value never flashes. */
+const toSyncResult = (
+ sync: ReplicaSyncResult,
+ queryKey: string,
+ hasValue: boolean,
+ active: boolean,
+): SocialSyncResult => ({
+ ...sync,
+ isLoading: active && !hasValue && (!sync.isHydrated || sync.isValidating),
+ mutate: sync.revalidate,
+ queryKey: active ? queryKey : undefined,
+});
+
+export const createSocialSlice = (set: Setter, get: () => DiscoverStore, _api?: unknown) =>
+ new SocialActionImpl(set, get, _api);
export class SocialActionImpl {
+ readonly #favoriteAgents;
+ readonly #favoritePlugins;
+ readonly #followCounts;
+ readonly #followStatus;
+ readonly #followers;
+ readonly #following;
+ readonly #get: () => DiscoverStore;
+
constructor(set: Setter, get: () => DiscoverStore, _api?: unknown) {
void _api;
- void set;
- void get;
+ this.#get = get;
+ this.#followStatus = createReplicaSlice(followStatusResource, {
+ actionPrefix: n('followStatus'),
+ get,
+ set,
+ stateKey: 'followStatusReplica',
+ view: recordLens<DiscoverStore, FollowStatus>('followStatusMap'),
+ });
+ this.#followCounts = createReplicaSlice(followCountsResource, {
+ actionPrefix: n('followCounts'),
+ get,
+ set,
+ stateKey: 'followCountsReplica',
+ view: recordLens<DiscoverStore, FollowCounts>('followCountsMap'),
+ });
+ this.#followers = createReplicaSlice(followersResource, {
+ actionPrefix: n('followers'),
+ get,
+ set,
+ stateKey: 'followersReplica',
+ view: recordLens<DiscoverStore, PaginatedResponse<FollowUserItem>>('followersMap'),
+ });
+ this.#following = createReplicaSlice(followingResource, {
+ actionPrefix: n('following'),
+ get,
+ set,
+ stateKey: 'followingReplica',
+ view: recordLens<DiscoverStore, PaginatedResponse<FollowUserItem>>('followingMap'),
+ });
+ this.#favoriteAgents = createReplicaSlice(favoriteAgentsResource, {
+ actionPrefix: n('favoriteAgents'),
+ get,
+ set,
+ stateKey: 'favoriteAgentsReplica',
+ view: recordLens<DiscoverStore, PaginatedResponse<FavoriteAgentItem>>('favoriteAgentsMap'),
+ });
+ this.#favoritePlugins = createReplicaSlice(favoritePluginsResource, {
+ actionPrefix: n('favoritePlugins'),
+ get,
+ set,
+ stateKey: 'favoritePluginsReplica',
+ view: recordLens<DiscoverStore, PaginatedResponse<FavoritePluginItem>>('favoritePluginsMap'),
+ });
}
- addFavorite = async (targetType: SocialTargetType, targetId: number): Promise<void> => {
- await socialService.addFavorite(targetType, targetId);
- // Invalidate favorite-related caches
- await mutate(
- (key) =>
- Array.isArray(key) &&
- (key[0] === discoverKeys.favoriteAgents.root ||
- key[0] === discoverKeys.favoritePlugins.root),
- undefined,
- {
- revalidate: true,
- },
+ /**
+ * Whether the viewer follows the target user. Read it with
+ * `socialSelectors.followStatus(queryKey)`; `undefined` while unloaded.
+ */
+ useFollowStatus = (userId?: number): SocialSyncResult => {
+ const active = typeof userId === 'number';
+ const params = userParams(userId ?? 0);
+ const queryKey = socialUserKey(params);
+ const sync = this.#followStatus.useSync(active ? params : null, {
+ enabled: active,
+ revalidateOnFocus: false,
+ });
+ return toSyncResult(
+ sync,
+ queryKey,
+ active && this.#get().followStatusMap[queryKey] !== undefined,
+ active,
);
};
- follow = async (followingId: number): Promise<void> => {
- await socialService.follow(followingId);
- await updateFollowCaches(followingId, true);
- };
-
- removeFavorite = async (targetType: SocialTargetType, targetId: number): Promise<void> => {
- await socialService.removeFavorite(targetType, targetId);
- // Invalidate favorite-related caches
- await mutate(
- (key) =>
- Array.isArray(key) &&
- (key[0] === discoverKeys.favoriteAgents.root ||
- key[0] === discoverKeys.favoritePlugins.root),
- undefined,
- {
- revalidate: true,
- },
+ /**
+ * The target user's follower / following counts. Read them with
+ * `socialSelectors.followCounts(queryKey)`.
+ */
+ useFollowCounts = (userId?: number): SocialSyncResult => {
+ const active = typeof userId === 'number';
+ const params = userParams(userId ?? 0);
+ const queryKey = socialUserKey(params);
+ const sync = this.#followCounts.useSync(active ? params : null, {
+ enabled: active,
+ revalidateOnFocus: false,
+ });
+ return toSyncResult(
+ sync,
+ queryKey,
+ active && this.#get().followCountsMap[queryKey] !== undefined,
+ active,
);
};
- toggleLike = async (
- targetType: SocialTargetType,
- targetId: number,
- ): Promise<{ liked: boolean }> => {
- const result = await socialService.toggleLike(targetType, targetId);
- // Invalidate like-related caches
- await mutate((key) => typeof key === 'string' && key.startsWith('liked-'), undefined, {
- revalidate: true,
+ /** A user's followers page. Read it with `socialSelectors.followers(queryKey)`. */
+ useFollowers = (
+ userId: number | undefined,
+ params?: { page?: number; pageSize?: number },
+ ): SocialSyncResult => {
+ const active = typeof userId === 'number';
+ const normalized = listParams(userId ?? 0, params);
+ const queryKey = socialListKey(normalized);
+ const sync = this.#followers.useSync(active ? normalized : null, {
+ enabled: active,
+ revalidateOnFocus: false,
});
- return result;
+ return toSyncResult(
+ sync,
+ queryKey,
+ active && this.#get().followersMap[queryKey] !== undefined,
+ active,
+ );
};
- unfollow = async (followingId: number): Promise<void> => {
- await socialService.unfollow(followingId);
- await updateFollowCaches(followingId, false);
+ /** A user's following page. Read it with `socialSelectors.following(queryKey)`. */
+ useFollowing = (
+ userId: number | undefined,
+ params?: { page?: number; pageSize?: number },
+ ): SocialSyncResult => {
+ const active = typeof userId === 'number';
+ const normalized = listParams(userId ?? 0, params);
+ const queryKey = socialListKey(normalized);
+ const sync = this.#following.useSync(active ? normalized : null, {
+ enabled: active,
+ revalidateOnFocus: false,
+ });
+ return toSyncResult(
+ sync,
+ queryKey,
+ active && this.#get().followingMap[queryKey] !== undefined,
+ active,
+ );
};
+ /** A user's favorited agents page. Read it with `socialSelectors.favoriteAgents(queryKey)`. */
useFavoriteAgents = (
userId: number | undefined,
params?: { page?: number; pageSize?: number },
- ): SWRResponse<PaginatedResponse<FavoriteAgentItem>> => {
- return useSWR(
- userId ? discoverKeys.favoriteAgents(userId, params) : null,
- async () => socialService.getUserFavoriteAgents(userId!, params),
- { revalidateOnFocus: false },
+ ): SocialSyncResult => {
+ const active = typeof userId === 'number';
+ const normalized = listParams(userId ?? 0, params);
+ const queryKey = socialListKey(normalized);
+ const sync = this.#favoriteAgents.useSync(active ? normalized : null, {
+ enabled: active,
+ revalidateOnFocus: false,
+ });
+ return toSyncResult(
+ sync,
+ queryKey,
+ active && this.#get().favoriteAgentsMap[queryKey] !== undefined,
+ active,
);
};
+ /** A user's favorited plugins page. Read it with `socialSelectors.favoritePlugins(queryKey)`. */
useFavoritePlugins = (
userId: number | undefined,
params?: { page?: number; pageSize?: number },
- ): SWRResponse<PaginatedResponse<FavoritePluginItem>> => {
- return useSWR(
- userId ? discoverKeys.favoritePlugins(userId, params) : null,
- async () => socialService.getUserFavoritePlugins(userId!, params),
- { revalidateOnFocus: false },
+ ): SocialSyncResult => {
+ const active = typeof userId === 'number';
+ const normalized = listParams(userId ?? 0, params);
+ const queryKey = socialListKey(normalized);
+ const sync = this.#favoritePlugins.useSync(active ? normalized : null, {
+ enabled: active,
+ revalidateOnFocus: false,
+ });
+ return toSyncResult(
+ sync,
+ queryKey,
+ active && this.#get().favoritePluginsMap[queryKey] !== undefined,
+ active,
);
};
- useFollowCounts = (userId: number | undefined): SWRResponse<FollowCounts> => {
- return useSWR(
- userId ? discoverKeys.followCounts(userId) : null,
- async () => socialService.getFollowCounts(userId!),
- { revalidateOnFocus: false },
- );
+ /** Refresh every loaded favorites page after a favorite mutation. */
+ #refreshFavorites = async (): Promise<void> => {
+ await Promise.all([this.#favoriteAgents.revalidate(), this.#favoritePlugins.revalidate()]);
};
- useFollowStatus = (userId: number | undefined): SWRResponse<FollowStatus> => {
- return useSWR(
- userId ? discoverKeys.followStatus(userId) : null,
- async () => socialService.checkFollowStatus(userId!),
- { revalidateOnFocus: false },
- );
+ addFavorite = async (targetType: SocialTargetType, targetId: number): Promise<void> => {
+ await socialService.addFavorite(targetType, targetId);
+ await this.#refreshFavorites();
};
- useFollowers = (
- userId: number | undefined,
- params?: { page?: number; pageSize?: number },
- ): SWRResponse<PaginatedResponse<FollowUserItem>> => {
- return useSWR(
- userId ? discoverKeys.followers(userId, params) : null,
- async () => socialService.getFollowers(userId!, params),
- { revalidateOnFocus: false },
- );
+ removeFavorite = async (targetType: SocialTargetType, targetId: number): Promise<void> => {
+ await socialService.removeFavorite(targetType, targetId);
+ await this.#refreshFavorites();
};
- useFollowing = (
- userId: number | undefined,
- params?: { page?: number; pageSize?: number },
- ): SWRResponse<PaginatedResponse<FollowUserItem>> => {
- return useSWR(
- userId ? discoverKeys.following(userId, params) : null,
- async () => socialService.getFollowing(userId!, params),
- { revalidateOnFocus: false },
- );
+ /**
+ * One follow toggle: optimistically flip the status and shift the target's
+ * follower count, then confirm (or roll back) once the server answers. The
+ * follower / following lists are refreshed afterwards, because the toggle
+ * changes lists the viewer may have loaded for other profiles.
+ */
+ #setFollowing = async (
+ followingId: number,
+ isFollowing: boolean,
+ run: () => Promise<void>,
+ ): Promise<void> => {
+ const key = socialUserKey({ userId: followingId });
+ const status = this.#followStatus.beginOptimistic(key, (current) => ({
+ ...current,
+ isFollowing,
+ isMutual: false,
+ }));
+ const counts = this.#followCounts.beginOptimistic(key, optimisticFollowCounts(isFollowing));
+
+ try {
+ await run();
+ status.commit();
+ counts.commit();
+ } catch (error) {
+ status.rollback();
+ counts.rollback();
+ throw error;
+ }
+
+ await Promise.all([this.#followers.revalidate(), this.#following.revalidate()]);
};
+
+ follow = (followingId: number): Promise<void> =>
+ this.#setFollowing(followingId, true, () => socialService.follow(followingId));
+
+ unfollow = (followingId: number): Promise<void> =>
+ this.#setFollowing(followingId, false, () => socialService.unfollow(followingId));
+
+ /**
+ * Like / unlike a market target. The liked lists are not part of this slice's
+ * replica, so there is no local view to refresh β€” the call just reports the
+ * new state for the caller.
+ */
+ toggleLike = async (
+ targetType: SocialTargetType,
+ targetId: number,
+ ): Promise<{ liked: boolean }> => socialService.toggleLike(targetType, targetId);
}
export type SocialAction = Pick<SocialActionImpl, keyof SocialActionImpl>;
diff --git a/src/store/discover/slices/social/initialState.ts b/src/store/discover/slices/social/initialState.ts
new file mode 100644
index 00000000000..1367d503bd9
--- /dev/null
+++ b/src/store/discover/slices/social/initialState.ts
@@ -0,0 +1,57 @@
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
+import {
+ type FavoriteAgentItem,
+ type FavoritePluginItem,
+ type FollowCounts,
+ type FollowStatus,
+ type FollowUserItem,
+ type PaginatedResponse,
+} from '@/services/social';
+
+/**
+ * Replica views of the social reads, each beside its bookkeeping slot. The
+ * views are plain records keyed by the entry key of the matching resource
+ * (`projection.ts`); components read them through `socialSelectors`, never
+ * through the fetch hook.
+ */
+export interface SocialSliceState {
+ /** A user's favorited agents per query (`socialListKey`). */
+ favoriteAgentsMap: Record<string, PaginatedResponse<FavoriteAgentItem>>;
+ /** Replica bookkeeping of `favoriteAgentsMap`. */
+ favoriteAgentsReplica: ReplicaState<PaginatedResponse<FavoriteAgentItem>>;
+ /** A user's favorited plugins per query (`socialListKey`). */
+ favoritePluginsMap: Record<string, PaginatedResponse<FavoritePluginItem>>;
+ /** Replica bookkeeping of `favoritePluginsMap`. */
+ favoritePluginsReplica: ReplicaState<PaginatedResponse<FavoritePluginItem>>;
+ /** Target user's follower / following counts (`socialUserKey`). */
+ followCountsMap: Record<string, FollowCounts>;
+ /** Replica bookkeeping of `followCountsMap`. */
+ followCountsReplica: ReplicaState<FollowCounts>;
+ /** A user's followers per query (`socialListKey`). */
+ followersMap: Record<string, PaginatedResponse<FollowUserItem>>;
+ /** Replica bookkeeping of `followersMap`. */
+ followersReplica: ReplicaState<PaginatedResponse<FollowUserItem>>;
+ /** A user's following per query (`socialListKey`). */
+ followingMap: Record<string, PaginatedResponse<FollowUserItem>>;
+ /** Replica bookkeeping of `followingMap`. */
+ followingReplica: ReplicaState<PaginatedResponse<FollowUserItem>>;
+ /** Whether the viewer follows the target user (`socialUserKey`). */
+ followStatusMap: Record<string, FollowStatus>;
+ /** Replica bookkeeping of `followStatusMap`. */
+ followStatusReplica: ReplicaState<FollowStatus>;
+}
+
+export const initialSocialSliceState: SocialSliceState = {
+ favoriteAgentsMap: {},
+ favoriteAgentsReplica: createReplicaState(),
+ favoritePluginsMap: {},
+ favoritePluginsReplica: createReplicaState(),
+ followCountsMap: {},
+ followCountsReplica: createReplicaState(),
+ followStatusMap: {},
+ followStatusReplica: createReplicaState(),
+ followersMap: {},
+ followersReplica: createReplicaState(),
+ followingMap: {},
+ followingReplica: createReplicaState(),
+};
diff --git a/src/store/discover/slices/social/projection.ts b/src/store/discover/slices/social/projection.ts
new file mode 100644
index 00000000000..bc83fbb3178
--- /dev/null
+++ b/src/store/discover/slices/social/projection.ts
@@ -0,0 +1,105 @@
+import { defineReplica, stableQueryKey } from '@/libs/replica';
+import {
+ type FavoriteAgentItem,
+ type FavoritePluginItem,
+ type FollowCounts,
+ type FollowStatus,
+ type FollowUserItem,
+ type PaginatedResponse,
+} from '@/services/social';
+import { socialService } from '@/services/social';
+
+/**
+ * The social reads are **per viewer** and mostly read-only: the community
+ * profile paints the last confirmed follow state / counts / lists before the
+ * network answers, and one cache partition per identity (`cacheScope`) keeps a
+ * signed-in viewer from reading another account's rows.
+ *
+ * Each distinct query is its own entry (`key`), exactly like the SWR key it
+ * replaces β€” the follow status and counts are keyed by the target user, the
+ * paged lists by target user plus page / page size.
+ */
+
+/** A viewer-relative read addressed by the target user (status, counts). */
+export interface SocialUserParams {
+ userId: number;
+}
+
+/** One page of a user's followers / following / favorites. */
+export interface SocialListParams {
+ page?: number;
+ pageSize?: number;
+ userId: number;
+}
+
+/** Entry key of a per-user read (`followStatusMap[userId]`). */
+export const socialUserKey = ({ userId }: SocialUserParams): string => String(userId);
+
+/** Entry key of one page of a user's list β€” user, page and page size all matter. */
+export const socialListKey = (params: SocialListParams): string => stableQueryKey(params);
+
+/** Whether the viewer follows the target user (`followStatusMap[key]`). */
+export const followStatusResource = defineReplica<SocialUserParams, FollowStatus>({
+ fetcher: ({ userId }) => socialService.checkFollowStatus(userId),
+ key: socialUserKey,
+ name: 'discoverFollowStatus',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** The target user's follower / following counts (`followCountsMap[key]`). */
+export const followCountsResource = defineReplica<SocialUserParams, FollowCounts>({
+ fetcher: ({ userId }) => socialService.getFollowCounts(userId),
+ key: socialUserKey,
+ name: 'discoverFollowCounts',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** A user's followers (`followersMap[key]`). */
+export const followersResource = defineReplica<SocialListParams, PaginatedResponse<FollowUserItem>>(
+ {
+ fetcher: ({ page, pageSize, userId }) => socialService.getFollowers(userId, { page, pageSize }),
+ key: socialListKey,
+ name: 'discoverFollowers',
+ storage: 'indexedDB',
+ version: 1,
+ },
+);
+
+/** A user's following (`followingMap[key]`). */
+export const followingResource = defineReplica<SocialListParams, PaginatedResponse<FollowUserItem>>(
+ {
+ fetcher: ({ page, pageSize, userId }) => socialService.getFollowing(userId, { page, pageSize }),
+ key: socialListKey,
+ name: 'discoverFollowing',
+ storage: 'indexedDB',
+ version: 1,
+ },
+);
+
+/** A user's favorited agents (`favoriteAgentsMap[key]`). */
+export const favoriteAgentsResource = defineReplica<
+ SocialListParams,
+ PaginatedResponse<FavoriteAgentItem>
+>({
+ fetcher: ({ page, pageSize, userId }) =>
+ socialService.getUserFavoriteAgents(userId, { page, pageSize }),
+ key: socialListKey,
+ name: 'discoverFavoriteAgents',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** A user's favorited plugins (`favoritePluginsMap[key]`). */
+export const favoritePluginsResource = defineReplica<
+ SocialListParams,
+ PaginatedResponse<FavoritePluginItem>
+>({
+ fetcher: ({ page, pageSize, userId }) =>
+ socialService.getUserFavoritePlugins(userId, { page, pageSize }),
+ key: socialListKey,
+ name: 'discoverFavoritePlugins',
+ storage: 'indexedDB',
+ version: 1,
+});
diff --git a/src/store/discover/slices/user/action.test.ts b/src/store/discover/slices/user/action.test.ts
new file mode 100644
index 00000000000..ba30b79756e
--- /dev/null
+++ b/src/store/discover/slices/user/action.test.ts
@@ -0,0 +1,184 @@
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { discoverService } from '@/services/discover';
+import { globalHelpers } from '@/store/global/helpers';
+import { type DiscoverUserProfile } from '@/types/discover';
+
+import { userSelectors } from '../../selectors';
+import { useDiscoverStore as useStore } from '../../store';
+import { initialUserSliceState } from './initialState';
+import { userProfileQueryKey } from './projection';
+
+vi.mock('@/services/discover', () => ({
+ discoverService: {
+ getUserInfo: vi.fn(),
+ },
+}));
+
+// The replica schedules its fetches through the app's SWR driver; the engine
+// itself is what these tests exercise, so the driver is a bare recorder.
+vi.mock('@/libs/swr', () => ({
+ mutate: vi.fn(),
+ useClientDataSWR: vi.fn(() => ({ isValidating: false, mutate: vi.fn() })),
+}));
+
+const profile: DiscoverUserProfile = {
+ agents: [],
+ user: {
+ avatarUrl: null,
+ bannerUrl: null,
+ createdAt: '2024-01-01T00:00:00.000Z',
+ description: null,
+ displayName: 'Alice',
+ id: 1,
+ namespace: 'alice',
+ socialLinks: null,
+ type: null,
+ userName: 'alice',
+ },
+};
+
+/** The entry key `useUserProfile` derives in this test environment. */
+const entryKey = (username: string) =>
+ userProfileQueryKey({ locale: globalHelpers.getCurrentLanguage(), username });
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ useStore.setState({ ...initialUserSliceState });
+});
+
+/** The replica network syncs registered with the SWR driver, per resource name. */
+const syncCalls = async (name: string) => {
+ const { useClientDataSWR } = await import('@/libs/swr');
+ return vi
+ .mocked(useClientDataSWR)
+ .mock.calls.filter(
+ ([key]) => Array.isArray(key) && key[0] === 'replica:sync' && key[1] === name,
+ )
+ .map(([key, fetcher, config]) => ({
+ config: config as { onSuccess?: (data: unknown) => void; revalidateOnFocus?: boolean },
+ fetcher: fetcher as () => Promise<any>,
+ key: key as unknown[],
+ }));
+};
+
+const fold = async (name: string, data: unknown) => {
+ const [call] = await syncCalls(name);
+ act(() => call.config.onSuccess!(data));
+};
+
+describe('UserSlice (replica)', () => {
+ describe('useUserProfile', () => {
+ it('requests the community profile for the username', async () => {
+ renderHook(() => useStore.getState().useUserProfile({ username: 'alice' }));
+
+ const [call] = await syncCalls('discoverUserProfile');
+ await call.fetcher();
+
+ expect(discoverService.getUserInfo).toHaveBeenCalledWith({ username: 'alice' });
+ });
+
+ it('registers the network sync under the replica key of this entry', async () => {
+ renderHook(() => useStore.getState().useUserProfile({ username: 'alice' }));
+
+ const [call] = await syncCalls('discoverUserProfile');
+
+ expect(call.key[1]).toBe('discoverUserProfile');
+ expect(call.key[4]).toBe(entryKey('alice'));
+ });
+
+ it('keys each username as its own entry', () => {
+ const { result } = renderHook(() => [
+ useStore.getState().useUserProfile({ username: 'alice' }),
+ useStore.getState().useUserProfile({ username: 'bob' }),
+ ]);
+
+ expect(new Set(result.current.map((sync) => sync.queryKey)).size).toBe(2);
+ });
+
+ it('does not register a sync β€” and reports no loading β€” without a username', async () => {
+ const { result } = renderHook(() => useStore.getState().useUserProfile({ username: '' }));
+
+ expect(result.current.queryKey).toBeUndefined();
+ expect(result.current.isLoading).toBe(false);
+ expect(await syncCalls('discoverUserProfile')).toHaveLength(0);
+ });
+
+ it('reports loading until the entry has a value to show', () => {
+ const { result } = renderHook(() =>
+ useStore.getState().useUserProfile({ username: 'alice' }),
+ );
+
+ expect(result.current.isLoading).toBe(true);
+ });
+
+ it('does not report loading when the entry already has a value', () => {
+ useStore.setState({ userProfileMap: { [entryKey('alice')]: profile } });
+
+ const { result } = renderHook(() =>
+ useStore.getState().useUserProfile({ username: 'alice' }),
+ );
+
+ expect(result.current.queryKey).toBe(entryKey('alice'));
+ expect(result.current.isLoading).toBe(false);
+ });
+
+ it('folds the response into the replica view the selector reads', async () => {
+ renderHook(() => useStore.getState().useUserProfile({ username: 'alice' }));
+ await fold('discoverUserProfile', profile);
+
+ expect(userSelectors.userProfile(entryKey('alice'))(useStore.getState())).toEqual(profile);
+ });
+
+ it('leaves the entry absent when the server does not know the handle', async () => {
+ renderHook(() => useStore.getState().useUserProfile({ username: 'ghost' }));
+ await fold('discoverUserProfile', undefined);
+
+ expect(userSelectors.userProfile(entryKey('ghost'))(useStore.getState())).toBeUndefined();
+ });
+
+ it('drops a cached profile once the server no longer knows the handle', async () => {
+ renderHook(() => useStore.getState().useUserProfile({ username: 'alice' }));
+ const [call] = await syncCalls('discoverUserProfile');
+
+ vi.mocked(discoverService.getUserInfo).mockResolvedValueOnce(profile);
+ const cached = await call.fetcher();
+ act(() => call.config.onSuccess!(cached));
+ expect(userSelectors.userProfile(entryKey('alice'))(useStore.getState())).toEqual(profile);
+
+ // The handle was deleted or renamed: the service answers `undefined`.
+ vi.mocked(discoverService.getUserInfo).mockResolvedValueOnce(undefined);
+ const missing = await call.fetcher();
+ act(() => call.config.onSuccess!(missing));
+
+ expect(userSelectors.userProfile(entryKey('alice'))(useStore.getState())).toBeUndefined();
+ expect(useStore.getState().userProfileMap[entryKey('alice')]).toBeUndefined();
+ });
+
+ it('does not revalidate the profile on window focus', async () => {
+ renderHook(() => useStore.getState().useUserProfile({ username: 'alice' }));
+
+ const [call] = await syncCalls('discoverUserProfile');
+ expect(call.config.revalidateOnFocus).toBe(false);
+ });
+
+ it('reads undefined for a disabled entry', () => {
+ expect(userSelectors.userProfile(undefined)(useStore.getState())).toBeUndefined();
+ });
+ });
+
+ describe('replica key helpers', () => {
+ it('produces stable, distinct keys per username and locale', () => {
+ expect(userProfileQueryKey({ locale: 'en-US', username: 'a' })).toBe(
+ userProfileQueryKey({ locale: 'en-US', username: 'a' }),
+ );
+ expect(userProfileQueryKey({ locale: 'en-US', username: 'a' })).not.toBe(
+ userProfileQueryKey({ locale: 'en-US', username: 'b' }),
+ );
+ expect(userProfileQueryKey({ locale: 'en-US', username: 'a' })).not.toBe(
+ userProfileQueryKey({ locale: 'zh-CN', username: 'a' }),
+ );
+ });
+ });
+});
diff --git a/src/store/discover/slices/user/action.ts b/src/store/discover/slices/user/action.ts
index d5abf843502..1196f6af336 100644
--- a/src/store/discover/slices/user/action.ts
+++ b/src/store/discover/slices/user/action.ts
@@ -1,33 +1,78 @@
-import { type SWRResponse } from 'swr';
-import useSWR from 'swr';
-
-import { discoverKeys } from '@/libs/swr/keys';
-import { discoverService } from '@/services/discover';
+import { createReplicaSlice, recordLens, type ReplicaSyncResult } from '@/libs/replica';
import { type DiscoverStore } from '@/store/discover';
import { globalHelpers } from '@/store/global/helpers';
import { type StoreSetter } from '@/store/types';
import { type DiscoverUserProfile } from '@/types/discover';
+import { setNamespace } from '@/utils/storeDebug';
+
+import { type UserProfileParams, userProfileQueryKey, userProfileResource } from './projection';
+
+const n = setNamespace('discover/user');
+
+/**
+ * Sync flags of a community profile read, plus the aliases the old SWR hook
+ * returned (`isLoading` / `mutate`) so a call site only has to move its `data`
+ * read to `userSelectors.userProfile(fetchHook.queryKey)`.
+ */
+export interface UserProfileSyncResult extends ReplicaSyncResult {
+ /** A request is in flight and this entry has no value to show yet. */
+ isLoading: boolean;
+ /** Alias of `revalidate`. */
+ mutate: () => Promise<unknown>;
+ /** Read the value with `userSelectors.userProfile(queryKey)`; undefined while disabled. */
+ queryKey?: string;
+}
type Setter = StoreSetter<DiscoverStore>;
+
export const createUserSlice = (set: Setter, get: () => DiscoverStore, _api?: unknown) =>
new UserActionImpl(set, get, _api);
export class UserActionImpl {
+ readonly #get: () => DiscoverStore;
+ readonly #profile;
+
constructor(set: Setter, get: () => DiscoverStore, _api?: unknown) {
void _api;
- void set;
- void get;
+ this.#get = get;
+ this.#profile = createReplicaSlice(userProfileResource, {
+ actionPrefix: n('profile'),
+ get,
+ // The server no longer knows this handle: drop the entry and its
+ // persisted row rather than keep serving the cached profile.
+ isMissing: (profile) => profile === null,
+ set,
+ stateKey: 'userProfileReplica',
+ view: recordLens<DiscoverStore, DiscoverUserProfile>('userProfileMap'),
+ });
}
- useUserProfile = (params: { username: string }): SWRResponse<DiscoverUserProfile | undefined> => {
- const locale = globalHelpers.getCurrentLanguage();
- return useSWR(
- params.username ? discoverKeys.userProfile(locale, params.username) : null,
- async () => discoverService.getUserInfo({ username: params.username }),
- {
- revalidateOnFocus: false,
- },
- );
+ /**
+ * A community user / organization profile by username. Read it with
+ * `userSelectors.userProfile(queryKey)`; `undefined` while unloaded or for a
+ * handle the server does not know. A blank username disables the read.
+ */
+ useUserProfile = (params: { username: string }): UserProfileSyncResult => {
+ const active = params.username.length > 0;
+ const normalized: UserProfileParams = {
+ locale: globalHelpers.getCurrentLanguage(),
+ username: params.username,
+ };
+ const queryKey = userProfileQueryKey(normalized);
+ const sync = this.#profile.useSync(active ? normalized : null, {
+ enabled: active,
+ revalidateOnFocus: false,
+ });
+
+ return {
+ ...sync,
+ isLoading:
+ active &&
+ this.#get().userProfileMap[queryKey] === undefined &&
+ (!sync.isHydrated || sync.isValidating),
+ mutate: sync.revalidate,
+ queryKey: active ? queryKey : undefined,
+ };
};
}
diff --git a/src/store/discover/slices/user/initialState.ts b/src/store/discover/slices/user/initialState.ts
new file mode 100644
index 00000000000..b52d1ba5dcf
--- /dev/null
+++ b/src/store/discover/slices/user/initialState.ts
@@ -0,0 +1,19 @@
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
+import { type DiscoverUserProfile } from '@/types/discover';
+
+/**
+ * Replica view of the community profile reads, beside its bookkeeping slot.
+ * The view is a plain record keyed by the profile's username (`projection.ts`);
+ * components read it through `userSelectors`, never through the fetch hook.
+ */
+export interface UserSliceState {
+ /** A community user / organization profile per username (`userProfileKey`). */
+ userProfileMap: Record<string, DiscoverUserProfile>;
+ /** Replica bookkeeping of `userProfileMap`. */
+ userProfileReplica: ReplicaState<DiscoverUserProfile>;
+}
+
+export const initialUserSliceState: UserSliceState = {
+ userProfileMap: {},
+ userProfileReplica: createReplicaState(),
+};
diff --git a/src/store/discover/slices/user/projection.ts b/src/store/discover/slices/user/projection.ts
new file mode 100644
index 00000000000..a4b067076aa
--- /dev/null
+++ b/src/store/discover/slices/user/projection.ts
@@ -0,0 +1,36 @@
+import { defineReplica, stableQueryKey } from '@/libs/replica';
+import { discoverService } from '@/services/discover';
+import { type DiscoverUserProfile } from '@/types/discover';
+
+/**
+ * A community profile read, addressed by the profile's username. Profile copy
+ * is resolved in the viewer's language, so a locale switch is a different
+ * entry β€” exactly like the SWR key it replaces (`[locale, username]`).
+ *
+ * The server answers `undefined` for a handle it does not know (a 404 profile).
+ * The fetcher turns that into `null` so the slice's `isMissing` drops the entry
+ * (memory and persisted row) β€” a deleted or renamed handle stops painting its
+ * cached profile β€” and the surface falls back to "not found" once the sync
+ * settles.
+ */
+export interface UserProfileParams {
+ /** Current UI language; part of the entry so a locale switch refetches. */
+ locale: string;
+ username: string;
+}
+
+/** Entry key of one community profile (`userProfileMap[queryKey]`). */
+export const userProfileQueryKey = (params: UserProfileParams): string => stableQueryKey(params);
+
+/** A community user / organization profile (`userProfileMap[queryKey]`). */
+export const userProfileResource = defineReplica<
+ UserProfileParams,
+ DiscoverUserProfile,
+ DiscoverUserProfile | null
+>({
+ fetcher: async ({ username }) => (await discoverService.getUserInfo({ username })) ?? null,
+ key: userProfileQueryKey,
+ name: 'discoverUserProfile',
+ storage: 'indexedDB',
+ version: 1,
+});
diff --git a/src/store/test-coverage.md b/src/store/test-coverage.md
index 53185efa1c9..223696848f3 100644
--- a/src/store/test-coverage.md
+++ b/src/store/test-coverage.md
@@ -318,8 +318,8 @@ Task({
prompt: `Write comprehensive tests for src/store/discover/slices/plugin/action.ts following .agents/skills/testing/references/zustand-store-action-test.md.
Requirements:
-1. Write tests covering all actions (usePluginCategories, usePluginDetail, usePluginList, usePluginIdentifiers)
-2. Follow SWR hooks testing pattern
+1. Write tests covering all actions (useFetchPluginCategories, useFetchPluginDetail, useFetchPluginList, useFetchPluginIdentifiers)
+2. Follow the replica-backed fetch hook testing pattern
3. run type-check and lint to verify
4. Run tests to ensure they pass
5. Report back with number of tests written and coverage areas
@@ -532,7 +532,7 @@ bunx eslint src/store/[domain]/
- **Coverage**: 74.24% overall (+26 tests, 2 new test files)
- **New Test Files**:
- - `discover/slices/plugin/action.test.ts` - 15 tests covering plugin discovery (SWR hooks)
+ - `discover/slices/plugin/action.test.ts` - tests covering plugin discovery (replica fetch hooks)
- `discover/slices/mcp/action.test.ts` - 11 tests covering MCP discovery (SWR hooks)
- **Features Tested**:
- Plugin categories, detail, identifiers, and list fetching