Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ModelPickerContent.tsx

957 lines35.3 KB

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