diff --git a/client/src/components/Insights/InsightsView.tsx b/client/src/components/Insights/InsightsView.tsx index 31c80bfdda..df42fe84eb 100644 --- a/client/src/components/Insights/InsightsView.tsx +++ b/client/src/components/Insights/InsightsView.tsx @@ -1,7 +1,7 @@ import { useEffect, useId, useMemo, useRef, useState } from 'react'; import { useTranslation } from 'react-i18next'; -import { AlertCircle, Info, Search } from 'lucide-react'; import { Navigate, useSearchParams } from 'react-router-dom'; +import { AlertCircle, Check, Info, Minus, Search } from 'lucide-react'; import { Button, Input, @@ -565,6 +565,7 @@ export default function InsightsView() { const [searchInput, setSearchInput] = useState(''); const [search, setSearch] = useState(''); const [page, setPage] = useState(1); + const [pendingAgentIds, setPendingAgentIds] = useState(null); const dateRangeSelectionTimeout = useRef(); const isSmallScreen = useMediaQuery('(max-width: 768px)'); const insightsFeatureEnabled = startupConfig?.insightsEnabled === true; @@ -621,6 +622,7 @@ export default function InsightsView() { () => (selectedAgentIds.length > 0 ? selectedAgentIds : agentItems.map((agent) => agent.value)), [agentItems, selectedAgentIds], ); + const displayedAgentIds = pendingAgentIds ?? effectiveAgentIds; useDocumentTitle(`${localize('com_insights_title')} | LibreChat`); @@ -699,9 +701,14 @@ export default function InsightsView() { }; const handleAgentSelection = (agentIds: string[]) => { - if (agentIds.length === 0 || !data) { + if (!data) { return; } + if (agentIds.length === 0) { + setPendingAgentIds([]); + return; + } + setPendingAgentIds(null); const normalizedIds = [...new Set(agentIds)].sort(); const allAgentIds = data.agents.map((agent) => agent.id).sort(); const nextParams = new URLSearchParams(urlSearchParams); @@ -717,6 +724,9 @@ export default function InsightsView() { setUrlSearchParams(nextParams, { replace: true }); setPage(1); }; + const allAgentsDisplayed = + agentItems.length > 0 && displayedAgentIds.length === agentItems.length; + const someAgentsDisplayed = displayedAgentIds.length > 0; if ( configLoading || @@ -742,16 +752,30 @@ export default function InsightsView() {
{data && ( { + if (!open) { + setPendingAgentIds(null); + } + }} + disabled={agentItems.length <= 1} showSelectedValues - className="w-full min-w-0 sm:w-56" + showItemCheckboxes + searchPlaceholder={ + agentItems.length > 10 ? localize('com_insights_search_agents') : undefined + } + searchEmptyText={localize('com_insights_no_agents_found')} + className="w-full min-w-0 sm:w-72" selectClassName="h-8 w-full rounded border border-border-medium bg-surface-tertiary px-3 py-1 shadow-none hover:border-border-heavy data-[state=open]:border-border-heavy dark:hover:bg-chart-widget-stroke dark:data-[state=open]:bg-chart-widget-stroke" itemClassName="rounded-none px-4 py-1.5" popoverClassName="max-h-80 rounded border-border-medium bg-surface-primary px-0 py-2 dark:bg-chart-widget-surface" renderSelectedValues={(values) => { + if (values.length === 0) { + return localize('com_insights_no_agents_selected'); + } if (values.length === agentItems.length) { return localize('com_insights_all_agents', { count: agentItems.length }); } @@ -761,16 +785,40 @@ export default function InsightsView() { return localize('com_insights_agents_selected', { count: values.length }); }} popoverHeader={ -
+
} diff --git a/client/src/components/Insights/__tests__/InsightsView.spec.tsx b/client/src/components/Insights/__tests__/InsightsView.spec.tsx new file mode 100644 index 0000000000..a95343e1d8 --- /dev/null +++ b/client/src/components/Insights/__tests__/InsightsView.spec.tsx @@ -0,0 +1,166 @@ +import React from 'react'; +import { MemoryRouter } from 'react-router-dom'; +import userEvent from '@testing-library/user-event'; +import { render, screen, waitFor } from '@testing-library/react'; +import type { TInsightsParams } from 'librechat-data-provider'; +import InsightsView from '../InsightsView'; + +const insightsData = { + agents: [ + { id: 'agent-1', name: 'Alpha' }, + { id: 'agent-2', name: 'Beta' }, + { id: 'agent-3', name: 'Gamma' }, + ], + summary: { totalConversations: 4, totalUsers: 2, totalMessages: 8, totalTokens: 100 }, + daily: [], + latest: { conversations: [], page: 1, pages: 1 }, + topUsers: [], + churnedUsers: [], +}; + +const mockUseInsightsQuery = jest.fn((params: TInsightsParams) => ({ + data: insightsData, + isLoading: false, + isFetching: false, + error: null, + params, +})); + +jest.mock('~/data-provider', () => ({ + useGetStartupConfig: () => ({ data: { insightsEnabled: true }, isLoading: false }), + useInsightsQuery: (params: TInsightsParams) => mockUseInsightsQuery(params), +})); + +jest.mock('~/hooks', () => ({ + useLocalize: () => (key: string, options?: { count?: number; name?: string }) => { + if (options?.count != null) { + return `${key}:${options.count}`; + } + return options?.name ? `${key}:${options.name}` : key; + }, + useAuthContext: () => ({ user: { id: 'user-1' } }), + useDocumentTitle: () => undefined, +})); + +jest.mock('react-i18next', () => ({ + useTranslation: () => ({ i18n: { language: 'en', resolvedLanguage: 'en' } }), +})); + +jest.mock('~/components/Chat/Menus/OpenSidebar', () => ({ + __esModule: true, + default: () => null, +})); + +jest.mock('~/components/ui', () => ({ + LocalizedDateRangePicker: () => null, +})); + +function lastQueryParams(): TInsightsParams { + return mockUseInsightsQuery.mock.calls[mockUseInsightsQuery.mock.calls.length - 1][0]; +} + +function renderView() { + return render( + + + , + ); +} + +async function openAgentMenu(user: ReturnType) { + await user.click(screen.getByText('com_insights_all_agents:3')); + await screen.findByRole('option', { name: 'Alpha' }); +} + +describe('InsightsView agent selection', () => { + beforeEach(() => { + mockUseInsightsQuery.mockClear(); + mockUseInsightsQuery.mockImplementation((params) => ({ + data: insightsData, + isLoading: false, + isFetching: false, + error: null, + params, + })); + }); + + it('filters names without changing selection and clears search on close', async () => { + mockUseInsightsQuery.mockImplementation((params) => ({ + data: { + ...insightsData, + agents: Array.from({ length: 12 }, (_, i) => ({ id: `agent-${i}`, name: `Agent ${i}` })), + }, + isLoading: false, + isFetching: false, + error: null, + params, + })); + const user = userEvent.setup(); + renderView(); + await user.click(screen.getByText('com_insights_all_agents:12')); + const search = screen.getByRole('textbox', { name: 'com_insights_search_agents' }); + await user.type(search, 'AGENT 11'); + expect(screen.getAllByRole('option')).toHaveLength(1); + expect(lastQueryParams().agentIds).toBeUndefined(); + await user.click(screen.getByRole('button', { name: 'com_ui_clear_all' })); + await user.click(screen.getByRole('button', { name: 'com_insights_select_all_agents' })); + expect(screen.getByText('com_insights_all_agents:12')).toBeInTheDocument(); + await user.clear(search); + await user.type(search, 'no match'); + expect(screen.getByRole('status')).toHaveTextContent('com_insights_no_agents_found'); + await user.keyboard('{Escape}'); + await user.click(screen.getByText('com_insights_all_agents:12')); + expect(screen.getByRole('textbox', { name: 'com_insights_search_agents' })).toHaveValue(''); + expect(screen.getAllByRole('option')).toHaveLength(12); + }); + + it('clears every agent without committing the empty selection', async () => { + const user = userEvent.setup(); + renderView(); + await openAgentMenu(user); + + await user.click(screen.getByRole('button', { name: 'com_ui_clear_all' })); + + expect(screen.getByText('com_insights_no_agents_selected')).toBeInTheDocument(); + for (const option of screen.getAllByRole('option')) { + expect(option).toHaveAttribute('aria-selected', 'false'); + } + expect(lastQueryParams().agentIds).toBeUndefined(); + }); + + it('commits only the agents picked after clearing', async () => { + const user = userEvent.setup(); + renderView(); + await openAgentMenu(user); + + await user.click(screen.getByRole('button', { name: 'com_ui_clear_all' })); + await user.click(screen.getByRole('option', { name: 'Beta' })); + + await waitFor(() => expect(lastQueryParams().agentIds).toEqual(['agent-2'])); + }); + + it('restores the committed selection when the menu closes while empty', async () => { + const user = userEvent.setup(); + renderView(); + await openAgentMenu(user); + + await user.click(screen.getByRole('button', { name: 'com_ui_clear_all' })); + await user.keyboard('{Escape}'); + + await waitFor(() => expect(screen.getByText('com_insights_all_agents:3')).toBeInTheDocument()); + expect(lastQueryParams().agentIds).toBeUndefined(); + }); + + it('re-enables select all from the cleared state', async () => { + const user = userEvent.setup(); + renderView(); + await openAgentMenu(user); + + await user.click(screen.getByRole('button', { name: 'com_ui_clear_all' })); + const selectAll = screen.getByRole('button', { name: 'com_insights_select_all_agents' }); + + await user.click(selectAll); + expect(screen.getByText('com_insights_all_agents:3')).toBeInTheDocument(); + expect(lastQueryParams().agentIds).toBeUndefined(); + }); +}); diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json index 03581e6469..99516df07c 100644 --- a/client/src/locales/en/translation.json +++ b/client/src/locales/en/translation.json @@ -2656,7 +2656,11 @@ "com_insights_load_error": "Insights could not be loaded. Try again.", "com_insights_forbidden": "You do not have access to insights for these agents.", "com_insights_all_agents": "All {{count}} agents", + "com_insights_all_agents_label": "All agents", "com_insights_agents_selected": "{{count}} agents", + "com_insights_no_agents_selected": "No agents selected", + "com_insights_search_agents": "Search agents", + "com_insights_no_agents_found": "No agents found", "com_insights_select_all_agents": "Select all", "com_insights_total_users": "Unique users", "com_insights_total_conversations": "Conversations", diff --git a/e2e/specs/mock/steering-escalation.spec.ts b/e2e/specs/mock/steering-escalation.spec.ts index 29550026e3..615bfc3365 100644 --- a/e2e/specs/mock/steering-escalation.spec.ts +++ b/e2e/specs/mock/steering-escalation.spec.ts @@ -166,9 +166,8 @@ test.describe('escalating waiting messages to an interrupt', () => { expect(armResponse.status()).toBe(200); expect(((await armResponse.json()) as { armed?: boolean }).armed).toBe(true); - // Relabelled IN PLACE: still exactly one bubble with the same text, and - // an interrupting steer no longer offers its escalation control. - await expect(inFlightSteers(page)).toHaveCount(1); + // The stream can consume the armed steer before the HTTP response arrives. + // Whether waiting or already applied, it must no longer offer escalation. await expect(bubble.getByTestId('steer-escalate-now')).toHaveCount(0); // The armed steer seals mid-stream and injects with no tool boundary. diff --git a/packages/client/src/components/MultiSelect.tsx b/packages/client/src/components/MultiSelect.tsx index 2e4da83d1b..0c5f9d4583 100644 --- a/packages/client/src/components/MultiSelect.tsx +++ b/packages/client/src/components/MultiSelect.tsx @@ -1,10 +1,12 @@ import React, { useRef, useState } from 'react'; +import { Check, Search } from 'lucide-react'; import { Select, SelectArrow, SelectItem, SelectItemCheck, SelectLabel, + SelectList, SelectPopover, SelectProvider, } from '@ariakit/react'; @@ -47,8 +49,12 @@ interface MultiSelectProps { isSelected: boolean, ) => React.ReactNode; popoverHeader?: React.ReactNode; + searchPlaceholder?: string; + searchEmptyText?: string; disabled?: boolean; showSelectedValues?: boolean; + showItemCheckboxes?: boolean; + onOpenChange?: (open: boolean) => void; } function defaultRender( @@ -89,11 +95,19 @@ export default function MultiSelect({ setSelectedValues, renderItemContent, popoverHeader, + searchPlaceholder, + searchEmptyText, disabled = false, showSelectedValues = false, + showItemCheckboxes = false, + onOpenChange, }: MultiSelectProps): JSX.Element { const selectRef = useRef(null); const [isPopoverOpen, setIsPopoverOpen] = useState(false); + const [search, setSearch] = useState(''); + const visibleItems = items.filter((item) => + getItemLabel(item).toLowerCase().includes(search.trim().toLowerCase()), + ); const handleValueChange = (values: T[]) => { setSelectedValues(values); @@ -102,13 +116,23 @@ export default function MultiSelect({ } }; + const handleOpenChange = (open: boolean) => { + setIsPopoverOpen(open); + if (!open) { + setSearch(''); + } + if (onOpenChange) { + onOpenChange(open); + } + }; + return (
{label && ( @@ -142,6 +166,8 @@ export default function MultiSelect({ /> ({ finalFocus={selectRef} className={cn( 'animate-popover z-40 flex max-h-[300px]', - 'flex-col overflow-auto overscroll-contain rounded-xl', + 'flex-col overflow-hidden rounded-xl', 'bg-surface-secondary px-1.5 py-1 text-text-primary shadow-lg', 'border border-border-light', 'outline-none', popoverClassName, )} > - {popoverHeader} - {items.map((item) => { - const value = getItemValue(item); - const label = getItemLabel(item); - const defaultContent = ( - <> - - {label} - - ); - const isCurrentItemSelected = selectedValues.includes(value); - return ( - - {renderItemContent - ? (renderItemContent( - value, - defaultContent, - isCurrentItemSelected, - ) as React.JSX.Element) - : (defaultContent as React.JSX.Element)} - - ); - })} +
+ {searchPlaceholder && ( +
+
+ )} + {popoverHeader} +
+ + {visibleItems.map((item) => { + const value = getItemValue(item); + const label = getItemLabel(item); + const isCurrentItemSelected = selectedValues.includes(value); + const defaultContent = ( + <> + {showItemCheckboxes ? ( + + ) : ( + + )} + {label} + + ); + return ( + + {renderItemContent + ? (renderItemContent( + value, + defaultContent, + isCurrentItemSelected, + ) as React.JSX.Element) + : (defaultContent as React.JSX.Element)} + + ); + })} + + {visibleItems.length === 0 && searchEmptyText && ( +
+ {searchEmptyText} +
+ )}