mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-01-01 16:18:51 +01:00
refactor: unify agent marketplace to single endpoint with cursor pagination
- Replace multiple marketplace routes with unified /marketplace endpoint - Add query string controls: category, search, limit, cursor, promoted, requiredPermission - Implement cursor-based pagination replacing page-based system - Integrate ACL permissions for proper access control - Fix ObjectId constructor error in Agent model - Update React components to use unified useGetMarketplaceAgentsQuery hook - Enhance type safety and remove deprecated useDynamicAgentQuery - Update tests for new marketplace architecture -Known issues: see more button after category switching + Unit tests
This commit is contained in:
parent
be7476d530
commit
2eef94d58d
22 changed files with 458 additions and 1128 deletions
|
|
@ -1,4 +1,4 @@
|
|||
import React, { useEffect, useState } from 'react';
|
||||
import React, { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
useFormContext,
|
||||
|
|
@ -10,7 +10,6 @@ import {
|
|||
} from 'react-hook-form';
|
||||
import ControlCombobox from '~/components/ui/ControlCombobox';
|
||||
import { useAgentCategories } from '~/hooks/Agents';
|
||||
import { OptionWithIcon } from '~/common/types';
|
||||
import { cn } from '~/utils';
|
||||
|
||||
/**
|
||||
|
|
@ -20,7 +19,9 @@ const useCategorySync = (agent_id: string | null) => {
|
|||
const [handled, setHandled] = useState(false);
|
||||
|
||||
return {
|
||||
syncCategory: (field: ControllerRenderProps<FieldValues, FieldPath<FieldValues>>) => {
|
||||
syncCategory: <T extends FieldPath<FieldValues>>(
|
||||
field: ControllerRenderProps<FieldValues, T>,
|
||||
) => {
|
||||
// Only run once and only for new agents
|
||||
if (!handled && agent_id === '' && !field.value) {
|
||||
field.onChange('general');
|
||||
|
|
@ -33,7 +34,7 @@ const useCategorySync = (agent_id: string | null) => {
|
|||
/**
|
||||
* A component for selecting agent categories with form validation
|
||||
*/
|
||||
const AgentCategorySelector: React.FC = () => {
|
||||
const AgentCategorySelector: React.FC<{ className?: string }> = ({ className }) => {
|
||||
const { t } = useTranslation();
|
||||
const formContext = useFormContext();
|
||||
const { categories } = useAgentCategories();
|
||||
|
|
@ -81,7 +82,7 @@ const AgentCategorySelector: React.FC = () => {
|
|||
field.onChange(value);
|
||||
}}
|
||||
items={comboboxItems}
|
||||
className=""
|
||||
className={cn(className)}
|
||||
ariaLabel={ariaLabel}
|
||||
isCollapsed={false}
|
||||
showCarat={true}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,8 @@ import React, { useState } from 'react';
|
|||
|
||||
import type t from 'librechat-data-provider';
|
||||
|
||||
import { useDynamicAgentQuery, useAgentCategories } from '~/hooks/Agents';
|
||||
import { useGetMarketplaceAgentsQuery } from 'librechat-data-provider/react-query';
|
||||
import { useAgentCategories } from '~/hooks/Agents';
|
||||
import useLocalize from '~/hooks/useLocalize';
|
||||
import { Button } from '~/components/ui';
|
||||
import { Spinner } from '~/components/svg';
|
||||
|
|
@ -17,42 +18,73 @@ interface AgentGridProps {
|
|||
onSelectAgent: (agent: t.Agent) => void; // Callback when agent is selected
|
||||
}
|
||||
|
||||
// Interface for the actual data structure returned by the API
|
||||
interface AgentGridData {
|
||||
agents: t.Agent[];
|
||||
pagination?: {
|
||||
hasMore: boolean;
|
||||
current: number;
|
||||
total: number;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Component for displaying a grid of agent cards
|
||||
*/
|
||||
const AgentGrid: React.FC<AgentGridProps> = ({ category, searchQuery, onSelectAgent }) => {
|
||||
const localize = useLocalize();
|
||||
const [page, setPage] = useState(1);
|
||||
const [cursor, setCursor] = useState<string | undefined>(undefined);
|
||||
const [allAgents, setAllAgents] = useState<t.Agent[]>([]);
|
||||
|
||||
// Get category data from API
|
||||
const { categories } = useAgentCategories();
|
||||
|
||||
// Single dynamic query that handles all cases - much cleaner!
|
||||
const {
|
||||
data: rawData,
|
||||
isLoading,
|
||||
error,
|
||||
isFetching,
|
||||
refetch,
|
||||
} = useDynamicAgentQuery({
|
||||
category,
|
||||
searchQuery,
|
||||
page,
|
||||
limit: 6,
|
||||
});
|
||||
// Build query parameters based on current state
|
||||
const queryParams = React.useMemo(() => {
|
||||
const params: {
|
||||
requiredPermission: number;
|
||||
category?: string;
|
||||
search?: string;
|
||||
limit: number;
|
||||
cursor?: string;
|
||||
promoted?: 0 | 1;
|
||||
} = {
|
||||
requiredPermission: 1, // Read permission for marketplace viewing
|
||||
limit: 6,
|
||||
};
|
||||
|
||||
// Type the data properly
|
||||
const data = rawData as AgentGridData | undefined;
|
||||
if (cursor) {
|
||||
params.cursor = cursor;
|
||||
}
|
||||
|
||||
// Handle search
|
||||
if (searchQuery) {
|
||||
params.search = searchQuery;
|
||||
// Include category filter for search if it's not 'all' or 'promoted'
|
||||
if (category !== 'all' && category !== 'promoted') {
|
||||
params.category = category;
|
||||
}
|
||||
} else {
|
||||
// Handle category-based queries
|
||||
if (category === 'promoted') {
|
||||
params.promoted = 1;
|
||||
} else if (category !== 'all') {
|
||||
params.category = category;
|
||||
}
|
||||
// For 'all' category, no additional filters needed
|
||||
}
|
||||
|
||||
return params;
|
||||
}, [category, searchQuery, cursor]);
|
||||
|
||||
// Single unified query that handles all cases
|
||||
const { data, isLoading, error, isFetching, refetch } = useGetMarketplaceAgentsQuery(queryParams);
|
||||
|
||||
// Handle data accumulation for pagination
|
||||
React.useEffect(() => {
|
||||
if (data?.data) {
|
||||
if (cursor) {
|
||||
// Append new data for pagination
|
||||
setAllAgents((prev) => [...prev, ...data.data]);
|
||||
} else {
|
||||
// Replace data for new queries
|
||||
setAllAgents(data.data);
|
||||
}
|
||||
}
|
||||
}, [data, cursor]);
|
||||
|
||||
// Get current agents to display
|
||||
const currentAgents = cursor ? allAgents : data?.data || [];
|
||||
|
||||
// Check if we have meaningful data to prevent unnecessary loading states
|
||||
const hasData = useHasData(data);
|
||||
|
|
@ -82,14 +114,17 @@ const AgentGrid: React.FC<AgentGridProps> = ({ category, searchQuery, onSelectAg
|
|||
* Load more agents when "See More" button is clicked
|
||||
*/
|
||||
const handleLoadMore = () => {
|
||||
setPage((prevPage) => prevPage + 1);
|
||||
if (data?.after) {
|
||||
setCursor(data.after);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Reset page when category or search changes
|
||||
* Reset cursor and agents when category or search changes
|
||||
*/
|
||||
React.useEffect(() => {
|
||||
setPage(1);
|
||||
setCursor(undefined);
|
||||
setAllAgents([]);
|
||||
}, [category, searchQuery]);
|
||||
|
||||
/**
|
||||
|
|
@ -163,7 +198,7 @@ const AgentGrid: React.FC<AgentGridProps> = ({ category, searchQuery, onSelectAg
|
|||
<h2
|
||||
className="text-xl font-bold text-gray-900 dark:text-white"
|
||||
id={`category-heading-${category}`}
|
||||
aria-label={`${getGridTitle()}, ${data?.agents?.length || 0} agents available`}
|
||||
aria-label={`${getGridTitle()}, ${currentAgents.length || 0} agents available`}
|
||||
>
|
||||
{getGridTitle()}
|
||||
</h2>
|
||||
|
|
@ -171,7 +206,7 @@ const AgentGrid: React.FC<AgentGridProps> = ({ category, searchQuery, onSelectAg
|
|||
)}
|
||||
|
||||
{/* Handle empty results with enhanced accessibility */}
|
||||
{(!data?.agents || data.agents.length === 0) && !isLoading && !isFetching ? (
|
||||
{(!currentAgents || currentAgents.length === 0) && !isLoading && !isFetching ? (
|
||||
<div
|
||||
className="py-12 text-center text-gray-500"
|
||||
role="status"
|
||||
|
|
@ -198,22 +233,22 @@ const AgentGrid: React.FC<AgentGridProps> = ({ category, searchQuery, onSelectAg
|
|||
{/* Announcement for screen readers */}
|
||||
<div id="search-results-count" className="sr-only" aria-live="polite" aria-atomic="true">
|
||||
{localize('com_agents_grid_announcement', {
|
||||
count: data?.agents?.length || 0,
|
||||
count: currentAgents?.length || 0,
|
||||
category: getCategoryDisplayName(category),
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Agent grid - 2 per row with proper semantic structure */}
|
||||
{data?.agents && data.agents.length > 0 && (
|
||||
{currentAgents && currentAgents.length > 0 && (
|
||||
<div
|
||||
className="grid grid-cols-1 gap-6 md:grid-cols-2"
|
||||
role="grid"
|
||||
aria-label={localize('com_agents_grid_announcement', {
|
||||
count: data.agents.length,
|
||||
count: currentAgents.length,
|
||||
category: getCategoryDisplayName(category),
|
||||
})}
|
||||
>
|
||||
{data.agents.map((agent: t.Agent, index: number) => (
|
||||
{currentAgents.map((agent: t.Agent, index: number) => (
|
||||
<div key={`${agent.id}-${index}`} role="gridcell">
|
||||
<AgentCard agent={agent} onClick={() => onSelectAgent(agent)} />
|
||||
</div>
|
||||
|
|
@ -222,7 +257,7 @@ const AgentGrid: React.FC<AgentGridProps> = ({ category, searchQuery, onSelectAg
|
|||
)}
|
||||
|
||||
{/* Loading indicator when fetching more with accessibility */}
|
||||
{isFetching && page > 1 && (
|
||||
{isFetching && cursor && (
|
||||
<div
|
||||
className="flex justify-center py-4"
|
||||
role="status"
|
||||
|
|
@ -235,7 +270,7 @@ const AgentGrid: React.FC<AgentGridProps> = ({ category, searchQuery, onSelectAg
|
|||
)}
|
||||
|
||||
{/* Load more button with enhanced accessibility */}
|
||||
{data?.pagination?.hasMore && !isFetching && (
|
||||
{data?.has_more && !isFetching && (
|
||||
<div className="mt-8 flex justify-center">
|
||||
<Button
|
||||
variant="outline"
|
||||
|
|
|
|||
|
|
@ -6,7 +6,8 @@ import { useSetRecoilState, useRecoilValue } from 'recoil';
|
|||
import type t from 'librechat-data-provider';
|
||||
import type { ContextType } from '~/common';
|
||||
|
||||
import { useGetAgentCategoriesQuery, useGetEndpointsQuery } from '~/data-provider';
|
||||
import { useGetEndpointsQuery } from '~/data-provider';
|
||||
import { useGetAgentCategoriesQuery } from 'librechat-data-provider/react-query';
|
||||
import { useDocumentTitle } from '~/hooks';
|
||||
import useLocalize from '~/hooks/useLocalize';
|
||||
import { TooltipAnchor, Button } from '~/components/ui';
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
import { AgentListResponse } from 'librechat-data-provider';
|
||||
import React, { useState, useEffect } from 'react';
|
||||
|
||||
import { cn } from '~/utils';
|
||||
|
||||
interface SmartLoaderProps {
|
||||
/** Whether the content is currently loading */
|
||||
isLoading: boolean;
|
||||
|
|
@ -69,7 +68,7 @@ export const SmartLoader: React.FC<SmartLoaderProps> = ({
|
|||
* Hook to determine if we have meaningful data to show
|
||||
* Helps prevent loading states when we already have cached content
|
||||
*/
|
||||
export const useHasData = (data: unknown): boolean => {
|
||||
export const useHasData = (data: AgentListResponse | undefined): boolean => {
|
||||
if (!data) return false;
|
||||
|
||||
// Type guard for object data
|
||||
|
|
|
|||
|
|
@ -2,12 +2,17 @@ import React from 'react';
|
|||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import '@testing-library/jest-dom';
|
||||
import AgentGrid from '../AgentGrid';
|
||||
import { useDynamicAgentQuery } from '~/hooks/Agents';
|
||||
import { useGetMarketplaceAgentsQuery } from 'librechat-data-provider/react-query';
|
||||
import type t from 'librechat-data-provider';
|
||||
|
||||
// Mock the dynamic agent query hook
|
||||
// Mock the marketplace agent query hook
|
||||
jest.mock('~/hooks/Agents', () => ({
|
||||
useDynamicAgentQuery: jest.fn(),
|
||||
useGetMarketplaceAgentsQuery: jest.fn(),
|
||||
useAgentCategories: jest.fn(() => ({
|
||||
categories: [],
|
||||
isLoading: false,
|
||||
error: null,
|
||||
})),
|
||||
}));
|
||||
|
||||
// Mock useLocalize hook
|
||||
|
|
@ -22,59 +27,83 @@ jest.mock('~/hooks/useLocalize', () => () => (key: string) => {
|
|||
com_agents_error_searching: 'Error searching agents',
|
||||
com_agents_no_results: 'No agents found. Try another search term.',
|
||||
com_agents_none_in_category: 'No agents found in this category',
|
||||
com_agents_search_empty_heading: 'No results found',
|
||||
com_agents_empty_state_heading: 'No agents available',
|
||||
com_agents_loading: 'Loading...',
|
||||
com_agents_grid_announcement: '{{count}} agents in {{category}}',
|
||||
com_agents_load_more_label: 'Load more agents from {{category}}',
|
||||
};
|
||||
return mockTranslations[key] || key;
|
||||
return mockTranslations[key] || key.replace(/{{(\w+)}}/g, (match, key) => `[${key}]`);
|
||||
});
|
||||
|
||||
// Mock getCategoryDisplayName and getCategoryDescription
|
||||
jest.mock('~/utils/agents', () => ({
|
||||
getCategoryDisplayName: (category: string) => {
|
||||
const names: Record<string, string> = {
|
||||
promoted: 'Top Picks',
|
||||
all: 'All',
|
||||
general: 'General',
|
||||
hr: 'HR',
|
||||
finance: 'Finance',
|
||||
};
|
||||
return names[category] || category;
|
||||
},
|
||||
getCategoryDescription: (category: string) => {
|
||||
const descriptions: Record<string, string> = {
|
||||
promoted: 'Our recommended agents',
|
||||
all: 'Browse all available agents',
|
||||
general: 'General purpose agents',
|
||||
hr: 'HR agents',
|
||||
finance: 'Finance agents',
|
||||
};
|
||||
return descriptions[category] || '';
|
||||
},
|
||||
// Mock SmartLoader components
|
||||
jest.mock('../SmartLoader', () => ({
|
||||
SmartLoader: ({ children, isLoading }: { children: React.ReactNode; isLoading: boolean }) =>
|
||||
isLoading ? <div>Loading...</div> : <div>{children}</div>,
|
||||
useHasData: (data: any) => !!data?.agents?.length,
|
||||
}));
|
||||
|
||||
const mockUseDynamicAgentQuery = useDynamicAgentQuery as jest.MockedFunction<
|
||||
typeof useDynamicAgentQuery
|
||||
// Mock ErrorDisplay component
|
||||
jest.mock('../ErrorDisplay', () => ({
|
||||
__esModule: true,
|
||||
default: ({ error, onRetry }: { error: string; onRetry: () => void }) => (
|
||||
<div>
|
||||
<div>Error: {error}</div>
|
||||
<button onClick={onRetry}>Retry</button>
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
// Mock AgentCard component
|
||||
jest.mock('../AgentCard', () => ({
|
||||
__esModule: true,
|
||||
default: ({ agent, onClick }: { agent: t.Agent; onClick: () => void }) => (
|
||||
<div data-testid={`agent-card-${agent.id}`} onClick={onClick}>
|
||||
<h3>{agent.name}</h3>
|
||||
<p>{agent.description}</p>
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
const mockUseGetMarketplaceAgentsQuery = useGetMarketplaceAgentsQuery as jest.MockedFunction<
|
||||
typeof useGetMarketplaceAgentsQuery
|
||||
>;
|
||||
|
||||
describe('AgentGrid Integration with useDynamicAgentQuery', () => {
|
||||
describe('AgentGrid Integration with useGetMarketplaceAgentsQuery', () => {
|
||||
const mockOnSelectAgent = jest.fn();
|
||||
|
||||
const mockAgents: Partial<t.Agent>[] = [
|
||||
const mockAgents: t.Agent[] = [
|
||||
{
|
||||
id: '1',
|
||||
name: 'Test Agent 1',
|
||||
description: 'First test agent',
|
||||
avatar: '/avatar1.png',
|
||||
avatar: { filepath: '/avatar1.png', source: 'local' },
|
||||
category: 'finance',
|
||||
authorName: 'Author 1',
|
||||
created_at: 1672531200000,
|
||||
instructions: null,
|
||||
provider: 'custom',
|
||||
model: 'gpt-4',
|
||||
model_parameters: {},
|
||||
},
|
||||
{
|
||||
id: '2',
|
||||
name: 'Test Agent 2',
|
||||
description: 'Second test agent',
|
||||
avatar: { filepath: '/avatar2.png' },
|
||||
avatar: { filepath: '/avatar2.png', source: 'local' },
|
||||
category: 'finance',
|
||||
authorName: 'Author 2',
|
||||
created_at: 1672531200000,
|
||||
instructions: null,
|
||||
provider: 'custom',
|
||||
model: 'gpt-4',
|
||||
model_parameters: {},
|
||||
},
|
||||
];
|
||||
|
||||
const defaultMockQueryResult = {
|
||||
data: {
|
||||
agents: mockAgents,
|
||||
data: mockAgents,
|
||||
pagination: {
|
||||
current: 1,
|
||||
hasMore: true,
|
||||
|
|
@ -84,256 +113,168 @@ describe('AgentGrid Integration with useDynamicAgentQuery', () => {
|
|||
isLoading: false,
|
||||
error: null,
|
||||
isFetching: false,
|
||||
queryType: 'promoted' as const,
|
||||
refetch: jest.fn(),
|
||||
isSuccess: true,
|
||||
isError: false,
|
||||
status: 'success' as const,
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
mockUseDynamicAgentQuery.mockReturnValue(defaultMockQueryResult);
|
||||
mockUseGetMarketplaceAgentsQuery.mockReturnValue(defaultMockQueryResult);
|
||||
});
|
||||
|
||||
describe('Query Integration', () => {
|
||||
it('should call useDynamicAgentQuery with correct parameters', () => {
|
||||
it('should call useGetMarketplaceAgentsQuery with correct parameters for category search', () => {
|
||||
render(
|
||||
<AgentGrid category="finance" searchQuery="test query" onSelectAgent={mockOnSelectAgent} />,
|
||||
);
|
||||
|
||||
expect(mockUseDynamicAgentQuery).toHaveBeenCalledWith({
|
||||
expect(mockUseGetMarketplaceAgentsQuery).toHaveBeenCalledWith({
|
||||
requiredPermission: 1,
|
||||
category: 'finance',
|
||||
searchQuery: 'test query',
|
||||
page: 1,
|
||||
search: 'test query',
|
||||
limit: 6,
|
||||
});
|
||||
});
|
||||
|
||||
it('should update page when "See More" is clicked', async () => {
|
||||
render(<AgentGrid category="hr" searchQuery="" onSelectAgent={mockOnSelectAgent} />);
|
||||
|
||||
const seeMoreButton = screen.getByText('See more');
|
||||
fireEvent.click(seeMoreButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockUseDynamicAgentQuery).toHaveBeenCalledWith({
|
||||
category: 'hr',
|
||||
searchQuery: '',
|
||||
page: 2,
|
||||
limit: 6,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('should reset page when category changes', () => {
|
||||
const { rerender } = render(
|
||||
<AgentGrid category="general" searchQuery="" onSelectAgent={mockOnSelectAgent} />,
|
||||
);
|
||||
|
||||
// Simulate clicking "See More" to increment page
|
||||
const seeMoreButton = screen.getByText('See more');
|
||||
fireEvent.click(seeMoreButton);
|
||||
|
||||
// Change category - should reset page to 1
|
||||
rerender(<AgentGrid category="finance" searchQuery="" onSelectAgent={mockOnSelectAgent} />);
|
||||
|
||||
expect(mockUseDynamicAgentQuery).toHaveBeenLastCalledWith({
|
||||
category: 'finance',
|
||||
searchQuery: '',
|
||||
page: 1,
|
||||
limit: 6,
|
||||
});
|
||||
});
|
||||
|
||||
it('should reset page when search query changes', () => {
|
||||
const { rerender } = render(
|
||||
<AgentGrid category="hr" searchQuery="" onSelectAgent={mockOnSelectAgent} />,
|
||||
);
|
||||
|
||||
// Change search query - should reset page to 1
|
||||
rerender(
|
||||
<AgentGrid category="hr" searchQuery="new search" onSelectAgent={mockOnSelectAgent} />,
|
||||
);
|
||||
|
||||
expect(mockUseDynamicAgentQuery).toHaveBeenLastCalledWith({
|
||||
category: 'hr',
|
||||
searchQuery: 'new search',
|
||||
page: 1,
|
||||
limit: 6,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Different Query Types Display', () => {
|
||||
it('should display correct title for promoted category', () => {
|
||||
mockUseDynamicAgentQuery.mockReturnValue({
|
||||
...defaultMockQueryResult,
|
||||
queryType: 'promoted',
|
||||
});
|
||||
|
||||
it('should call useGetMarketplaceAgentsQuery with promoted=1 for promoted category', () => {
|
||||
render(<AgentGrid category="promoted" searchQuery="" onSelectAgent={mockOnSelectAgent} />);
|
||||
|
||||
expect(screen.getByText('Top Picks')).toBeInTheDocument();
|
||||
expect(screen.getByText('Our recommended agents')).toBeInTheDocument();
|
||||
expect(mockUseGetMarketplaceAgentsQuery).toHaveBeenCalledWith({
|
||||
requiredPermission: 1,
|
||||
promoted: 1,
|
||||
limit: 6,
|
||||
});
|
||||
});
|
||||
|
||||
it('should display correct title for search results', () => {
|
||||
mockUseDynamicAgentQuery.mockReturnValue({
|
||||
...defaultMockQueryResult,
|
||||
queryType: 'search',
|
||||
});
|
||||
|
||||
render(
|
||||
<AgentGrid category="all" searchQuery="test search" onSelectAgent={mockOnSelectAgent} />,
|
||||
);
|
||||
|
||||
expect(screen.getByText('Results for "test search"')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should display correct title for specific category', () => {
|
||||
mockUseDynamicAgentQuery.mockReturnValue({
|
||||
...defaultMockQueryResult,
|
||||
queryType: 'category',
|
||||
});
|
||||
|
||||
render(<AgentGrid category="finance" searchQuery="" onSelectAgent={mockOnSelectAgent} />);
|
||||
|
||||
expect(screen.getByText('Finance')).toBeInTheDocument();
|
||||
expect(screen.getByText('Finance agents')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should display correct title for all category', () => {
|
||||
mockUseDynamicAgentQuery.mockReturnValue({
|
||||
...defaultMockQueryResult,
|
||||
queryType: 'all',
|
||||
});
|
||||
|
||||
it('should call useGetMarketplaceAgentsQuery without category filter for "all" category', () => {
|
||||
render(<AgentGrid category="all" searchQuery="" onSelectAgent={mockOnSelectAgent} />);
|
||||
|
||||
expect(screen.getByText('All')).toBeInTheDocument();
|
||||
expect(screen.getByText('Browse all available agents')).toBeInTheDocument();
|
||||
expect(mockUseGetMarketplaceAgentsQuery).toHaveBeenCalledWith({
|
||||
requiredPermission: 1,
|
||||
limit: 6,
|
||||
});
|
||||
});
|
||||
|
||||
it('should not include category in search when category is "all" or "promoted"', () => {
|
||||
render(<AgentGrid category="all" searchQuery="test" onSelectAgent={mockOnSelectAgent} />);
|
||||
|
||||
expect(mockUseGetMarketplaceAgentsQuery).toHaveBeenCalledWith({
|
||||
requiredPermission: 1,
|
||||
search: 'test',
|
||||
limit: 6,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Loading and Error States', () => {
|
||||
it('should show loading skeleton when isLoading is true and no data', () => {
|
||||
mockUseDynamicAgentQuery.mockReturnValue({
|
||||
...defaultMockQueryResult,
|
||||
data: undefined,
|
||||
isLoading: true,
|
||||
});
|
||||
describe('Agent Display', () => {
|
||||
it('should render agent cards when data is available', () => {
|
||||
render(<AgentGrid category="finance" searchQuery="" onSelectAgent={mockOnSelectAgent} />);
|
||||
|
||||
render(<AgentGrid category="general" searchQuery="" onSelectAgent={mockOnSelectAgent} />);
|
||||
|
||||
// Should show loading skeletons
|
||||
const loadingElements = screen.getAllByRole('generic');
|
||||
const hasLoadingClass = loadingElements.some((el) => el.className.includes('animate-pulse'));
|
||||
expect(hasLoadingClass).toBe(true);
|
||||
});
|
||||
|
||||
it('should show error message when there is an error', () => {
|
||||
mockUseDynamicAgentQuery.mockReturnValue({
|
||||
...defaultMockQueryResult,
|
||||
data: undefined,
|
||||
error: new Error('Test error'),
|
||||
});
|
||||
|
||||
render(<AgentGrid category="general" searchQuery="" onSelectAgent={mockOnSelectAgent} />);
|
||||
|
||||
expect(screen.getByText('Error loading agents')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should show loading spinner when fetching more data', () => {
|
||||
mockUseDynamicAgentQuery.mockReturnValue({
|
||||
...defaultMockQueryResult,
|
||||
isFetching: true,
|
||||
});
|
||||
|
||||
render(<AgentGrid category="general" searchQuery="" onSelectAgent={mockOnSelectAgent} />);
|
||||
|
||||
// Should show agents and loading spinner for pagination
|
||||
expect(screen.getByTestId('agent-card-1')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('agent-card-2')).toBeInTheDocument();
|
||||
expect(screen.getByText('Test Agent 1')).toBeInTheDocument();
|
||||
expect(screen.getByText('Test Agent 2')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Agent Interaction', () => {
|
||||
it('should call onSelectAgent when agent card is clicked', () => {
|
||||
render(<AgentGrid category="general" searchQuery="" onSelectAgent={mockOnSelectAgent} />);
|
||||
|
||||
const agentCard = screen.getByLabelText('Test Agent 1 agent card');
|
||||
fireEvent.click(agentCard);
|
||||
render(<AgentGrid category="finance" searchQuery="" onSelectAgent={mockOnSelectAgent} />);
|
||||
|
||||
fireEvent.click(screen.getByTestId('agent-card-1'));
|
||||
expect(mockOnSelectAgent).toHaveBeenCalledWith(mockAgents[0]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Pagination', () => {
|
||||
it('should show "See More" button when hasMore is true', () => {
|
||||
mockUseDynamicAgentQuery.mockReturnValue({
|
||||
describe('Loading States', () => {
|
||||
it('should show loading state when isLoading is true', () => {
|
||||
mockUseGetMarketplaceAgentsQuery.mockReturnValue({
|
||||
...defaultMockQueryResult,
|
||||
data: {
|
||||
agents: mockAgents,
|
||||
pagination: {
|
||||
current: 1,
|
||||
hasMore: true,
|
||||
total: 10,
|
||||
},
|
||||
},
|
||||
isLoading: true,
|
||||
data: undefined,
|
||||
});
|
||||
|
||||
render(<AgentGrid category="general" searchQuery="" onSelectAgent={mockOnSelectAgent} />);
|
||||
render(<AgentGrid category="finance" searchQuery="" onSelectAgent={mockOnSelectAgent} />);
|
||||
|
||||
expect(screen.getByText('See more')).toBeInTheDocument();
|
||||
expect(screen.getByText('Loading...')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should not show "See More" button when hasMore is false', () => {
|
||||
mockUseDynamicAgentQuery.mockReturnValue({
|
||||
it('should show empty state when no agents are available', () => {
|
||||
mockUseGetMarketplaceAgentsQuery.mockReturnValue({
|
||||
...defaultMockQueryResult,
|
||||
data: {
|
||||
agents: mockAgents,
|
||||
pagination: {
|
||||
current: 1,
|
||||
hasMore: false,
|
||||
total: 2,
|
||||
},
|
||||
},
|
||||
data: { data: [], pagination: { current: 1, hasMore: false, total: 0 } },
|
||||
});
|
||||
|
||||
render(<AgentGrid category="general" searchQuery="" onSelectAgent={mockOnSelectAgent} />);
|
||||
render(<AgentGrid category="finance" searchQuery="" onSelectAgent={mockOnSelectAgent} />);
|
||||
|
||||
expect(screen.queryByText('See more')).not.toBeInTheDocument();
|
||||
expect(screen.getByText('No agents available')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Empty States', () => {
|
||||
it('should show empty state for search results', () => {
|
||||
mockUseDynamicAgentQuery.mockReturnValue({
|
||||
describe('Error Handling', () => {
|
||||
it('should show error display when query has error', () => {
|
||||
const mockError = new Error('Failed to fetch agents');
|
||||
mockUseGetMarketplaceAgentsQuery.mockReturnValue({
|
||||
...defaultMockQueryResult,
|
||||
data: {
|
||||
agents: [],
|
||||
pagination: { current: 1, hasMore: false, total: 0 },
|
||||
},
|
||||
queryType: 'search',
|
||||
error: mockError,
|
||||
isError: true,
|
||||
data: undefined,
|
||||
});
|
||||
|
||||
render(<AgentGrid category="finance" searchQuery="" onSelectAgent={mockOnSelectAgent} />);
|
||||
|
||||
expect(screen.getByText('Error: Failed to fetch agents')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Search Results', () => {
|
||||
it('should show search results title when searching', () => {
|
||||
render(
|
||||
<AgentGrid category="finance" searchQuery="automation" onSelectAgent={mockOnSelectAgent} />,
|
||||
);
|
||||
|
||||
expect(screen.getByText('Results for "automation"')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should show empty search results message', () => {
|
||||
mockUseGetMarketplaceAgentsQuery.mockReturnValue({
|
||||
...defaultMockQueryResult,
|
||||
data: { data: [], pagination: { current: 1, hasMore: false, total: 0 } },
|
||||
});
|
||||
|
||||
render(
|
||||
<AgentGrid category="all" searchQuery="no results" onSelectAgent={mockOnSelectAgent} />,
|
||||
<AgentGrid
|
||||
category="finance"
|
||||
searchQuery="nonexistent"
|
||||
onSelectAgent={mockOnSelectAgent}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByText('No results found')).toBeInTheDocument();
|
||||
expect(screen.getByText('No agents found. Try another search term.')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('should show empty state for category with no agents', () => {
|
||||
mockUseDynamicAgentQuery.mockReturnValue({
|
||||
describe('Load More Functionality', () => {
|
||||
it('should show "See more" button when hasMore is true', () => {
|
||||
render(<AgentGrid category="finance" searchQuery="" onSelectAgent={mockOnSelectAgent} />);
|
||||
|
||||
expect(screen.getByRole('button', { name: 'See more' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should not show "See more" button when hasMore is false', () => {
|
||||
mockUseGetMarketplaceAgentsQuery.mockReturnValue({
|
||||
...defaultMockQueryResult,
|
||||
data: {
|
||||
agents: [],
|
||||
pagination: { current: 1, hasMore: false, total: 0 },
|
||||
...defaultMockQueryResult.data,
|
||||
pagination: { current: 1, hasMore: false, total: 2 },
|
||||
},
|
||||
queryType: 'category',
|
||||
});
|
||||
|
||||
render(<AgentGrid category="hr" searchQuery="" onSelectAgent={mockOnSelectAgent} />);
|
||||
render(<AgentGrid category="finance" searchQuery="" onSelectAgent={mockOnSelectAgent} />);
|
||||
|
||||
expect(screen.getByText('No agents found in this category')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'See more' })).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue