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