🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
♻️ refactor(discover): move the group-agent market slice onto @lobechat/replica (#20703)
Arvin Xu66b87377ba79
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 8b7ed2b37a8..7d55a1f15fc 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -490,28 +490,6 @@ export const discoverKeys = {userId,params,]),- groupAgentCategories: def('discover:groupAgentCategories', (locale: string, params: unknown) => [- 'discover:groupAgentCategories',- locale,- params,- ]),- groupAgentDetail: def(- 'discover:groupAgentDetail',- (locale: string, identifier: string, version?: string) => [- 'discover:groupAgentDetail',- locale,- identifier,- version,- ],- ),- groupAgentIdentifiers: def('discover:groupAgentIdentifiers', () => [- 'discover:groupAgentIdentifiers',- ]),- groupAgentList: def('discover:groupAgentList', (locale: string, params: unknown) => [- 'discover:groupAgentList',- locale,- params,- ]),modelCategories: def('discover:modelCategories', (params: unknown) => ['discover:modelCategories',params,diff --git a/src/routes/(main)/community/(detail)/group_agent/index.tsx b/src/routes/(main)/community/(detail)/group_agent/index.tsxindex 8b4fa0f40e1..d408d4944b6 100644--- a/src/routes/(main)/community/(detail)/group_agent/index.tsx+++ b/src/routes/(main)/community/(detail)/group_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 { groupAgentSelectors } from '@/store/discover/selectors';import NotFound from '../components/NotFound';import { TocProvider } from '../features/Toc/useToc';@@ -26,8 +27,10 @@ const GroupAgentDetailPage = memo<GroupAgentDetailPageProps>(({ mobile }) => {const { version } = useQuery() as { version?: string };// Fetch group agent detail- const useGroupAgentDetail = useDiscoverStore((s) => s.useGroupAgentDetail);- const { data, error, isLoading, mutate } = useGroupAgentDetail({ identifier, version });+ const useGroupAgentDetail = useDiscoverStore((s) => s.useFetchGroupAgentDetail);+ const { error, isLoading, mutate, queryKey } = useGroupAgentDetail({ identifier, version });+ // The replica view of this query; the sync hook only reports the fetch flags.+ const data = useDiscoverStore(groupAgentSelectors.groupAgentDetail(queryKey));if (data === undefined) {if (isLoading) return <RouteLoading />;diff --git a/src/store/discover/initialState.ts b/src/store/discover/initialState.tsindex b008d3a088d..9784c210566 100644--- a/src/store/discover/initialState.ts+++ b/src/store/discover/initialState.ts@@ -1,3 +1,5 @@+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 { ProviderSliceState } from './slices/provider/initialState';@@ -7,9 +9,10 @@ import { initialProviderSliceState } from './slices/provider/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 = MCPSliceState & ProviderSliceState;+export type DiscoverStoreState = GroupAgentSliceState & MCPSliceState & ProviderSliceState;export const initialState: DiscoverStoreState = {+ ...initialGroupAgentSliceState,...initialMCPSliceState,...initialProviderSliceState,};diff --git a/src/store/discover/selectors/groupAgentSelectors.ts b/src/store/discover/selectors/groupAgentSelectors.tsnew file mode 100644index 00000000000..b9645666fbe--- /dev/null+++ b/src/store/discover/selectors/groupAgentSelectors.ts@@ -0,0 +1,43 @@+import type { CategoryItem } from '@lobehub/market-sdk';++import type {+ DiscoverGroupAgentDetail,+ GroupAgentListResponse,+ IdentifiersResponse,+} from '@/types/discover';++import type { DiscoverStore } from '../store';++const EMPTY_CATEGORIES: CategoryItem[] = [];++/**+ * Readers of the group-agent 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 groupAgentList =+ (queryKey?: string) =>+ (s: DiscoverStore): GroupAgentListResponse | undefined =>+ queryKey ? s.groupAgentListMap[queryKey] : undefined;++const groupAgentDetail =+ (queryKey?: string) =>+ (s: DiscoverStore): DiscoverGroupAgentDetail | undefined =>+ queryKey ? s.groupAgentDetailMap[queryKey] : undefined;++const groupAgentCategories =+ (queryKey?: string) =>+ (s: DiscoverStore): CategoryItem[] =>+ (queryKey && s.groupAgentCategoriesMap[queryKey]) || EMPTY_CATEGORIES;++const groupAgentIdentifiers =+ (queryKey?: string) =>+ (s: DiscoverStore): IdentifiersResponse | undefined =>+ queryKey ? s.groupAgentIdentifiersMap[queryKey] : undefined;++export const groupAgentSelectors = {+ groupAgentCategories,+ groupAgentDetail,+ groupAgentIdentifiers,+ groupAgentList,+};diff --git a/src/store/discover/selectors/index.ts b/src/store/discover/selectors/index.tsindex c11b0fd5b4e..536803c2abb 100644--- a/src/store/discover/selectors/index.ts+++ b/src/store/discover/selectors/index.ts@@ -1,2 +1,3 @@+export { groupAgentSelectors } from './groupAgentSelectors';export { mcpSelectors } from './mcpSelectors';export { providerSelectors } from './providerSelectors';diff --git a/src/store/discover/slices/groupAgent/action.test.ts b/src/store/discover/slices/groupAgent/action.test.tsnew file mode 100644index 00000000000..44c47c93501--- /dev/null+++ b/src/store/discover/slices/groupAgent/action.test.ts@@ -0,0 +1,290 @@+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { createReplicaState } from '@/libs/replica';+import { globalHelpers } from '@/store/global/helpers';+import type { GroupAgentListResponse } from '@/types/discover';++import { groupAgentSelectors } from '../../selectors';+import { useDiscoverStore as useStore } from '../../store';+import {+ groupAgentCategoriesQueryKey,+ groupAgentDetailQueryKey,+ groupAgentIdentifiersQueryKey,+ groupAgentListQueryKey,+} from './projection';++vi.mock('@/services/discover', () => ({+ discoverService: {+ getGroupAgentCategories: vi.fn(),+ getGroupAgentDetail: vi.fn(),+ getGroupAgentIdentifiers: vi.fn(),+ getGroupAgentList: 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 = 'group-agent-1'): GroupAgentListResponse => ({+ currentPage: 1,+ items: [{ identifier } as any],+ totalCount: 1,+ totalPages: 1,+});++const emptyGroupAgentState = () => ({+ groupAgentCategoriesMap: {},+ groupAgentCategoriesReplica: createReplicaState(),+ groupAgentDetailMap: {},+ groupAgentDetailReplica: createReplicaState(),+ groupAgentIdentifiersMap: {},+ groupAgentIdentifiersReplica: createReplicaState(),+ groupAgentListMap: {},+ groupAgentListReplica: createReplicaState(),+});++beforeEach(() => {+ vi.clearAllMocks();+ vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');+ useStore.setState(emptyGroupAgentState());+});++/** The replica network syncs registered with the SWR driver, per resource name. */+const syncCalls = async (+ name: 'groupAgentCategories' | 'groupAgentDetail' | 'groupAgentIdentifiers' | 'groupAgentList',+) => {+ 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('GroupAgentSlice (replica)', () => {+ it('does not revalidate any group-agent read on window focus', async () => {+ renderHook(() => {+ const state = useStore.getState();+ state.useFetchGroupAgentList();+ state.useFetchGroupAgentDetail({ identifier: 'group-1' });+ state.useFetchGroupAgentCategories();+ state.useFetchGroupAgentIdentifiers();+ });++ for (const name of [+ 'groupAgentList',+ 'groupAgentDetail',+ 'groupAgentCategories',+ 'groupAgentIdentifiers',+ ] as const) {+ const calls = await syncCalls(name);+ expect(calls.length).toBeGreaterThan(0);+ for (const call of calls) expect(call.config.revalidateOnFocus).toBe(false);+ }+ });++ describe('useFetchGroupAgentList', () => {+ it('requests the list with normalized page / pageSize and the locale', async () => {+ const { discoverService } = await import('@/services/discover');++ renderHook(() => useStore.getState().useFetchGroupAgentList({ q: 'coding' }));++ const [call] = await syncCalls('groupAgentList');+ await call.fetcher();++ expect(discoverService.getGroupAgentList).toHaveBeenCalledWith({+ locale: 'en-US',+ page: 1,+ pageSize: 20,+ q: 'coding',+ });+ });++ it('keys each page and filter set as its own replica entry', () => {+ const { result } = renderHook(() => [+ useStore.getState().useFetchGroupAgentList({ page: 1 }),+ useStore.getState().useFetchGroupAgentList({ page: 2 }),+ useStore.getState().useFetchGroupAgentList({ category: 'development' }),+ ]);++ 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().useFetchGroupAgentList({ page: 1 }, { enabled: false }),+ );++ expect(result.current.queryKey).toBeUndefined();+ expect(result.current.isLoading).toBe(false);+ expect(await syncCalls('groupAgentList')).toHaveLength(0);+ });++ it('reports loading until the entry has a value to show', () => {+ const { result } = renderHook(() => useStore.getState().useFetchGroupAgentList({ page: 1 }));++ expect(result.current.isLoading).toBe(true);+ });++ it('does not report loading when the entry already has a (hydrated) value', () => {+ const key = groupAgentListQueryKey({ locale: 'en-US', page: 1, pageSize: 20 });+ useStore.setState({ groupAgentListMap: { [key]: makeList() } });++ const { result } = renderHook(() => useStore.getState().useFetchGroupAgentList({ 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().useFetchGroupAgentList({ page: 1 }));+ const [call] = await syncCalls('groupAgentList');+ act(() => call.config.onSuccess!(response));++ const key = groupAgentListQueryKey({ locale: 'en-US', page: 1, pageSize: 20 });+ expect(groupAgentSelectors.groupAgentList(key)(useStore.getState())).toEqual(response);+ });+ });++ describe('useFetchGroupAgentDetail', () => {+ it('requests the detail with identifier / version / locale', async () => {+ const { discoverService } = await import('@/services/discover');++ renderHook(() =>+ useStore+ .getState()+ .useFetchGroupAgentDetail({ identifier: 'writing-team', version: '1.0.0' }),+ );++ const [call] = await syncCalls('groupAgentDetail');+ await call.fetcher();++ expect(discoverService.getGroupAgentDetail).toHaveBeenCalledWith({+ identifier: 'writing-team',+ locale: 'en-US',+ version: '1.0.0',+ });+ });++ it('drops a cached detail once the market reports the group gone', async () => {+ const { discoverService } = await import('@/services/discover');++ const { result } = renderHook(() =>+ useStore.getState().useFetchGroupAgentDetail({ identifier: 'group-1' }),+ );+ const key = result.current.queryKey!;+ const [call] = await syncCalls('groupAgentDetail');++ vi.mocked(discoverService.getGroupAgentDetail).mockResolvedValueOnce({+ identifier: 'group-1',+ } as any);+ const cached = await call.fetcher();+ act(() => call.config.onSuccess!(cached));+ expect(groupAgentSelectors.groupAgentDetail(key)(useStore.getState())).toEqual({+ identifier: 'group-1',+ });++ // The listing was deleted: the service answers `undefined`.+ vi.mocked(discoverService.getGroupAgentDetail).mockResolvedValueOnce(undefined);+ const missing = await call.fetcher();+ act(() => call.config.onSuccess!(missing));++ expect(groupAgentSelectors.groupAgentDetail(key)(useStore.getState())).toBeUndefined();+ expect(useStore.getState().groupAgentDetailMap[key]).toBeUndefined();+ });++ it('keys the detail by identifier and version', () => {+ const { result } = renderHook(() => [+ useStore.getState().useFetchGroupAgentDetail({ identifier: 'writing-team' }),+ useStore+ .getState()+ .useFetchGroupAgentDetail({ identifier: 'writing-team', version: '1.0.0' }),+ useStore.getState().useFetchGroupAgentDetail({ identifier: 'research-team' }),+ ]);++ expect(new Set(result.current.map((sync) => sync.queryKey)).size).toBe(3);+ });++ it('keys the detail by the locale, so a language switch refetches', () => {+ const { result, rerender } = renderHook(() =>+ useStore.getState().useFetchGroupAgentDetail({ identifier: 'writing-team' }),+ );+ const first = result.current.queryKey;++ vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('zh-CN');+ rerender();++ expect(result.current.queryKey).not.toBe(first);+ });+ });++ describe('useFetchGroupAgentCategories', () => {+ it('requests category counts with the search term and locale', async () => {+ const { discoverService } = await import('@/services/discover');++ renderHook(() => useStore.getState().useFetchGroupAgentCategories({ q: 'coding' }));++ const [call] = await syncCalls('groupAgentCategories');+ await call.fetcher();++ expect(discoverService.getGroupAgentCategories).toHaveBeenCalledWith({+ locale: 'en-US',+ q: 'coding',+ });+ });++ it('skips the request when disabled', async () => {+ const { result } = renderHook(() =>+ useStore.getState().useFetchGroupAgentCategories({}, { enabled: false }),+ );++ expect(result.current.queryKey).toBeUndefined();+ expect(await syncCalls('groupAgentCategories')).toHaveLength(0);+ });++ it('falls back to an empty list when no category entry is loaded', () => {+ expect(groupAgentSelectors.groupAgentCategories(undefined)(useStore.getState())).toEqual([]);+ expect(groupAgentSelectors.groupAgentList(undefined)(useStore.getState())).toBeUndefined();+ expect(groupAgentSelectors.groupAgentDetail(undefined)(useStore.getState())).toBeUndefined();+ });+ });++ describe('useFetchGroupAgentIdentifiers', () => {+ it('requests the identifier index of the market', async () => {+ const { discoverService } = await import('@/services/discover');++ renderHook(() => useStore.getState().useFetchGroupAgentIdentifiers());++ const [call] = await syncCalls('groupAgentIdentifiers');+ await call.fetcher();++ expect(discoverService.getGroupAgentIdentifiers).toHaveBeenCalled();+ });+ });++ describe('replica key helpers', () => {+ it('produces stable, distinct keys per query dimension', () => {+ expect(groupAgentListQueryKey({ locale: 'en-US', page: 1, pageSize: 20 })).toBe(+ groupAgentListQueryKey({ locale: 'en-US', page: 1, pageSize: 20 }),+ );+ expect(groupAgentDetailQueryKey({ identifier: 'a' })).not.toBe(+ groupAgentDetailQueryKey({ identifier: 'b' }),+ );+ expect(groupAgentCategoriesQueryKey({ q: 'a' })).not.toBe(groupAgentCategoriesQueryKey({}));+ expect(groupAgentIdentifiersQueryKey()).toBe(groupAgentIdentifiersQueryKey({}));+ });+ });+});diff --git a/src/store/discover/slices/groupAgent/action.ts b/src/store/discover/slices/groupAgent/action.tsindex 282bc30047f..e9d6b881ba8 100644--- a/src/store/discover/slices/groupAgent/action.ts+++ b/src/store/discover/slices/groupAgent/action.ts@@ -1,78 +1,189 @@-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 DiscoverGroupAgentDetail,- type GroupAgentListResponse,- type GroupAgentQueryParams,- type IdentifiersResponse,+import type { StoreSetter } from '@/store/types';+import type {+ DiscoverGroupAgentDetail,+ GroupAgentListResponse,+ GroupAgentQueryParams,+ IdentifiersResponse,} from '@/types/discover';+import { setNamespace } from '@/utils/storeDebug';++import {+ type GroupAgentCategoriesParams,+ groupAgentCategoriesQueryKey,+ groupAgentCategoriesResource,+ type GroupAgentDetailParams,+ groupAgentDetailQueryKey,+ groupAgentDetailResource,+ type GroupAgentIdentifiersParams,+ groupAgentIdentifiersQueryKey,+ groupAgentIdentifiersResource,+ type GroupAgentListParams,+ groupAgentListQueryKey,+ groupAgentListResource,+} from './projection';++const n = setNamespace('discover/groupAgent');++/**+ * 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 `groupAgentSelectors` entry.+ */+export interface GroupAgentSyncResult 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 `groupAgentSelectors.*(queryKey)`; undefined while disabled. */+ queryKey?: string;+}type Setter = StoreSetter<DiscoverStore>;+export const createGroupAgentSlice = (set: Setter, get: () => DiscoverStore, _api?: unknown) =>new GroupAgentActionImpl(set, get, _api);export class GroupAgentActionImpl {+ 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(groupAgentListResource, {+ actionPrefix: n('list'),+ get,+ set,+ stateKey: 'groupAgentListReplica',+ view: recordLens<DiscoverStore, GroupAgentListResponse>('groupAgentListMap'),+ });+ this.#detail = createReplicaSlice(groupAgentDetailResource, {+ actionPrefix: n('detail'),+ get,+ // The market no longer has this group: drop the entry and its persisted+ // row rather than keep serving the cached copy.+ isMissing: (detail) => detail === null,+ set,+ stateKey: 'groupAgentDetailReplica',+ view: recordLens<DiscoverStore, DiscoverGroupAgentDetail>('groupAgentDetailMap'),+ });+ this.#categories = createReplicaSlice(groupAgentCategoriesResource, {+ actionPrefix: n('categories'),+ get,+ set,+ stateKey: 'groupAgentCategoriesReplica',+ view: recordLens<DiscoverStore, CategoryItem[]>('groupAgentCategoriesMap'),+ });+ this.#identifiers = createReplicaSlice(groupAgentIdentifiersResource, {+ actionPrefix: n('identifiers'),+ get,+ set,+ stateKey: 'groupAgentIdentifiersReplica',+ view: recordLens<DiscoverStore, IdentifiersResponse>('groupAgentIdentifiersMap'),+ });}- useGroupAgentCategories = (params: CategoryListQuery = {}): SWRResponse<CategoryItem[]> => {- const locale = globalHelpers.getCurrentLanguage();- return useSWR(- discoverKeys.groupAgentCategories(locale, params),- async () => discoverService.getGroupAgentCategories(params),- {- revalidateOnFocus: false,- },- );+ #toSyncResult = (+ sync: ReplicaSyncResult,+ queryKey: string | undefined,+ hasValue: boolean,+ active: boolean,+ ): GroupAgentSyncResult => ({+ ...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 group-agent 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 `groupAgentSelectors.groupAgentList(queryKey)`.+ */+ useFetchGroupAgentList = (+ params: GroupAgentQueryParams = {},+ options: { enabled?: boolean } = {},+ ): GroupAgentSyncResult => {+ const { enabled = true } = options;+ const normalized: GroupAgentListParams = {+ ...params,+ locale: globalHelpers.getCurrentLanguage(),+ page: params.page ? Number(params.page) : 1,+ pageSize: params.pageSize ? Number(params.pageSize) : 20,+ };+ const queryKey = groupAgentListQueryKey(normalized);+ const sync = this.#list.useSync(normalized, { enabled, revalidateOnFocus: false });+ return this.#toSyncResult(sync, queryKey, !!this.#get().groupAgentListMap[queryKey], enabled);};- useGroupAgentDetail = (params: {- identifier: string;- version?: string;- }): SWRResponse<DiscoverGroupAgentDetail | undefined> => {- const locale = globalHelpers.getCurrentLanguage();- return useSWR(- discoverKeys.groupAgentDetail(locale, params.identifier, params.version),- async () => discoverService.getGroupAgentDetail(params),- {- revalidateOnFocus: false,- },+ /**+ * One group-agent detail (identifier · version). Read it with+ * `groupAgentSelectors.groupAgentDetail(queryKey)`; `undefined` after the sync+ * settles means the market has no such identifier.+ */+ useFetchGroupAgentDetail = (+ params: GroupAgentDetailParams,+ options: { enabled?: boolean } = {},+ ): GroupAgentSyncResult => {+ const { enabled = true } = options;+ const normalized: GroupAgentDetailParams = {+ identifier: params.identifier,+ locale: globalHelpers.getCurrentLanguage(),+ version: params.version,+ };+ const queryKey = groupAgentDetailQueryKey(normalized);+ const sync = this.#detail.useSync(normalized, { enabled, revalidateOnFocus: false });+ return this.#toSyncResult(+ sync,+ queryKey,+ this.#get().groupAgentDetailMap[queryKey] !== undefined,+ enabled,);};- useGroupAgentIdentifiers = (): SWRResponse<IdentifiersResponse> => {- return useSWR(- discoverKeys.groupAgentIdentifiers(),- async () => discoverService.getGroupAgentIdentifiers(),- {- revalidateOnFocus: false,- },+ /**+ * Category counts of one query (the search term). The community sidebar reads+ * `groupAgentSelectors.groupAgentCategories(queryKey)`.+ */+ useFetchGroupAgentCategories = (+ params: GroupAgentCategoriesParams = {},+ options: { enabled?: boolean } = {},+ ): GroupAgentSyncResult => {+ const { enabled = true } = options;+ const normalized: GroupAgentCategoriesParams = {+ ...params,+ locale: globalHelpers.getCurrentLanguage(),+ };+ const queryKey = groupAgentCategoriesQueryKey(normalized);+ const sync = this.#categories.useSync(normalized, { enabled, revalidateOnFocus: false });+ return this.#toSyncResult(+ sync,+ queryKey,+ !!this.#get().groupAgentCategoriesMap[queryKey],+ enabled,);};- useGroupAgentList = (params: GroupAgentQueryParams = {}): SWRResponse<GroupAgentListResponse> => {- const locale = globalHelpers.getCurrentLanguage();- return useSWR(- discoverKeys.groupAgentList(locale, params),- async () =>- discoverService.getGroupAgentList({- ...params,- page: params.page ? Number(params.page) : 1,- pageSize: params.pageSize ? Number(params.pageSize) : 20,- }),- {- revalidateOnFocus: false,- },+ /** The group-agent identifier index of the market. */+ useFetchGroupAgentIdentifiers = (options: { enabled?: boolean } = {}): GroupAgentSyncResult => {+ const { enabled = true } = options;+ const params: GroupAgentIdentifiersParams = {};+ const queryKey = groupAgentIdentifiersQueryKey(params);+ const sync = this.#identifiers.useSync(params, { enabled, revalidateOnFocus: false });+ return this.#toSyncResult(+ sync,+ queryKey,+ !!this.#get().groupAgentIdentifiersMap[queryKey],+ enabled,);};}diff --git a/src/store/discover/slices/groupAgent/initialState.ts b/src/store/discover/slices/groupAgent/initialState.tsnew file mode 100644index 00000000000..f8b35d9cf96--- /dev/null+++ b/src/store/discover/slices/groupAgent/initialState.ts@@ -0,0 +1,44 @@+import type { CategoryItem } from '@lobehub/market-sdk';++import { createReplicaState, type ReplicaState } from '@/libs/replica';+import type {+ DiscoverGroupAgentDetail,+ GroupAgentListResponse,+ IdentifiersResponse,+} from '@/types/discover';++/**+ * Replica views of the group-agent 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+ * `groupAgentSelectors`, never through the fetch hook.+ */+export interface GroupAgentSliceState {+ /** Category counts per query (`groupAgentCategoriesQueryKey`). */+ groupAgentCategoriesMap: Record<string, CategoryItem[]>;+ /** Replica bookkeeping of `groupAgentCategoriesMap`. */+ groupAgentCategoriesReplica: ReplicaState<CategoryItem[]>;+ /** Group-agent detail per identifier / version (`groupAgentDetailQueryKey`). */+ groupAgentDetailMap: Record<string, DiscoverGroupAgentDetail>;+ /** Replica bookkeeping of `groupAgentDetailMap`. */+ groupAgentDetailReplica: ReplicaState<DiscoverGroupAgentDetail>;+ /** Identifier index of the market (`groupAgentIdentifiersQueryKey`). */+ groupAgentIdentifiersMap: Record<string, IdentifiersResponse>;+ /** Replica bookkeeping of `groupAgentIdentifiersMap`. */+ groupAgentIdentifiersReplica: ReplicaState<IdentifiersResponse>;+ /** Group-agent list per query (`groupAgentListQueryKey`). */+ groupAgentListMap: Record<string, GroupAgentListResponse>;+ /** Replica bookkeeping of `groupAgentListMap`. */+ groupAgentListReplica: ReplicaState<GroupAgentListResponse>;+}++export const initialGroupAgentSliceState: GroupAgentSliceState = {+ groupAgentCategoriesMap: {},+ groupAgentCategoriesReplica: createReplicaState(),+ groupAgentDetailMap: {},+ groupAgentDetailReplica: createReplicaState(),+ groupAgentIdentifiersMap: {},+ groupAgentIdentifiersReplica: createReplicaState(),+ groupAgentListMap: {},+ groupAgentListReplica: createReplicaState(),+};diff --git a/src/store/discover/slices/groupAgent/projection.ts b/src/store/discover/slices/groupAgent/projection.tsnew file mode 100644index 00000000000..9548d3dbf47--- /dev/null+++ b/src/store/discover/slices/groupAgent/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 {+ DiscoverGroupAgentDetail,+ GroupAgentListResponse,+ GroupAgentQueryParams,+ IdentifiersResponse,+} from '@/types/discover';++/**+ * The marketplace group-agent 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 `groupAgentList` params — the shape actually sent to the market endpoint. */+export interface GroupAgentListParams extends Omit<GroupAgentQueryParams, 'page' | 'pageSize'> {+ /** Current UI language; part of the entry so a locale switch refetches. */+ locale?: string;+ page: number;+ pageSize: number;+}++/**+ * Entry key of one group-agent list query. Includes the page, because the list+ * pages through the URL instead of appending pages to one entry.+ */+export const groupAgentListQueryKey = (params: GroupAgentListParams): string =>+ stableQueryKey(params);++export interface GroupAgentDetailParams {+ identifier: string;+ /** Current UI language; the market resolves localized copy server-side. */+ locale?: string;+ version?: string;+}++/** Entry key of one group-agent detail (`identifier` + version, localized). */+export const groupAgentDetailQueryKey = (params: GroupAgentDetailParams): string =>+ stableQueryKey(params);++export interface GroupAgentCategoriesParams extends CategoryListQuery {+ /** Current UI language; the market resolves localized category labels. */+ locale?: string;+}++/** Entry key of one category-counts query (the search term). */+export const groupAgentCategoriesQueryKey = (params: GroupAgentCategoriesParams): string =>+ stableQueryKey(params);++/** The group-agent identifier index takes no query — one entry for the whole index. */+export type GroupAgentIdentifiersParams = Record<string, never>;++/** Entry key of the group-agent identifier index. */+export const groupAgentIdentifiersQueryKey = (params: GroupAgentIdentifiersParams = {}): string =>+ stableQueryKey(params);++/**+ * Group-agent market list, one entry per query (`groupAgentListMap[queryKey]`).+ * The response already carries everything a row reader needs (`items`,+ * `currentPage`, `pageSize`, `totalCount`, `totalPages`), so it is stored as-is.+ */+export const groupAgentListResource = defineReplica<GroupAgentListParams, GroupAgentListResponse>({+ fetcher: (params) => discoverService.getGroupAgentList(params),+ key: groupAgentListQueryKey,+ name: 'groupAgentList',+ storage: 'indexedDB',+ version: 1,+});++/**+ * One group-agent detail by identifier / version (`groupAgentDetailMap[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 across reloads. The page then reaches "not+ * found" once the sync settles.+ */+export const groupAgentDetailResource = defineReplica<+ GroupAgentDetailParams,+ DiscoverGroupAgentDetail,+ DiscoverGroupAgentDetail | null+>({+ fetcher: async (params) => (await discoverService.getGroupAgentDetail(params)) ?? null,+ key: groupAgentDetailQueryKey,+ name: 'groupAgentDetail',+ storage: 'indexedDB',+ version: 1,+});++/**+ * Category counts of one query (`groupAgentCategoriesMap[queryKey]`). Small and+ * read on almost every community group screen, so localStorage keeps the first+ * frame populated instead of flashing an empty sidebar.+ */+export const groupAgentCategoriesResource = defineReplica<+ GroupAgentCategoriesParams,+ CategoryItem[]+>({+ fetcher: (params) => discoverService.getGroupAgentCategories(params),+ key: groupAgentCategoriesQueryKey,+ name: 'groupAgentCategories',+ storage: 'localStorage',+ version: 1,+});++/** The group-agent identifier index (`groupAgentIdentifiersMap[queryKey]`). */+export const groupAgentIdentifiersResource = defineReplica<+ GroupAgentIdentifiersParams,+ IdentifiersResponse+>({+ fetcher: () => discoverService.getGroupAgentIdentifiers(),+ key: groupAgentIdentifiersQueryKey,+ name: 'groupAgentIdentifiers',+ storage: 'localStorage',+ version: 1,+});