Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ModelPickerContent.tsx

799 lines29.6 KB

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