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 { ChevronRightIcon } from "lucide-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 "./modelPickerSearch";
35import {
36 Combobox,
37 ComboboxEmpty,
38 ComboboxSearchInput,
39 ComboboxItem,
40 ComboboxListVirtualized,
41} from "../ui/combobox";
42import { ModelEsque } from "./providerIconUtils";
43import { isCommandPaletteOpen } from "../../commandPaletteBus";
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 type ProviderInstanceEntry,
64} from "../../providerInstances";
65import { providerModelKey, sortProviderModelItems } from "../../modelOrdering";
66
67type ModelPickerItem = {
68 slug: string;
69 name: string;
70 shortName?: string;
71 subProvider?: string;
72 badge?: "new";
73 instanceId: ProviderInstanceId;
74 driverKind: ProviderDriverKind;
75 instanceDisplayName: string;
76 instanceAccentColor?: string | undefined;
77 acpRegistryAgentId?: string | undefined;
78 acpRegistryIconUrl?: string | undefined;
79 continuationGroupKey?: string | undefined;
80 isLegacy?: boolean | undefined;
81 isUnavailable?: boolean | undefined;
82};
83
84export function resolveModelPickerSelectedModel(input: {
85 driverKind: ProviderDriverKind | undefined;
86 model: string;
87 options: ReadonlyArray<ModelEsque>;
88}) {
89 if (input.driverKind === "antigravity" && input.model === ANTIGRAVITY_DEFAULT_MODEL) {
90 const availableModels = input.options.filter(
91 (option) => option.slug !== ANTIGRAVITY_DEFAULT_MODEL && !option.isUnavailable,
92 );
93 return (
94 availableModels.find((option) => option.aliases?.includes(ANTIGRAVITY_DEFAULT_MODEL)) ??
95 availableModels.find((option) => option.isDefault)
96 );
97 }
98 return input.options.find((option) => option.slug === input.model);
99}
100
101function shouldIncludeModelPickerOption(input: {
102 readonly entry: ProviderInstanceEntry;
103 readonly option: ModelEsque;
104 readonly activeInstanceId: ProviderInstanceId;
105 readonly activeModel: string;
106}): boolean {
107 if (input.entry.driverKind === "antigravity" && input.option.slug === ANTIGRAVITY_DEFAULT_MODEL) {
108 return false;
109 }
110 if (isProviderInstancePickerReady(input.entry)) return true;
111 return (
112 input.entry.enabled &&
113 (input.entry.driverKind === "opencode" || input.entry.driverKind === "antigravity") &&
114 input.entry.instanceId === input.activeInstanceId &&
115 input.option.slug === input.activeModel &&
116 input.option.isUnavailable === true
117 );
118}
119
120function shouldOfferModelPickerSetup(
121 entry: ProviderInstanceEntry,
122 options: ReadonlyArray<ModelEsque>,
123): boolean {
124 return (
125 entry.enabled &&
126 entry.status !== "disabled" &&
127 hasProviderSetup(entry.snapshot) &&
128 (!isProviderInstancePickerReady(entry) ||
129 !entry.installed ||
130 entry.snapshot.auth.status === "unauthenticated" ||
131 !options.some((option) => !option.isUnavailable))
132 );
133}
134
135function adjacentModelPickerProvider(input: {
136 entries: ReadonlyArray<ProviderInstanceEntry>;
137 selectedInstanceId: ProviderInstanceId | "favorites";
138 direction: 1 | -1;
139 disabledInstanceIds: ReadonlySet<ProviderInstanceId> | undefined;
140 selectableUnavailableInstanceIds: ReadonlySet<ProviderInstanceId> | undefined;
141}) {
142 const providers: Array<ProviderInstanceId | "favorites"> = [
143 "favorites",
144 ...input.entries
145 .filter(
146 (entry) =>
147 !input.disabledInstanceIds?.has(entry.instanceId) &&
148 (isProviderInstancePickerReady(entry) ||
149 input.selectableUnavailableInstanceIds?.has(entry.instanceId)),
150 )
151 .map((entry) => entry.instanceId),
152 ];
153 const index = providers.indexOf(input.selectedInstanceId);
154 return providers[
155 index < 0
156 ? input.direction === 1
157 ? 0
158 : providers.length - 1
159 : (index + input.direction + providers.length) % providers.length
160 ]!;
161}
162
163const EMPTY_MODEL_JUMP_LABELS = new Map<string, string>();
164const MODEL_LIST_ESTIMATED_ITEM_SIZE = 52;
165// Rendered heights in `--spacing` units. Chrome is the search box and list padding, plus a 1px border.
166const ONE_LINE_ROW_UNITS = 8;
167const TWO_LINE_ROW_UNITS = 12;
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}) {
366 const {
367 searchInputRef,
368 keybindings: providedKeybindings,
369 modelOptionsByInstance,
370 instanceEntries,
371 getModelDisabledReason,
372 onInstanceModelChange,
373 onToggleModel,
374 onRequestClose,
375 onOpenProviderSetup,
376 } = props;
377 const [searchQuery, setSearchQuery] = useState("");
378 const modelListRef = useRef<LegendListRef | null>(null);
379 const pickerContentRef = useRef<HTMLDivElement>(null);
380 const highlightedModelKeyRef = useRef<string | null>(null);
381 const { favorites } = useEnvironmentModelPreferences(props.environmentId);
382 const activeEntry = props.instanceEntries.find(
383 (entry) => entry.instanceId === props.activeInstanceId,
384 );
385 const activeModel = resolveModelPickerSelectedModel({
386 driverKind: activeEntry?.driverKind,
387 model: props.model,
388 options: modelOptionsByInstance.get(props.activeInstanceId) ?? [],
389 });
390 const activeModelSlug =
391 activeModel?.slug ?? (props.model === ANTIGRAVITY_DEFAULT_MODEL ? "" : props.model);
392 const activeModelKey = activeModelSlug
393 ? modelPickerModelKey(props.activeInstanceId, activeModelSlug)
394 : null;
395 const selectedModelKeys = props.selectedModels?.map((selection) => {
396 const entry = instanceEntries.find((entry) => entry.instanceId === selection.instanceId);
397 const model = resolveModelPickerSelectedModel({
398 driverKind: entry?.driverKind,
399 model: selection.model,
400 options: modelOptionsByInstance.get(selection.instanceId) ?? [],
401 });
402 return modelPickerModelKey(selection.instanceId, model?.slug ?? selection.model);
403 });
404 const selectedModelKeySet = new Set(
405 selectedModelKeys ?? (activeModelKey ? [activeModelKey] : []),
406 );
407 const activeInstanceHasSelectableUnavailableModel =
408 activeEntry !== undefined &&
409 (modelOptionsByInstance.get(props.activeInstanceId) ?? []).some((option) =>
410 shouldIncludeModelPickerOption({
411 entry: activeEntry,
412 option,
413 activeInstanceId: props.activeInstanceId,
414 activeModel: activeModelSlug,
415 }),
416 ) &&
417 !isProviderInstancePickerReady(activeEntry);
418 const activeInstanceNeedsSetup =
419 onOpenProviderSetup !== undefined &&
420 activeEntry !== undefined &&
421 shouldOfferModelPickerSetup(
422 activeEntry,
423 modelOptionsByInstance.get(props.activeInstanceId) ?? [],
424 );
425 const [selectedInstanceId, setSelectedInstanceId] = useState<ProviderInstanceId | "favorites">(
426 () => {
427 if (
428 props.lockedProvider !== null ||
429 activeInstanceHasSelectableUnavailableModel ||
430 activeInstanceNeedsSetup
431 ) {
432 return props.activeInstanceId;
433 }
434 return favorites.length > 0 ? "favorites" : props.activeInstanceId;
435 },
436 );
437 const favoritesSet = new Set(favorites.map((fav) => providerModelKey(fav.provider, fav.model)));
438 const [expandedLegacyInstances, setExpandedLegacyInstances] = useState(
439 () =>
440 new Set<ProviderInstanceId>(
441 activeModel?.isLegacy &&
442 !favoritesSet.has(providerModelKey(props.activeInstanceId, activeModelSlug))
443 ? [props.activeInstanceId]
444 : [],
445 ),
446 );
447 const serverKeybindings = useAtomValue(primaryServerKeybindingsAtom);
448 const keybindings = providedKeybindings ?? serverKeybindings;
449 const [searchHeight, setSearchHeight] = useState(0);
450 const toggleFavorite = useToggleEnvironmentModelFavorite(props.environmentId);
451
452 const focusSearchInput = () => {
453 searchInputRef.current?.focus({ preventScroll: true });
454 };
455
456 const handleSelectInstance = (instanceId: ProviderInstanceId | "favorites") => {
457 setSelectedInstanceId(instanceId);
458 window.requestAnimationFrame(() => {
459 focusSearchInput();
460 });
461 };
462
463 const toggleLegacySection = (instanceId: ProviderInstanceId) => {
464 setExpandedLegacyInstances((expanded) => {
465 const next = new Set(expanded);
466 if (next.has(instanceId)) {
467 next.delete(instanceId);
468 } else {
469 next.add(instanceId);
470 }
471 return next;
472 });
473 };
474
475 const handleModelSelect = (
476 modelSlug: string,
477 instanceId: ProviderInstanceId,
478 additive = false,
479 ): string | null => {
480 if (getModelDisabledReason?.(instanceId, modelSlug)) {
481 return null;
482 }
483 const options = modelOptionsByInstance.get(instanceId);
484 if (!options) {
485 return null;
486 }
487 const entry = instanceEntries.find((candidate) => candidate.instanceId === instanceId);
488 if (!entry) {
489 return null;
490 }
491 const resolvedModel = resolveSelectableModel(entry.driverKind, modelSlug, options);
492 if (!resolvedModel) return null;
493 if (additive && onToggleModel) {
494 onToggleModel(instanceId, resolvedModel);
495 } else {
496 onInstanceModelChange(instanceId, resolvedModel);
497 }
498 return resolvedModel;
499 };
500
501 const modelJumpShortcutContext = {
502 terminalFocus: false,
503 terminalOpen: props.terminalOpen,
504 modelPickerOpen: true,
505 } as const;
506 const lockedProvider = props.lockedProvider;
507 const lockedContinuationGroupKey = props.lockedContinuationGroupKey;
508 const canOpenProviderSetup = onOpenProviderSetup !== undefined;
509
510 const entryByInstanceId = new Map(instanceEntries.map((entry) => [entry.instanceId, entry]));
511 const matchesLockedProvider = (
512 entry: Pick<ProviderInstanceEntry, "driverKind" | "continuationGroupKey">,
513 ): boolean => {
514 if (lockedProvider === null) return true;
515 if (entry.driverKind !== lockedProvider) return false;
516 if (!lockedContinuationGroupKey) return true;
517 return entry.continuationGroupKey === lockedContinuationGroupKey;
518 };
519
520 const selectableUnavailableInstanceIds = (() => {
521 const instanceIds = new Set<ProviderInstanceId>();
522 if (activeInstanceHasSelectableUnavailableModel) {
523 instanceIds.add(props.activeInstanceId);
524 }
525 if (canOpenProviderSetup) {
526 for (const entry of instanceEntries) {
527 if (
528 shouldOfferModelPickerSetup(entry, modelOptionsByInstance.get(entry.instanceId) ?? [])
529 ) {
530 instanceIds.add(entry.instanceId);
531 }
532 }
533 }
534 return instanceIds.size > 0 ? instanceIds : undefined;
535 })();
536
537 const flatModels = (() => {
538 const out: ModelPickerItem[] = [];
539 for (const [instanceId, models] of modelOptionsByInstance) {
540 const entry = entryByInstanceId.get(instanceId);
541 if (!entry) {
542 continue;
543 }
544 for (const model of models) {
545 if (
546 !shouldIncludeModelPickerOption({
547 entry,
548 option: model,
549 activeInstanceId: props.activeInstanceId,
550 activeModel: activeModelSlug,
551 })
552 ) {
553 continue;
554 }
555 out.push({
556 slug: model.slug,
557 name: model.name,
558 ...(model.shortName ? { shortName: model.shortName } : {}),
559 ...(model.subProvider ? { subProvider: model.subProvider } : {}),
560 ...(model.badge ? { badge: model.badge } : {}),
561 ...(model.isLegacy ? { isLegacy: true } : {}),
562 ...(model.isUnavailable ? { isUnavailable: true } : {}),
563 instanceId,
564 driverKind: entry.driverKind,
565 instanceDisplayName: entry.displayName,
566 ...(entry.accentColor ? { instanceAccentColor: entry.accentColor } : {}),
567 ...(entry.acpRegistryAgentId ? { acpRegistryAgentId: entry.acpRegistryAgentId } : {}),
568 ...(entry.acpRegistryIconUrl ? { acpRegistryIconUrl: entry.acpRegistryIconUrl } : {}),
569 ...(entry.continuationGroupKey
570 ? { continuationGroupKey: entry.continuationGroupKey }
571 : {}),
572 });
573 }
574 }
575 return out;
576 })();
577
578 const isLocked = lockedProvider !== null;
579 const isSearching = searchQuery.trim().length > 0;
580 // Inside one provider's tab the provider line repeats the selected rail icon on every row.
581 const rowsMixProviders = isSearching || selectedInstanceId === "favorites";
582 // Fit the tallest tab so switching tabs never resizes the popup and moves the rail under the cursor.
583 const tallestTabUnits = (() => {
584 const unitsByTab = new Map<ProviderInstanceId | "favorites", number>();
585 const addRow = (tab: ProviderInstanceId | "favorites", twoLine: boolean) => {
586 const rowUnits = twoLine ? TWO_LINE_ROW_UNITS : ONE_LINE_ROW_UNITS;
587 const previous = unitsByTab.get(tab);
588 unitsByTab.set(
589 tab,
590 previous === undefined ? rowUnits : previous + ROW_SEPARATOR_UNITS + rowUnits,
591 );
592 };
593 const tabsWithLegacyRow = new Set<ProviderInstanceId>();
594 for (const model of flatModels) {
595 if (!matchesLockedProvider(model)) continue;
596 const isFavorite = favoritesSet.has(providerModelKey(model.instanceId, model.slug));
597 if (isFavorite) addRow("favorites", true);
598 if (model.isLegacy && !isFavorite) {
599 tabsWithLegacyRow.add(model.instanceId);
600 } else {
601 addRow(model.instanceId, Boolean(model.subProvider));
602 }
603 }
604 for (const instanceId of tabsWithLegacyRow) addRow(instanceId, true);
605 return Math.max(0, ...unitsByTab.values());
606 })();
607 const lockedDisabledInstanceIds = (() => {
608 if (!isLocked) {
609 return undefined;
610 }
611 const disabled = new Set<ProviderInstanceId>();
612 for (const entry of instanceEntries) {
613 if (!matchesLockedProvider(entry)) {
614 disabled.add(entry.instanceId);
615 }
616 }
617 return disabled;
618 })();
619 const sidebarInstanceEntries = (() => {
620 const enabledEntries = instanceEntries.filter(isProviderInstancePickerVisible);
621 if (!isLocked) {
622 return enabledEntries;
623 }
624 const available: ProviderInstanceEntry[] = [];
625 const disabled: ProviderInstanceEntry[] = [];
626 for (const entry of enabledEntries) {
627 if (matchesLockedProvider(entry)) {
628 available.push(entry);
629 } else {
630 disabled.push(entry);
631 }
632 }
633 return [...available, ...disabled];
634 })();
635 const showSidebar = !isSearching && sidebarInstanceEntries.length > 0;
636 const instanceOrder = instanceEntries.map((entry) => entry.instanceId);
637
638 const filteredModels = (() => {
639 let result = flatModels;
640
641 if (searchQuery.trim()) {
642 const candidates =
643 lockedProvider !== null ? result.filter((m) => matchesLockedProvider(m)) : result;
644 return rankModelPickerSearch(candidates, searchQuery, (model) => ({
645 name: model.name,
646 ...(model.shortName ? { shortName: model.shortName } : {}),
647 ...(model.subProvider ? { subProvider: model.subProvider } : {}),
648 driverKind: model.driverKind,
649 providerDisplayName: model.instanceDisplayName,
650 isFavorite: favoritesSet.has(providerModelKey(model.instanceId, model.slug)),
651 }));
652 }
653
654 if (lockedProvider !== null) {
655 result = result.filter((m) => matchesLockedProvider(m));
656 if (selectedInstanceId === "favorites") {
657 result = result.filter((m) => favoritesSet.has(providerModelKey(m.instanceId, m.slug)));
658 } else {
659 result = result.filter((m) => m.instanceId === selectedInstanceId);
660 }
661 } else 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
667 return sortProviderModelItems(result, {
668 favoriteModelKeys: favoritesSet,
669 groupFavorites: selectedInstanceId !== "favorites",
670 instanceOrder: selectedInstanceId === "favorites" ? instanceOrder : [],
671 });
672 })();
673
674 const legacySection = (() => {
675 if (isSearching || selectedInstanceId === "favorites") {
676 return null;
677 }
678 const currentModels: ModelPickerItem[] = [];
679 const legacyModels: ModelPickerItem[] = [];
680 for (const model of filteredModels) {
681 const isLegacy =
682 model.isLegacy && !favoritesSet.has(providerModelKey(model.instanceId, model.slug));
683 (isLegacy ? legacyModels : currentModels).push(model);
684 }
685 if (legacyModels.length === 0) {
686 return null;
687 }
688 return {
689 key: modelPickerLegacySectionKey(selectedInstanceId),
690 currentModels,
691 legacyModels,
692 isExpanded: expandedLegacyInstances.has(selectedInstanceId),
693 };
694 })();
695
696 const visibleModels = (() => {
697 if (!legacySection) {
698 return filteredModels;
699 }
700 return [
701 ...legacySection.currentModels,
702 ...(legacySection.isExpanded ? legacySection.legacyModels : []),
703 ];
704 })();
705
706 const selectedEntry =
707 selectedInstanceId === "favorites" ? undefined : entryByInstanceId.get(selectedInstanceId);
708 const providerSetupEntries =
709 !isSearching && canOpenProviderSetup
710 ? instanceEntries.filter(
711 (entry) =>
712 matchesLockedProvider(entry) &&
713 shouldOfferModelPickerSetup(
714 entry,
715 modelOptionsByInstance.get(entry.instanceId) ?? [],
716 ) &&
717 (selectedEntry
718 ? entry.instanceId === selectedEntry.instanceId
719 : filteredModels.length === 0),
720 )
721 : [];
722
723 const updateRequiredNotices = instanceEntries.flatMap((entry) => {
724 const shown = isSearching
725 ? matchesLockedProvider(entry)
726 : entry.instanceId === selectedEntry?.instanceId;
727 const notice = shown ? formatProviderUpdateRequiredNotice(entry.snapshot, searchQuery) : null;
728 return notice ? [{ instanceId: entry.instanceId, notice }] : [];
729 });
730
731 const modelJumpModelKeys = visibleModels
732 .filter((model) => !getModelDisabledReason?.(model.instanceId, model.slug))
733 .slice(0, MODEL_PICKER_JUMP_KEYBINDING_COMMANDS.length)
734 .map((model) => modelPickerModelKey(model.instanceId, model.slug));
735 const allItemKeys = ((): string[] => [
736 ...flatModels.map((model) => modelPickerModelKey(model.instanceId, model.slug)),
737 ...new Set(
738 flatModels
739 .filter((model) => model.isLegacy)
740 .map((model) => modelPickerLegacySectionKey(model.instanceId)),
741 ),
742 ])();
743 const filteredItemKeys = ((): string[] => {
744 const modelKeys = visibleModels.map((model) =>
745 modelPickerModelKey(model.instanceId, model.slug),
746 );
747 if (!legacySection) {
748 return modelKeys;
749 }
750 modelKeys.splice(legacySection.currentModels.length, 0, legacySection.key);
751 return 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 modelListExtraData = {
766 favoritesSet,
767 modelJumpLabelByKey,
768 activeModelKey,
769 selectedModelKeySet,
770 };
771
772 const onWindowKeyDown = (event: globalThis.KeyboardEvent) => {
773 if (event.defaultPrevented || event.repeat || isCommandPaletteOpen()) {
774 return;
775 }
776
777 const command = resolveShortcutCommand(event, keybindings, {
778 platform: navigator.platform,
779 context: modelJumpShortcutContext,
780 });
781 if (command === "modelPicker.previousProvider" || command === "modelPicker.nextProvider") {
782 event.preventDefault();
783 event.stopPropagation();
784 const next = adjacentModelPickerProvider({
785 entries: sidebarInstanceEntries,
786 selectedInstanceId,
787 direction: command === "modelPicker.nextProvider" ? 1 : -1,
788 disabledInstanceIds: lockedDisabledInstanceIds,
789 selectableUnavailableInstanceIds,
790 });
791 setSearchQuery("");
792 handleSelectInstance(next);
793 announce(
794 next === "favorites" ? "Favorites" : (entryByInstanceId.get(next)?.displayName ?? next),
795 "model-picker",
796 );
797 return;
798 }
799 const jumpIndex = modelPickerJumpIndexFromCommand(command ?? "");
800 if (jumpIndex === null) {
801 return;
802 }
803 event.preventDefault();
804 event.stopPropagation();
805
806 const targetModelKey = modelJumpModelKeys[jumpIndex];
807 if (!targetModelKey) {
808 return;
809 }
810 const model = parseModelPickerModelKey(targetModelKey);
811 if (!model) {
812 return;
813 }
814 const selectedSlug = handleModelSelect(model.slug, model.instanceId);
815 if (selectedSlug === null) return;
816 const name = flatModels.find(
817 (item) => item.slug === selectedSlug && item.instanceId === model.instanceId,
818 )?.name;
819 announce(`Model: ${name ?? selectedSlug}`, "model-picker");
820 };
821
822 return (
823 <TooltipProvider delay={0}>
824 <WindowKeyDownListener onKeyDown={onWindowKeyDown} />
825 <div
826 ref={pickerContentRef}
827 className="relative flex max-h-86.5 w-screen max-w-90 flex-row overflow-hidden"
828 style={
829 isSearching
830 ? { height: searchHeight }
831 : {
832 minHeight: `min(calc(var(--spacing) * ${tallestTabUnits + LIST_CHROME_UNITS} + 1px), calc(var(--spacing) * 86.5))`,
833 }
834 }
835 data-model-picker-content="true"
836 >
837 {showSidebar && (
838 <ModelPickerSidebar
839 selectedInstanceId={selectedInstanceId}
840 onSelectInstance={handleSelectInstance}
841 onFocusSearch={focusSearchInput}
842 instanceEntries={sidebarInstanceEntries}
843 showFavorites
844 {...(selectableUnavailableInstanceIds ? { selectableUnavailableInstanceIds } : {})}
845 {...(lockedDisabledInstanceIds
846 ? {
847 disabledInstanceIds: lockedDisabledInstanceIds,
848 getDisabledInstanceTooltip: (entry: ProviderInstanceEntry) =>
849 `${entry.displayName} is unavailable in this thread. Start a new thread to switch providers.`,
850 }
851 : {})}
852 />
853 )}
854
855 <Combobox<string, boolean>
856 inline
857 items={allItemKeys}
858 filteredItems={filteredItemKeys}
859 filter={null}
860 autoHighlight
861 open
862 virtualized
863 multiple={onToggleModel !== undefined}
864 value={onToggleModel ? [...selectedModelKeySet] : activeModelKey}
865 onItemHighlighted={(modelKey, eventDetails) => {
866 highlightedModelKeyRef.current = typeof modelKey === "string" ? modelKey : null;
867 if (eventDetails.reason === "keyboard" && eventDetails.index >= 0) {
868 void modelListRef.current?.scrollIndexIntoView?.({
869 index: eventDetails.index,
870 animated: false,
871 });
872 }
873 }}
874 onValueChange={(value, details) => {
875 const modelKey = Array.isArray(value)
876 ? (value.find((key) => !selectedModelKeySet.has(key)) ??
877 [...selectedModelKeySet].find((key) => !value.includes(key)))
878 : value;
879 if (typeof modelKey !== "string") {
880 return;
881 }
882 const legacyInstanceId = parseModelPickerLegacySectionKey(modelKey);
883 if (legacyInstanceId) {
884 toggleLegacySection(legacyInstanceId);
885 return;
886 }
887 const model = parseModelPickerModelKey(modelKey);
888 if (model) {
889 handleModelSelect(
890 model.slug,
891 model.instanceId,
892 "shiftKey" in details.event && details.event.shiftKey === true,
893 );
894 }
895 }}
896 >
897 <div
898 className={cn(
899 "flex min-h-0 flex-1 flex-col overflow-hidden bg-muted/40",
900 showSidebar && "border-l border-border/70",
901 )}
902 >
903 <ComboboxSearchInput
904 ref={searchInputRef}
905 placeholder="Search models..."
906 value={searchQuery}
907 onChange={(e) => {
908 if (!isSearching) setSearchHeight(pickerContentRef.current?.offsetHeight ?? 0);
909 setSearchQuery(e.target.value);
910 }}
911 onKeyDown={(e) => {
912 if (
913 showSidebar &&
914 !e.altKey &&
915 !e.ctrlKey &&
916 !e.metaKey &&
917 ((e.key === "ArrowLeft" && !e.shiftKey && searchQuery.length === 0) ||
918 (e.key === "Tab" && e.shiftKey))
919 ) {
920 const sidebar = e.currentTarget
921 .closest("[data-model-picker-content]")
922 ?.querySelector("[data-model-picker-sidebar]");
923 const button =
924 sidebar?.querySelector<HTMLButtonElement>(
925 'button[aria-pressed="true"]:not(:disabled)',
926 ) ?? sidebar?.querySelector<HTMLButtonElement>("button:not(:disabled)");
927 if (button) {
928 e.preventDefault();
929 e.stopPropagation();
930 button.focus();
931 return;
932 }
933 }
934 if (e.key === "Escape") {
935 e.preventDefault();
936 e.stopPropagation();
937 onRequestClose?.();
938 return;
939 }
940 if (e.key === "Enter" && highlightedModelKeyRef.current) {
941 (e as typeof e & { preventBaseUIHandler?: () => void }).preventBaseUIHandler?.();
942 e.preventDefault();
943 e.stopPropagation();
944 const legacyInstanceId = parseModelPickerLegacySectionKey(
945 highlightedModelKeyRef.current,
946 );
947 if (legacyInstanceId) {
948 toggleLegacySection(legacyInstanceId);
949 return;
950 }
951 const model = parseModelPickerModelKey(highlightedModelKeyRef.current);
952 if (model) {
953 handleModelSelect(model.slug, model.instanceId, e.shiftKey);
954 }
955 return;
956 }
957 e.stopPropagation();
958 }}
959 onMouseDown={(e) => e.stopPropagation()}
960 onTouchStart={(e) => e.stopPropagation()}
961 />
962
963 <ModelPickerList
964 listRef={modelListRef}
965 itemKeys={filteredItemKeys}
966 extraData={modelListExtraData}
967 renderItem={({ item: modelKey, index }) => {
968 if (legacySection?.key === modelKey) {
969 return (
970 <ComboboxItem
971 hideIndicator
972 index={index}
973 value={modelKey}
974 aria-expanded={legacySection.isExpanded}
975 className="group w-full cursor-pointer"
976 >
977 <div className="min-w-0 flex-1 text-left">
978 <div className="text-sm font-normal leading-snug">Legacy models</div>
979 <div className="mt-1 text-xs font-normal leading-snug text-muted-foreground">
980 {legacySection.legacyModels.length} models
981 </div>
982 </div>
983 <ChevronRightIcon
984 className={cn(
985 "size-4 transition-transform",
986 legacySection.isExpanded && "rotate-90",
987 )}
988 />
989 </ComboboxItem>
990 );
991 }
992 const model = filteredModelByKey.get(modelKey);
993 if (!model) {
994 return null;
995 }
996 const disabledReason =
997 getModelDisabledReason?.(model.instanceId, model.slug) ?? null;
998 return (
999 <ModelListRow
1000 key={modelKey}
1001 index={index}
1002 slug={model.slug}
1003 name={model.name}
1004 subProvider={model.subProvider}
1005 instanceId={model.instanceId}
1006 driverKind={model.driverKind}
1007 providerDisplayName={model.instanceDisplayName}
1008 providerAccentColor={model.instanceAccentColor}
1009 acpRegistryAgentId={model.acpRegistryAgentId}
1010 acpRegistryIconUrl={model.acpRegistryIconUrl}
1011 isFavorite={favoritesSet.has(providerModelKey(model.instanceId, model.slug))}
1012 isSelected={
1013 selectedModelKeys !== undefined
1014 ? selectedModelKeySet.has(modelKey)
1015 : modelKey === activeModelKey
1016 }
1017 showProvider={rowsMixProviders || Boolean(model.subProvider)}
1018 showNewBadge={model.badge === "new"}
1019 unavailable={model.isUnavailable === true}
1020 jumpLabel={modelJumpLabelByKey.get(modelKey) ?? null}
1021 disabledReason={disabledReason}
1022 onToggleFavorite={toggleFavorite}
1023 />
1024 );
1025 }}
1026 />
1027 <ModelPickerProviderNotices
1028 setupEntries={providerSetupEntries}
1029 updateRequiredNotices={updateRequiredNotices}
1030 emptyLabel={
1031 selectedInstanceId === "favorites" && !isSearching
1032 ? "No favorites yet"
1033 : "No models found"
1034 }
1035 onRequestClose={onRequestClose}
1036 onOpenProviderSetup={onOpenProviderSetup}
1037 />
1038 </div>
1039 </Combobox>
1040 </div>
1041 </TooltipProvider>
1042 );
1043});