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