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