Open History to see the last commit
1import {
2 type ProviderInstanceId,
3 type ProviderDriverKind,
4 type ResolvedKeybindingsConfig,
5} from "@t3tools/contracts";
6import { resolveSelectableModel } from "@t3tools/shared/model";
7import { LegendList, type LegendListRef } from "@legendapp/list/react";
8import { memo, useMemo, useState, useCallback, useEffect, useLayoutEffect, useRef } from "react";
9import { ChevronRightIcon, SearchIcon } from "lucide-react";
10import { ModelListRow } from "./ModelListRow";
11import { ModelPickerSidebar } from "./ModelPickerSidebar";
12import {
13 modelPickerLegacySectionKey,
14 modelPickerModelKey,
15 parseModelPickerLegacySectionKey,
16 parseModelPickerModelKey,
17} from "./modelPickerKeys";
18import { isModelPickerNewModel } from "./modelPickerModelHighlights";
19import { buildModelPickerSearchText, scoreModelPickerSearch } from "./modelPickerSearch";
20import {
21 Combobox,
22 ComboboxEmpty,
23 ComboboxInput,
24 ComboboxItem,
25 ComboboxListVirtualized,
26} from "../ui/combobox";
27import { ModelEsque } from "./providerIconUtils";
28import {
29 modelPickerJumpCommandForIndex,
30 modelPickerJumpIndexFromCommand,
31 resolveShortcutCommand,
32 shortcutLabelForCommand,
33} from "../../keybindings";
34import { useClientSettings, useUpdateClientSettings } from "~/hooks/useSettings";
35import { cn } from "~/lib/utils";
36import { getVirtualizedScrollFadeClassName } from "../ui/scroll-area";
37import { TooltipProvider } from "../ui/tooltip";
38import {
39 isProviderInstancePickerReady,
40 isProviderInstancePickerVisible,
41 type ProviderInstanceEntry,
42} from "../../providerInstances";
43import { providerModelKey, sortProviderModelItems } from "../../modelOrdering";
44
45type ModelPickerItem = {
46 slug: string;
47 name: string;
48 shortName?: string;
49 subProvider?: string;
50 instanceId: ProviderInstanceId;
51 driverKind: ProviderDriverKind;
52 instanceDisplayName: string;
53 instanceAccentColor?: string | undefined;
54 continuationGroupKey?: string | undefined;
55 isLegacy?: boolean | undefined;
56};
57
58const EMPTY_MODEL_JUMP_LABELS = new Map<string, string>();
59
60function ModelListSeparator() {
61 return <div className="h-0.5" />;
62}
63
64export const ModelPickerContent = memo(function ModelPickerContent(props: {
65 /** The instance currently selected in the composer (combobox "value"). */
66 activeInstanceId: ProviderInstanceId;
67 model: string;
68 /**
69 * When set, the picker is locked to the given driver kind — typically
70 * because the user is editing a previously-sent message and can't change
71 * which driver served the turn. Multiple instances of the same kind
72 * remain selectable (e.g. locked to `codex` still lets the user switch
73 * between the default Codex and a custom Codex Personal).
74 */
75 lockedProvider: ProviderDriverKind | null;
76 lockedContinuationGroupKey?: string | null;
77 /**
78 * All configured provider instances in display order. Used to render
79 * the sidebar (one button per instance) and to resolve display names
80 * for the locked-mode header.
81 */
82 instanceEntries: ReadonlyArray<ProviderInstanceEntry>;
83 keybindings?: ResolvedKeybindingsConfig;
84 /**
85 * Model options per instance. Keyed by `ProviderInstanceId` so the
86 * default Codex instance and any custom Codex instances each have their
87 * own list (custom instances typically start with the same built-in
88 * model set but are free to diverge via customModels).
89 */
90 modelOptionsByInstance: ReadonlyMap<ProviderInstanceId, ReadonlyArray<ModelEsque>>;
91 terminalOpen: boolean;
92 onRequestClose?: () => void;
93 getModelDisabledReason?: (instanceId: ProviderInstanceId, model: string) => string | null;
94 onInstanceModelChange: (instanceId: ProviderInstanceId, model: string) => void;
95}) {
96 const {
97 keybindings: providedKeybindings,
98 modelOptionsByInstance,
99 instanceEntries,
100 getModelDisabledReason,
101 onInstanceModelChange,
102 } = props;
103 const [searchQuery, setSearchQuery] = useState("");
104 const [showTopScrollFade, setShowTopScrollFade] = useState(false);
105 const [showBottomScrollFade, setShowBottomScrollFade] = useState(false);
106 const searchInputRef = useRef<HTMLInputElement>(null);
107 const modelListRef = useRef<LegendListRef | null>(null);
108 const highlightedModelKeyRef = useRef<string | null>(null);
109 const favorites = useClientSettings((s) => s.favorites ?? []);
110 const [selectedInstanceId, setSelectedInstanceId] = useState<ProviderInstanceId | "favorites">(
111 () => {
112 if (props.lockedProvider !== null) {
113 // When locked, prime the sidebar to the currently-active instance
114 // so jumping into the picker keeps the focused instance visible.
115 return props.activeInstanceId;
116 }
117 return favorites.length > 0 ? "favorites" : props.activeInstanceId;
118 },
119 );
120 const [expandedLegacyInstances, setExpandedLegacyInstances] = useState(
121 () =>
122 new Set<ProviderInstanceId>(
123 modelOptionsByInstance
124 .get(props.activeInstanceId)
125 ?.some((model) => model.slug === props.model && model.isLegacy)
126 ? [props.activeInstanceId]
127 : [],
128 ),
129 );
130 const keybindings = useMemo<ResolvedKeybindingsConfig>(
131 () => providedKeybindings ?? [],
132 [providedKeybindings],
133 );
134 const updateSettings = useUpdateClientSettings();
135
136 const focusSearchInput = useCallback(() => {
137 searchInputRef.current?.focus({ preventScroll: true });
138 }, []);
139
140 const handleSelectInstance = useCallback(
141 (instanceId: ProviderInstanceId | "favorites") => {
142 setSelectedInstanceId(instanceId);
143 window.requestAnimationFrame(() => {
144 focusSearchInput();
145 });
146 },
147 [focusSearchInput],
148 );
149
150 useLayoutEffect(() => {
151 focusSearchInput();
152 const frame = window.requestAnimationFrame(() => {
153 focusSearchInput();
154 });
155 const timeout = window.setTimeout(() => {
156 focusSearchInput();
157 }, 0);
158 return () => {
159 window.cancelAnimationFrame(frame);
160 window.clearTimeout(timeout);
161 };
162 }, [focusSearchInput]);
163
164 // Create a Set for efficient lookup. Favorites are keyed by
165 // `${instanceId}:${slug}`; the storage schema widened from ProviderDriverKind
166 // to ProviderInstanceId so pre-migration favorites keyed by driver slugs
167 // (e.g. `"codex:gpt-5"`) still resolve — the default instance id equals
168 // the driver slug.
169 const favoritesSet = useMemo(() => {
170 return new Set(favorites.map((fav) => providerModelKey(fav.provider, fav.model)));
171 }, [favorites]);
172
173 /**
174 * Lookup table keyed by `instanceId`. Used for display name + driver
175 * kind enrichment and for `ready`/enabled filtering before flattening
176 * models into the search list.
177 */
178 const entryByInstanceId = useMemo(
179 () => new Map(instanceEntries.map((entry) => [entry.instanceId, entry])),
180 [instanceEntries],
181 );
182 const matchesLockedProvider = useCallback(
183 (entry: Pick<ProviderInstanceEntry, "driverKind" | "continuationGroupKey">): boolean => {
184 if (props.lockedProvider === null) return true;
185 if (entry.driverKind !== props.lockedProvider) return false;
186 if (!props.lockedContinuationGroupKey) return true;
187 return entry.continuationGroupKey === props.lockedContinuationGroupKey;
188 },
189 [props.lockedContinuationGroupKey, props.lockedProvider],
190 );
191
192 const readyInstanceSet = useMemo(() => {
193 const ready = new Set<ProviderInstanceId>();
194 for (const entry of instanceEntries) {
195 if (isProviderInstancePickerReady(entry)) {
196 ready.add(entry.instanceId);
197 }
198 }
199 return ready;
200 }, [instanceEntries]);
201
202 // Flatten models into a searchable array. One pass over the
203 // instance-keyed map; each model carries its instance id + driver kind
204 // so the list row can render the right icon and display name without
205 // another lookup.
206 const flatModels = useMemo(() => {
207 const out: ModelPickerItem[] = [];
208 for (const [instanceId, models] of modelOptionsByInstance) {
209 const entry = entryByInstanceId.get(instanceId);
210 if (!entry) {
211 // Instance disappeared between renders (configuration change). Skip
212 // its models — stale options shouldn't appear in the picker.
213 continue;
214 }
215 if (!readyInstanceSet.has(instanceId)) {
216 continue;
217 }
218 for (const model of models) {
219 out.push({
220 slug: model.slug,
221 name: model.name,
222 ...(model.shortName ? { shortName: model.shortName } : {}),
223 ...(model.subProvider ? { subProvider: model.subProvider } : {}),
224 ...(model.isLegacy ? { isLegacy: true } : {}),
225 instanceId,
226 driverKind: entry.driverKind,
227 instanceDisplayName: entry.displayName,
228 ...(entry.accentColor ? { instanceAccentColor: entry.accentColor } : {}),
229 ...(entry.continuationGroupKey
230 ? { continuationGroupKey: entry.continuationGroupKey }
231 : {}),
232 });
233 }
234 }
235 return out;
236 }, [modelOptionsByInstance, entryByInstanceId, readyInstanceSet]);
237
238 const isLocked = props.lockedProvider !== null;
239 const isSearching = searchQuery.trim().length > 0;
240 const lockedDisabledInstanceIds = useMemo(() => {
241 if (!isLocked) {
242 return undefined;
243 }
244 const disabled = new Set<ProviderInstanceId>();
245 for (const entry of instanceEntries) {
246 if (!matchesLockedProvider(entry)) {
247 disabled.add(entry.instanceId);
248 }
249 }
250 return disabled;
251 }, [instanceEntries, isLocked, matchesLockedProvider]);
252 const sidebarInstanceEntries = useMemo(() => {
253 const enabledEntries = instanceEntries.filter(isProviderInstancePickerVisible);
254 if (!isLocked) {
255 return enabledEntries;
256 }
257 const available: ProviderInstanceEntry[] = [];
258 const disabled: ProviderInstanceEntry[] = [];
259 for (const entry of enabledEntries) {
260 if (matchesLockedProvider(entry)) {
261 available.push(entry);
262 } else {
263 disabled.push(entry);
264 }
265 }
266 return [...available, ...disabled];
267 }, [instanceEntries, isLocked, matchesLockedProvider]);
268 const showSidebar = !isSearching && sidebarInstanceEntries.length > 0;
269 const instanceOrder = useMemo(
270 () => instanceEntries.map((entry) => entry.instanceId),
271 [instanceEntries],
272 );
273
274 // Filter models based on search query and selected instance
275 const filteredModels = useMemo(() => {
276 let result = flatModels;
277
278 // Apply tokenized fuzzy search across the combined provider/model search fields.
279 if (searchQuery.trim()) {
280 const rankedMatches = result
281 .map((model) => ({
282 model,
283 score: scoreModelPickerSearch(
284 {
285 name: model.name,
286 ...(model.shortName ? { shortName: model.shortName } : {}),
287 ...(model.subProvider ? { subProvider: model.subProvider } : {}),
288 driverKind: model.driverKind,
289 providerDisplayName: model.instanceDisplayName,
290 isFavorite: favoritesSet.has(providerModelKey(model.instanceId, model.slug)),
291 },
292 searchQuery,
293 ),
294 isFavorite: favoritesSet.has(providerModelKey(model.instanceId, model.slug)),
295 tieBreaker: buildModelPickerSearchText({
296 name: model.name,
297 ...(model.shortName ? { shortName: model.shortName } : {}),
298 ...(model.subProvider ? { subProvider: model.subProvider } : {}),
299 driverKind: model.driverKind,
300 providerDisplayName: model.instanceDisplayName,
301 }),
302 }))
303 .filter(
304 (
305 rankedModel,
306 ): rankedModel is {
307 model: ModelPickerItem;
308 score: number;
309 isFavorite: boolean;
310 tieBreaker: string;
311 } => rankedModel.score !== null,
312 );
313
314 // When searching, we only respect locked provider (by driver kind),
315 // ignoring sidebar selection so account-scoped searches can find a
316 // model before the user chooses a specific instance rail item.
317 if (props.lockedProvider !== null) {
318 const lockedProviderMatches: Array<(typeof rankedMatches)[number]> = [];
319 for (const rankedModel of rankedMatches) {
320 if (matchesLockedProvider(rankedModel.model)) {
321 lockedProviderMatches.push(rankedModel);
322 }
323 }
324 return lockedProviderMatches
325 .toSorted((a, b) => {
326 const scoreDelta = a.score - b.score;
327 if (scoreDelta !== 0) {
328 return scoreDelta;
329 }
330 if (a.isFavorite !== b.isFavorite) {
331 return a.isFavorite ? -1 : 1;
332 }
333 return a.tieBreaker.localeCompare(b.tieBreaker);
334 })
335 .map((rankedModel) => rankedModel.model);
336 }
337
338 return rankedMatches
339 .toSorted((a, b) => {
340 const scoreDelta = a.score - b.score;
341 if (scoreDelta !== 0) {
342 return scoreDelta;
343 }
344 if (a.isFavorite !== b.isFavorite) {
345 return a.isFavorite ? -1 : 1;
346 }
347 return a.tieBreaker.localeCompare(b.tieBreaker);
348 })
349 .map((rankedModel) => rankedModel.model);
350 }
351
352 if (props.lockedProvider !== null) {
353 result = result.filter((m) => matchesLockedProvider(m));
354 if (selectedInstanceId === "favorites") {
355 result = result.filter((m) => favoritesSet.has(providerModelKey(m.instanceId, m.slug)));
356 } else {
357 result = result.filter((m) => m.instanceId === selectedInstanceId);
358 }
359 } else if (selectedInstanceId === "favorites") {
360 result = result.filter((m) => favoritesSet.has(providerModelKey(m.instanceId, m.slug)));
361 } else {
362 result = result.filter((m) => m.instanceId === selectedInstanceId);
363 }
364
365 return sortProviderModelItems(result, {
366 favoriteModelKeys: favoritesSet,
367 groupFavorites: selectedInstanceId !== "favorites",
368 instanceOrder: selectedInstanceId === "favorites" ? instanceOrder : [],
369 });
370 }, [
371 favoritesSet,
372 flatModels,
373 instanceOrder,
374 matchesLockedProvider,
375 props.lockedProvider,
376 searchQuery,
377 selectedInstanceId,
378 ]);
379
380 const legacySection = useMemo(() => {
381 if (isSearching || selectedInstanceId === "favorites") {
382 return null;
383 }
384 const currentModels = filteredModels.filter((model) => !model.isLegacy);
385 const legacyModels = filteredModels.filter((model) => model.isLegacy);
386 if (legacyModels.length === 0) {
387 return null;
388 }
389 return {
390 key: modelPickerLegacySectionKey(selectedInstanceId),
391 currentModels,
392 legacyModels,
393 isExpanded: expandedLegacyInstances.has(selectedInstanceId),
394 };
395 }, [expandedLegacyInstances, filteredModels, isSearching, selectedInstanceId]);
396
397 const visibleModels = useMemo(() => {
398 if (!legacySection) {
399 return filteredModels;
400 }
401 return [
402 ...legacySection.currentModels,
403 ...(legacySection.isExpanded ? legacySection.legacyModels : []),
404 ];
405 }, [filteredModels, legacySection]);
406
407 const toggleLegacySection = useCallback((instanceId: ProviderInstanceId) => {
408 setExpandedLegacyInstances((expanded) => {
409 const next = new Set(expanded);
410 if (next.has(instanceId)) {
411 next.delete(instanceId);
412 } else {
413 next.add(instanceId);
414 }
415 return next;
416 });
417 }, []);
418
419 const handleModelSelect = useCallback(
420 (modelSlug: string, instanceId: ProviderInstanceId) => {
421 if (getModelDisabledReason?.(instanceId, modelSlug)) {
422 return;
423 }
424 const options = modelOptionsByInstance.get(instanceId);
425 if (!options) {
426 return;
427 }
428 const entry = entryByInstanceId.get(instanceId);
429 if (!entry) {
430 return;
431 }
432 // `resolveSelectableModel` uses the driver kind for normalization
433 // (slug casing etc.). Custom instances share their driver's
434 // normalization rules, so pass the driver kind here.
435 const resolvedModel = resolveSelectableModel(entry.driverKind, modelSlug, options);
436 if (resolvedModel) {
437 onInstanceModelChange(instanceId, resolvedModel);
438 }
439 },
440 [entryByInstanceId, getModelDisabledReason, modelOptionsByInstance, onInstanceModelChange],
441 );
442
443 const toggleFavorite = useCallback(
444 (instanceId: ProviderInstanceId, model: string) => {
445 const newFavorites = [...favorites];
446 const index = newFavorites.findIndex((f) => f.provider === instanceId && f.model === model);
447 if (index >= 0) {
448 newFavorites.splice(index, 1);
449 } else {
450 newFavorites.push({ provider: instanceId, model });
451 }
452 updateSettings({ favorites: newFavorites });
453 },
454 [favorites, updateSettings],
455 );
456
457 const modelJumpCommandByKey = useMemo(() => {
458 const mapping = new Map<
459 string,
460 NonNullable<ReturnType<typeof modelPickerJumpCommandForIndex>>
461 >();
462 let selectableModelIndex = 0;
463 for (const model of visibleModels) {
464 if (getModelDisabledReason?.(model.instanceId, model.slug)) {
465 continue;
466 }
467 const jumpCommand = modelPickerJumpCommandForIndex(selectableModelIndex);
468 if (!jumpCommand) {
469 return mapping;
470 }
471 mapping.set(modelPickerModelKey(model.instanceId, model.slug), jumpCommand);
472 selectableModelIndex += 1;
473 }
474 return mapping;
475 }, [getModelDisabledReason, visibleModels]);
476 const modelJumpModelKeys = useMemo(
477 () => [...modelJumpCommandByKey.keys()],
478 [modelJumpCommandByKey],
479 );
480 const allItemKeys = useMemo(
481 (): string[] => [
482 ...flatModels.map((model) => modelPickerModelKey(model.instanceId, model.slug)),
483 ...new Set(
484 flatModels
485 .filter((model) => model.isLegacy)
486 .map((model) => modelPickerLegacySectionKey(model.instanceId)),
487 ),
488 ],
489 [flatModels],
490 );
491 const filteredItemKeys = useMemo((): string[] => {
492 const modelKeys = visibleModels.map((model) =>
493 modelPickerModelKey(model.instanceId, model.slug),
494 );
495 if (!legacySection) {
496 return modelKeys;
497 }
498 modelKeys.splice(legacySection.currentModels.length, 0, legacySection.key);
499 return modelKeys;
500 }, [legacySection, visibleModels]);
501 const filteredModelByKey = useMemo(
502 (): ReadonlyMap<string, ModelPickerItem> =>
503 new Map(
504 visibleModels.map(
505 (model) => [modelPickerModelKey(model.instanceId, model.slug), model] as const,
506 ),
507 ),
508 [visibleModels],
509 );
510 const updateModelListScrollFades = useCallback(() => {
511 const scrollElement = modelListRef.current?.getScrollableNode();
512 if (!(scrollElement instanceof HTMLElement)) {
513 return;
514 }
515 const maxScrollOffset = Math.max(0, scrollElement.scrollHeight - scrollElement.clientHeight);
516 setShowTopScrollFade(scrollElement.scrollTop > 1);
517 setShowBottomScrollFade(maxScrollOffset - scrollElement.scrollTop > 1);
518 }, []);
519 const modelJumpShortcutContext = useMemo(
520 () =>
521 ({
522 terminalFocus: false,
523 terminalOpen: props.terminalOpen,
524 modelPickerOpen: true,
525 }) as const,
526 [props.terminalOpen],
527 );
528 const modelJumpLabelByKey = useMemo((): ReadonlyMap<string, string> => {
529 if (modelJumpCommandByKey.size === 0) {
530 return EMPTY_MODEL_JUMP_LABELS;
531 }
532 const shortcutLabelOptions = {
533 platform: navigator.platform,
534 context: modelJumpShortcutContext,
535 };
536 const mapping = new Map<string, string>();
537 for (const [modelKey, command] of modelJumpCommandByKey) {
538 const label = shortcutLabelForCommand(keybindings, command, shortcutLabelOptions);
539 if (label) {
540 mapping.set(modelKey, label);
541 }
542 }
543 return mapping.size > 0 ? mapping : EMPTY_MODEL_JUMP_LABELS;
544 }, [keybindings, modelJumpCommandByKey, modelJumpShortcutContext]);
545 const modelListExtraData = useMemo(
546 () => ({ favoritesSet, modelJumpLabelByKey }),
547 [favoritesSet, modelJumpLabelByKey],
548 );
549
550 useEffect(() => {
551 const onWindowKeyDown = (event: globalThis.KeyboardEvent) => {
552 if (event.defaultPrevented || event.repeat) {
553 return;
554 }
555
556 const command = resolveShortcutCommand(event, keybindings, {
557 platform: navigator.platform,
558 context: modelJumpShortcutContext,
559 });
560 const jumpIndex = modelPickerJumpIndexFromCommand(command ?? "");
561 if (jumpIndex === null) {
562 return;
563 }
564
565 const targetModelKey = modelJumpModelKeys[jumpIndex];
566 if (!targetModelKey) {
567 return;
568 }
569 const model = parseModelPickerModelKey(targetModelKey);
570 if (!model) {
571 return;
572 }
573 event.preventDefault();
574 event.stopPropagation();
575 handleModelSelect(model.slug, model.instanceId);
576 };
577
578 window.addEventListener("keydown", onWindowKeyDown, true);
579
580 return () => {
581 window.removeEventListener("keydown", onWindowKeyDown, true);
582 };
583 }, [handleModelSelect, keybindings, modelJumpModelKeys, modelJumpShortcutContext]);
584
585 useLayoutEffect(() => {
586 setShowTopScrollFade(false);
587 setShowBottomScrollFade(filteredItemKeys.length > 5);
588 let nestedFrame = 0;
589 const frame = window.requestAnimationFrame(() => {
590 updateModelListScrollFades();
591 nestedFrame = window.requestAnimationFrame(updateModelListScrollFades);
592 });
593 return () => {
594 window.cancelAnimationFrame(frame);
595 window.cancelAnimationFrame(nestedFrame);
596 };
597 }, [filteredItemKeys, updateModelListScrollFades]);
598
599 return (
600 <TooltipProvider delay={0}>
601 <div
602 className="dropdown-glass relative flex h-screen max-h-86.5 w-screen max-w-90 flex-row overflow-hidden rounded-lg text-popover-foreground shadow-[0_16px_40px_-18px_rgb(0_0_0/55%)] [clip-path:inset(0_round_var(--radius-lg))] dark:shadow-[0_18px_44px_-18px_rgb(0_0_0/80%)]"
603 data-model-picker-content="true"
604 >
605 {/* Sidebar */}
606 {showSidebar && (
607 <ModelPickerSidebar
608 selectedInstanceId={selectedInstanceId}
609 onSelectInstance={handleSelectInstance}
610 instanceEntries={sidebarInstanceEntries}
611 showFavorites
612 {...(lockedDisabledInstanceIds
613 ? {
614 disabledInstanceIds: lockedDisabledInstanceIds,
615 getDisabledInstanceTooltip: (entry: ProviderInstanceEntry) =>
616 `${entry.displayName} is unavailable in this thread. Start a new thread to switch providers.`,
617 }
618 : {})}
619 />
620 )}
621
622 {/* Main content area */}
623 <Combobox
624 inline
625 items={allItemKeys}
626 filteredItems={filteredItemKeys}
627 filter={null}
628 autoHighlight
629 open
630 virtualized
631 value={modelPickerModelKey(props.activeInstanceId, props.model)}
632 onItemHighlighted={(modelKey, eventDetails) => {
633 highlightedModelKeyRef.current = typeof modelKey === "string" ? modelKey : null;
634 if (eventDetails.reason === "keyboard" && eventDetails.index >= 0) {
635 void modelListRef.current?.scrollIndexIntoView?.({
636 index: eventDetails.index,
637 animated: false,
638 });
639 }
640 }}
641 onValueChange={(modelKey) => {
642 if (typeof modelKey !== "string") {
643 return;
644 }
645 const legacyInstanceId = parseModelPickerLegacySectionKey(modelKey);
646 if (legacyInstanceId) {
647 toggleLegacySection(legacyInstanceId);
648 return;
649 }
650 const model = parseModelPickerModelKey(modelKey);
651 if (model) {
652 handleModelSelect(model.slug, model.instanceId);
653 }
654 }}
655 >
656 <div
657 className={cn(
658 "flex min-h-0 flex-1 flex-col overflow-hidden bg-muted/40",
659 showSidebar && "border-l border-border/70",
660 )}
661 >
662 {/* Search bar */}
663 <div className="px-2 pt-2">
664 <div className="border-b border-border/70 pb-2.5 transition-colors focus-within:border-ring">
665 <ComboboxInput
666 ref={searchInputRef}
667 className="[&_input]:h-6.5 [&_input]:font-sans [&_input]:leading-6.5"
668 inputClassName="rounded-none bg-transparent text-sm"
669 placeholder="Search models..."
670 showTrigger={false}
671 startAddon={
672 <SearchIcon className="-translate-x-0.5 size-4 shrink-0 text-muted-foreground opacity-70" />
673 }
674 value={searchQuery}
675 onChange={(e) => setSearchQuery(e.target.value)}
676 onKeyDown={(e) => {
677 if (e.key === "Escape") {
678 e.preventDefault();
679 e.stopPropagation();
680 props.onRequestClose?.();
681 return;
682 }
683 if (e.key === "Enter" && highlightedModelKeyRef.current) {
684 (
685 e as typeof e & { preventBaseUIHandler?: () => void }
686 ).preventBaseUIHandler?.();
687 e.preventDefault();
688 e.stopPropagation();
689 const legacyInstanceId = parseModelPickerLegacySectionKey(
690 highlightedModelKeyRef.current,
691 );
692 if (legacyInstanceId) {
693 toggleLegacySection(legacyInstanceId);
694 return;
695 }
696 const model = parseModelPickerModelKey(highlightedModelKeyRef.current);
697 if (model) {
698 handleModelSelect(model.slug, model.instanceId);
699 }
700 return;
701 }
702 e.stopPropagation();
703 }}
704 onMouseDown={(e) => e.stopPropagation()}
705 onTouchStart={(e) => e.stopPropagation()}
706 size="sm"
707 unstyled
708 />
709 </div>
710 </div>
711
712 {/* Model list */}
713 <div className="relative min-h-0 flex-1 overflow-hidden pr-px">
714 <ComboboxListVirtualized className="size-full min-w-0 p-0 not-empty:p-0">
715 <LegendList<string>
716 ref={modelListRef}
717 data={filteredItemKeys}
718 extraData={modelListExtraData}
719 keyExtractor={(modelKey) => modelKey}
720 renderItem={({ item: modelKey, index }) => {
721 if (legacySection?.key === modelKey) {
722 return (
723 <ComboboxItem
724 hideIndicator
725 index={index}
726 value={modelKey}
727 aria-expanded={legacySection.isExpanded}
728 className="group w-full cursor-pointer rounded-md px-2 py-2"
729 contentClassName="flex w-full items-center gap-3"
730 >
731 <div className="min-w-0 flex-1 text-left">
732 <div className="text-xs font-medium leading-snug">Legacy models</div>
733 <div className="mt-1 text-xs font-normal leading-snug text-muted-foreground/70">
734 {legacySection.legacyModels.length} models
735 </div>
736 </div>
737 <ChevronRightIcon
738 className={cn(
739 "size-4 transition-transform",
740 legacySection.isExpanded && "rotate-90",
741 )}
742 />
743 </ComboboxItem>
744 );
745 }
746 const model = filteredModelByKey.get(modelKey);
747 if (!model) {
748 return null;
749 }
750 const disabledReason =
751 getModelDisabledReason?.(model.instanceId, model.slug) ?? null;
752 return (
753 <ModelListRow
754 key={modelKey}
755 index={index}
756 model={model}
757 instanceId={model.instanceId}
758 driverKind={model.driverKind}
759 providerDisplayName={model.instanceDisplayName}
760 providerAccentColor={model.instanceAccentColor}
761 isFavorite={favoritesSet.has(
762 providerModelKey(model.instanceId, model.slug),
763 )}
764 isSelected={
765 modelKey === modelPickerModelKey(props.activeInstanceId, props.model)
766 }
767 showProvider
768 preferShortName={!isLocked}
769 useTriggerLabel={false}
770 showNewBadge={isModelPickerNewModel(model.driverKind, model.slug)}
771 jumpLabel={modelJumpLabelByKey.get(modelKey) ?? null}
772 disabledReason={disabledReason}
773 onToggleFavorite={() => toggleFavorite(model.instanceId, model.slug)}
774 />
775 );
776 }}
777 estimatedItemSize={52}
778 drawDistance={480}
779 recycleItems
780 contentContainerClassName="pl-2 pr-px"
781 ItemSeparatorComponent={ModelListSeparator}
782 onLayout={updateModelListScrollFades}
783 onScroll={updateModelListScrollFades}
784 className={cn(
785 "scrollbar-gutter-stable h-full overflow-x-hidden overscroll-y-contain py-1.5 [&::-webkit-scrollbar-track]:my-2",
786 getVirtualizedScrollFadeClassName({
787 top: showTopScrollFade,
788 bottom: showBottomScrollFade,
789 }),
790 )}
791 />
792 </ComboboxListVirtualized>
793 </div>
794 <ComboboxEmpty className="not-empty:py-6 empty:h-0 text-xs font-normal leading-snug">
795 No models found
796 </ComboboxEmpty>
797 </div>
798 </Combobox>
799 </div>
800 </TooltipProvider>
801 );
802});