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.

fix: align agent categories with search results (#18714)

YuTengjingda866a91c02b
diff --git a/apps/server/src/routers/lambda/market/index.ts b/apps/server/src/routers/lambda/market/index.ts
index 856f066c9cb..73a8fe1d017 100644
--- a/apps/server/src/routers/lambda/market/index.ts
+++ b/apps/server/src/routers/lambda/market/index.ts
@@ -166,6 +166,7 @@ export const marketRouter = router({
category: z.string().optional(),
connectionType: z.nativeEnum(McpConnectionType).optional(),
includeAgentGroup: z.boolean().optional(),
+ includeCategoryCounts: z.boolean().optional(),
locale: z.string().optional(),
order: z.enum(['asc', 'desc']).optional(),
ownerId: z.string().optional(),
diff --git a/apps/server/src/services/discover/index.test.ts b/apps/server/src/services/discover/index.test.ts
index f14aa673781..bd5d7750094 100644
--- a/apps/server/src/services/discover/index.test.ts
+++ b/apps/server/src/services/discover/index.test.ts
@@ -262,6 +262,10 @@ describe('DiscoverService', () => {
mockMarket = {
agents: {
getAgentList: vi.fn().mockResolvedValue({
+ categoryCounts: [
+ { category: 'creativity', count: 1 },
+ { category: 'productivity', count: 1 },
+ ],
items: mockMarketAssistantList,
totalCount: mockMarketAssistantList.length,
currentPage: 1,
@@ -312,9 +316,11 @@ describe('DiscoverService', () => {
describe('Assistant Market (new source)', () => {
it('getAssistantList should transform market SDK response', async () => {
- const result = await service.getAssistantList();
+ const result = await service.getAssistantList({ includeCategoryCounts: true });
- expect(mockMarket.agents.getAgentList).toHaveBeenCalled();
+ expect(mockMarket.agents.getAgentList).toHaveBeenCalledWith(
+ expect.objectContaining({ includeCategoryCounts: true }),
+ );
expect(result.items[0]).toEqual(
expect.objectContaining({
identifier: 'market-assistant-1',
@@ -324,6 +330,10 @@ describe('DiscoverService', () => {
pluginCount: 1,
}),
);
+ expect(result.categoryCounts).toEqual([
+ { category: 'creativity', count: 1 },
+ { category: 'productivity', count: 1 },
+ ]);
});
it('getAssistantList should preserve a successful empty response in strict mode', async () => {
diff --git a/apps/server/src/services/discover/index.ts b/apps/server/src/services/discover/index.ts
index 974d569667c..026c5633654 100644
--- a/apps/server/src/services/discover/index.ts
+++ b/apps/server/src/services/discover/index.ts
@@ -689,6 +689,7 @@ export class DiscoverService {
sort = AssistantSorts.Recommended,
ownerId,
includeAgentGroup,
+ includeCategoryCounts,
} = rest;
const shouldOmitCategory = [AssistantCategory.All, AssistantCategory.Discover].includes(
category as AssistantCategory,
@@ -729,6 +730,7 @@ export class DiscoverService {
haveSkills,
// includeAgentGroup may not be in SDK type definition yet, using 'as any'
includeAgentGroup,
+ includeCategoryCounts,
locale: normalizedLocale,
order,
ownerId,
@@ -767,6 +769,7 @@ export class DiscoverService {
});
const result: AssistantListResponse = {
+ ...((data as any).categoryCounts ? { categoryCounts: (data as any).categoryCounts } : {}),
currentPage: data.currentPage || page,
items: transformedItems,
pageSize: data.pageSize || pageSize,
diff --git a/packages/types/src/discover/assistants.ts b/packages/types/src/discover/assistants.ts
index 8baffbf53b4..7dbc50c7ae3 100644
--- a/packages/types/src/discover/assistants.ts
+++ b/packages/types/src/discover/assistants.ts
@@ -76,6 +76,7 @@ export interface AssistantQueryParams {
category?: string;
haveSkills?: boolean;
includeAgentGroup?: boolean;
+ includeCategoryCounts?: boolean;
locale?: string;
order?: 'asc' | 'desc';
ownerId?: string;
@@ -87,6 +88,7 @@ export interface AssistantQueryParams {
}
export interface AssistantListResponse {
+ categoryCounts?: { category: string; count: number }[];
currentPage: number;
items: DiscoverAssistantItem[];
pageSize: number;
diff --git a/src/features/CommunityAgentList/assistantListQuery.test.ts b/src/features/CommunityAgentList/assistantListQuery.test.ts
new file mode 100644
index 00000000000..1ad31f65ce1
--- /dev/null
+++ b/src/features/CommunityAgentList/assistantListQuery.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from 'vitest';
+
+import { AssistantSorts } from '@/types/discover';
+
+import { buildAssistantListQuery } from './assistantListQuery';
+
+describe('buildAssistantListQuery', () => {
+ it('should request the mixed list and category counts with one shared query', () => {
+ expect(buildAssistantListQuery({ page: 2, q: 'pptx' })).toEqual({
+ category: undefined,
+ includeAgentGroup: true,
+ includeCategoryCounts: true,
+ order: undefined,
+ page: 2,
+ pageSize: 21,
+ q: 'pptx',
+ sort: AssistantSorts.Recommended,
+ source: undefined,
+ });
+ });
+
+ it('should preserve the browse path when there is no keyword search', () => {
+ expect(buildAssistantListQuery({})).toEqual({
+ category: undefined,
+ includeAgentGroup: true,
+ includeCategoryCounts: false,
+ order: undefined,
+ page: undefined,
+ pageSize: 21,
+ q: undefined,
+ sort: AssistantSorts.Recommended,
+ source: undefined,
+ });
+ });
+});
diff --git a/src/features/CommunityAgentList/assistantListQuery.ts b/src/features/CommunityAgentList/assistantListQuery.ts
new file mode 100644
index 00000000000..955381c0b45
--- /dev/null
+++ b/src/features/CommunityAgentList/assistantListQuery.ts
@@ -0,0 +1,14 @@
+import { type AssistantQueryParams, AssistantSorts } from '@/types/discover';
+
+/** Keep the list and category sidebar on the same SWR request. */
+export const buildAssistantListQuery = (params: AssistantQueryParams): AssistantQueryParams => ({
+ category: params.category,
+ includeAgentGroup: true,
+ includeCategoryCounts: Boolean(params.q?.trim()),
+ order: params.order,
+ page: params.page,
+ pageSize: 21,
+ q: params.q,
+ sort: params.sort ?? AssistantSorts.Recommended,
+ source: params.source,
+});
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 61040783a6f..b3460b333bc 100644
--- a/src/routes/(main)/community/(list)/agent/features/Category/index.tsx
+++ b/src/routes/(main)/community/(list)/agent/features/Category/index.tsx
@@ -5,24 +5,29 @@ import qs from 'query-string';
import { memo, useMemo } from 'react';
import { withSuspense } from '@/components/withSuspense';
+import { buildAssistantListQuery } from '@/features/CommunityAgentList/assistantListQuery';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
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 { AssistantCategory, AssistantSorts } from '@/types/discover';
+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 {
- category = AssistantCategory.Discover,
- q,
- source,
- } = useQuery() as { category?: AssistantCategory; q?: string; source?: string };
- const { data: items = [] } = useAssistantCategories({ q, source: source as any });
+ const useAssistantList = useDiscoverStore((s) => s.useAssistantList);
+ 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(
+ { q, source },
+ { enabled: shouldLoadFallbackCategories },
+ );
+ 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 9890410a985..547117b7b4d 100644
--- a/src/routes/(main)/community/(list)/agent/index.tsx
+++ b/src/routes/(main)/community/(list)/agent/index.tsx
@@ -4,10 +4,11 @@ import { Flexbox } from '@lobehub/ui';
import { memo } from 'react';
import AsyncBoundary from '@/components/AsyncBoundary';
+import { buildAssistantListQuery } from '@/features/CommunityAgentList/assistantListQuery';
import { useQuery } from '@/hooks/useQuery';
import { useDiscoverStore } from '@/store/discover';
import { type AssistantQueryParams } from '@/types/discover';
-import { AssistantSorts, DiscoverTab } from '@/types/discover';
+import { DiscoverTab } from '@/types/discover';
import AssistantEmpty from '../../features/AssistantEmpty';
import Pagination from '../features/Pagination';
@@ -15,18 +16,9 @@ import List from './features/List';
import Loading from './loading';
const AssistantPage = memo(() => {
- const { q, page, category, sort, order, source } = useQuery() as AssistantQueryParams;
+ const query = useQuery() as AssistantQueryParams;
const useAssistantList = useDiscoverStore((s) => s.useAssistantList);
- const { data, isLoading, error, mutate } = useAssistantList({
- category,
- includeAgentGroup: true,
- order,
- page,
- pageSize: 21,
- q,
- sort: sort ?? AssistantSorts.Recommended,
- source,
- });
+ const { data, isLoading, error, mutate } = useAssistantList(buildAssistantListQuery(query));
const items = data?.items ?? [];
diff --git a/src/store/discover/slices/assistant/action.test.ts b/src/store/discover/slices/assistant/action.test.ts
index 96c39bc9fe7..7943ebc2b91 100644
--- a/src/store/discover/slices/assistant/action.test.ts
+++ b/src/store/discover/slices/assistant/action.test.ts
@@ -1,4 +1,4 @@
-import { renderHook, waitFor } from '@testing-library/react';
+import { act, renderHook, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { discoverService } from '@/services/discover';
@@ -48,6 +48,17 @@ describe('AssistantAction', () => {
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();
+ });
});
describe('useAssistantDetail', () => {
@@ -112,6 +123,32 @@ describe('AssistantAction', () => {
});
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');
+
+ const q = `keep-previous-${Date.now()}`;
+ const { rerender, result } = renderHook(
+ ({ page }) => useStore.getState().useAssistantList({ page, q }, { keepPreviousData: true }),
+ { initialProps: { page: 1 } },
+ );
+ await waitFor(() => expect(result.current.data).toEqual(firstPage));
+
+ rerender({ page: 2 });
+ expect(result.current.data).toEqual(firstPage);
+
+ await act(async () => resolveSecondPage(secondPage));
+ await waitFor(() => expect(result.current.data).toEqual(secondPage));
+ });
+
it('should fetch assistant list with default parameters', async () => {
const mockList = {
items: [{ identifier: 'assistant-1' }, { identifier: 'assistant-2' }],
diff --git a/src/store/discover/slices/assistant/action.ts b/src/store/discover/slices/assistant/action.ts
index d8e98788946..ea39f07f867 100644
--- a/src/store/discover/slices/assistant/action.ts
+++ b/src/store/discover/slices/assistant/action.ts
@@ -28,10 +28,11 @@ export class AssistantActionImpl {
useAssistantCategories = (
params: CategoryListQuery & { source?: AssistantMarketSource },
+ options: { enabled?: boolean } = {},
): SWRResponse<CategoryItem[]> => {
const locale = globalHelpers.getCurrentLanguage();
return useSWR(
- discoverKeys.assistantCategories(locale, params),
+ options.enabled === false ? null : discoverKeys.assistantCategories(locale, params),
async () => discoverService.getAssistantCategories(params),
{
revalidateOnFocus: false,
@@ -66,7 +67,10 @@ export class AssistantActionImpl {
);
};
- useAssistantList = (params: AssistantQueryParams = {}): SWRResponse<AssistantListResponse> => {
+ useAssistantList = (
+ params: AssistantQueryParams = {},
+ options: { keepPreviousData?: boolean } = {},
+ ): SWRResponse<AssistantListResponse> => {
const locale = globalHelpers.getCurrentLanguage();
return useSWR(
discoverKeys.assistantList(locale, params),
@@ -77,6 +81,7 @@ export class AssistantActionImpl {
pageSize: params.pageSize ? Number(params.pageSize) : 21,
}),
{
+ keepPreviousData: options.keepPreviousData,
revalidateOnFocus: false,
},
);