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 /** Closes the list column, inside the popup's fixed height. */
370 listFooter?: ReactNode;
371}) {
372 const {
373 searchInputRef,
374 keybindings: providedKeybindings,
375 modelOptionsByInstance,
376 instanceEntries,
377 getModelDisabledReason,
378 onInstanceModelChange,
379 onToggleModel,
380 onRequestClose,
381 onOpenProviderSetup,
382 } = props;
383 const [searchQuery, setSearchQuery] = useState("");
384 const modelListRef = useRef<LegendListRef | null>(null);
385 const pickerContentRef = useRef<HTMLDivElement>(null);
386 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes this picker's mount to global keydown handlers
387 useLayoutEffect(() => registerModelPickerContent(), []);
388 const highlightedModelKeyRef = useRef<string | null>(null);
389 const { favorites } = useEnvironmentModelPreferences(props.environmentId);
390 const activeEntry = props.instanceEntries.find(
391 (entry) => entry.instanceId === props.activeInstanceId,
392 );
393 const activeModel = resolveModelPickerSelectedModel({
394 driverKind: activeEntry?.driverKind,
395 model: props.model,
396 options: modelOptionsByInstance.get(props.activeInstanceId) ?? [],
397 });
398 const activeModelSlug =
399 activeModel?.slug ?? (props.model === ANTIGRAVITY_DEFAULT_MODEL ? "" : props.model);
400 const activeModelKey = activeModelSlug
401 ? modelPickerModelKey(props.activeInstanceId, activeModelSlug)
402 : null;
403 const selectedModelKeys = props.selectedModels?.map((selection) => {
404 const entry = instanceEntries.find((entry) => entry.instanceId === selection.instanceId);
405 const model = resolveModelPickerSelectedModel({
406 driverKind: entry?.driverKind,
407 model: selection.model,
408 options: modelOptionsByInstance.get(selection.instanceId) ?? [],
409 });
410 return modelPickerModelKey(selection.instanceId, model?.slug ?? selection.model);
411 });
412 const selectedModelKeySet = new Set(
413 selectedModelKeys ?? (activeModelKey ? [activeModelKey] : []),
414 );
415 const activeInstanceHasSelectableUnavailableModel =
416 activeEntry !== undefined &&
417 (modelOptionsByInstance.get(props.activeInstanceId) ?? []).some((option) =>
418 shouldIncludeModelPickerOption({
419 entry: activeEntry,
420 option,
421 activeInstanceId: props.activeInstanceId,
422 activeModel: activeModelSlug,
423 }),
424 ) &&
425 !isProviderInstancePickerReady(activeEntry);
426 const activeInstanceNeedsSetup =
427 onOpenProviderSetup !== undefined &&
428 activeEntry !== undefined &&
429 shouldOfferModelPickerSetup(
430 activeEntry,
431 modelOptionsByInstance.get(props.activeInstanceId) ?? [],
432 );
433 const [selectedInstanceId, setSelectedInstanceId] = useState<ProviderInstanceId | "favorites">(
434 () => {
435 if (
436 props.lockedProvider !== null ||
437 activeInstanceHasSelectableUnavailableModel ||
438 activeInstanceNeedsSetup
439 ) {
440 return props.activeInstanceId;
441 }
442 return favorites.length > 0 ? "favorites" : props.activeInstanceId;
443 },
444 );
445 const favoritesSet = new Set(favorites.map((fav) => providerModelKey(fav.provider, fav.model)));
446 const [expandedLegacyInstances, setExpandedLegacyInstances] = useState(
447 () =>
448 new Set<ProviderInstanceId>(
449 activeModel?.isLegacy &&
450 !favoritesSet.has(providerModelKey(props.activeInstanceId, activeModelSlug))
451 ? [props.activeInstanceId]
452 : [],
453 ),
454 );
455 const serverKeybindings = useAtomValue(primaryServerKeybindingsAtom);
456 const keybindings = providedKeybindings ?? serverKeybindings;
457 const [searchHeight, setSearchHeight] = useState(0);
458 const toggleFavorite = useToggleEnvironmentModelFavorite(props.environmentId);
459
460 const focusSearchInput = () => {
461 searchInputRef.current?.focus({ preventScroll: true });
462 };
463
464 const handleSelectInstance = (instanceId: ProviderInstanceId | "favorites") => {
465 setSelectedInstanceId(instanceId);
466 window.requestAnimationFrame(() => {
467 focusSearchInput();
468 });
469 };
470
471 const toggleLegacySection = (instanceId: ProviderInstanceId) => {
472 setExpandedLegacyInstances((expanded) => {
473 const next = new Set(expanded);
474 if (next.has(instanceId)) {
475 next.delete(instanceId);
476 } else {
477 next.add(instanceId);
478 }
479 return next;
480 });
481 };
482
483 const handleModelSelect = (
484 modelSlug: string,
485 instanceId: ProviderInstanceId,
486 additive = false,
487 ): string | null => {
488 if (getModelDisabledReason?.(instanceId, modelSlug)) {
489 return null;
490 }
491 const options = modelOptionsByInstance.get(instanceId);
492 if (!options) {
493 return null;
494 }
495 const entry = instanceEntries.find((candidate) => candidate.instanceId === instanceId);
496 if (!entry) {
497 return null;
498 }
499 const resolvedModel = resolveSelectableModel(entry.driverKind, modelSlug, options);
500 if (!resolvedModel) return null;
501 if (additive && onToggleModel) {
502 onToggleModel(instanceId, resolvedModel);
503 } else {
504 onInstanceModelChange(instanceId, resolvedModel);
505 }
506 return resolvedModel;
507 };
508
509 const modelJumpShortcutContext = {
510 terminalFocus: false,
511 terminalOpen: props.terminalOpen,
512 modelPickerOpen: true,
513 } as const;
514 const lockedProvider = props.lockedProvider;
515 const lockedContinuationGroupKey = props.lockedContinuationGroupKey;
516 const canOpenProviderSetup = onOpenProviderSetup !== undefined;
517
518 const entryByInstanceId = new Map(instanceEntries.map((entry) => [entry.instanceId, entry]));
519 const matchesLockedProvider = (
520 entry: Pick<ProviderInstanceEntry, "driverKind" | "continuationGroupKey">,
521 ): boolean => {
522 if (lockedProvider === null) return true;
523 if (entry.driverKind !== lockedProvider) return false;
524 if (!lockedContinuationGroupKey) return true;
525 return entry.continuationGroupKey === lockedContinuationGroupKey;
526 };
527
528 const selectableUnavailableInstanceIds = (() => {
529 const instanceIds = new Set<ProviderInstanceId>();
530 if (activeInstanceHasSelectableUnavailableModel) {
531 instanceIds.add(props.activeInstanceId);
532 }
533 if (canOpenProviderSetup) {
534 for (const entry of instanceEntries) {
535 if (
536 shouldOfferModelPickerSetup(entry, modelOptionsByInstance.get(entry.instanceId) ?? [])
537 ) {
538 instanceIds.add(entry.instanceId);
539 }
540 }
541 }
542 return instanceIds.size > 0 ? instanceIds : undefined;
543 })();
544
545 const flatModels = (() => {
546 const out: ModelPickerItem[] = [];
547 for (const [instanceId, models] of modelOptionsByInstance) {
548 const entry = entryByInstanceId.get(instanceId);
549 if (!entry) {
550 continue;
551 }
552 for (const model of models) {
553 if (
554 !shouldIncludeModelPickerOption({
555 entry,
556 option: model,
557 activeInstanceId: props.activeInstanceId,
558 activeModel: activeModelSlug,
559 })
560 ) {
561 continue;
562 }
563 out.push({
564 slug: model.slug,
565 name: model.name,
566 ...(model.shortName ? { shortName: model.shortName } : {}),
567 ...(model.subProvider ? { subProvider: model.subProvider } : {}),
568 ...(model.badge ? { badge: model.badge } : {}),
569 ...(model.isLegacy ? { isLegacy: true } : {}),
570 ...(model.isUnavailable ? { isUnavailable: true } : {}),
571 instanceId,
572 driverKind: entry.driverKind,
573 instanceDisplayName: entry.displayName,
574 ...(entry.accentColor ? { instanceAccentColor: entry.accentColor } : {}),
575 ...(entry.acpRegistryAgentId ? { acpRegistryAgentId: entry.acpRegistryAgentId } : {}),
576 ...(entry.acpRegistryIconUrl ? { acpRegistryIconUrl: entry.acpRegistryIconUrl } : {}),
577 ...(entry.continuationGroupKey
578 ? { continuationGroupKey: entry.continuationGroupKey }
579 : {}),
580 });
581 }
582 }
583 return out;
584 })();
585
586 const isLocked = lockedProvider !== null;
587 const isSearching = searchQuery.trim().length > 0;
588 // Fit the tallest tab so switching tabs never resizes the popup and moves the rail under the cursor.
589 const tallestTabUnits = (() => {
590 const unitsByTab = new Map<ProviderInstanceId | "favorites", number>();
591 const addRow = (tab: ProviderInstanceId | "favorites") => {
592 const previous = unitsByTab.get(tab);
593 unitsByTab.set(
594 tab,
595 previous === undefined ? ROW_UNITS : previous + ROW_SEPARATOR_UNITS + ROW_UNITS,
596 );
597 };
598 const tabsWithLegacyRow = new Set<ProviderInstanceId>();
599 for (const model of flatModels) {
600 if (!matchesLockedProvider(model)) continue;
601 const isFavorite = favoritesSet.has(providerModelKey(model.instanceId, model.slug));
602 if (isFavorite) addRow("favorites");
603 if (model.isLegacy && !isFavorite) {
604 tabsWithLegacyRow.add(model.instanceId);
605 } else {
606 addRow(model.instanceId);
607 }
608 }
609 for (const instanceId of tabsWithLegacyRow) addRow(instanceId);
610 return Math.max(0, ...unitsByTab.values());
611 })();
612 const lockedDisabledInstanceIds = (() => {
613 if (!isLocked) {
614 return undefined;
615 }
616 const disabled = new Set<ProviderInstanceId>();
617 for (const entry of instanceEntries) {
618 if (!matchesLockedProvider(entry)) {
619 disabled.add(entry.instanceId);
620 }
621 }
622 return disabled;
623 })();
624 const sidebarInstanceEntries = (() => {
625 const enabledEntries = instanceEntries.filter(isProviderInstancePickerVisible);
626 if (!isLocked) {
627 return enabledEntries;
628 }
629 const available: ProviderInstanceEntry[] = [];
630 const disabled: ProviderInstanceEntry[] = [];
631 for (const entry of enabledEntries) {
632 if (matchesLockedProvider(entry)) {
633 available.push(entry);
634 } else {
635 disabled.push(entry);
636 }
637 }
638 return [...available, ...disabled];
639 })();
640 const showSidebar = !isSearching && sidebarInstanceEntries.length > 0;
641 const instanceOrder = instanceEntries.map((entry) => entry.instanceId);
642
643 const filteredModels = (() => {
644 let result = flatModels;
645
646 if (searchQuery.trim()) {
647 const candidates =
648 lockedProvider !== null ? result.filter((m) => matchesLockedProvider(m)) : result;
649 return rankModelPickerSearch(candidates, searchQuery, (model) => ({
650 name: model.name,
651 ...(model.shortName ? { shortName: model.shortName } : {}),
652 ...(model.subProvider ? { subProvider: model.subProvider } : {}),
653 driverKind: model.driverKind,
654 providerDisplayName: model.instanceDisplayName,
655 isFavorite: favoritesSet.has(providerModelKey(model.instanceId, model.slug)),
656 }));
657 }
658
659 if (lockedProvider !== null) {
660 result = result.filter((m) => matchesLockedProvider(m));
661 if (selectedInstanceId === "favorites") {
662 result = result.filter((m) => favoritesSet.has(providerModelKey(m.instanceId, m.slug)));
663 } else {
664 result = result.filter((m) => m.instanceId === selectedInstanceId);
665 }
666 } else if (selectedInstanceId === "favorites") {
667 result = result.filter((m) => favoritesSet.has(providerModelKey(m.instanceId, m.slug)));
668 } else {
669 result = result.filter((m) => m.instanceId === selectedInstanceId);
670 }
671
672 return sortProviderModelItems(result, {
673 favoriteModelKeys: favoritesSet,
674 groupFavorites: selectedInstanceId !== "favorites",
675 instanceOrder: selectedInstanceId === "favorites" ? instanceOrder : [],
676 });
677 })();
678
679 const legacySection = (() => {
680 if (isSearching || selectedInstanceId === "favorites") {
681 return null;
682 }
683 const currentModels: ModelPickerItem[] = [];
684 const legacyModels: ModelPickerItem[] = [];
685 for (const model of filteredModels) {
686 const isLegacy =
687 model.isLegacy && !favoritesSet.has(providerModelKey(model.instanceId, model.slug));
688 (isLegacy ? legacyModels : currentModels).push(model);
689 }
690 if (legacyModels.length === 0) {
691 return null;
692 }
693 return {
694 key: modelPickerLegacySectionKey(selectedInstanceId),
695 currentModels,
696 legacyModels,
697 isExpanded: expandedLegacyInstances.has(selectedInstanceId),
698 };
699 })();
700
701 const visibleModels = (() => {
702 if (!legacySection) {
703 return filteredModels;
704 }
705 return [
706 ...legacySection.currentModels,
707 ...(legacySection.isExpanded ? legacySection.legacyModels : []),
708 ];
709 })();
710
711 const selectedEntry =
712 selectedInstanceId === "favorites" ? undefined : entryByInstanceId.get(selectedInstanceId);
713 const providerSetupEntries =
714 !isSearching && canOpenProviderSetup
715 ? instanceEntries.filter(
716 (entry) =>
717 matchesLockedProvider(entry) &&
718 shouldOfferModelPickerSetup(
719 entry,
720 modelOptionsByInstance.get(entry.instanceId) ?? [],
721 ) &&
722 (selectedEntry
723 ? entry.instanceId === selectedEntry.instanceId
724 : filteredModels.length === 0),
725 )
726 : [];
727
728 const updateRequiredNotices = instanceEntries.flatMap((entry) => {
729 const shown = isSearching
730 ? matchesLockedProvider(entry)
731 : entry.instanceId === selectedEntry?.instanceId;
732 const notice = shown ? formatProviderUpdateRequiredNotice(entry.snapshot, searchQuery) : null;
733 return notice ? [{ instanceId: entry.instanceId, notice }] : [];
734 });
735
736 const modelJumpModelKeys = visibleModels
737 .filter((model) => !getModelDisabledReason?.(model.instanceId, model.slug))
738 .slice(0, MODEL_PICKER_JUMP_KEYBINDING_COMMANDS.length)
739 .map((model) => modelPickerModelKey(model.instanceId, model.slug));
740 const allItemKeys = ((): string[] => [
741 ...flatModels.map((model) => modelPickerModelKey(model.instanceId, model.slug)),
742 ...new Set(
743 flatModels
744 .filter((model) => model.isLegacy)
745 .map((model) => modelPickerLegacySectionKey(model.instanceId)),
746 ),
747 ])();
748 const filteredItemKeys = ((): string[] => {
749 const modelKeys = visibleModels.map((model) =>
750 modelPickerModelKey(model.instanceId, model.slug),
751 );
752 // The toggle trails the list, so expanding it reveals older models above it.
753 return legacySection ? [...modelKeys, legacySection.key] : modelKeys;
754 })();
755 const filteredModelByKey = ((): ReadonlyMap<string, ModelPickerItem> =>
756 new Map(
757 visibleModels.map(
758 (model) => [modelPickerModelKey(model.instanceId, model.slug), model] as const,
759 ),
760 ))();
761
762 const modelJumpLabelByKey = modelJumpLabelsByKey(
763 modelJumpModelKeys,
764 keybindings,
765 props.terminalOpen,
766 );
767 const badgedInstanceIds = new Set(
768 instanceEntries
769 .filter((entry) => shouldShowInstanceBadge(entry, instanceEntries))
770 .map((entry) => entry.instanceId),
771 );
772 const modelListExtraData = {
773 badgedInstanceIds,
774 favoritesSet,
775 modelJumpLabelByKey,
776 activeModelKey,
777 selectedModelKeySet,
778 };
779
780 const onWindowKeyDown = (event: globalThis.KeyboardEvent) => {
781 if (
782 event.defaultPrevented ||
783 event.repeat ||
784 event.isComposing ||
785 event.keyCode === 229 ||
786 isCommandPaletteOpen()
787 ) {
788 return;
789 }
790
791 const command = resolveShortcutCommand(event, keybindings, {
792 platform: navigator.platform,
793 context: modelJumpShortcutContext,
794 });
795 if (command === "modelPicker.previousProvider" || command === "modelPicker.nextProvider") {
796 event.preventDefault();
797 event.stopPropagation();
798 const next = adjacentModelPickerProvider({
799 entries: sidebarInstanceEntries,
800 selectedInstanceId,
801 direction: command === "modelPicker.nextProvider" ? 1 : -1,
802 disabledInstanceIds: lockedDisabledInstanceIds,
803 selectableUnavailableInstanceIds,
804 });
805 setSearchQuery("");
806 handleSelectInstance(next);
807 announce(
808 next === "favorites" ? "Favorites" : (entryByInstanceId.get(next)?.displayName ?? next),
809 "model-picker",
810 );
811 return;
812 }
813 const jumpIndex = modelPickerJumpIndexFromCommand(command ?? "");
814 if (jumpIndex === null) {
815 return;
816 }
817 event.preventDefault();
818 event.stopPropagation();
819
820 const targetModelKey = modelJumpModelKeys[jumpIndex];
821 if (!targetModelKey) {
822 return;
823 }
824 const model = parseModelPickerModelKey(targetModelKey);
825 if (!model) {
826 return;
827 }
828 const selectedSlug = handleModelSelect(model.slug, model.instanceId);
829 if (selectedSlug === null) return;
830 const name = flatModels.find(
831 (item) => item.slug === selectedSlug && item.instanceId === model.instanceId,
832 )?.name;
833 announce(`Model: ${name ?? selectedSlug}`, "model-picker");
834 };
835
836 return (
837 <TooltipProvider delay={0}>
838 <WindowKeyDownListener onKeyDown={onWindowKeyDown} />
839 <div
840 ref={pickerContentRef}
841 className={cn(
842 "relative flex w-screen max-w-90 flex-row overflow-hidden",
843 props.docked ? "max-sm:h-56 max-sm:w-full max-sm:max-w-none" : "max-h-86.5",
844 )}
845 // Docked, the popup sets the height; a minimum here would overflow short windows.
846 style={
847 props.docked
848 ? undefined
849 : isSearching
850 ? { height: searchHeight }
851 : {
852 minHeight: `min(calc(var(--spacing) * ${tallestTabUnits + LIST_CHROME_UNITS} + 1px), calc(var(--spacing) * 86.5))`,
853 }
854 }
855 data-model-picker-content="true"
856 >
857 {showSidebar && (
858 <ModelPickerSidebar
859 selectedInstanceId={selectedInstanceId}
860 onSelectInstance={handleSelectInstance}
861 onFocusSearch={focusSearchInput}
862 instanceEntries={sidebarInstanceEntries}
863 showFavorites
864 {...(selectableUnavailableInstanceIds ? { selectableUnavailableInstanceIds } : {})}
865 {...(lockedDisabledInstanceIds
866 ? {
867 disabledInstanceIds: lockedDisabledInstanceIds,
868 getDisabledInstanceTooltip: (entry: ProviderInstanceEntry) =>
869 `${entry.displayName} is unavailable in this thread. Start a new thread to switch providers.`,
870 }
871 : {})}
872 />
873 )}
874
875 <Combobox<string, boolean>
876 inline
877 items={allItemKeys}
878 filteredItems={filteredItemKeys}
879 filter={null}
880 autoHighlight
881 open
882 virtualized
883 multiple={onToggleModel !== undefined}
884 value={onToggleModel ? [...selectedModelKeySet] : activeModelKey}
885 onItemHighlighted={(modelKey, eventDetails) => {
886 highlightedModelKeyRef.current = typeof modelKey === "string" ? modelKey : null;
887 if (eventDetails.reason === "keyboard" && eventDetails.index >= 0) {
888 void modelListRef.current?.scrollIndexIntoView?.({
889 index: eventDetails.index,
890 animated: false,
891 });
892 }
893 }}
894 onValueChange={(value, details) => {
895 const modelKey = Array.isArray(value)
896 ? (value.find((key) => !selectedModelKeySet.has(key)) ??
897 [...selectedModelKeySet].find((key) => !value.includes(key)))
898 : value;
899 if (typeof modelKey !== "string") {
900 return;
901 }
902 const legacyInstanceId = parseModelPickerLegacySectionKey(modelKey);
903 if (legacyInstanceId) {
904 toggleLegacySection(legacyInstanceId);
905 return;
906 }
907 const model = parseModelPickerModelKey(modelKey);
908 if (model) {
909 handleModelSelect(
910 model.slug,
911 model.instanceId,
912 "shiftKey" in details.event && details.event.shiftKey === true,
913 );
914 }
915 }}
916 >
917 <div
918 className={cn(
919 "flex min-h-0 flex-1 flex-col overflow-hidden bg-muted/40",
920 showSidebar && "border-l border-border/70",
921 )}
922 >
923 <ComboboxSearchInput
924 ref={searchInputRef}
925 placeholder="Search models..."
926 value={searchQuery}
927 onChange={(e) => {
928 if (!isSearching) setSearchHeight(pickerContentRef.current?.offsetHeight ?? 0);
929 setSearchQuery(e.target.value);
930 }}
931 onKeyDown={(e) => {
932 if (e.nativeEvent.isComposing || e.keyCode === 229) {
933 (e as typeof e & { preventBaseUIHandler?: () => void }).preventBaseUIHandler?.();
934 e.stopPropagation();
935 return;
936 }
937 if (
938 showSidebar &&
939 !e.altKey &&
940 !e.ctrlKey &&
941 !e.metaKey &&
942 ((e.key === "ArrowLeft" && !e.shiftKey && searchQuery.length === 0) ||
943 (e.key === "Tab" && e.shiftKey))
944 ) {
945 const sidebar = e.currentTarget
946 .closest("[data-model-picker-content]")
947 ?.querySelector("[data-model-picker-sidebar]");
948 const button =
949 sidebar?.querySelector<HTMLButtonElement>(
950 'button[aria-pressed="true"]:not(:disabled)',
951 ) ?? sidebar?.querySelector<HTMLButtonElement>("button:not(:disabled)");
952 if (button) {
953 e.preventDefault();
954 e.stopPropagation();
955 button.focus();
956 return;
957 }
958 }
959 if (e.key === "Escape") {
960 e.preventDefault();
961 e.stopPropagation();
962 onRequestClose?.();
963 return;
964 }
965 if (
966 props.onFocusEffort &&
967 e.key === "ArrowRight" &&
968 !e.altKey &&
969 !e.ctrlKey &&
970 !e.metaKey &&
971 !e.shiftKey &&
972 e.currentTarget.selectionStart === searchQuery.length
973 ) {
974 e.preventDefault();
975 e.stopPropagation();
976 // The column shows the selected model's effort, so a highlighted model is picked
977 // first; the owning popup then moves focus to that model's levels.
978 const highlighted = highlightedModelKeyRef.current
979 ? parseModelPickerModelKey(highlightedModelKeyRef.current)
980 : null;
981 const pickedNew =
982 highlighted !== null &&
983 highlightedModelKeyRef.current !== activeModelKey &&
984 handleModelSelect(highlighted.slug, highlighted.instanceId) !== null;
985 if (!pickedNew) props.onFocusEffort();
986 return;
987 }
988 if (e.key === "Enter" && highlightedModelKeyRef.current) {
989 (e as typeof e & { preventBaseUIHandler?: () => void }).preventBaseUIHandler?.();
990 e.preventDefault();
991 e.stopPropagation();
992 const legacyInstanceId = parseModelPickerLegacySectionKey(
993 highlightedModelKeyRef.current,
994 );
995 if (legacyInstanceId) {
996 toggleLegacySection(legacyInstanceId);
997 return;
998 }
999 const model = parseModelPickerModelKey(highlightedModelKeyRef.current);
1000 if (model) {
1001 handleModelSelect(model.slug, model.instanceId, e.shiftKey);
1002 }
1003 return;
1004 }
1005 e.stopPropagation();
1006 }}
1007 onMouseDown={(e) => e.stopPropagation()}
1008 onTouchStart={(e) => e.stopPropagation()}
1009 />
1010
1011 <ModelPickerList
1012 listRef={modelListRef}
1013 itemKeys={filteredItemKeys}
1014 extraData={modelListExtraData}
1015 renderItem={({ item: modelKey, index }) => {
1016 if (legacySection?.key === modelKey) {
1017 return (
1018 <ComboboxItem
1019 hideIndicator
1020 index={index}
1021 value={modelKey}
1022 aria-expanded={legacySection.isExpanded}
1023 className="group w-full cursor-pointer"
1024 >
1025 <span className="text-sm leading-snug text-muted-foreground group-hover:text-foreground group-data-highlighted:text-foreground">
1026 {legacySection.isExpanded ? "Show less" : "Show more"}
1027 </span>
1028 </ComboboxItem>
1029 );
1030 }
1031 const model = filteredModelByKey.get(modelKey);
1032 if (!model) {
1033 return null;
1034 }
1035 const disabledReason =
1036 getModelDisabledReason?.(model.instanceId, model.slug) ?? null;
1037 return (
1038 <ModelListRow
1039 key={modelKey}
1040 index={index}
1041 slug={model.slug}
1042 name={model.name}
1043 subProvider={model.subProvider}
1044 instanceId={model.instanceId}
1045 driverKind={model.driverKind}
1046 providerDisplayName={model.instanceDisplayName}
1047 providerAccentColor={model.instanceAccentColor}
1048 acpRegistryAgentId={model.acpRegistryAgentId}
1049 acpRegistryIconUrl={model.acpRegistryIconUrl}
1050 isFavorite={favoritesSet.has(providerModelKey(model.instanceId, model.slug))}
1051 isSelected={
1052 selectedModelKeys !== undefined
1053 ? selectedModelKeySet.has(modelKey)
1054 : modelKey === activeModelKey
1055 }
1056 favoriteStarOnHover={selectedInstanceId === "favorites" && !isSearching}
1057 showInstanceBadge={badgedInstanceIds.has(model.instanceId)}
1058 showNewBadge={model.badge === "new"}
1059 unavailable={model.isUnavailable === true}
1060 jumpLabel={modelJumpLabelByKey.get(modelKey) ?? null}
1061 disabledReason={disabledReason}
1062 onToggleFavorite={toggleFavorite}
1063 />
1064 );
1065 }}
1066 />
1067 <ModelPickerProviderNotices
1068 setupEntries={providerSetupEntries}
1069 updateRequiredNotices={updateRequiredNotices}
1070 emptyLabel={
1071 selectedInstanceId === "favorites" && !isSearching
1072 ? "No favorites yet"
1073 : "No models found"
1074 }
1075 onRequestClose={onRequestClose}
1076 onOpenProviderSetup={onOpenProviderSetup}
1077 />
1078 {props.listFooter}
1079 </div>
1080 </Combobox>
1081 </div>
1082 </TooltipProvider>
1083 );
1084});