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