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

ModelPickerContent.tsx

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