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