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