Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🩻 feat: improve agent filter controls for insights (#15807)

Ravi Kumar L980f3ede77cf
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<string[] | null>(null);
const dateRangeSelectionTimeout = useRef<number>();
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() {
<div className="flex max-w-full flex-wrap items-center gap-2 md:flex-nowrap">
{data && (
<MultiSelect
+ placeholder={localize('com_ui_agents')}
items={agentItems}
- selectedValues={effectiveAgentIds}
+ selectedValues={displayedAgentIds}
setSelectedValues={handleAgentSelection}
- disabled={agentItems.length === 1}
+ onOpenChange={(open) => {
+ 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={
- <div className="border-b border-border-light pb-2">
+ <div className="border-b border-border-light">
<Button
type="button"
size="sm"
variant="ghost"
- className="h-8 w-full justify-start rounded-none px-4 font-normal text-text-secondary hover:bg-surface-hover hover:text-text-primary"
- disabled={effectiveAgentIds.length === agentItems.length}
- onClick={() => handleAgentSelection(agentItems.map((agent) => agent.value))}
+ aria-label={
+ displayedAgentIds.length > 0
+ ? localize('com_ui_clear_all')
+ : localize('com_insights_select_all_agents')
+ }
+ className="h-10 w-full justify-start gap-2 rounded-none px-4 font-medium text-text-primary hover:bg-surface-hover"
+ onClick={() =>
+ handleAgentSelection(
+ displayedAgentIds.length > 0 ? [] : agentItems.map((agent) => agent.value),
+ )
+ }
>
- {localize('com_insights_select_all_agents')}
+ <span
+ aria-hidden="true"
+ className={cn(
+ 'flex size-4 shrink-0 items-center justify-center rounded-sm border border-border-xheavy',
+ displayedAgentIds.length > 0 && 'bg-surface-inverted text-text-inverted',
+ )}
+ >
+ {allAgentsDisplayed && <Check className="size-3.5" strokeWidth={2} />}
+ {someAgentsDisplayed && !allAgentsDisplayed && (
+ <Minus className="size-3.5" strokeWidth={2} />
+ )}
+ </span>
+ <span>{localize('com_insights_all_agents_label')}</span>
+ {displayedAgentIds.length > 0 &&
+ displayedAgentIds.length < agentItems.length && (
+ <span className="text-text-secondary">({displayedAgentIds.length})</span>
+ )}
</Button>
</div>
}
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(
+ <MemoryRouter initialEntries={['/insights']}>
+ <InsightsView />
+ </MemoryRouter>,
+ );
+}
+
+async function openAgentMenu(user: ReturnType<typeof userEvent.setup>) {
+ 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<T extends string> {
isSelected: boolean,
) => React.ReactNode;
popoverHeader?: React.ReactNode;
+ searchPlaceholder?: string;
+ searchEmptyText?: string;
disabled?: boolean;
showSelectedValues?: boolean;
+ showItemCheckboxes?: boolean;
+ onOpenChange?: (open: boolean) => void;
}
function defaultRender<T extends string>(
@@ -89,11 +95,19 @@ export default function MultiSelect<T extends string>({
setSelectedValues,
renderItemContent,
popoverHeader,
+ searchPlaceholder,
+ searchEmptyText,
disabled = false,
showSelectedValues = false,
+ showItemCheckboxes = false,
+ onOpenChange,
}: MultiSelectProps<T>): JSX.Element {
const selectRef = useRef<HTMLButtonElement>(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<T extends string>({
}
};
+ const handleOpenChange = (open: boolean) => {
+ setIsPopoverOpen(open);
+ if (!open) {
+ setSearch('');
+ }
+ if (onOpenChange) {
+ onOpenChange(open);
+ }
+ };
+
return (
<div className={className}>
<SelectProvider
value={selectedValues}
setValue={handleValueChange}
open={isPopoverOpen}
- setOpen={setIsPopoverOpen}
+ setOpen={handleOpenChange}
>
{label && (
<SelectLabel className={cn('mb-1 block text-sm text-text-primary', labelClassName)}>
@@ -142,6 +166,8 @@ export default function MultiSelect<T extends string>({
/>
</Select>
<SelectPopover
+ role="dialog"
+ aria-label={label || placeholder}
gutter={4}
sameWidth
modal
@@ -149,47 +175,81 @@ export default function MultiSelect<T extends string>({
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 = (
- <>
- <SelectItemCheck className="mr-0.5 text-text-primary" />
- <span className="truncate">{label}</span>
- </>
- );
- const isCurrentItemSelected = selectedValues.includes(value);
- return (
- <SelectItem
- key={value}
- value={value}
- className={cn(
- 'flex items-center gap-2 rounded-lg px-2 py-1.5 hover:cursor-pointer',
- 'scroll-m-1 outline-none transition-colors',
- 'hover:bg-surface-hover',
- 'data-[active-item]:bg-surface-active',
- 'w-full min-w-0 text-sm',
- itemClassName,
- )}
- >
- {renderItemContent
- ? (renderItemContent(
- value,
- defaultContent,
- isCurrentItemSelected,
- ) as React.JSX.Element)
- : (defaultContent as React.JSX.Element)}
- </SelectItem>
- );
- })}
+ <div className="shrink-0">
+ {searchPlaceholder && (
+ <div className="flex items-center gap-2 border-b border-border-light px-4 py-2">
+ <Search aria-hidden="true" className="size-4 shrink-0 text-text-secondary" />
+ <input
+ aria-label={searchPlaceholder}
+ placeholder={searchPlaceholder}
+ value={search}
+ onChange={(event) => setSearch(event.target.value)}
+ className="min-w-0 flex-1 bg-transparent text-sm outline-none focus-visible:ring-2 focus-visible:ring-text-primary"
+ />
+ </div>
+ )}
+ {popoverHeader}
+ </div>
+ <SelectList className="min-h-0 overflow-y-auto overscroll-contain">
+ {visibleItems.map((item) => {
+ const value = getItemValue(item);
+ const label = getItemLabel(item);
+ const isCurrentItemSelected = selectedValues.includes(value);
+ const defaultContent = (
+ <>
+ {showItemCheckboxes ? (
+ <span
+ aria-hidden="true"
+ className={cn(
+ 'flex size-4 shrink-0 items-center justify-center rounded-sm border border-border-xheavy',
+ isCurrentItemSelected && 'bg-surface-inverted text-text-inverted',
+ )}
+ >
+ {isCurrentItemSelected && <Check className="size-3.5" strokeWidth={2} />}
+ </span>
+ ) : (
+ <SelectItemCheck className="mr-0.5 text-text-primary" />
+ )}
+ <span className="truncate">{label}</span>
+ </>
+ );
+ return (
+ <SelectItem
+ key={value}
+ value={value}
+ aria-label={label}
+ className={cn(
+ 'flex items-center gap-2 rounded-lg px-2 py-1.5 hover:cursor-pointer',
+ 'scroll-m-1 outline-none transition-colors',
+ 'hover:bg-surface-hover',
+ 'data-[active-item]:bg-surface-active',
+ 'w-full min-w-0 text-sm',
+ itemClassName,
+ )}
+ >
+ {renderItemContent
+ ? (renderItemContent(
+ value,
+ defaultContent,
+ isCurrentItemSelected,
+ ) as React.JSX.Element)
+ : (defaultContent as React.JSX.Element)}
+ </SelectItem>
+ );
+ })}
+ </SelectList>
+ {visibleItems.length === 0 && searchEmptyText && (
+ <div role="status" className="px-4 py-3 text-sm text-text-secondary">
+ {searchEmptyText}
+ </div>
+ )}
</SelectPopover>
</SelectProvider>
</div>