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 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.isLegacy ? { isLegacy: true } : {}),
260 ...(model.isUnavailable ? { isUnavailable: true } : {}),
261 instanceId,
262 driverKind: entry.driverKind,
263 instanceDisplayName: entry.displayName,
264 ...(entry.accentColor ? { instanceAccentColor: entry.accentColor } : {}),
265 ...(entry.continuationGroupKey
266 ? { continuationGroupKey: entry.continuationGroupKey }
267 : {}),
268 });
269 }
270 }
271 return out;
272 }, [modelOptionsByInstance, entryByInstanceId, props.activeInstanceId, props.model]);
273
274 const isLocked = props.lockedProvider !== null;
275 const isSearching = searchQuery.trim().length > 0;
276 const lockedDisabledInstanceIds = useMemo(() => {
277 if (!isLocked) {
278 return undefined;
279 }
280 const disabled = new Set<ProviderInstanceId>();
281 for (const entry of instanceEntries) {
282 if (!matchesLockedProvider(entry)) {
283 disabled.add(entry.instanceId);
284 }
285 }
286 return disabled;
287 }, [instanceEntries, isLocked, matchesLockedProvider]);
288 const sidebarInstanceEntries = useMemo(() => {
289 const enabledEntries = instanceEntries.filter(isProviderInstancePickerVisible);
290 if (!isLocked) {
291 return enabledEntries;
292 }
293 const available: ProviderInstanceEntry[] = [];
294 const disabled: ProviderInstanceEntry[] = [];
295 for (const entry of enabledEntries) {
296 if (matchesLockedProvider(entry)) {
297 available.push(entry);
298 } else {
299 disabled.push(entry);
300 }
301 }
302 return [...available, ...disabled];
303 }, [instanceEntries, isLocked, matchesLockedProvider]);
304 const showSidebar = !isSearching && sidebarInstanceEntries.length > 0;
305 const instanceOrder = useMemo(
306 () => instanceEntries.map((entry) => entry.instanceId),
307 [instanceEntries],
308 );
309
310 // Filter models based on search query and selected instance
311 const filteredModels = useMemo(() => {
312 let result = flatModels;
313
314 // Apply tokenized fuzzy search across the combined provider/model search fields.
315 if (searchQuery.trim()) {
316 const rankedMatches = result
317 .map((model) => ({
318 model,
319 score: scoreModelPickerSearch(
320 {
321 name: model.name,
322 ...(model.shortName ? { shortName: model.shortName } : {}),
323 ...(model.subProvider ? { subProvider: model.subProvider } : {}),
324 driverKind: model.driverKind,
325 providerDisplayName: model.instanceDisplayName,
326 isFavorite: favoritesSet.has(providerModelKey(model.instanceId, model.slug)),
327 },
328 searchQuery,
329 ),
330 isFavorite: favoritesSet.has(providerModelKey(model.instanceId, model.slug)),
331 tieBreaker: buildModelPickerSearchText({
332 name: model.name,
333 ...(model.shortName ? { shortName: model.shortName } : {}),
334 ...(model.subProvider ? { subProvider: model.subProvider } : {}),
335 driverKind: model.driverKind,
336 providerDisplayName: model.instanceDisplayName,
337 }),
338 }))
339 .filter(
340 (
341 rankedModel,
342 ): rankedModel is {
343 model: ModelPickerItem;
344 score: number;
345 isFavorite: boolean;
346 tieBreaker: string;
347 } => rankedModel.score !== null,
348 );
349
350 // When searching, we only respect locked provider (by driver kind),
351 // ignoring sidebar selection so account-scoped searches can find a
352 // model before the user chooses a specific instance rail item.
353 if (props.lockedProvider !== null) {
354 const lockedProviderMatches: Array<(typeof rankedMatches)[number]> = [];
355 for (const rankedModel of rankedMatches) {
356 if (matchesLockedProvider(rankedModel.model)) {
357 lockedProviderMatches.push(rankedModel);
358 }
359 }
360 return lockedProviderMatches
361 .toSorted((a, b) => {
362 const scoreDelta = a.score - b.score;
363 if (scoreDelta !== 0) {
364 return scoreDelta;
365 }
366 if (a.isFavorite !== b.isFavorite) {
367 return a.isFavorite ? -1 : 1;
368 }
369 return a.tieBreaker.localeCompare(b.tieBreaker);
370 })
371 .map((rankedModel) => rankedModel.model);
372 }
373
374 return rankedMatches
375 .toSorted((a, b) => {
376 const scoreDelta = a.score - b.score;
377 if (scoreDelta !== 0) {
378 return scoreDelta;
379 }
380 if (a.isFavorite !== b.isFavorite) {
381 return a.isFavorite ? -1 : 1;
382 }
383 return a.tieBreaker.localeCompare(b.tieBreaker);
384 })
385 .map((rankedModel) => rankedModel.model);
386 }
387
388 if (props.lockedProvider !== null) {
389 result = result.filter((m) => matchesLockedProvider(m));
390 if (selectedInstanceId === "favorites") {
391 result = result.filter((m) => favoritesSet.has(providerModelKey(m.instanceId, m.slug)));
392 } else {
393 result = result.filter((m) => m.instanceId === selectedInstanceId);
394 }
395 } else if (selectedInstanceId === "favorites") {
396 result = result.filter((m) => favoritesSet.has(providerModelKey(m.instanceId, m.slug)));
397 } else {
398 result = result.filter((m) => m.instanceId === selectedInstanceId);
399 }
400
401 return sortProviderModelItems(result, {
402 favoriteModelKeys: favoritesSet,
403 groupFavorites: selectedInstanceId !== "favorites",
404 instanceOrder: selectedInstanceId === "favorites" ? instanceOrder : [],
405 });
406 }, [
407 favoritesSet,
408 flatModels,
409 instanceOrder,
410 matchesLockedProvider,
411 props.lockedProvider,
412 searchQuery,
413 selectedInstanceId,
414 ]);
415
416 const legacySection = useMemo(() => {
417 if (isSearching || selectedInstanceId === "favorites") {
418 return null;
419 }
420 const currentModels = filteredModels.filter((model) => !model.isLegacy);
421 const legacyModels = filteredModels.filter((model) => model.isLegacy);
422 if (legacyModels.length === 0) {
423 return null;
424 }
425 return {
426 key: modelPickerLegacySectionKey(selectedInstanceId),
427 currentModels,
428 legacyModels,
429 isExpanded: expandedLegacyInstances.has(selectedInstanceId),
430 };
431 }, [expandedLegacyInstances, filteredModels, isSearching, selectedInstanceId]);
432
433 const visibleModels = useMemo(() => {
434 if (!legacySection) {
435 return filteredModels;
436 }
437 return [
438 ...legacySection.currentModels,
439 ...(legacySection.isExpanded ? legacySection.legacyModels : []),
440 ];
441 }, [filteredModels, legacySection]);
442
443 const toggleLegacySection = useCallback((instanceId: ProviderInstanceId) => {
444 setExpandedLegacyInstances((expanded) => {
445 const next = new Set(expanded);
446 if (next.has(instanceId)) {
447 next.delete(instanceId);
448 } else {
449 next.add(instanceId);
450 }
451 return next;
452 });
453 }, []);
454
455 const handleModelSelect = useCallback(
456 (modelSlug: string, instanceId: ProviderInstanceId) => {
457 if (getModelDisabledReason?.(instanceId, modelSlug)) {
458 return;
459 }
460 const options = modelOptionsByInstance.get(instanceId);
461 if (!options) {
462 return;
463 }
464 const entry = entryByInstanceId.get(instanceId);
465 if (!entry) {
466 return;
467 }
468 // `resolveSelectableModel` uses the driver kind for normalization
469 // (slug casing etc.). Custom instances share their driver's
470 // normalization rules, so pass the driver kind here.
471 const resolvedModel = resolveSelectableModel(entry.driverKind, modelSlug, options);
472 if (resolvedModel) {
473 onInstanceModelChange(instanceId, resolvedModel);
474 }
475 },
476 [entryByInstanceId, getModelDisabledReason, modelOptionsByInstance, onInstanceModelChange],
477 );
478
479 const toggleFavorite = useCallback(
480 (instanceId: ProviderInstanceId, model: string) => {
481 const newFavorites = [...favorites];
482 const index = newFavorites.findIndex((f) => f.provider === instanceId && f.model === model);
483 if (index >= 0) {
484 newFavorites.splice(index, 1);
485 } else {
486 newFavorites.push({ provider: instanceId, model });
487 }
488 updateSettings({ favorites: newFavorites });
489 },
490 [favorites, updateSettings],
491 );
492
493 const modelJumpCommandByKey = useMemo(() => {
494 const mapping = new Map<
495 string,
496 NonNullable<ReturnType<typeof modelPickerJumpCommandForIndex>>
497 >();
498 let selectableModelIndex = 0;
499 for (const model of visibleModels) {
500 if (getModelDisabledReason?.(model.instanceId, model.slug)) {
501 continue;
502 }
503 const jumpCommand = modelPickerJumpCommandForIndex(selectableModelIndex);
504 if (!jumpCommand) {
505 return mapping;
506 }
507 mapping.set(modelPickerModelKey(model.instanceId, model.slug), jumpCommand);
508 selectableModelIndex += 1;
509 }
510 return mapping;
511 }, [getModelDisabledReason, visibleModels]);
512 const modelJumpModelKeys = useMemo(
513 () => [...modelJumpCommandByKey.keys()],
514 [modelJumpCommandByKey],
515 );
516 const allItemKeys = useMemo(
517 (): string[] => [
518 ...flatModels.map((model) => modelPickerModelKey(model.instanceId, model.slug)),
519 ...new Set(
520 flatModels
521 .filter((model) => model.isLegacy)
522 .map((model) => modelPickerLegacySectionKey(model.instanceId)),
523 ),
524 ],
525 [flatModels],
526 );
527 const filteredItemKeys = useMemo((): string[] => {
528 const modelKeys = visibleModels.map((model) =>
529 modelPickerModelKey(model.instanceId, model.slug),
530 );
531 if (!legacySection) {
532 return modelKeys;
533 }
534 modelKeys.splice(legacySection.currentModels.length, 0, legacySection.key);
535 return modelKeys;
536 }, [legacySection, visibleModels]);
537 const filteredModelByKey = useMemo(
538 (): ReadonlyMap<string, ModelPickerItem> =>
539 new Map(
540 visibleModels.map(
541 (model) => [modelPickerModelKey(model.instanceId, model.slug), model] as const,
542 ),
543 ),
544 [visibleModels],
545 );
546 const updateModelListScrollFades = useCallback(() => {
547 const scrollElement = modelListRef.current?.getScrollableNode();
548 if (!(scrollElement instanceof HTMLElement)) {
549 return;
550 }
551 const maxScrollOffset = Math.max(0, scrollElement.scrollHeight - scrollElement.clientHeight);
552 setShowTopScrollFade(scrollElement.scrollTop > 1);
553 setShowBottomScrollFade(maxScrollOffset - scrollElement.scrollTop > 1);
554 }, []);
555 const modelJumpShortcutContext = useMemo(
556 () =>
557 ({
558 terminalFocus: false,
559 terminalOpen: props.terminalOpen,
560 modelPickerOpen: true,
561 }) as const,
562 [props.terminalOpen],
563 );
564 const modelJumpLabelByKey = useMemo((): ReadonlyMap<string, string> => {
565 if (modelJumpCommandByKey.size === 0) {
566 return EMPTY_MODEL_JUMP_LABELS;
567 }
568 const shortcutLabelOptions = {
569 platform: navigator.platform,
570 context: modelJumpShortcutContext,
571 };
572 const mapping = new Map<string, string>();
573 for (const [modelKey, command] of modelJumpCommandByKey) {
574 const label = shortcutLabelForCommand(keybindings, command, shortcutLabelOptions);
575 if (label) {
576 mapping.set(modelKey, label);
577 }
578 }
579 return mapping.size > 0 ? mapping : EMPTY_MODEL_JUMP_LABELS;
580 }, [keybindings, modelJumpCommandByKey, modelJumpShortcutContext]);
581 const modelListExtraData = useMemo(
582 () => ({ favoritesSet, modelJumpLabelByKey }),
583 [favoritesSet, modelJumpLabelByKey],
584 );
585
586 useEffect(() => {
587 const onWindowKeyDown = (event: globalThis.KeyboardEvent) => {
588 if (event.defaultPrevented || event.repeat) {
589 return;
590 }
591
592 const command = resolveShortcutCommand(event, keybindings, {
593 platform: navigator.platform,
594 context: modelJumpShortcutContext,
595 });
596 const jumpIndex = modelPickerJumpIndexFromCommand(command ?? "");
597 if (jumpIndex === null) {
598 return;
599 }
600
601 const targetModelKey = modelJumpModelKeys[jumpIndex];
602 if (!targetModelKey) {
603 return;
604 }
605 const model = parseModelPickerModelKey(targetModelKey);
606 if (!model) {
607 return;
608 }
609 event.preventDefault();
610 event.stopPropagation();
611 handleModelSelect(model.slug, model.instanceId);
612 };
613
614 window.addEventListener("keydown", onWindowKeyDown, true);
615
616 return () => {
617 window.removeEventListener("keydown", onWindowKeyDown, true);
618 };
619 }, [handleModelSelect, keybindings, modelJumpModelKeys, modelJumpShortcutContext]);
620
621 useLayoutEffect(() => {
622 setShowTopScrollFade(false);
623 setShowBottomScrollFade(filteredItemKeys.length > 5);
624 let nestedFrame = 0;
625 const frame = window.requestAnimationFrame(() => {
626 updateModelListScrollFades();
627 nestedFrame = window.requestAnimationFrame(updateModelListScrollFades);
628 });
629 return () => {
630 window.cancelAnimationFrame(frame);
631 window.cancelAnimationFrame(nestedFrame);
632 };
633 }, [filteredItemKeys, updateModelListScrollFades]);
634
635 return (
636 <TooltipProvider delay={0}>
637 <div
638 className="relative flex h-screen max-h-86.5 w-screen max-w-90 flex-row overflow-hidden"
639 data-model-picker-content="true"
640 >
641 {/* Sidebar */}
642 {showSidebar && (
643 <ModelPickerSidebar
644 selectedInstanceId={selectedInstanceId}
645 onSelectInstance={handleSelectInstance}
646 instanceEntries={sidebarInstanceEntries}
647 showFavorites
648 {...(selectableUnavailableInstanceIds ? { selectableUnavailableInstanceIds } : {})}
649 {...(lockedDisabledInstanceIds
650 ? {
651 disabledInstanceIds: lockedDisabledInstanceIds,
652 getDisabledInstanceTooltip: (entry: ProviderInstanceEntry) =>
653 `${entry.displayName} is unavailable in this thread. Start a new thread to switch providers.`,
654 }
655 : {})}
656 />
657 )}
658
659 {/* Main content area */}
660 <Combobox
661 inline
662 items={allItemKeys}
663 filteredItems={filteredItemKeys}
664 filter={null}
665 autoHighlight
666 open
667 virtualized
668 value={modelPickerModelKey(props.activeInstanceId, props.model)}
669 onItemHighlighted={(modelKey, eventDetails) => {
670 highlightedModelKeyRef.current = typeof modelKey === "string" ? modelKey : null;
671 if (eventDetails.reason === "keyboard" && eventDetails.index >= 0) {
672 void modelListRef.current?.scrollIndexIntoView?.({
673 index: eventDetails.index,
674 animated: false,
675 });
676 }
677 }}
678 onValueChange={(modelKey) => {
679 if (typeof modelKey !== "string") {
680 return;
681 }
682 const legacyInstanceId = parseModelPickerLegacySectionKey(modelKey);
683 if (legacyInstanceId) {
684 toggleLegacySection(legacyInstanceId);
685 return;
686 }
687 const model = parseModelPickerModelKey(modelKey);
688 if (model) {
689 handleModelSelect(model.slug, model.instanceId);
690 }
691 }}
692 >
693 <div
694 className={cn(
695 "flex min-h-0 flex-1 flex-col overflow-hidden bg-muted/40",
696 showSidebar && "border-l border-border/70",
697 )}
698 >
699 {/* Search bar */}
700 <div className="px-2 pt-2">
701 <div className="border-b border-border/70 pb-2.5 transition-colors focus-within:border-ring">
702 <ComboboxInput
703 ref={searchInputRef}
704 className="[&_input]:h-6.5 [&_input]:font-sans [&_input]:leading-6.5"
705 inputClassName="rounded-none bg-transparent text-sm"
706 placeholder="Search models..."
707 showTrigger={false}
708 startAddon={
709 <SearchIcon className="-translate-x-0.5 size-4 shrink-0 text-muted-foreground opacity-70" />
710 }
711 value={searchQuery}
712 onChange={(e) => setSearchQuery(e.target.value)}
713 onKeyDown={(e) => {
714 if (e.key === "Escape") {
715 e.preventDefault();
716 e.stopPropagation();
717 props.onRequestClose?.();
718 return;
719 }
720 if (e.key === "Enter" && highlightedModelKeyRef.current) {
721 (
722 e as typeof e & { preventBaseUIHandler?: () => void }
723 ).preventBaseUIHandler?.();
724 e.preventDefault();
725 e.stopPropagation();
726 const legacyInstanceId = parseModelPickerLegacySectionKey(
727 highlightedModelKeyRef.current,
728 );
729 if (legacyInstanceId) {
730 toggleLegacySection(legacyInstanceId);
731 return;
732 }
733 const model = parseModelPickerModelKey(highlightedModelKeyRef.current);
734 if (model) {
735 handleModelSelect(model.slug, model.instanceId);
736 }
737 return;
738 }
739 e.stopPropagation();
740 }}
741 onMouseDown={(e) => e.stopPropagation()}
742 onTouchStart={(e) => e.stopPropagation()}
743 size="sm"
744 unstyled
745 />
746 </div>
747 </div>
748
749 {/* Model list */}
750 <div className="relative min-h-0 flex-1 overflow-hidden pr-px">
751 <ComboboxListVirtualized className="size-full min-w-0 p-0 not-empty:p-0">
752 <LegendList<string>
753 ref={modelListRef}
754 data={filteredItemKeys}
755 extraData={modelListExtraData}
756 keyExtractor={(modelKey) => modelKey}
757 renderItem={({ item: modelKey, index }) => {
758 if (legacySection?.key === modelKey) {
759 return (
760 <ComboboxItem
761 hideIndicator
762 index={index}
763 value={modelKey}
764 aria-expanded={legacySection.isExpanded}
765 className="group w-full cursor-pointer rounded-md px-2 py-2"
766 contentClassName="flex w-full items-center gap-3"
767 >
768 <div className="min-w-0 flex-1 text-left">
769 <div className="text-xs font-medium leading-snug">Legacy models</div>
770 <div className="mt-1 text-xs font-normal leading-snug text-muted-foreground/70">
771 {legacySection.legacyModels.length} models
772 </div>
773 </div>
774 <ChevronRightIcon
775 className={cn(
776 "size-4 transition-transform",
777 legacySection.isExpanded && "rotate-90",
778 )}
779 />
780 </ComboboxItem>
781 );
782 }
783 const model = filteredModelByKey.get(modelKey);
784 if (!model) {
785 return null;
786 }
787 const disabledReason =
788 getModelDisabledReason?.(model.instanceId, model.slug) ?? null;
789 return (
790 <ModelListRow
791 key={modelKey}
792 index={index}
793 model={model}
794 instanceId={model.instanceId}
795 driverKind={model.driverKind}
796 providerDisplayName={model.instanceDisplayName}
797 providerAccentColor={model.instanceAccentColor}
798 isFavorite={favoritesSet.has(
799 providerModelKey(model.instanceId, model.slug),
800 )}
801 isSelected={
802 modelKey === modelPickerModelKey(props.activeInstanceId, props.model)
803 }
804 showProvider
805 preferShortName={!isLocked}
806 useTriggerLabel={false}
807 showNewBadge={isModelPickerNewModel(model.driverKind, model.slug)}
808 unavailable={model.isUnavailable === true}
809 jumpLabel={modelJumpLabelByKey.get(modelKey) ?? null}
810 disabledReason={disabledReason}
811 onToggleFavorite={() => toggleFavorite(model.instanceId, model.slug)}
812 />
813 );
814 }}
815 estimatedItemSize={52}
816 drawDistance={480}
817 recycleItems
818 contentContainerClassName="pl-2 pr-px"
819 ItemSeparatorComponent={ModelListSeparator}
820 onLayout={updateModelListScrollFades}
821 onScroll={updateModelListScrollFades}
822 className={cn(
823 "scrollbar-gutter-stable h-full overflow-x-hidden overscroll-y-contain py-1.5 [&::-webkit-scrollbar-track]:my-2",
824 getVirtualizedScrollFadeClassName({
825 top: showTopScrollFade,
826 bottom: showBottomScrollFade,
827 }),
828 )}
829 />
830 </ComboboxListVirtualized>
831 </div>
832 <ComboboxEmpty className="not-empty:py-6 empty:h-0 text-xs font-normal leading-snug">
833 No models found
834 </ComboboxEmpty>
835 </div>
836 </Combobox>
837 </div>
838 </TooltipProvider>
839 );
840});