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