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