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