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

ModelPickerContent.tsx

1,096 lines41.0 KB

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