LibreChat/client/src/components/Agents/tests/AgentDetail.spec.tsx
Marco Beretta b6e5ea5d33
📌 feat: Pin Agents and Models in the Sidebar (#10634)
* 🪦 refactor: Remove Legacy Code (#10533)

* 🗑️ chore: Remove unused Legacy Provider clients and related helpers

* Deleted OpenAIClient and GoogleClient files along with their associated tests.
* Removed references to these clients in the clients index file.
* Cleaned up typedefs by removing the OpenAISpecClient export.
* Updated chat controllers to use the OpenAI SDK directly instead of the removed client classes.

* chore/remove-openapi-specs

* 🗑️ chore: Remove unused mergeSort and misc utility functions

* Deleted mergeSort.js and misc.js files as they are no longer needed.
* Removed references to cleanUpPrimaryKeyValue in messages.js and adjusted related logic.
* Updated mongoMeili.ts to eliminate local implementations of removed functions.

* chore: remove legacy endpoints

* chore: remove all plugins endpoint related code

* chore: remove unused prompt handling code and clean up imports

* Deleted handleInputs.js and instructions.js files as they are no longer needed.
* Removed references to these files in the prompts index.js.
* Updated docker-compose.yml to simplify reverse proxy configuration.

* chore: remove unused LightningIcon import from Icons.tsx

* chore: clean up translation.json by removing deprecated and unused keys

* chore: update Jest configuration and remove unused mock file

    * Simplified the setupFiles array in jest.config.js by removing the fetchEventSource mock.
    * Deleted the fetchEventSource.js mock file as it is no longer needed.

* fix: simplify endpoint type check in Landing and ConversationStarters components

    * Updated the endpoint type check to use strict equality for better clarity and performance.
    * Ensured consistency in the handling of the azureOpenAI endpoint across both components.

* chore: remove unused dependencies from package.json and package-lock.json

* chore: remove legacy EditController, associated routes and imports

* chore: update banResponse logic to refine request handling for banned users

* chore: remove unused validateEndpoint middleware and its references

* chore: remove unused 'res' parameter from initializeClient in multiple endpoint files

* chore: remove unused 'isSmallScreen' prop from BookmarkNav and NewChat components; clean up imports in ArchivedChatsTable and useSetIndexOptions hooks; enhance localization in PromptVersions

* chore: remove unused import of Constants and TMessage from MobileNav; retain only necessary QueryKeys import

* chore: remove unused TResPlugin type and related references; clean up imports in types and schemas

* 🪦 refactor: Remove Legacy Code (#10533)

* 🗑️ chore: Remove unused Legacy Provider clients and related helpers

* Deleted OpenAIClient and GoogleClient files along with their associated tests.
* Removed references to these clients in the clients index file.
* Cleaned up typedefs by removing the OpenAISpecClient export.
* Updated chat controllers to use the OpenAI SDK directly instead of the removed client classes.

* chore/remove-openapi-specs

* 🗑️ chore: Remove unused mergeSort and misc utility functions

* Deleted mergeSort.js and misc.js files as they are no longer needed.
* Removed references to cleanUpPrimaryKeyValue in messages.js and adjusted related logic.
* Updated mongoMeili.ts to eliminate local implementations of removed functions.

* chore: remove legacy endpoints

* chore: remove all plugins endpoint related code

* chore: remove unused prompt handling code and clean up imports

* Deleted handleInputs.js and instructions.js files as they are no longer needed.
* Removed references to these files in the prompts index.js.
* Updated docker-compose.yml to simplify reverse proxy configuration.

* chore: remove unused LightningIcon import from Icons.tsx

* chore: clean up translation.json by removing deprecated and unused keys

* chore: update Jest configuration and remove unused mock file

    * Simplified the setupFiles array in jest.config.js by removing the fetchEventSource mock.
    * Deleted the fetchEventSource.js mock file as it is no longer needed.

* fix: simplify endpoint type check in Landing and ConversationStarters components

    * Updated the endpoint type check to use strict equality for better clarity and performance.
    * Ensured consistency in the handling of the azureOpenAI endpoint across both components.

* chore: remove unused dependencies from package.json and package-lock.json

* chore: remove legacy EditController, associated routes and imports

* chore: update banResponse logic to refine request handling for banned users

* chore: remove unused validateEndpoint middleware and its references

* chore: remove unused 'res' parameter from initializeClient in multiple endpoint files

* chore: remove unused 'isSmallScreen' prop from BookmarkNav and NewChat components; clean up imports in ArchivedChatsTable and useSetIndexOptions hooks; enhance localization in PromptVersions

* chore: remove unused import of Constants and TMessage from MobileNav; retain only necessary QueryKeys import

* chore: remove unused TResPlugin type and related references; clean up imports in types and schemas

* 📦 chore: Bump Express.js to v5 (#10671)

* chore: update express to version 5.1.0 in package.json

* chore: update express-rate-limit to version 8.2.1 in package.json and package-lock.json

* fix: Enhance server startup error handling in experimental and index files

* Added error handling for server startup in both experimental.js and index.js to log errors and exit the process if the server fails to start.
* Updated comments in openidStrategy.js to clarify the purpose of the CustomOpenIDStrategy class and its relation to Express version changes.

* chore: Implement rate limiting for all POST routes excluding /speech, required for express v5

* Added middleware to apply IP and user rate limiters to all POST requests, ensuring that the /speech route remains unaffected.
* Enhanced code clarity with comments explaining the new rate limiting logic.

* chore: Enable writable req.query for mongoSanitize compatibility in Express 5

* chore: Ensure req.body exists in multiple middleware and route files for Express 5 compatibility

* 🗣 feat: MCP Status Accessibility Improvements (#10738)

* feat: make MultiSelect highlight same opacity as other focus highlights in app

* feat: add better screenreader announcements for mcp server and variable states

* feat: memoize fullTitle calculation

* 🪨 feat: Add PROXY support for AWS Bedrock endpoints (#8871)

* feat: added PROXY support for AWS Bedrock endpoint

* chore: explicit install of new packages required for bedrock proxy

---------

Co-authored-by: Danny Avila <danny@librechat.ai>

*  feat: Implement Favorites functionality with controllers, hooks, and UI components

*  feat: Refactor Favorites functionality to support new data structure and enhance UI interactions

*  feat: Add endpoint to new conversation for agent favorites

*  feat: Enhance Conversations and Favorites components with expanded functionality and improved UI interactions

*  feat: Remove 'Pinned' label from UI translations for cleaner interface

* feat: clean up comments and improve code readability in favorites and agent components; bump @librechat/data-schemas to 0.0.24

*  feat: Enhance favorites management with validation, update data structure, and improve UI interactions

*  feat: Simplify rendering logic in EndpointModelItem and optimize useEffect dependencies in Conversations component

*  test: Update favorites mock implementation and improve button focus styles in AgentDetail tests

*  feat: Enhance favorites management by adding loading and error states, and refactor related hooks and components

*  feat: Add loading skeletons for favorites while agents are being fetched

*  feat: Improve loading experience in FavoritesList by adding skeleton placeholders for favorites and marketplace

* feat: Optimize cache handling in Conversations and enhance FavoritesList to notify height changes on loading completion

*  feat: Add loading skeleton for SearchBar in Nav component and update agent avatar fallback icon to Feather

* feat: Refactor FavoritesController validation, streamline ModelSelector component, and enhance EndpointModelItem with selection state

* feat: Adjust padding in Conversations and FavoritesList components for improved layout consistency

* feat: Refactor FavoritesController to use model methods for user updates and retrieval

* feat: Enhance Favorites functionality with validation, cleanup, and improved error handling

* tests: Update AgentCard and agent utilities to use Feather icon fallback instead of Bot icon

* refactor: Remove collapsible animation styles from CSS

* feat: Migrate favorites state management from Recoil to Jotai

* fix: Correct type definition in useGetFavoritesQuery and ensure useFavorites is exported

* refactor: Simplify AuthField component by removing TooltipAnchor and directly rendering Label

* fix: Ensure favorites are always an array and update references in FavoritesList

* style: Update Conversation component styles for improved UI consistency

* feat: re-integrate AuthContext to manage agent marketplace visibility based on authentication state

* fix: Improve optimistic updates in favorites mutation handling

* feat: Implement error handling for favorites limit and consolidate marketplace access logic

* fix: package-lock

---------

Co-authored-by: Danny Avila <danny@librechat.ai>
Co-authored-by: Dustin Healy <54083382+dustinhealy@users.noreply.github.com>
Co-authored-by: Arthur Barrett <abarrett@fas.harvard.edu>
2025-12-11 16:38:20 -05:00

418 lines
14 KiB
TypeScript

/* eslint-disable @typescript-eslint/no-require-imports */
import React from 'react';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter, useNavigate } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { RecoilRoot } from 'recoil';
import type t from 'librechat-data-provider';
import { Constants, EModelEndpoint } from 'librechat-data-provider';
import AgentDetail from '../AgentDetail';
// Mock dependencies
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useNavigate: jest.fn(),
}));
jest.mock('~/hooks', () => ({
useMediaQuery: jest.fn(() => false), // Mock as desktop by default
useLocalize: jest.fn(),
useDefaultConvo: jest.fn(),
useFavorites: jest.fn(() => ({
favorites: [],
isFavoriteAgent: jest.fn(() => false),
toggleFavoriteAgent: jest.fn(),
isFavoriteModel: jest.fn(() => false),
toggleFavoriteModel: jest.fn(),
addFavoriteAgent: jest.fn(),
removeFavoriteAgent: jest.fn(),
addFavoriteModel: jest.fn(),
removeFavoriteModel: jest.fn(),
reorderFavorites: jest.fn(),
isLoading: false,
isError: false,
isUpdating: false,
fetchError: null,
updateError: null,
})),
}));
jest.mock('@librechat/client', () => ({
...jest.requireActual('@librechat/client'),
useToastContext: jest.fn(),
}));
jest.mock('~/utils/agents', () => ({
renderAgentAvatar: jest.fn((agent, options) => (
<div data-testid="agent-avatar" data-size={options?.size} />
)),
}));
jest.mock('~/Providers', () => ({
useChatContext: jest.fn(),
}));
jest.mock('@tanstack/react-query', () => ({
...jest.requireActual('@tanstack/react-query'),
useQueryClient: jest.fn(),
}));
// Mock clipboard API
const mockWriteText = jest.fn();
const mockNavigate = jest.fn();
const mockShowToast = jest.fn();
const mockLocalize = jest.fn((key: string, values?: Record<string, any>) => {
if (key === 'com_agents_chat_with' && values?.name) {
return `Chat with ${values.name}`;
}
return key;
});
const mockAgent: t.Agent = {
id: 'test-agent-id',
name: 'Test Agent',
description: 'This is a test agent for unit testing',
avatar: {
filepath: '/path/to/avatar.png',
source: 'local' as const,
},
model: 'gpt-4',
provider: 'openai',
instructions: 'You are a helpful test agent',
tools: [],
author: 'test-user-id',
created_at: new Date().getTime(),
version: 1,
support_contact: {
name: 'Support Team',
email: 'support@test.com',
},
model_parameters: {
model: undefined,
temperature: null,
maxContextTokens: null,
max_context_tokens: null,
max_output_tokens: null,
top_p: null,
frequency_penalty: null,
presence_penalty: null,
},
};
// Helper function to render with providers
const renderWithProviders = (ui: React.ReactElement, options = {}) => {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
mutations: { retry: false },
},
});
const Wrapper = ({ children }: { children: React.ReactNode }) => (
<QueryClientProvider client={queryClient}>
<RecoilRoot>
<MemoryRouter>{children}</MemoryRouter>
</RecoilRoot>
</QueryClientProvider>
);
return render(ui, { wrapper: Wrapper, ...options });
};
describe('AgentDetail', () => {
beforeEach(() => {
jest.clearAllMocks();
(useNavigate as jest.Mock).mockReturnValue(mockNavigate);
const { useToastContext } = require('@librechat/client');
(useToastContext as jest.Mock).mockReturnValue({ showToast: mockShowToast });
const { useLocalize, useDefaultConvo } = require('~/hooks');
(useLocalize as jest.Mock).mockReturnValue(mockLocalize);
(useDefaultConvo as jest.Mock).mockReturnValue(() => ({
conversationId: Constants.NEW_CONVO,
endpoint: EModelEndpoint.agents,
}));
// Mock useChatContext
const { useChatContext } = require('~/Providers');
(useChatContext as jest.Mock).mockReturnValue({
conversation: { conversationId: 'test-convo-id' },
newConversation: jest.fn(),
});
// Mock useQueryClient
const { useQueryClient } = require('@tanstack/react-query');
(useQueryClient as jest.Mock).mockReturnValue({
getQueryData: jest.fn(),
setQueryData: jest.fn(),
invalidateQueries: jest.fn(),
});
// Setup clipboard mock if it doesn't exist
if (!navigator.clipboard) {
Object.defineProperty(navigator, 'clipboard', {
value: {
writeText: mockWriteText,
},
configurable: true,
});
} else {
// If clipboard exists, spy on it
jest.spyOn(navigator.clipboard, 'writeText').mockImplementation(mockWriteText);
}
mockWriteText.mockResolvedValue(undefined);
});
const defaultProps = {
agent: mockAgent,
isOpen: true,
onClose: jest.fn(),
};
describe('Rendering', () => {
it('should render agent details correctly', () => {
renderWithProviders(<AgentDetail {...defaultProps} />);
expect(screen.getByText('Test Agent')).toBeInTheDocument();
expect(screen.getByText('This is a test agent for unit testing')).toBeInTheDocument();
expect(screen.getByTestId('agent-avatar')).toBeInTheDocument();
expect(screen.getByTestId('agent-avatar')).toHaveAttribute('data-size', 'xl');
});
it('should render contact information when available', () => {
renderWithProviders(<AgentDetail {...defaultProps} />);
expect(screen.getByText('com_agents_contact:')).toBeInTheDocument();
expect(screen.getByRole('link', { name: 'Support Team' })).toBeInTheDocument();
expect(screen.getByRole('link', { name: 'Support Team' })).toHaveAttribute(
'href',
'mailto:support@test.com',
);
});
it('should not render contact information when not available', () => {
const agentWithoutContact = { ...mockAgent };
delete (agentWithoutContact as any).support_contact;
renderWithProviders(<AgentDetail {...defaultProps} agent={agentWithoutContact} />);
expect(screen.queryByText('com_agents_contact:')).not.toBeInTheDocument();
});
it('should render loading state when agent is null', () => {
renderWithProviders(<AgentDetail {...defaultProps} agent={null as any} />);
expect(screen.getByText('com_agents_loading')).toBeInTheDocument();
});
it('should render copy link button', () => {
renderWithProviders(<AgentDetail {...defaultProps} />);
const copyLinkButton = screen.getByRole('button', { name: 'com_agents_copy_link' });
expect(copyLinkButton).toBeInTheDocument();
expect(copyLinkButton).toHaveAttribute('aria-label', 'com_agents_copy_link');
});
it('should render Start Chat button', () => {
renderWithProviders(<AgentDetail {...defaultProps} />);
const startChatButton = screen.getByRole('button', { name: 'com_agents_start_chat' });
expect(startChatButton).toBeInTheDocument();
expect(startChatButton).not.toBeDisabled();
});
});
describe('Interactions', () => {
it('should navigate to chat when Start Chat button is clicked', async () => {
const user = userEvent.setup();
const mockNewConversation = jest.fn();
const mockQueryClient = {
getQueryData: jest.fn().mockReturnValue(null),
setQueryData: jest.fn(),
invalidateQueries: jest.fn(),
};
// Update mocks for this test
const { useChatContext } = require('~/Providers');
(useChatContext as jest.Mock).mockReturnValue({
conversation: { conversationId: 'test-convo-id' },
newConversation: mockNewConversation,
});
const { useQueryClient } = require('@tanstack/react-query');
(useQueryClient as jest.Mock).mockReturnValue(mockQueryClient);
renderWithProviders(<AgentDetail {...defaultProps} />);
const startChatButton = screen.getByRole('button', { name: 'com_agents_start_chat' });
await user.click(startChatButton);
expect(mockNewConversation).toHaveBeenCalledWith({
template: {
conversationId: Constants.NEW_CONVO,
endpoint: EModelEndpoint.agents,
},
preset: {
conversationId: Constants.NEW_CONVO,
endpoint: EModelEndpoint.agents,
agent_id: 'test-agent-id',
title: 'Chat with Test Agent',
},
});
});
it('should not navigate when agent is null', async () => {
const user = userEvent.setup();
renderWithProviders(<AgentDetail {...defaultProps} agent={null as any} />);
const startChatButton = screen.getByRole('button', { name: 'com_agents_start_chat' });
expect(startChatButton).toBeDisabled();
await user.click(startChatButton);
expect(mockNavigate).not.toHaveBeenCalled();
});
it('should copy link and show success toast when Copy Link is clicked', async () => {
const user = userEvent.setup();
renderWithProviders(<AgentDetail {...defaultProps} />);
// Click copy link button directly (no dropdown needed)
const copyLinkButton = screen.getByRole('button', { name: 'com_agents_copy_link' });
await user.click(copyLinkButton);
// Wait for async clipboard operation to complete
await waitFor(() => {
expect(mockWriteText).toHaveBeenCalledWith(
`${window.location.origin}/c/new?agent_id=test-agent-id`,
);
});
await waitFor(() => {
expect(mockShowToast).toHaveBeenCalledWith({
message: 'com_agents_link_copied',
});
});
});
it('should show error toast when clipboard write fails', async () => {
const user = userEvent.setup();
mockWriteText.mockRejectedValue(new Error('Clipboard error'));
renderWithProviders(<AgentDetail {...defaultProps} />);
// Click copy link button directly
const copyLinkButton = screen.getByRole('button', { name: 'com_agents_copy_link' });
await user.click(copyLinkButton);
// Wait for clipboard operation to fail and error toast to show
await waitFor(() => {
expect(mockWriteText).toHaveBeenCalled();
});
await waitFor(() => {
expect(mockShowToast).toHaveBeenCalledWith({
message: 'com_agents_link_copy_failed',
});
});
});
it('should call onClose when dialog is closed', () => {
const mockOnClose = jest.fn();
renderWithProviders(<AgentDetail {...defaultProps} onClose={mockOnClose} isOpen={false} />);
// Since we're testing the onOpenChange callback, we need to trigger it
// This would normally be done by the Dialog component when ESC is pressed or overlay is clicked
// We'll test this by checking that onClose is properly passed to the Dialog
expect(mockOnClose).toBeDefined();
});
});
describe('Accessibility', () => {
it('should have proper ARIA attributes', () => {
renderWithProviders(<AgentDetail {...defaultProps} />);
const copyLinkButton = screen.getByRole('button', { name: 'com_agents_copy_link' });
expect(copyLinkButton).toHaveAttribute('aria-label', 'com_agents_copy_link');
});
it('should support keyboard navigation', async () => {
const user = userEvent.setup();
renderWithProviders(<AgentDetail {...defaultProps} />);
const copyLinkButton = screen.getByRole('button', { name: 'com_agents_copy_link' });
// Focus and activate with Enter key
copyLinkButton.focus();
await user.keyboard('{Enter}');
await waitFor(() => {
expect(mockWriteText).toHaveBeenCalledWith(
`${window.location.origin}/c/new?agent_id=test-agent-id`,
);
});
});
it('should have proper focus management', async () => {
renderWithProviders(<AgentDetail {...defaultProps} />);
const copyLinkButton = screen.getByRole('button', { name: 'com_agents_copy_link' });
expect(copyLinkButton).toHaveClass('focus-visible:outline-none', 'focus-visible:ring-2');
});
});
describe('Edge Cases', () => {
it('should handle agent with only email contact', () => {
const agentWithEmailOnly = {
...mockAgent,
support_contact: {
email: 'support@test.com',
},
};
renderWithProviders(<AgentDetail {...defaultProps} agent={agentWithEmailOnly} />);
expect(screen.getByRole('link', { name: 'support@test.com' })).toBeInTheDocument();
});
it('should handle agent with only name contact', () => {
const agentWithNameOnly = {
...mockAgent,
support_contact: {
name: 'Support Team',
},
};
renderWithProviders(<AgentDetail {...defaultProps} agent={agentWithNameOnly} />);
expect(screen.getByText('Support Team')).toBeInTheDocument();
expect(screen.queryByRole('link')).not.toBeInTheDocument();
});
it('should handle very long description with proper text wrapping', () => {
const agentWithLongDescription = {
...mockAgent,
description:
'This is a very long description that should wrap properly and be displayed in multiple lines when the content exceeds the available width of the container.',
};
renderWithProviders(<AgentDetail {...defaultProps} agent={agentWithLongDescription} />);
const description = screen.getByText(agentWithLongDescription.description);
expect(description).toHaveClass('whitespace-pre-wrap');
});
it('should handle special characters in agent name', () => {
const agentWithSpecialChars = {
...mockAgent,
name: 'Test Agent™ & Co. (v2.0)',
};
renderWithProviders(<AgentDetail {...defaultProps} agent={agentWithSpecialChars} />);
expect(screen.getByText('Test Agent™ & Co. (v2.0)')).toBeInTheDocument();
});
});
});