Open History to see the last commit
1import { useLegendListRef } from "~/hooks/useLegendListRef";
2import {
3 ANTIGRAVITY_DEFAULT_MODEL,
4 type ProviderInstanceId,
5 type EnvironmentId,
6 type ProviderDriverKind,
7 type ResolvedKeybindingsConfig,
8 MODEL_PICKER_JUMP_KEYBINDING_COMMANDS,
9} from "@t3tools/contracts";
10import { resolveSelectableModel } from "@t3tools/shared/model";
11import { useAtomValue } from "@effect/atom-react";
12import { formatProviderUpdateRequiredNotice } from "@t3tools/client-runtime/providerUpdateRequiredModels";
13import { useNavigate } from "@tanstack/react-router";
14import { LegendList, type LegendListRef } from "@legendapp/list/react";
15import {
16 memo,
17 useState,
18 useEffect,
19 useEffectEvent,
20 useLayoutEffect,
21 useRef,
22 type ReactNode,
23 type RefObject,
24} from "react";
25import { ModelListRow } from "./ModelListRow";
26import { ModelPickerSidebar } from "./ModelPickerSidebar";
27import { getProviderStatusMessage, hasProviderSetup } from "./ProviderStatusBanner";
28import {
29 modelPickerLegacySectionKey,
30 modelPickerModelKey,
31 parseModelPickerLegacySectionKey,
32 parseModelPickerModelKey,
33} from "./modelPickerKeys";
34import { rankModelPickerSearch } from "@t3tools/client-runtime/model-search";
35import {
36 Combobox,
37 ComboboxEmpty,
38 ComboboxSearchInput,
39 ComboboxItem,
40 ComboboxListVirtualized,
41} from "../ui/combobox";
42import { ModelEsque } from "./providerIconUtils";
43import { isCommandPaletteOpen } from "../../commandPaletteBus";
44import { registerModelPickerContent } from "../../modelPickerVisibility";
45import { primaryServerKeybindingsAtom } from "../../state/server";
46import {
47 modelPickerJumpCommandForIndex,
48 modelPickerJumpIndexFromCommand,
49 resolveShortcutCommand,
50 shortcutLabelForCommand,
51} from "../../keybindings";
52import {
53 useEnvironmentModelPreferences,
54 useToggleEnvironmentModelFavorite,
55} from "~/hooks/useSettings";
56import { announce } from "~/lib/announce";
57import { cn } from "~/lib/utils";
58import { getVirtualizedScrollFadeClassName } from "../ui/scroll-area";
59import { TooltipProvider } from "../ui/tooltip";
60import { InlineButton } from "../ui/button";
61import {
62 isProviderInstancePickerReady,
63 isProviderInstancePickerVisible,
64 shouldShowInstanceBadge,
65 type ProviderInstanceEntry,
66} from "../../providerInstances";
67import { providerModelKey, sortProviderModelItems } from "../../modelOrdering";
68
69type ModelPickerItem = {
70 slug: string;
71 name: string;
72 shortName?: string;
73 subProvider?: string;
74 badge?: "new";
75 instanceId: ProviderInstanceId;
76 driverKind: ProviderDriverKind;
77 instanceDisplayName: string;
78 instanceAccentColor?: string | undefined;
79 acpRegistryAgentId?: string | undefined;
80 acpRegistryIconUrl?: string | undefined;
81 continuationGroupKey?: string | undefined;
82 isLegacy?: boolean | undefined;
83 isUnavailable?: boolean | undefined;
84};
85
86export function resolveModelPickerSelectedModel(input: {
87 driverKind: ProviderDriverKind | undefined;
88 model: string;
89 options: ReadonlyArray<ModelEsque>;
90}) {
91 if (input.driverKind === "antigravity" && input.model === ANTIGRAVITY_DEFAULT_MODEL) {
92 const availableModels = input.options.filter(
93 (option) => option.slug !== ANTIGRAVITY_DEFAULT_MODEL && !option.isUnavailable,
94 );
95 return (
96 availableModels.find((option) => option.aliases?.includes(ANTIGRAVITY_DEFAULT_MODEL)) ??
97 availableModels.find((option) => option.isDefault)
98 );
99 }
100 return input.options.find((option) => option.slug === input.model);
101}
102
103function shouldIncludeModelPickerOption(input: {
104 readonly entry: ProviderInstanceEntry;
105 readonly option: ModelEsque;
106 readonly activeInstanceId: ProviderInstanceId;
107 readonly activeModel: string;
108}): boolean {
109 if (input.entry.driverKind === "antigravity" && input.option.slug === ANTIGRAVITY_DEFAULT_MODEL) {
110 return false;
111 }
112 if (isProviderInstancePickerReady(input.entry)) return true;
113 return (
114 input.entry.enabled &&
115 (input.entry.driverKind === "opencode" || input.entry.driverKind === "antigravity") &&
116 input.entry.instanceId === input.activeInstanceId &&
117 input.option.slug === input.activeModel &&
118 input.option.isUnavailable === true
119 );
120}
121
122function shouldOfferModelPickerSetup(
123 entry: ProviderInstanceEntry,
124 options: ReadonlyArray<ModelEsque>,
125): boolean {
126 return (
127 entry.enabled &&
128 entry.status !== "disabled" &&
129 hasProviderSetup(entry.snapshot) &&
130 (!isProviderInstancePickerReady(entry) ||
131 !entry.installed ||
132 entry.snapshot.auth.status === "unauthenticated" ||
133 !options.some((option) => !option.isUnavailable))
134 );
135}
136
137function adjacentModelPickerProvider(input: {
138 entries: ReadonlyArray<ProviderInstanceEntry>;
139 selectedInstanceId: ProviderInstanceId | "favorites";
140 direction: 1 | -1;
141 disabledInstanceIds: ReadonlySet<ProviderInstanceId> | undefined;
142 selectableUnavailableInstanceIds: ReadonlySet<ProviderInstanceId> | undefined;
143}) {
144 const providers: Array<ProviderInstanceId | "favorites"> = [
145 "favorites",
146 ...input.entries
147 .filter(
148 (entry) =>
149 !input.disabledInstanceIds?.has(entry.instanceId) &&
150 (isProviderInstancePickerReady(entry) ||
151 input.selectableUnavailableInstanceIds?.has(entry.instanceId)),
152 )
153 .map((entry) => entry.instanceId),
154 ];
155 const index = providers.indexOf(input.selectedInstanceId);
156 return providers[
157 index < 0
158 ? input.direction === 1
159 ? 0
160 : providers.length - 1
161 : (index + input.direction + providers.length) % providers.length
162 ]!;
163}
164
165const EMPTY_MODEL_JUMP_LABELS = new Map<string, string>();
166const MODEL_LIST_ESTIMATED_ITEM_SIZE = 32;
167// Rendered heights in `--spacing` units. Chrome is the search box and list padding, plus a 1px border.
168const ROW_UNITS = 8;
169const ROW_SEPARATOR_UNITS = 0.5;
170const LIST_CHROME_UNITS = 15.5;
171
172function ModelListSeparator() {
173 return <div className="h-0.5" />;
174}
175
176function modelJumpLabelsByKey(
177 modelKeys: ReadonlyArray<string>,
178 keybindings: ResolvedKeybindingsConfig,
179 terminalOpen: boolean,
180): ReadonlyMap<string, string> {
181 const shortcutLabelOptions = {
182 platform: navigator.platform,
183 context: { terminalFocus: false, terminalOpen, modelPickerOpen: true },
184 };
185 const mapping = new Map<string, string>();
186 for (const [index, modelKey] of modelKeys.entries()) {
187 const command = modelPickerJumpCommandForIndex(index);
188 const label = command && shortcutLabelForCommand(keybindings, command, shortcutLabelOptions);
189 if (label) {
190 mapping.set(modelKey, label);
191 }
192 }
193 return mapping.size > 0 ? mapping : EMPTY_MODEL_JUMP_LABELS;
194}
195
196function ModelPickerProviderNotices({
197 setupEntries,
198 updateRequiredNotices,
199 emptyLabel,
200 onRequestClose,
201 onOpenProviderSetup,
202}: {
203 setupEntries: ReadonlyArray<ProviderInstanceEntry>;
204 emptyLabel: string;
205 updateRequiredNotices: ReadonlyArray<{ instanceId: ProviderInstanceId; notice: string }>;
206 onRequestClose: (() => void) | undefined;
207 onOpenProviderSetup: ((instanceId: ProviderInstanceId) => void) | undefined;
208}) {
209 const navigate = useNavigate();
210 return (
211 <>
212 {setupEntries.length > 0 ? (
213 <div className="max-h-44 shrink-0 overflow-y-auto border-t border-border/70 p-2">
214 {setupEntries.map((entry) => (
215 <div key={entry.instanceId} className="px-1 py-1.5 text-xs leading-snug">
216 <p className="line-clamp-3 text-muted-foreground">
217 {getProviderStatusMessage(entry.snapshot)}
218 </p>
219 <InlineButton
220 className="mt-1"
221 onClick={() => {
222 onRequestClose?.();
223 onOpenProviderSetup?.(entry.instanceId);
224 }}
225 >
226 {setupEntries.length > 1 ? `Set up ${entry.displayName}` : "Open provider setup"}
227 </InlineButton>
228 </div>
229 ))}
230 </div>
231 ) : (
232 <ComboboxEmpty className="empty:h-0">{emptyLabel}</ComboboxEmpty>
233 )}
234 {updateRequiredNotices.map(({ instanceId, notice }) => (
235 <p
236 key={instanceId}
237 className="shrink-0 border-t border-border/70 px-3 py-2 text-xs leading-snug text-muted-foreground"
238 >
239 {notice}{" "}
240 <InlineButton
241 onClick={() => {
242 onRequestClose?.();
243 void navigate({ to: "/settings/providers" });
244 }}
245 >
246 Provider settings
247 </InlineButton>
248 </p>
249 ))}
250 </>
251 );
252}
253
254function ModelPickerList({
255 listRef,
256 itemKeys,
257 extraData,
258 renderItem,
259}: {
260 listRef: RefObject<LegendListRef | null>;
261 itemKeys: ReadonlyArray<string>;
262 extraData: unknown;
263 renderItem: (props: { item: string; index: number }) => ReactNode;
264}) {
265 const [showTopScrollFade, setShowTopScrollFade] = useState(false);
266 const [showBottomScrollFade, setShowBottomScrollFade] = useState(false);
267 const updateScrollFades = () => {
268 const metrics = listRef.current?.getState();
269 if (!metrics) return;
270 setShowTopScrollFade(!metrics.isAtStart);
271 setShowBottomScrollFade(!metrics.isAtEnd);
272 };
273 const scrollRef = useLegendListRef(listRef, updateScrollFades);
274
275 return (
276 <div
277 className={cn(
278 "relative min-h-0 overflow-hidden pr-px",
279 itemKeys.length > 0 ? "flex-1" : "h-0",
280 )}
281 >
282 <ComboboxListVirtualized>
283 <LegendList<string>
284 ref={scrollRef}
285 data={itemKeys}
286 extraData={extraData}
287 keyExtractor={(modelKey) => modelKey}
288 renderItem={renderItem}
289 estimatedItemSize={MODEL_LIST_ESTIMATED_ITEM_SIZE}
290 drawDistance={480}
291 recycleItems
292 contentContainerClassName="pl-2 pr-px"
293 ItemSeparatorComponent={ModelListSeparator}
294 onLayout={updateScrollFades}
295 onScroll={updateScrollFades}
296 onReady={updateScrollFades}
297 className={cn(
298 "scrollbar-gutter-stable h-full overflow-x-hidden overscroll-y-contain py-1.5 [&::-webkit-scrollbar-track]:my-2",
299 getVirtualizedScrollFadeClassName({
300 top: showTopScrollFade,
301 bottom: showBottomScrollFade,
302 }),
303 )}
304 />
305 </ComboboxListVirtualized>
306 </div>
307 );
308}
309
310// Capture gives picker shortcuts priority over the composer.
311function WindowKeyDownListener({ onKeyDown }: { onKeyDown: (event: KeyboardEvent) => void }) {
312 const handleKeyDown = useEffectEvent(onKeyDown);
313 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes a capture-phase window keydown listener for the picker's lifetime
314 useEffect(() => {
315 const listener = (event: KeyboardEvent) => handleKeyDown(event);
316 window.addEventListener("keydown", listener, true);
317 return () => {
318 window.removeEventListener("keydown", listener, true);
319 };
320 }, []);
321 return null;
322}
323
324export const ModelPickerContent = memo(function ModelPickerContent(props: {
325 environmentId: EnvironmentId | null;
326 activeInstanceId: ProviderInstanceId;
327 model: string;
328 selectedModels?: ReadonlyArray<{ instanceId: ProviderInstanceId; model: string }>;
329 onToggleModel?: (instanceId: ProviderInstanceId, model: string) => void;
330 lockedProvider: ProviderDriverKind | null;
331 lockedContinuationGroupKey?: string | null;
332 instanceEntries: ReadonlyArray<ProviderInstanceEntry>;
333 keybindings?: ResolvedKeybindingsConfig;
334 modelOptionsByInstance: ReadonlyMap<ProviderInstanceId, ReadonlyArray<ModelEsque>>;
335 terminalOpen: boolean;
336 onRequestClose?: () => void;
337 onOpenProviderSetup?: (instanceId: ProviderInstanceId) => void;
338 getModelDisabledReason?: (instanceId: ProviderInstanceId, model: string) => string | null;
339 onInstanceModelChange: (instanceId: ProviderInstanceId, model: string) => void;
340 /** The owning popup moves focus here when it opens (its `initialFocus`). */
341 searchInputRef: RefObject<HTMLInputElement | null>;
342 /** Sits beside an effort column: fills the shared row, and stacks above it on narrow screens. */
343 docked?: boolean;
344 /** Right at the end of the search text moves into the popup's effort column. */
345 onFocusEffort?: () => void;
346 /** Closes the list column, inside the popup's fixed height. */
347 listFooter?: ReactNode;
348}) {
349 const {
350 searchInputRef,
351 keybindings: providedKeybindings,
352 modelOptionsByInstance,
353 instanceEntries,
354 getModelDisabledReason,
355 onInstanceModelChange,
356 onToggleModel,
357 onRequestClose,
358 onOpenProviderSetup,
359 } = props;
360 const [searchQuery, setSearchQuery] = useState("");
361 const modelListRef = useRef<LegendListRef | null>(null);
362 const pickerContentRef = useRef<HTMLDivElement>(null);
363 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes this picker's mount to global keydown handlers
364 useLayoutEffect(() => registerModelPickerContent(), []);
365 const highlightedModelKeyRef = useRef<string | null>(null);
366 const { favorites } = useEnvironmentModelPreferences(props.environmentId);
367 const activeEntry = props.instanceEntries.find(
368 (entry) => entry.instanceId === props.activeInstanceId,
369 );
370 const activeModel = resolveModelPickerSelectedModel({
371 driverKind: activeEntry?.driverKind,
372 model: props.model,
373 options: modelOptionsByInstance.get(props.activeInstanceId) ?? [],
374 });
375 const activeModelSlug =
376 activeModel?.slug ?? (props.model === ANTIGRAVITY_DEFAULT_MODEL ? "" : props.model);
377 const activeModelKey = activeModelSlug
378 ? modelPickerModelKey(props.activeInstanceId, activeModelSlug)
379 : null;
380 const selectedModelKeys = props.selectedModels?.map((selection) => {
381 const entry = instanceEntries.find((entry) => entry.instanceId === selection.instanceId);
382 const model = resolveModelPickerSelectedModel({
383 driverKind: entry?.driverKind,
384 model: selection.model,
385 options: modelOptionsByInstance.get(selection.instanceId) ?? [],
386 });
387 return modelPickerModelKey(selection.instanceId, model?.slug ?? selection.model);
388 });
389 const selectedModelKeySet = new Set(
390 selectedModelKeys ?? (activeModelKey ? [activeModelKey] : []),
391 );
392 const activeInstanceHasSelectableUnavailableModel =
393 activeEntry !== undefined &&
394 (modelOptionsByInstance.get(props.activeInstanceId) ?? []).some((option) =>
395 shouldIncludeModelPickerOption({
396 entry: activeEntry,
397 option,
398 activeInstanceId: props.activeInstanceId,
399 activeModel: activeModelSlug,
400 }),
401 ) &&
402 !isProviderInstancePickerReady(activeEntry);
403 const activeInstanceNeedsSetup =
404 onOpenProviderSetup !== undefined &&
405 activeEntry !== undefined &&
406 shouldOfferModelPickerSetup(
407 activeEntry,
408 modelOptionsByInstance.get(props.activeInstanceId) ?? [],
409 );
410 const [selectedInstanceId, setSelectedInstanceId] = useState<ProviderInstanceId | "favorites">(
411 () => {
412 if (
413 props.lockedProvider !== null ||
414 activeInstanceHasSelectableUnavailableModel ||
415 activeInstanceNeedsSetup
416 ) {
417 return props.activeInstanceId;
418 }
419 return favorites.length > 0 ? "favorites" : props.activeInstanceId;
420 },
421 );
422 const favoritesSet = new Set(favorites.map((fav) => providerModelKey(fav.provider, fav.model)));
423 const [expandedLegacyInstances, setExpandedLegacyInstances] = useState(
424 () =>
425 new Set<ProviderInstanceId>(
426 activeModel?.isLegacy &&
427 !favoritesSet.has(providerModelKey(props.activeInstanceId, activeModelSlug))
428 ? [props.activeInstanceId]
429 : [],
430 ),
431 );
432 const serverKeybindings = useAtomValue(primaryServerKeybindingsAtom);
433 const keybindings = providedKeybindings ?? serverKeybindings;
434 const [searchHeight, setSearchHeight] = useState(0);
435 const toggleFavorite = useToggleEnvironmentModelFavorite(props.environmentId);
436
437 const focusSearchInput = () => {
438 searchInputRef.current?.focus({ preventScroll: true });
439 };
440
441 const handleSelectInstance = (instanceId: ProviderInstanceId | "favorites") => {
442 setSelectedInstanceId(instanceId);
443 window.requestAnimationFrame(() => {
444 focusSearchInput();
445 });
446 };
447
448 const toggleLegacySection = (instanceId: ProviderInstanceId) => {
449 setExpandedLegacyInstances((expanded) => {
450 const next = new Set(expanded);
451 if (next.has(instanceId)) {
452 next.delete(instanceId);
453 } else {
454 next.add(instanceId);
455 }
456 return next;
457 });
458 };
459
460 const handleModelSelect = (
461 modelSlug: string,
462 instanceId: ProviderInstanceId,
463 additive = false,
464 ): string | null => {
465 if (getModelDisabledReason?.(instanceId, modelSlug)) {
466 return null;
467 }
468 const options = modelOptionsByInstance.get(instanceId);
469 if (!options) {
470 return null;
471 }
472 const entry = instanceEntries.find((candidate) => candidate.instanceId === instanceId);
473 if (!entry) {
474 return null;
475 }
476 const resolvedModel = resolveSelectableModel(entry.driverKind, modelSlug, options);
477 if (!resolvedModel) return null;
478 if (additive && onToggleModel) {
479 onToggleModel(instanceId, resolvedModel);
480 } else {
481 onInstanceModelChange(instanceId, resolvedModel);
482 }
483 return resolvedModel;
484 };
485
486 const modelJumpShortcutContext = {
487 terminalFocus: false,
488 terminalOpen: props.terminalOpen,
489 modelPickerOpen: true,
490 } as const;
491 const lockedProvider = props.lockedProvider;
492 const lockedContinuationGroupKey = props.lockedContinuationGroupKey;
493 const canOpenProviderSetup = onOpenProviderSetup !== undefined;
494
495 const entryByInstanceId = new Map(instanceEntries.map((entry) => [entry.instanceId, entry]));
496 const matchesLockedProvider = (
497 entry: Pick<ProviderInstanceEntry, "driverKind" | "continuationGroupKey">,
498 ): boolean => {
499 if (lockedProvider === null) return true;
500 if (entry.driverKind !== lockedProvider) return false;
501 if (!lockedContinuationGroupKey) return true;
502 return entry.continuationGroupKey === lockedContinuationGroupKey;
503 };
504
505 const selectableUnavailableInstanceIds = (() => {
506 const instanceIds = new Set<ProviderInstanceId>();
507 if (activeInstanceHasSelectableUnavailableModel) {
508 instanceIds.add(props.activeInstanceId);
509 }
510 if (canOpenProviderSetup) {
511 for (const entry of instanceEntries) {
512 if (
513 shouldOfferModelPickerSetup(entry, modelOptionsByInstance.get(entry.instanceId) ?? [])
514 ) {
515 instanceIds.add(entry.instanceId);
516 }
517 }
518 }
519 return instanceIds.size > 0 ? instanceIds : undefined;
520 })();
521
522 const flatModels = (() => {
523 const out: ModelPickerItem[] = [];
524 for (const [instanceId, models] of modelOptionsByInstance) {
525 const entry = entryByInstanceId.get(instanceId);
526 if (!entry) {
527 continue;
528 }
529 for (const model of models) {
530 if (
531 !shouldIncludeModelPickerOption({
532 entry,
533 option: model,
534 activeInstanceId: props.activeInstanceId,
535 activeModel: activeModelSlug,
536 })
537 ) {
538 continue;
539 }
540 out.push({
541 slug: model.slug,
542 name: model.name,
543 ...(model.shortName ? { shortName: model.shortName } : {}),
544 ...(model.subProvider ? { subProvider: model.subProvider } : {}),
545 ...(model.badge ? { badge: model.badge } : {}),
546 ...(model.isLegacy ? { isLegacy: true } : {}),
547 ...(model.isUnavailable ? { isUnavailable: true } : {}),
548 instanceId,
549 driverKind: entry.driverKind,
550 instanceDisplayName: entry.displayName,
551 ...(entry.accentColor ? { instanceAccentColor: entry.accentColor } : {}),
552 ...(entry.acpRegistryAgentId ? { acpRegistryAgentId: entry.acpRegistryAgentId } : {}),
553 ...(entry.acpRegistryIconUrl ? { acpRegistryIconUrl: entry.acpRegistryIconUrl } : {}),
554 ...(entry.continuationGroupKey
555 ? { continuationGroupKey: entry.continuationGroupKey }
556 : {}),
557 });
558 }
559 }
560 return out;
561 })();
562
563 const isLocked = lockedProvider !== null;
564 const isSearching = searchQuery.trim().length > 0;
565 // Fit the tallest tab so switching tabs never resizes the popup and moves the rail under the cursor.
566 const tallestTabUnits = (() => {
567 const unitsByTab = new Map<ProviderInstanceId | "favorites", number>();
568 const addRow = (tab: ProviderInstanceId | "favorites") => {
569 const previous = unitsByTab.get(tab);
570 unitsByTab.set(
571 tab,
572 previous === undefined ? ROW_UNITS : previous + ROW_SEPARATOR_UNITS + ROW_UNITS,
573 );
574 };
575 const tabsWithLegacyRow = new Set<ProviderInstanceId>();
576 for (const model of flatModels) {
577 if (!matchesLockedProvider(model)) continue;
578 const isFavorite = favoritesSet.has(providerModelKey(model.instanceId, model.slug));
579 if (isFavorite) addRow("favorites");
580 if (model.isLegacy && !isFavorite) {
581 tabsWithLegacyRow.add(model.instanceId);
582 } else {
583 addRow(model.instanceId);
584 }
585 }
586 for (const instanceId of tabsWithLegacyRow) addRow(instanceId);
587 return Math.max(0, ...unitsByTab.values());
588 })();
589 const lockedDisabledInstanceIds = (() => {
590 if (!isLocked) {
591 return undefined;
592 }
593 const disabled = new Set<ProviderInstanceId>();
594 for (const entry of instanceEntries) {
595 if (!matchesLockedProvider(entry)) {
596 disabled.add(entry.instanceId);
597 }
598 }
599 return disabled;
600 })();
601 const sidebarInstanceEntries = (() => {
602 const enabledEntries = instanceEntries.filter(isProviderInstancePickerVisible);
603 if (!isLocked) {
604 return enabledEntries;
605 }
606 const available: ProviderInstanceEntry[] = [];
607 const disabled: ProviderInstanceEntry[] = [];
608 for (const entry of enabledEntries) {
609 if (matchesLockedProvider(entry)) {
610 available.push(entry);
611 } else {
612 disabled.push(entry);
613 }
614 }
615 return [...available, ...disabled];
616 })();
617 const showSidebar = !isSearching && sidebarInstanceEntries.length > 0;
618 const instanceOrder = instanceEntries.map((entry) => entry.instanceId);
619
620 const filteredModels = (() => {
621 let result = flatModels;
622
623 if (searchQuery.trim()) {
624 const candidates =
625 lockedProvider !== null ? result.filter((m) => matchesLockedProvider(m)) : result;
626 return rankModelPickerSearch(candidates, searchQuery, (model) => ({
627 name: model.name,
628 ...(model.shortName ? { shortName: model.shortName } : {}),
629 ...(model.subProvider ? { subProvider: model.subProvider } : {}),
630 driverKind: model.driverKind,
631 providerDisplayName: model.instanceDisplayName,
632 isFavorite: favoritesSet.has(providerModelKey(model.instanceId, model.slug)),
633 }));
634 }
635
636 if (lockedProvider !== null) {
637 result = result.filter((m) => matchesLockedProvider(m));
638 if (selectedInstanceId === "favorites") {
639 result = result.filter((m) => favoritesSet.has(providerModelKey(m.instanceId, m.slug)));
640 } else {
641 result = result.filter((m) => m.instanceId === selectedInstanceId);
642 }
643 } else if (selectedInstanceId === "favorites") {
644 result = result.filter((m) => favoritesSet.has(providerModelKey(m.instanceId, m.slug)));
645 } else {
646 result = result.filter((m) => m.instanceId === selectedInstanceId);
647 }
648
649 return sortProviderModelItems(result, {
650 favoriteModelKeys: favoritesSet,
651 groupFavorites: selectedInstanceId !== "favorites",
652 instanceOrder: selectedInstanceId === "favorites" ? instanceOrder : [],
653 });
654 })();
655
656 const legacySection = (() => {
657 if (isSearching || selectedInstanceId === "favorites") {
658 return null;
659 }
660 const currentModels: ModelPickerItem[] = [];
661 const legacyModels: ModelPickerItem[] = [];
662 for (const model of filteredModels) {
663 const isLegacy =
664 model.isLegacy && !favoritesSet.has(providerModelKey(model.instanceId, model.slug));
665 (isLegacy ? legacyModels : currentModels).push(model);
666 }
667 if (legacyModels.length === 0) {
668 return null;
669 }
670 return {
671 key: modelPickerLegacySectionKey(selectedInstanceId),
672 currentModels,
673 legacyModels,
674 isExpanded: expandedLegacyInstances.has(selectedInstanceId),
675 };
676 })();
677
678 const visibleModels = (() => {
679 if (!legacySection) {
680 return filteredModels;
681 }
682 return [
683 ...legacySection.currentModels,
684 ...(legacySection.isExpanded ? legacySection.legacyModels : []),
685 ];
686 })();
687
688 const selectedEntry =
689 selectedInstanceId === "favorites" ? undefined : entryByInstanceId.get(selectedInstanceId);
690 const providerSetupEntries =
691 !isSearching && canOpenProviderSetup
692 ? instanceEntries.filter(
693 (entry) =>
694 matchesLockedProvider(entry) &&
695 shouldOfferModelPickerSetup(
696 entry,
697 modelOptionsByInstance.get(entry.instanceId) ?? [],
698 ) &&
699 (selectedEntry
700 ? entry.instanceId === selectedEntry.instanceId
701 : filteredModels.length === 0),
702 )
703 : [];
704
705 const updateRequiredNotices = instanceEntries.flatMap((entry) => {
706 const shown = isSearching
707 ? matchesLockedProvider(entry)
708 : entry.instanceId === selectedEntry?.instanceId;
709 const notice = shown ? formatProviderUpdateRequiredNotice(entry.snapshot, searchQuery) : null;
710 return notice ? [{ instanceId: entry.instanceId, notice }] : [];
711 });
712
713 const modelJumpModelKeys = visibleModels
714 .filter((model) => !getModelDisabledReason?.(model.instanceId, model.slug))
715 .slice(0, MODEL_PICKER_JUMP_KEYBINDING_COMMANDS.length)
716 .map((model) => modelPickerModelKey(model.instanceId, model.slug));
717 const allItemKeys = ((): string[] => [
718 ...flatModels.map((model) => modelPickerModelKey(model.instanceId, model.slug)),
719 ...new Set(
720 flatModels
721 .filter((model) => model.isLegacy)
722 .map((model) => modelPickerLegacySectionKey(model.instanceId)),
723 ),
724 ])();
725 const filteredItemKeys = ((): string[] => {
726 const modelKeys = visibleModels.map((model) =>
727 modelPickerModelKey(model.instanceId, model.slug),
728 );
729 // The toggle trails the list, so expanding it reveals older models above it.
730 return legacySection ? [...modelKeys, legacySection.key] : modelKeys;
731 })();
732 const filteredModelByKey = ((): ReadonlyMap<string, ModelPickerItem> =>
733 new Map(
734 visibleModels.map(
735 (model) => [modelPickerModelKey(model.instanceId, model.slug), model] as const,
736 ),
737 ))();
738
739 const modelJumpLabelByKey = modelJumpLabelsByKey(
740 modelJumpModelKeys,
741 keybindings,
742 props.terminalOpen,
743 );
744 const badgedInstanceIds = new Set(
745 instanceEntries
746 .filter((entry) => shouldShowInstanceBadge(entry, instanceEntries))
747 .map((entry) => entry.instanceId),
748 );
749 const modelListExtraData = {
750 badgedInstanceIds,
751 favoritesSet,
752 modelJumpLabelByKey,
753 activeModelKey,
754 selectedModelKeySet,
755 };
756
757 const onWindowKeyDown = (event: globalThis.KeyboardEvent) => {
758 if (
759 event.defaultPrevented ||
760 event.repeat ||
761 event.isComposing ||
762 event.keyCode === 229 ||
763 isCommandPaletteOpen()
764 ) {
765 return;
766 }
767
768 const command = resolveShortcutCommand(event, keybindings, {
769 platform: navigator.platform,
770 context: modelJumpShortcutContext,
771 });
772 if (command === "modelPicker.previousProvider" || command === "modelPicker.nextProvider") {
773 event.preventDefault();
774 event.stopPropagation();
775 const next = adjacentModelPickerProvider({
776 entries: sidebarInstanceEntries,
777 selectedInstanceId,
778 direction: command === "modelPicker.nextProvider" ? 1 : -1,
779 disabledInstanceIds: lockedDisabledInstanceIds,
780 selectableUnavailableInstanceIds,
781 });
782 setSearchQuery("");
783 handleSelectInstance(next);
784 announce(
785 next === "favorites" ? "Favorites" : (entryByInstanceId.get(next)?.displayName ?? next),
786 "model-picker",
787 );
788 return;
789 }
790 const jumpIndex = modelPickerJumpIndexFromCommand(command ?? "");
791 if (jumpIndex === null) {
792 return;
793 }
794 event.preventDefault();
795 event.stopPropagation();
796
797 const targetModelKey = modelJumpModelKeys[jumpIndex];
798 if (!targetModelKey) {
799 return;
800 }
801 const model = parseModelPickerModelKey(targetModelKey);
802 if (!model) {
803 return;
804 }
805 const selectedSlug = handleModelSelect(model.slug, model.instanceId);
806 if (selectedSlug === null) return;
807 const name = flatModels.find(
808 (item) => item.slug === selectedSlug && item.instanceId === model.instanceId,
809 )?.name;
810 announce(`Model: ${name ?? selectedSlug}`, "model-picker");
811 };
812
813 return (
814 <TooltipProvider delay={0}>
815 <WindowKeyDownListener onKeyDown={onWindowKeyDown} />
816 <div
817 ref={pickerContentRef}
818 className={cn(
819 "relative flex w-screen max-w-90 flex-row overflow-hidden",
820 props.docked ? "max-sm:h-56 max-sm:w-full max-sm:max-w-none" : "max-h-86.5",
821 )}
822 // Docked, the popup sets the height; a minimum here would overflow short windows.
823 style={
824 props.docked
825 ? undefined
826 : isSearching
827 ? { height: searchHeight }
828 : {
829 minHeight: `min(calc(var(--spacing) * ${tallestTabUnits + LIST_CHROME_UNITS} + 1px), calc(var(--spacing) * 86.5))`,
830 }
831 }
832 data-model-picker-content="true"
833 >
834 {showSidebar && (
835 <ModelPickerSidebar
836 selectedInstanceId={selectedInstanceId}
837 onSelectInstance={handleSelectInstance}
838 onFocusSearch={focusSearchInput}
839 instanceEntries={sidebarInstanceEntries}
840 showFavorites
841 {...(selectableUnavailableInstanceIds ? { selectableUnavailableInstanceIds } : {})}
842 {...(lockedDisabledInstanceIds
843 ? {
844 disabledInstanceIds: lockedDisabledInstanceIds,
845 getDisabledInstanceTooltip: (entry: ProviderInstanceEntry) =>
846 `${entry.displayName} is unavailable in this thread. Start a new thread to switch providers.`,
847 }
848 : {})}
849 />
850 )}
851
852 <Combobox<string, boolean>
853 inline
854 items={allItemKeys}
855 filteredItems={filteredItemKeys}
856 filter={null}
857 autoHighlight
858 open
859 virtualized
860 multiple={onToggleModel !== undefined}
861 value={onToggleModel ? [...selectedModelKeySet] : activeModelKey}
862 onItemHighlighted={(modelKey, eventDetails) => {
863 highlightedModelKeyRef.current = typeof modelKey === "string" ? modelKey : null;
864 if (eventDetails.reason === "keyboard" && eventDetails.index >= 0) {
865 void modelListRef.current?.scrollIndexIntoView?.({
866 index: eventDetails.index,
867 animated: false,
868 });
869 }
870 }}
871 onValueChange={(value, details) => {
872 const modelKey = Array.isArray(value)
873 ? (value.find((key) => !selectedModelKeySet.has(key)) ??
874 [...selectedModelKeySet].find((key) => !value.includes(key)))
875 : value;
876 if (typeof modelKey !== "string") {
877 return;
878 }
879 const legacyInstanceId = parseModelPickerLegacySectionKey(modelKey);
880 if (legacyInstanceId) {
881 toggleLegacySection(legacyInstanceId);
882 return;
883 }
884 const model = parseModelPickerModelKey(modelKey);
885 if (model) {
886 handleModelSelect(
887 model.slug,
888 model.instanceId,
889 "shiftKey" in details.event && details.event.shiftKey === true,
890 );
891 }
892 }}
893 >
894 <div
895 className={cn(
896 "flex min-h-0 flex-1 flex-col overflow-hidden bg-muted/40",
897 showSidebar && "border-l border-border/70",
898 )}
899 >
900 <ComboboxSearchInput
901 ref={searchInputRef}
902 placeholder="Search models..."
903 value={searchQuery}
904 onChange={(e) => {
905 if (!isSearching) setSearchHeight(pickerContentRef.current?.offsetHeight ?? 0);
906 setSearchQuery(e.target.value);
907 }}
908 onKeyDown={(e) => {
909 if (e.nativeEvent.isComposing || e.keyCode === 229) {
910 (e as typeof e & { preventBaseUIHandler?: () => void }).preventBaseUIHandler?.();
911 e.stopPropagation();
912 return;
913 }
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 onRequestClose?.();
940 return;
941 }
942 if (
943 props.onFocusEffort &&
944 e.key === "ArrowRight" &&
945 !e.altKey &&
946 !e.ctrlKey &&
947 !e.metaKey &&
948 !e.shiftKey &&
949 e.currentTarget.selectionStart === searchQuery.length
950 ) {
951 e.preventDefault();
952 e.stopPropagation();
953 // The column shows the selected model's effort, so a highlighted model is picked
954 // first; the owning popup then moves focus to that model's levels.
955 const highlighted = highlightedModelKeyRef.current
956 ? parseModelPickerModelKey(highlightedModelKeyRef.current)
957 : null;
958 const pickedNew =
959 highlighted !== null &&
960 highlightedModelKeyRef.current !== activeModelKey &&
961 handleModelSelect(highlighted.slug, highlighted.instanceId) !== null;
962 if (!pickedNew) props.onFocusEffort();
963 return;
964 }
965 if (e.key === "Enter" && highlightedModelKeyRef.current) {
966 (e as typeof e & { preventBaseUIHandler?: () => void }).preventBaseUIHandler?.();
967 e.preventDefault();
968 e.stopPropagation();
969 const legacyInstanceId = parseModelPickerLegacySectionKey(
970 highlightedModelKeyRef.current,
971 );
972 if (legacyInstanceId) {
973 toggleLegacySection(legacyInstanceId);
974 return;
975 }
976 const model = parseModelPickerModelKey(highlightedModelKeyRef.current);
977 if (model) {
978 handleModelSelect(model.slug, model.instanceId, e.shiftKey);
979 }
980 return;
981 }
982 e.stopPropagation();
983 }}
984 onMouseDown={(e) => e.stopPropagation()}
985 onTouchStart={(e) => e.stopPropagation()}
986 />
987
988 <ModelPickerList
989 listRef={modelListRef}
990 itemKeys={filteredItemKeys}
991 extraData={modelListExtraData}
992 renderItem={({ item: modelKey, index }) => {
993 if (legacySection?.key === modelKey) {
994 return (
995 <ComboboxItem
996 hideIndicator
997 index={index}
998 value={modelKey}
999 aria-expanded={legacySection.isExpanded}
1000 className="group w-full cursor-pointer"
1001 >
1002 <span className="text-sm leading-snug text-muted-foreground group-hover:text-foreground group-data-highlighted:text-foreground">
1003 {legacySection.isExpanded ? "Show less" : "Show more"}
1004 </span>
1005 </ComboboxItem>
1006 );
1007 }
1008 const model = filteredModelByKey.get(modelKey);
1009 if (!model) {
1010 return null;
1011 }
1012 const disabledReason =
1013 getModelDisabledReason?.(model.instanceId, model.slug) ?? null;
1014 return (
1015 <ModelListRow
1016 key={modelKey}
1017 index={index}
1018 slug={model.slug}
1019 name={model.name}
1020 subProvider={model.subProvider}
1021 instanceId={model.instanceId}
1022 driverKind={model.driverKind}
1023 providerDisplayName={model.instanceDisplayName}
1024 providerAccentColor={model.instanceAccentColor}
1025 acpRegistryAgentId={model.acpRegistryAgentId}
1026 acpRegistryIconUrl={model.acpRegistryIconUrl}
1027 isFavorite={favoritesSet.has(providerModelKey(model.instanceId, model.slug))}
1028 isSelected={
1029 selectedModelKeys !== undefined
1030 ? selectedModelKeySet.has(modelKey)
1031 : modelKey === activeModelKey
1032 }
1033 favoriteStarOnHover={selectedInstanceId === "favorites" && !isSearching}
1034 showInstanceBadge={badgedInstanceIds.has(model.instanceId)}
1035 showNewBadge={model.badge === "new"}
1036 unavailable={model.isUnavailable === true}
1037 jumpLabel={modelJumpLabelByKey.get(modelKey) ?? null}
1038 disabledReason={disabledReason}
1039 onToggleFavorite={toggleFavorite}
1040 />
1041 );
1042 }}
1043 />
1044 <ModelPickerProviderNotices
1045 setupEntries={providerSetupEntries}
1046 updateRequiredNotices={updateRequiredNotices}
1047 emptyLabel={
1048 selectedInstanceId === "favorites" && !isSearching
1049 ? "No favorites yet"
1050 : "No models found"
1051 }
1052 onRequestClose={onRequestClose}
1053 onOpenProviderSetup={onOpenProviderSetup}
1054 />
1055 {props.listFooter}
1056 </div>
1057 </Combobox>
1058 </div>
1059 </TooltipProvider>
1060 );
1061});