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
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
⚡ perf: Virtualize the Model Selector's Search Results (#16074)
Marco Beretta7dc745a95ba4
diff --git a/client/src/components/Chat/Menus/Endpoints/components/SearchResults.tsx b/client/src/components/Chat/Menus/Endpoints/components/SearchResults.tsxindex 72541f80ab..fa0a4046cc 100644--- a/client/src/components/Chat/Menus/Endpoints/components/SearchResults.tsx+++ b/client/src/components/Chat/Menus/Endpoints/components/SearchResults.tsx@@ -1,38 +1,189 @@-import React, { Fragment } from 'react';+import React, { Fragment, useCallback, useMemo } from 'react';+import { CheckCircle2 } from 'lucide-react';import { VisuallyHidden } from '@ariakit/react';-import { CheckCircle2, EarthIcon } from 'lucide-react';import { isAgentsEndpoint, isAssistantsEndpoint } from 'librechat-data-provider';import type { TModelSpec } from 'librechat-data-provider';-import type { Endpoint } from '~/common';+import type { Endpoint, LocalizeFunction } from '~/common';+import { EndpointModelItem, VIRTUALIZE_THRESHOLD } from './EndpointModelItem';import MarketplaceItem, { marketplaceSearchMatches } from './Marketplace';import { useModelSelectorContext } from '../ModelSelectorContext';import { CustomMenuItem as MenuItem } from '../CustomMenu';+import VirtualizedModelList from './VirtualizedModelList';import { shouldRenderEndpointOption } from '../utils';import { cn, getSpecAgentAvatarURL } from '~/utils';import SpecDescription from './SpecDescription';+import { useFavorites } from '~/hooks';import SpecIcon from './SpecIcon';+type SearchModel = { name: string; isGlobal?: boolean };++type SearchResult =+ | { kind: 'spec'; spec: TModelSpec }+ | {+ kind: 'models';+ endpoint: Endpoint;+ filteredModels: SearchModel[];+ showMarketplace: boolean;+ }+ | { kind: 'endpoint'; endpoint: Endpoint };++/**+ * Resolves the same selectable search entries that are rendered below and+ * counts only options, not endpoint headings. Keeping this as one pass makes+ * the ARIA offset and set size cover every option in the shared listbox.+ */+function prepareSearchResults(+ results: (TModelSpec | Endpoint)[],+ localize: LocalizeFunction,+ searchValue: string,+): SearchResult[] {+ const lowerQuery = searchValue.toLowerCase();++ return results.flatMap<SearchResult>((item): SearchResult[] => {+ if ('name' in item && 'label' in item) {+ return [{ kind: 'spec', spec: item as TModelSpec }];+ }++ const endpoint = item as Endpoint;+ if (!shouldRenderEndpointOption(endpoint)) {+ return [];+ }++ if (!endpoint.hasModels) {+ return [{ kind: 'endpoint', endpoint }];+ }++ const endpointMatches = endpoint.label.toLowerCase().includes(lowerQuery);+ const showMarketplace =+ endpoint.showMarketplace === true &&+ (endpointMatches || marketplaceSearchMatches(searchValue, localize));+ const models = endpoint.models ?? [];+ const filteredModels = endpointMatches+ ? models+ : models.filter((model) => {+ let modelName = model.name;+ if (+ isAgentsEndpoint(endpoint.value) &&+ endpoint.agentNames &&+ endpoint.agentNames[model.name]+ ) {+ modelName = endpoint.agentNames[model.name];+ } else if (+ isAssistantsEndpoint(endpoint.value) &&+ endpoint.assistantNames &&+ endpoint.assistantNames[model.name]+ ) {+ modelName = endpoint.assistantNames[model.name];+ }+ return modelName.toLowerCase().includes(lowerQuery);+ });++ if (!filteredModels.length && !showMarketplace) {+ return [];+ }++ return [{ kind: 'models', endpoint, filteredModels, showMarketplace }];+ });+}++function searchResultOptionCount(result: SearchResult): number {+ if (result.kind === 'spec' || result.kind === 'endpoint') {+ return 1;+ }+ return result.filteredModels.length + (result.showMarketplace ? 1 : 0);+}++/**+ * Renders search matches with the same row component as the endpoint list. The+ * virtualized branch only changes how many rows are mounted, not the row+ * affordances or selection/favorite behavior.+ */+function SearchModelRows({+ endpoint,+ filteredModels,+ precedingOptionCount,+ listboxSetSize,+ searchValue,+}: {+ endpoint: Endpoint;+ filteredModels: SearchModel[];+ precedingOptionCount: number;+ listboxSetSize: number;+ searchValue: string;+}) {+ const { isFavoriteModel, toggleFavoriteModel, isFavoriteAgent, toggleFavoriteAgent } =+ useFavorites();+ const isAgent = isAgentsEndpoint(endpoint.value);++ const isFavorite = useCallback(+ (modelId: string) =>+ isAgent ? isFavoriteAgent(modelId) : isFavoriteModel(modelId, endpoint.value),+ [isAgent, isFavoriteAgent, isFavoriteModel, endpoint.value],+ );+ const onToggleFavorite = useCallback(+ (modelId: string) => {+ if (isAgent) {+ toggleFavoriteAgent(modelId);+ } else {+ toggleFavoriteModel({ model: modelId, endpoint: endpoint.value });+ }+ },+ [isAgent, toggleFavoriteAgent, toggleFavoriteModel, endpoint.value],+ );++ const modelIds = useMemo(() => filteredModels.map((model) => model.name), [filteredModels]);+ const globalByName = useMemo(+ () => new Map(filteredModels.map((model) => [model.name, model.isGlobal ?? false])),+ [filteredModels],+ );++ if (filteredModels.length > VIRTUALIZE_THRESHOLD) {+ return (+ <VirtualizedModelList+ key={searchValue}+ endpoint={endpoint}+ modelIds={modelIds}+ globalByName={globalByName}+ isFavorite={isFavorite}+ onToggleFavorite={onToggleFavorite}+ precedingOptionCount={precedingOptionCount}+ listboxSetSize={listboxSetSize}+ />+ );+ }++ return modelIds.map((modelId, index) => (+ <EndpointModelItem+ key={`${endpoint.value}-${modelId}-search`}+ modelId={modelId}+ endpoint={endpoint}+ isGlobal={globalByName.get(modelId) ?? false}+ isFavorite={isFavorite(modelId)}+ onToggleFavorite={onToggleFavorite}+ posInSet={precedingOptionCount + index + 1}+ setSize={listboxSetSize}+ />+ ));+}+interface SearchResultsProps {results: (TModelSpec | Endpoint)[] | null;- localize: (phraseKey: any, options?: any) => string;+ localize: LocalizeFunction;searchValue: string;}export function SearchResults({ results, localize, searchValue }: SearchResultsProps) {- const {- selectedValues,- handleSelectSpec,- handleSelectModel,- handleSelectEndpoint,- endpointsConfig,- agentsMap,- } = useModelSelectorContext();-- const {- modelSpec: selectedSpec,- endpoint: selectedEndpoint,- model: selectedModel,- } = selectedValues;+ const { selectedValues, handleSelectSpec, handleSelectEndpoint, endpointsConfig, agentsMap } =+ useModelSelectorContext();+ const { modelSpec: selectedSpec, endpoint: selectedEndpoint } = selectedValues;+ const preparedResults = useMemo(+ () => (results ? prepareSearchResults(results, localize, searchValue) : []),+ [results, localize, searchValue],+ );+ const listboxSetSize = preparedResults.reduce(+ (total, result) => total + searchResultOptionCount(result),+ 0,+ );if (!results) {return null;@@ -50,6 +201,8 @@ export function SearchResults({ results, localize, searchValue }: SearchResultsP);}+ let precedingOptionCount = 0;+return (<><div role="alert" aria-live="polite" className="sr-only">@@ -57,15 +210,20 @@ export function SearchResults({ results, localize, searchValue }: SearchResultsP? localize('com_files_result_found', { count: results.length }): localize('com_files_results_found', { count: results.length })}</div>- {results.map((item, i) => {- if ('name' in item && 'label' in item) {- // Render model spec- const spec = item as TModelSpec;+ {preparedResults.map((result) => {+ const resultOffset = precedingOptionCount;+ const resultOptionCount = searchResultOptionCount(result);+ precedingOptionCount += resultOptionCount;++ if (result.kind === 'spec') {+ const { spec } = result;return (<MenuItemkey={spec.name}onClick={() => handleSelectSpec(spec)}aria-selected={selectedSpec === spec.name || undefined}+ aria-posinset={resultOffset + 1}+ aria-setsize={listboxSetSize}className={cn('flex w-full cursor-pointer justify-between rounded-lg px-2 text-sm',spec.description ? 'items-start' : 'items-center',@@ -105,158 +263,69 @@ export function SearchResults({ results, localize, searchValue }: SearchResultsP)}</MenuItem>);- } else {- // For an endpoint item- const endpoint = item as Endpoint;- if (!shouldRenderEndpointOption(endpoint)) {- return null;- }-- if (endpoint.hasModels) {- const lowerQuery = searchValue.toLowerCase();- const endpointMatches = endpoint.label.toLowerCase().includes(lowerQuery);- const showMarketplace =- endpoint.showMarketplace === true &&- (endpointMatches || marketplaceSearchMatches(searchValue, localize));- const models = endpoint.models ?? [];- const filteredModels = endpointMatches- ? models- : models.filter((model) => {- let modelName = model.name;- if (- isAgentsEndpoint(endpoint.value) &&- endpoint.agentNames &&- endpoint.agentNames[model.name]- ) {- modelName = endpoint.agentNames[model.name];- } else if (- isAssistantsEndpoint(endpoint.value) &&- endpoint.assistantNames &&- endpoint.assistantNames[model.name]- ) {- modelName = endpoint.assistantNames[model.name];- }- return modelName.toLowerCase().includes(lowerQuery);- });-- if (!filteredModels.length && !showMarketplace) {- return null; // skip if no models match- }+ }- return (- <Fragment key={`endpoint-${endpoint.value}-search-${i}`}>- <div className="flex items-center gap-2 px-3 py-1 text-sm font-medium">- {endpoint.icon && (- <div className="flex items-center justify-center overflow-hidden rounded-full p-1">- {endpoint.icon}- </div>- )}- {endpoint.label}- </div>- {showMarketplace && (- <MarketplaceItem- className="px-3 py-2 pl-6"- label={localize('com_agents_marketplace')}- />+ if (result.kind === 'models') {+ const { endpoint, filteredModels, showMarketplace } = result;+ return (+ <Fragment key={`endpoint-${endpoint.value}-search`}>+ <div className="flex items-center gap-2 px-3 py-1 text-sm font-medium">+ {endpoint.icon && (+ <div className="flex items-center justify-center overflow-hidden rounded-full p-1">+ {endpoint.icon}+ </div>)}- {filteredModels.map((model) => {- const modelId = model.name;-- let isGlobal = false;- let modelName = modelId;- if (- isAgentsEndpoint(endpoint.value) &&- endpoint.agentNames &&- endpoint.agentNames[modelId]- ) {- modelName = endpoint.agentNames[modelId];- const modelInfo = endpoint?.models?.find((m) => m.name === modelId);- isGlobal = modelInfo?.isGlobal ?? false;- } else if (- isAssistantsEndpoint(endpoint.value) &&- endpoint.assistantNames &&- endpoint.assistantNames[modelId]- ) {- modelName = endpoint.assistantNames[modelId];- }+ {endpoint.label}+ </div>+ {showMarketplace && (+ <MarketplaceItem+ className="px-3 py-2 pl-6"+ label={localize('com_agents_marketplace')}+ posInSet={resultOffset + 1}+ setSize={listboxSetSize}+ />+ )}+ <SearchModelRows+ endpoint={endpoint}+ filteredModels={filteredModels}+ precedingOptionCount={resultOffset + (showMarketplace ? 1 : 0)}+ listboxSetSize={listboxSetSize}+ searchValue={searchValue}+ />+ </Fragment>+ );+ }- const isModelSelected =- !selectedSpec &&- selectedEndpoint === endpoint.value &&- selectedModel === modelId;- return (- <MenuItem- key={`${endpoint.value}-${modelId}-search-${i}`}- onClick={() => handleSelectModel(endpoint, modelId)}- aria-selected={isModelSelected || undefined}- className="flex w-full cursor-pointer items-center justify-start rounded-lg px-3 py-2 pl-6 text-sm"- >- <div className="flex items-center gap-2">- {endpoint.modelIcons?.[modelId] && (- <div className="flex h-5 w-5 items-center justify-center overflow-hidden rounded-full">- <img- src={endpoint.modelIcons[modelId]}- alt={modelName}- className="h-full w-full object-cover"- />- </div>- )}- <span>{modelName}</span>- </div>- {isGlobal && (- <EarthIcon- className="ml-auto size-4 text-accent-primary"- aria-hidden="true"- />- )}- {isModelSelected && (- <>- <CheckCircle2- className="size-4 shrink-0 text-text-primary"- aria-hidden="true"- />- <VisuallyHidden>{localize('com_a11y_selected')}</VisuallyHidden>- </>- )}- </MenuItem>- );- })}- </Fragment>- );- } else {- // Endpoints with no models- const isEndpointSelected = !selectedSpec && selectedEndpoint === endpoint.value;- return (- <MenuItem- key={`endpoint-${endpoint.value}-search-item`}- onClick={() => handleSelectEndpoint(endpoint)}- aria-selected={isEndpointSelected || undefined}- className="flex w-full cursor-pointer items-center justify-between rounded-xl px-3 py-2 text-sm"- >- <div className="flex items-center gap-2">- {endpoint.icon && (- <div- className="flex items-center justify-center overflow-hidden rounded-full border border-border-light p-1"- style={{ borderRadius: '50%' }}- >- {endpoint.icon}- </div>- )}- <span>{endpoint.label}</span>+ const { endpoint } = result;+ const isEndpointSelected = !selectedSpec && selectedEndpoint === endpoint.value;+ return (+ <MenuItem+ key={`endpoint-${endpoint.value}-search-item`}+ onClick={() => handleSelectEndpoint(endpoint)}+ aria-selected={isEndpointSelected || undefined}+ aria-posinset={resultOffset + 1}+ aria-setsize={listboxSetSize}+ className="flex w-full cursor-pointer items-center justify-between rounded-xl px-3 py-2 text-sm"+ >+ <div className="flex items-center gap-2">+ {endpoint.icon && (+ <div+ className="flex items-center justify-center overflow-hidden rounded-full border border-border-light p-1"+ style={{ borderRadius: '50%' }}+ >+ {endpoint.icon}</div>- {isEndpointSelected && (- <>- <CheckCircle2- className="size-4 shrink-0 text-text-primary"- aria-hidden="true"- />- <VisuallyHidden>{localize('com_a11y_selected')}</VisuallyHidden>- </>- )}- </MenuItem>- );- }- }+ )}+ <span>{endpoint.label}</span>+ </div>+ {isEndpointSelected && (+ <>+ <CheckCircle2 className="size-4 shrink-0 text-text-primary" aria-hidden="true" />+ <VisuallyHidden>{localize('com_a11y_selected')}</VisuallyHidden>+ </>+ )}+ </MenuItem>+ );})}</>);@@ -264,7 +333,7 @@ export function SearchResults({ results, localize, searchValue }: SearchResultsPexport function renderSearchResults(results: (TModelSpec | Endpoint)[] | null,- localize: (phraseKey: any, options?: any) => string,+ localize: LocalizeFunction,searchValue: string,) {return (diff --git a/client/src/components/Chat/Menus/Endpoints/components/VirtualizedModelList.tsx b/client/src/components/Chat/Menus/Endpoints/components/VirtualizedModelList.tsxindex 2fe7654d4e..91d0daf44f 100644--- a/client/src/components/Chat/Menus/Endpoints/components/VirtualizedModelList.tsx+++ b/client/src/components/Chat/Menus/Endpoints/components/VirtualizedModelList.tsx@@ -1,6 +1,6 @@import { useCallback, useEffect, useMemo, useRef } from 'react';-import { List } from 'react-virtualized';import * as Ariakit from '@ariakit/react';+import { AutoSizer, List } from 'react-virtualized';import type { ListRowProps } from 'react-virtualized';import type { Endpoint } from '~/common';import { EndpointModelItem } from './EndpointModelItem';@@ -17,9 +17,10 @@ interface VirtualizedModelListProps {isFavorite: (modelId: string) => boolean;onToggleFavorite: (modelId: string) => void;endpointIndex?: number;- /** Count of options rendered ahead of this list in the same listbox (marketplace entry,- * model specs), so `aria-posinset` is relative to the whole listbox and not just this list. */+ /** Count of options rendered ahead of this list in the same listbox. */precedingOptionCount: number;+ /** Total selectable options in the surrounding listbox, when known. */+ listboxSetSize?: number;}/**@@ -44,6 +45,7 @@ export default function VirtualizedModelList({onToggleFavorite,endpointIndex,precedingOptionCount,+ listboxSetSize,}: VirtualizedModelListProps) {const listRef = useRef<List>(null);const containerRef = useRef<HTMLDivElement>(null);@@ -71,26 +73,42 @@ export default function VirtualizedModelList({};const handleBoundaryNavigation = (event: KeyboardEvent) => {const delta = deltaFor(event.key);- if (delta === 0) {+ if (delta === 0 || !containerRef.current) {return;}const activeId = combobox.getState().activeId;const activeRow = activeId ? document.getElementById(activeId) : null;const wrapper = activeRow?.closest<HTMLElement>('[data-row-index]');- if (!wrapper || !containerRef.current?.contains(wrapper)) {- return;- }- const next = Number(wrapper.dataset.rowIndex) + delta;- /** Let Ariakit own both the in-window case and the ends of the list. */- if (next < 0 || next >= rowCount || rowAt(next)) {- return;+ let next: number | null = null;++ if (wrapper && containerRef.current.contains(wrapper)) {+ const currentIndex = Number(wrapper.dataset.rowIndex);+ const candidate = currentIndex + delta;+ /** Let Ariakit own both the in-window case and the ends of the list. */+ if (candidate < 0 || candidate >= rowCount || rowAt(candidate)) {+ return;+ }+ next = candidate;+ } else {+ const activePosition = Number(activeRow?.getAttribute('aria-posinset'));+ const entersFromBefore = delta === 1 && activePosition === precedingOptionCount;+ const entersFromAfter =+ delta === -1 && activePosition === precedingOptionCount + rowCount + 1;+ if (entersFromBefore) {+ next = 0;+ } else if (entersFromAfter) {+ next = rowCount - 1;+ } else {+ return;+ }}+event.preventDefault();event.stopPropagation();- listRef.current?.scrollToRow(next);+ listRef.current?.scrollToRow(next!);requestAnimationFrame(() => {requestAnimationFrame(() => {- const id = rowAt(next)?.id;+ const id = rowAt(next!)?.id;if (id) {combobox.move(id);}@@ -99,7 +117,7 @@ export default function VirtualizedModelList({};document.addEventListener('keydown', handleBoundaryNavigation, true);return () => document.removeEventListener('keydown', handleBoundaryNavigation, true);- }, [combobox, rowCount, rowAt]);+ }, [combobox, precedingOptionCount, rowCount, rowAt]);const height = useMemo(() => Math.min(MAX_LIST_HEIGHT, Math.max(ROW_HEIGHT, rowCount * ROW_HEIGHT)),@@ -118,15 +136,16 @@ export default function VirtualizedModelList({isFavorite={isFavorite(modelId)}onToggleFavorite={onToggleFavorite}posInSet={precedingOptionCount + index + 1}- setSize={precedingOptionCount + rowCount}+ setSize={listboxSetSize ?? precedingOptionCount + rowCount}/></div>);},[- endpoint,globalByName,+ endpoint,isFavorite,+ listboxSetSize,modelIds,onToggleFavorite,precedingOptionCount,@@ -135,29 +154,37 @@ export default function VirtualizedModelList({);return (- <div ref={containerRef} data-endpoint-models={`${endpoint.value}${indexSuffix}`}>- <List- ref={listRef}- width={360}- height={height}- rowCount={rowCount}- rowHeight={ROW_HEIGHT}- overscanRowCount={OVERSCAN}- rowRenderer={rowRenderer}- className="outline-none!"- style={{ width: '100%' }}- /**- * `List` spreads its props onto the underlying `Grid`, whose defaults are- * `role="grid"`, `containerRole="row"` and `tabIndex={0}`. Left alone, that puts a- * focusable grid between Ariakit's listbox and its options: tabbing out of the- * search field lands on the wrapper instead of a row, where the combobox no longer- * owns the keystroke, and the grid/row semantics fight the surrounding listbox.- * Neutralise both so focus and ARIA stay with the combobox items.- */- role="presentation"- containerRole="presentation"- tabIndex={-1}- />+ <div+ ref={containerRef}+ data-endpoint-models={`${endpoint.value}${indexSuffix}`}+ className="w-full"+ >+ <AutoSizer disableHeight>+ {({ width }) => (+ <List+ ref={listRef}+ width={width}+ height={height}+ rowCount={rowCount}+ rowHeight={ROW_HEIGHT}+ overscanRowCount={OVERSCAN}+ rowRenderer={rowRenderer}+ className="outline-none!"+ style={{ width: '100%' }}+ /**+ * `List` spreads its props onto the underlying `Grid`, whose defaults are+ * `role="grid"`, `containerRole="row"` and `tabIndex={0}`. Left alone, that puts a+ * focusable grid between Ariakit's listbox and its options: tabbing out of the+ * search field lands on the wrapper instead of a row, where the combobox no longer+ * owns the keystroke, and the grid/row semantics fight the surrounding listbox.+ * Neutralise both so focus and ARIA stay with the combobox items.+ */+ role="presentation"+ containerRole="presentation"+ tabIndex={-1}+ />+ )}+ </AutoSizer></div>);}diff --git a/client/src/components/Chat/Menus/Endpoints/components/__tests__/SearchResults.test.tsx b/client/src/components/Chat/Menus/Endpoints/components/__tests__/SearchResults.test.tsxindex 34acdd0e79..c094ae36e8 100644--- a/client/src/components/Chat/Menus/Endpoints/components/__tests__/SearchResults.test.tsx+++ b/client/src/components/Chat/Menus/Endpoints/components/__tests__/SearchResults.test.tsx@@ -1,4 +1,5 @@-import { fireEvent, render, screen } from '@testing-library/react';+import { fireEvent, render, screen, within } from '@testing-library/react';+import type { TModelSpec } from 'librechat-data-provider';import type { Endpoint, SelectedValues } from '~/common';import { SearchResults } from '../SearchResults';@@ -6,6 +7,8 @@ const mockHandleSelectSpec = jest.fn();const mockHandleSelectModel = jest.fn();const mockHandleSelectEndpoint = jest.fn();const mockNavigate = jest.fn();+const mockToggleFavoriteAgent = jest.fn();+const mockToggleFavoriteModel = jest.fn();let mockSelectedValues: SelectedValues;jest.mock('~/components/Chat/Menus/Endpoints/ModelSelectorContext', () => ({@@ -25,7 +28,7 @@ jest.mock('~/components/Chat/Menus/Endpoints/CustomMenu', () => {{ children, ...rest }: { children?: React.ReactNode },ref: React.Ref<HTMLDivElement>,) {- return React.createElement('div', { ref, role: 'menuitem', ...rest }, children);+ return React.createElement('div', { ref, role: 'menuitem', tabIndex: 0, ...rest }, children);}),};});@@ -34,6 +37,55 @@ jest.mock('react-router-dom', () => ({useNavigate: () => mockNavigate,}));+jest.mock('~/hooks', () => ({+ useFavorites: () => ({+ isFavoriteModel: () => false,+ toggleFavoriteModel: mockToggleFavoriteModel,+ isFavoriteAgent: () => false,+ toggleFavoriteAgent: mockToggleFavoriteAgent,+ }),+ useLocalize: () => (key: string) => key,+}));++jest.mock('~/components/Chat/Menus/Endpoints/useActiveItem', () => ({+ __esModule: true,+ default: () => ({ ref: { current: null }, isActive: false }),+}));++const mockVirtualizedModelList = jest.fn();+jest.mock('../VirtualizedModelList', () => {+ const React = jest.requireActual<typeof import('react')>('react');+ return {+ __esModule: true,+ default: (props: {+ endpoint: Endpoint;+ modelIds: string[];+ globalByName: Map<string, boolean>;+ isFavorite: (modelId: string) => boolean;+ onToggleFavorite: (modelId: string) => void;+ precedingOptionCount: number;+ listboxSetSize?: number;+ }) => {+ mockVirtualizedModelList(props);+ const { EndpointModelItem } = jest.requireActual('../EndpointModelItem');+ const modelId = props.modelIds[0];+ return React.createElement(+ 'div',+ { 'data-testid': 'virtualized-list' },+ React.createElement(EndpointModelItem, {+ modelId,+ endpoint: props.endpoint,+ isGlobal: props.globalByName.get(modelId) ?? false,+ isFavorite: props.isFavorite(modelId),+ onToggleFavorite: props.onToggleFavorite,+ posInSet: props.precedingOptionCount + 1,+ setSize: props.listboxSetSize,+ }),+ );+ },+ };+});+jest.mock('../SpecIcon', () => {const React = jest.requireActual<typeof import('react')>('react');return {@@ -93,6 +145,32 @@ describe('SearchResults', () => {expect(selectedItem).toBeDefined();expect(selectedItem).toHaveTextContent('claude-opus-4-6');});+ it('keeps selection, badges, icons, and favorite controls on non-virtualized rows', () => {+ mockSelectedValues = { endpoint: 'agents', model: 'agent-1', modelSpec: '' };+ render(+ <SearchResults+ results={[+ {+ ...agentsMarketplaceEndpoint,+ showMarketplace: false,+ models: [{ name: 'agent-1', isGlobal: true }],+ modelIcons: { 'agent-1': '/agent.png' },+ },+ ]}+ localize={localize}+ searchValue="agent"+ />,+ );++ const item = screen.getByRole('menuitem', { name: /Support Agent/ });+ expect(item).toHaveAttribute('aria-selected', 'true');+ expect(item).toHaveTextContent('com_a11y_selected');+ expect(item.querySelector('.lucide-earth')).toBeInTheDocument();+ expect(within(item).getByAltText('Support Agent')).toBeInTheDocument();++ fireEvent.click(within(item).getByRole('button', { name: 'com_ui_pin' }));+ expect(mockToggleFavoriteAgent).toHaveBeenCalledWith('agent-1');+ });it('does not mark model as selected when a spec is active', () => {mockSelectedValues = {@@ -148,6 +226,105 @@ describe('SearchResults', () => {expect(mockHandleSelectModel).not.toHaveBeenCalled();});+ it('assigns search option positions across specs, marketplace, and endpoint rows', () => {+ mockSelectedValues = { endpoint: '', model: '', modelSpec: '' };+ const spec = { name: 'preset', label: 'Preset' } as TModelSpec;+ const models = Array.from({ length: 101 }, (_, index) => ({+ name: `agent-${index}`,+ }));+ const secondEndpoint: Endpoint = {+ value: 'other',+ label: 'Other',+ hasModels: true,+ models: [{ name: 'agent-other-1' }, { name: 'agent-other-2' }],+ icon: null,+ };++ render(+ <SearchResults+ results={[spec, { ...agentsMarketplaceEndpoint, models }, secondEndpoint]}+ localize={localize}+ searchValue="agent"+ />,+ );++ const firstVirtualRow = within(screen.getByTestId('virtualized-list')).getByRole('menuitem');+ expect(firstVirtualRow).toHaveAttribute('aria-posinset', '3');+ expect(firstVirtualRow).toHaveAttribute('aria-setsize', '105');+ expect(screen.getByTestId('model-selector-marketplace-item')).toHaveAttribute(+ 'aria-posinset',+ '2',+ );+ expect(screen.getByTestId('model-selector-marketplace-item')).toHaveAttribute(+ 'aria-setsize',+ '105',+ );+ expect(screen.getByRole('menuitem', { name: 'agent-other-1' })).toHaveAttribute(+ 'aria-posinset',+ '104',+ );+ });++ it('renders every matching row directly at or below the virtualization threshold', () => {+ mockSelectedValues = { endpoint: '', model: '', modelSpec: '' };+ const models = Array.from({ length: 100 }, (_, i) => ({+ name: `agent-${i}`,+ isGlobal: i % 2 === 0,+ }));+ render(+ <SearchResults+ results={[{ ...agentsMarketplaceEndpoint, showMarketplace: false, models }]}+ localize={localize}+ searchValue="agent"+ />,+ );++ expect(screen.queryByTestId('virtualized-list')).not.toBeInTheDocument();+ expect(screen.getAllByRole('menuitem')).toHaveLength(100);+ });++ it('windows the rows while preserving keyboard and selected-state affordances', () => {+ mockSelectedValues = { endpoint: 'agents', model: 'agent-0', modelSpec: '' };+ const models = Array.from({ length: 101 }, (_, i) => ({+ name: `agent-${i}`,+ isGlobal: i === 0,+ }));+ render(+ <SearchResults+ results={[+ {+ ...agentsMarketplaceEndpoint,+ models,+ agentNames: { 'agent-0': 'Virtual Agent' },+ },+ ]}+ localize={localize}+ searchValue="agent"+ />,+ );++ expect(screen.getByTestId('virtualized-list')).toBeInTheDocument();+ expect(mockVirtualizedModelList).toHaveBeenCalledWith(+ expect.objectContaining({+ modelIds: models.map((m) => m.name),+ precedingOptionCount: 1,+ }),+ );+ const { globalByName } = mockVirtualizedModelList.mock.calls[0][0];+ expect(globalByName.get('agent-0')).toBe(true);+ expect(globalByName.get('agent-4')).toBe(false);++ const item = screen.getByRole('menuitem', { name: /Virtual Agent/ });+ expect(item).toHaveAttribute('aria-selected', 'true');+ expect(item).toHaveTextContent('com_a11y_selected');+ expect(item.querySelector('.lucide-earth')).toBeInTheDocument();+ item.focus();+ expect(document.activeElement).toBe(item);+ fireEvent.keyDown(item, { key: 'ArrowDown' });+ fireEvent.click(within(item).getByRole('button', { name: 'com_ui_pin' }));+ expect(mockToggleFavoriteAgent).toHaveBeenCalledWith('agent-0');+ });+it('does not render agents as a selectable endpoint when marketplace and agent rows are unavailable', () => {mockSelectedValues = { endpoint: '', model: '', modelSpec: '' };render(diff --git a/client/src/components/Chat/Menus/Endpoints/components/__tests__/VirtualizedModelList.test.tsx b/client/src/components/Chat/Menus/Endpoints/components/__tests__/VirtualizedModelList.test.tsxnew file mode 100644index 0000000000..cf7cf91e52--- /dev/null+++ b/client/src/components/Chat/Menus/Endpoints/components/__tests__/VirtualizedModelList.test.tsx@@ -0,0 +1,142 @@+import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import type { ListRowProps } from 'react-virtualized';+import type { ForwardedRef, ReactNode } from 'react';+import type { Endpoint } from '~/common';+import VirtualizedModelList from '../VirtualizedModelList';++type MockListProps = {+ width: number;+ rowCount: number;+ rowRenderer: (props: ListRowProps) => ReactNode;+};++let mockActiveIdForTest: string | null = null;+const mockMoveForTest = jest.fn();+const mockScrollToRowForTest = jest.fn();+jest.mock('react-virtualized', () => {+ const React = jest.requireActual<typeof import('react')>('react');+ return {+ AutoSizer: ({ children }: { children: (size: { width: number }) => ReactNode }) =>+ children({ width: 280 }),+ List: React.forwardRef(function MockList(+ { width, rowCount, rowRenderer }: MockListProps,+ ref: ForwardedRef<unknown>,+ ) {+ React.useImperativeHandle(ref, () => ({ scrollToRow: mockScrollToRowForTest }));+ return React.createElement(+ 'div',+ { 'data-testid': 'virtual-list', 'data-width': width, 'data-row-count': rowCount },+ [0, 1].map((index) =>+ rowRenderer({+ index,+ key: `row-${index}`,+ style: { height: 36, top: index * 36 },+ isScrolling: false,+ isVisible: true,+ columnIndex: 0,+ parent: {} as ListRowProps['parent'],+ }),+ ),+ );+ }),+ };+});+jest.mock('@ariakit/react', () => ({+ useComboboxContext: () => ({+ getState: () => ({ activeId: mockActiveIdForTest }),+ move: mockMoveForTest,+ }),+}));++jest.mock('../EndpointModelItem', () => ({+ EndpointModelItem: ({ modelId }: { modelId: string }) => (+ <div role="option" aria-selected="false" data-testid={`model-${modelId}`}>+ {modelId}+ </div>+ ),+}));++const endpoint: Endpoint = {+ value: 'agents',+ label: 'My Agents',+ hasModels: true,+ models: [],+ icon: null,+};++describe('VirtualizedModelList', () => {+ beforeEach(() => {+ mockActiveIdForTest = null;+ mockMoveForTest.mockClear();+ mockScrollToRowForTest.mockClear();+ });+ it('uses measured container width and mounts only the rendered window', () => {+ const modelIds = Array.from({ length: 101 }, (_, index) => `agent-${index}`);+ render(+ <VirtualizedModelList+ endpoint={endpoint}+ modelIds={modelIds}+ globalByName={new Map()}+ isFavorite={() => false}+ onToggleFavorite={() => undefined}+ precedingOptionCount={0}+ />,+ );++ const list = screen.getByTestId('virtual-list');+ expect(list).toHaveAttribute('data-width', '280');+ expect(list).toHaveAttribute('data-row-count', '101');+ expect(screen.getAllByRole('option')).toHaveLength(2);+ expect(screen.getByTestId('model-agent-0')).toBeInTheDocument();+ expect(screen.getByTestId('model-agent-1')).toBeInTheDocument();+ expect(screen.queryByTestId('model-agent-100')).not.toBeInTheDocument();+ });+ it('uses logical positions when two virtualized groups share a listbox', async () => {+ const modelIds = Array.from({ length: 101 }, (_, index) => `agent-${index}`);+ render(+ <div role="listbox">+ <div+ id="before"+ role="option"+ aria-selected={false}+ aria-posinset={2}+ data-testid="before"+ />+ <VirtualizedModelList+ endpoint={endpoint}+ modelIds={modelIds}+ globalByName={new Map()}+ isFavorite={() => false}+ onToggleFavorite={() => undefined}+ precedingOptionCount={2}+ />+ <div+ id="after-first"+ role="option"+ aria-selected={false}+ aria-posinset={104}+ data-testid="after-first"+ />+ <VirtualizedModelList+ endpoint={{ ...endpoint, value: 'agents-b' }}+ modelIds={modelIds}+ globalByName={new Map()}+ isFavorite={() => false}+ onToggleFavorite={() => undefined}+ precedingOptionCount={103}+ />+ </div>,+ );++ mockActiveIdForTest = 'before';+ fireEvent.keyDown(document, { key: 'ArrowDown' });+ await waitFor(() => expect(mockScrollToRowForTest).toHaveBeenCalledTimes(1));+ expect(mockScrollToRowForTest).toHaveBeenLastCalledWith(0);++ mockScrollToRowForTest.mockClear();+ mockActiveIdForTest = 'after-first';+ fireEvent.keyDown(document, { key: 'ArrowUp' });+ await waitFor(() => expect(mockScrollToRowForTest).toHaveBeenCalledTimes(1));+ expect(mockScrollToRowForTest).toHaveBeenLastCalledWith(100);+ });+});diff --git a/e2e/specs/mock/scenarios/model-selector-search.spec.ts b/e2e/specs/mock/scenarios/model-selector-search.spec.tsnew file mode 100644index 0000000000..a46c4cdf4e--- /dev/null+++ b/e2e/specs/mock/scenarios/model-selector-search.spec.ts@@ -0,0 +1,113 @@+import { expect, test } from '@playwright/test';+import type { Page } from '@playwright/test';+import { NEW_CHAT_PATH } from '../helpers';+import { resetPinnedState } from './pinned.helpers';+const modelTrigger = (page: Page) => page.getByRole('button', { name: 'Select a model' }).first();++async function openModelSearch(page: Page, query: string) {+ await modelTrigger(page).click();+ const search = page.locator('#model-search');+ await expect(search).toBeVisible();+ await search.fill(query);+ await expect(page.getByRole('option').first()).toBeVisible();+ return search;+}++test.describe('model selector search', () => {+ test.afterEach(async ({ page }) => {+ await resetPinnedState(page);+ });+ test('keyboard navigation reaches every rendered search result @scenario:model-selector-search-keyboard-navigation-reaches-every-rendered-result', async ({+ page,+ }) => {+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });+ const search = await openModelSearch(page, 'mock');+ const options = page.locator('[role="option"]');+ const optionCount = await options.count();+ expect(optionCount).toBeGreaterThan(1);++ for (let index = 0; index < Math.min(optionCount, 3); index++) {+ await search.press('ArrowDown');+ await expect(search).toBeFocused();+ }+ const announcement = page.locator('[role="alert"]').first();+ const initialAnnouncement = await announcement.textContent();+ await search.fill('zzzz-no-results');+ await expect(announcement).toHaveText(/no results/i);+ expect(await announcement.textContent()).not.toBe(initialAnnouncement);+ });++ test('pinning a search result is keyboard reachable @scenario:model-selector-search-result-pin-is-keyboard-reachable', async ({+ page,+ }) => {+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });+ await resetPinnedState(page);+ const search = await openModelSearch(page, 'mock');+ const modelRows = page.getByRole('option').filter({ hasText: /mock-model-[a-z]/i });+ const tabbablePin = modelRows.locator('button[aria-label="Pin"][tabindex="0"]');++ for (+ let index = 0, optionCount = await page.getByRole('option').count();+ index <= optionCount && (await tabbablePin.count()) === 0;+ index+++ ) {+ await search.press('ArrowDown');+ }+ await expect(tabbablePin).toHaveCount(1);+ const activeRow = tabbablePin.locator('xpath=ancestor::*[@role="option"][1]');+ const modelName = (await activeRow.innerText()).match(/mock-model-[a-z]/i)?.[0];+ expect(modelName).toBeTruthy();+ const row = page.getByRole('option').filter({ hasText: modelName! }).first();+ await page.keyboard.press('Tab');+ await expect(tabbablePin).toBeFocused();+ await tabbablePin.press('Enter');+ await expect(row.locator('button[aria-label="Unpin"]')).toHaveCount(1);+ });++ test('search options expose one global position sequence @scenario:model-selector-search-options-report-global-positions', async ({+ page,+ }) => {+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });+ await openModelSearch(page, 'mock');++ const options = page.locator('[role="option"][aria-posinset]');+ await expect(options.first()).toBeVisible();+ const metadata = await options.evaluateAll((nodes) =>+ nodes.map((node) => ({+ position: Number(node.getAttribute('aria-posinset')),+ setSize: Number(node.getAttribute('aria-setsize')),+ })),+ );+ expect(metadata.length).toBeGreaterThan(0);+ expect(new Set(metadata.map((entry) => entry.setSize)).size).toBe(1);+ expect(metadata.map((entry) => entry.position)).toEqual(+ Array.from({ length: metadata.length }, (_, index) => index + 1),+ );+ });++ test('mobile search rows keep their controls inside the popover @scenario:model-selector-search-row-fits-mobile-popover', async ({+ page,+ }) => {+ await page.setViewportSize({ width: 390, height: 844 });+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });+ await openModelSearch(page, 'mock');++ const row = page+ .locator('[role="option"]')+ .filter({+ has: page.locator('button[aria-label="Pin"]'),+ })+ .first();+ const pin = row.locator('button[aria-label="Pin"]');+ const menu = page.locator('[role="listbox"]').first();+ const rowBox = await row.boundingBox();+ const pinBox = await pin.boundingBox();+ const menuBox = await menu.boundingBox();+ expect(rowBox).not.toBeNull();+ expect(pinBox).not.toBeNull();+ expect(menuBox).not.toBeNull();+ expect(rowBox!.x).toBeGreaterThanOrEqual(menuBox!.x);+ expect(pinBox!.x + pinBox!.width).toBeLessThanOrEqual(menuBox!.x + menuBox!.width + 1);+ expect(pinBox!.x + pinBox!.width).toBeLessThanOrEqual(390);+ });+});