Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ModelPickerContent.tsx

1,089 lines39.5 KB

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