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

ModelPickerContent.tsx

1,038 lines38.4 KB

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