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