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

ModelPickerContent.tsx

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