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

ModelPickerContent.tsx

1,261 lines46.1 KB

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);
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 );
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 );
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 ]!;
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" />;
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;
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 );
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 );
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;
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 ...(model.shortName ? { shortName: model.shortName } : {}),
711 ...(model.subProvider ? { subProvider: model.subProvider } : {}),
712 driverKind: model.driverKind,
713 providerDisplayName: model.instanceDisplayName,
714 isFavorite: favoritesSet.has(providerModelKey(model.instanceId, model.slug)),
715 }));
716 }
717​
718 if (lockedProvider !== null) {
719 result = result.filter((m) => matchesLockedProvider(m));
720 if (selectedInstanceId === "favorites") {
721 result = result.filter((m) => favoritesSet.has(providerModelKey(m.instanceId, m.slug)));
722 } else {
723 result = result.filter((m) => m.instanceId === selectedInstanceId);
724 }
725 } else if (selectedInstanceId === "favorites") {
726 result = result.filter((m) => favoritesSet.has(providerModelKey(m.instanceId, m.slug)));
727 } else {
728 result = result.filter((m) => m.instanceId === selectedInstanceId);
729 }
730​
731 return sortProviderModelItems(result, {
732 favoriteModelKeys: favoritesSet,
733 groupFavorites: selectedInstanceId !== "favorites",
734 instanceOrder: selectedInstanceId === "favorites" ? instanceOrder : [],
735 });
736 })();
737​
738 const legacySection = (() => {
739 if (isSearching || selectedInstanceId === "favorites") {
740 return null;
741 }
742 const currentModels: ModelPickerItem[] = [];
743 const legacyModels: ModelPickerItem[] = [];
744 for (const model of filteredModels) {
745 const isLegacy =
746 model.isLegacy && !favoritesSet.has(providerModelKey(model.instanceId, model.slug));
747 (isLegacy ? legacyModels : currentModels).push(model);
748 }
749 if (legacyModels.length === 0) {
750 return null;
751 }
752 return {
753 key: modelPickerLegacySectionKey(selectedInstanceId),
754 currentModels,
755 legacyModels,
756 isExpanded: expandedLegacyInstances.has(selectedInstanceId),
757 };
758 })();
759​
760 // A provider whose models run on several backends, such as fx, lists each
761 // backend as a collapsible heading. Search and Favorites stay flat.
762 const subProviderSections = (() => {
763 const subProviders =
764 isSearching || selectedInstanceId === "favorites"
765 ? undefined
766 : subProvidersByInstance.get(selectedInstanceId);
767 if (!subProviders || selectedInstanceId === "favorites") return null;
768 const { ungrouped, groups } = groupModelsBySubProvider(
769 filteredModels,
770 subProviders,
771 (model) => model.subProvider,
772 );
773 return {
774 ungrouped,
775 sections: groups.map(({ subProvider, models }) => {
776 const key = modelPickerSubProviderSectionKey(selectedInstanceId, subProvider.name);
777 return {
778 key,
779 name: subProvider.name,
780 unavailableReason: subProvider.unavailableReason,
781 models,
782 isExpanded: expandedSubProviderKeys.has(key),
783 };
784 }),
785 };
786 })();
787 const subProviderSectionByKey = new Map(
788 subProviderSections?.sections.map((section) => [section.key, section] as const),
789 );
790​
791 const visibleModels = (() => {
792 if (subProviderSections) {
793 return [
794 ...subProviderSections.ungrouped,
795 ...subProviderSections.sections.flatMap((section) =>
796 section.isExpanded ? section.models : [],
797 ),
798 ];
799 }
800 if (!legacySection) {
801 return filteredModels;
802 }
803 return [
804 ...legacySection.currentModels,
805 ...(legacySection.isExpanded ? legacySection.legacyModels : []),
806 ];
807 })();
808​
809 const selectedEntry =
810 selectedInstanceId === "favorites" ? undefined : entryByInstanceId.get(selectedInstanceId);
811 const providerSetupEntries =
812 !isSearching && canOpenProviderSetup
813 ? instanceEntries.filter(
814 (entry) =>
815 matchesLockedProvider(entry) &&
816 shouldOfferModelPickerSetup(
817 entry,
818 modelOptionsByInstance.get(entry.instanceId) ?? [],
819 ) &&
820 (selectedEntry
821 ? entry.instanceId === selectedEntry.instanceId
822 : filteredModels.length === 0),
823 )
824 : [];
825​
826 const updateRequiredNotices = instanceEntries.flatMap((entry) => {
827 const shown = isSearching
828 ? matchesLockedProvider(entry)
829 : entry.instanceId === selectedEntry?.instanceId;
830 const notice = shown
831 ? formatProviderUpdateRequiredNotice(entry.snapshot, searchQuery, messages, locale)
832 : null;
833 return notice
834 ? [
835 {
836 instanceId: entry.instanceId,
837 notice,
838 canUpdateInSettings: !providerUpdateChannelLags(entry.snapshot, searchQuery),
839 },
840 ]
841 : [];
842 });
843​
844 const modelJumpModelKeys = visibleModels
845 .filter((model) => !getModelDisabledReason?.(model.instanceId, model.slug))
846 .slice(0, MODEL_PICKER_JUMP_KEYBINDING_COMMANDS.length)
847 .map((model) => modelPickerModelKey(model.instanceId, model.slug));
848 const allItemKeys = ((): string[] => [
849 ...flatModels.map((model) => modelPickerModelKey(model.instanceId, model.slug)),
850 ...new Set(
851 flatModels
852 .filter((model) => model.isLegacy)
853 .map((model) => modelPickerLegacySectionKey(model.instanceId)),
854 ),
855 ...[...subProvidersByInstance].flatMap(([instanceId, subProviders]) =>
856 subProviders.map((subProvider) =>
857 modelPickerSubProviderSectionKey(instanceId, subProvider.name),
858 ),
859 ),
860 ])();
861 const filteredItemKeys = ((): string[] => {
862 const keyOf = (model: ModelPickerItem) => modelPickerModelKey(model.instanceId, model.slug);
863 if (subProviderSections) {
864 return [
865 ...subProviderSections.ungrouped.map(keyOf),
866 ...subProviderSections.sections.flatMap((section) => [
867 section.key,
868 ...(section.isExpanded ? section.models.map(keyOf) : []),
869 ]),
870 ];
871 }
872 const modelKeys = visibleModels.map(keyOf);
873 // The toggle trails the list, so expanding it reveals older models above it.
874 return legacySection ? [...modelKeys, legacySection.key] : modelKeys;
875 })();
876 const filteredModelByKey = ((): ReadonlyMap<string, ModelPickerItem> =>
877 new Map(
878 visibleModels.map(
879 (model) => [modelPickerModelKey(model.instanceId, model.slug), model] as const,
880 ),
881 ))();
882​
883 const modelJumpLabelByKey = modelJumpLabelsByKey(
884 modelJumpModelKeys,
885 keybindings,
886 props.terminalOpen,
887 );
888 const badgedInstanceIds = new Set(
889 instanceEntries
890 .filter((entry) => shouldShowInstanceBadge(entry, instanceEntries))
891 .map((entry) => entry.instanceId),
892 );
893 const modelListExtraData = {
894 badgedInstanceIds,
895 favoritesSet,
896 modelJumpLabelByKey,
897 activeModelKey,
898 selectedModelKeySet,
899 };
900​
901 const onWindowKeyDown = (event: globalThis.KeyboardEvent) => {
902 if (
903 event.defaultPrevented ||
904 event.repeat ||
905 event.isComposing ||
906 event.keyCode === 229 ||
907 isCommandPaletteOpen()
908 ) {
909 return;
910 }
911​
912 const command = resolveShortcutCommand(event, keybindings, {
913 platform: navigator.platform,
914 context: modelJumpShortcutContext,
915 });
916 if (command === "modelPicker.previousProvider" || command === "modelPicker.nextProvider") {
917 event.preventDefault();
918 event.stopPropagation();
919 const next = adjacentModelPickerProvider({
920 entries: sidebarInstanceEntries,
921 selectedInstanceId,
922 direction: command === "modelPicker.nextProvider" ? 1 : -1,
923 disabledInstanceIds: lockedDisabledInstanceIds,
924 selectableUnavailableInstanceIds,
925 });
926 setSearchQuery("");
927 handleSelectInstance(next);
928 announce(
929 next === "favorites" ? gt("Favorites") : (entryByInstanceId.get(next)?.displayName ?? next),
930 "model-picker",
931 );
932 return;
933 }
934 const jumpIndex = modelPickerJumpIndexFromCommand(command ?? "");
935 if (jumpIndex === null) {
936 return;
937 }
938 event.preventDefault();
939 event.stopPropagation();
940​
941 const targetModelKey = modelJumpModelKeys[jumpIndex];
942 if (!targetModelKey) {
943 return;
944 }
945 const model = parseModelPickerModelKey(targetModelKey);
946 if (!model) {
947 return;
948 }
949 const selectedSlug = handleModelSelect(model.slug, model.instanceId);
950 if (selectedSlug === null) return;
951 const name = flatModels.find(
952 (item) => item.slug === selectedSlug && item.instanceId === model.instanceId,
953 )?.name;
954 announce(gt("Model: {name}", { name: name ?? selectedSlug }), "model-picker");
955 };
956​
957 return (
958 <TooltipProvider delay={0}>
959 <WindowKeyDownListener onKeyDown={onWindowKeyDown} />
960 <div
961 ref={pickerContentRef}
962 className={cn(
963 "relative flex w-screen max-w-90 flex-row overflow-hidden",
964 props.docked ? "max-sm:h-56 max-sm:w-full max-sm:max-w-none" : "max-h-86.5",
965 )}
966 // Docked, the popup sets the height; a minimum here would overflow short windows.
967 style={
968 props.docked
969 ? undefined
970 : isSearching
971 ? { height: searchHeight }
972 : {
973 minHeight: `min(calc(var(--spacing) * ${tallestTabUnits + LIST_CHROME_UNITS} + 1px), calc(var(--spacing) * 86.5))`,
974 }
975 }
976 data-model-picker-content="true"
977 >
978 {showSidebar && (
979 <ModelPickerSidebar
980 selectedInstanceId={selectedInstanceId}
981 onSelectInstance={handleSelectInstance}
982 onFocusSearch={focusSearchInput}
983 instanceEntries={sidebarInstanceEntries}
984 showFavorites
985 {...(selectableUnavailableInstanceIds ? { selectableUnavailableInstanceIds } : {})}
986 {...(lockedDisabledInstanceIds
987 ? {
988 disabledInstanceIds: lockedDisabledInstanceIds,
989 getDisabledInstanceTooltip: (entry: ProviderInstanceEntry) =>
990 gt(
991 "{provider} is unavailable in this thread. Start a new thread to switch providers.",
992 { provider: entry.displayName },
993 ),
994 }
995 : {})}
996 />
997 )}
998​
999 <Combobox<string, boolean>
1000 inline
1001 items={allItemKeys}
1002 filteredItems={filteredItemKeys}
1003 filter={null}
1004 autoHighlight
1005 open
1006 virtualized
1007 multiple={onToggleModel !== undefined}
1008 value={onToggleModel ? [...selectedModelKeySet] : activeModelKey}
1009 onItemHighlighted={(modelKey, eventDetails) => {
1010 highlightedModelKeyRef.current = typeof modelKey === "string" ? modelKey : null;
1011 if (eventDetails.reason === "keyboard" && eventDetails.index >= 0) {
1012 void modelListRef.current?.scrollIndexIntoView?.({
1013 index: eventDetails.index,
1014 animated: false,
1015 });
1017 }}
1018 onValueChange={(value, details) => {
1019 const modelKey = Array.isArray(value)
1020 ? (value.find((key) => !selectedModelKeySet.has(key)) ??
1021 [...selectedModelKeySet].find((key) => !value.includes(key)))
1022 : value;
1023 if (typeof modelKey !== "string") {
1024 return;
1026 const legacyInstanceId = parseModelPickerLegacySectionKey(modelKey);
1027 if (legacyInstanceId) {
1028 toggleLegacySection(legacyInstanceId);
1029 return;
1031 if (subProviderSectionByKey.has(modelKey)) {
1032 toggleSubProviderSection(modelKey);
1033 return;
1035 const model = parseModelPickerModelKey(modelKey);
1036 if (model) {
1037 handleModelSelect(
1038 model.slug,
1039 model.instanceId,
1040 "shiftKey" in details.event && details.event.shiftKey === true,
1041 );
1043 }}
1045 <div
1046 className={cn(
1047 "flex min-h-0 flex-1 flex-col overflow-hidden bg-muted/40",
1048 showSidebar && "border-l border-border/70",
1049 )}
1051 <ComboboxSearchInput
1052 ref={searchInputRef}
1053 placeholder={gt("Search models...")}
1054 value={searchQuery}
1055 onChange={(e) => {
1056 if (!isSearching) setSearchHeight(pickerContentRef.current?.offsetHeight ?? 0);
1057 setSearchQuery(e.target.value);
1058 }}
1059 onKeyDown={(e) => {
1060 if (e.nativeEvent.isComposing || e.keyCode === 229) {
1061 (e as typeof e & { preventBaseUIHandler?: () => void }).preventBaseUIHandler?.();
1062 e.stopPropagation();
1063 return;
1065 if (
1066 showSidebar &&
1067 !e.altKey &&
1068 !e.ctrlKey &&
1069 !e.metaKey &&
1070 ((e.key === "ArrowLeft" && !e.shiftKey && searchQuery.length === 0) ||
1071 (e.key === "Tab" && e.shiftKey))
1072 ) {
1073 const sidebar = e.currentTarget
1074 .closest("[data-model-picker-content]")
1075 ?.querySelector("[data-model-picker-sidebar]");
1076 const button =
1077 sidebar?.querySelector<HTMLButtonElement>(
1078 'button[aria-pressed="true"]:not(:disabled)',
1079 ) ?? sidebar?.querySelector<HTMLButtonElement>("button:not(:disabled)");
1080 if (button) {
1081 e.preventDefault();
1082 e.stopPropagation();
1083 button.focus();
1084 return;
1087 if (e.key === "Escape") {
1088 e.preventDefault();
1089 e.stopPropagation();
1090 onRequestClose?.();
1091 return;
1093 if (
1094 props.onFocusEffort &&
1095 e.key === "ArrowRight" &&
1096 !e.altKey &&
1097 !e.ctrlKey &&
1098 !e.metaKey &&
1099 !e.shiftKey &&
1100 e.currentTarget.selectionStart === searchQuery.length
1101 ) {
1102 e.preventDefault();
1103 e.stopPropagation();
1104 // The column shows the selected model's effort, so a highlighted model is picked
1105 // first; the owning popup then moves focus to that model's levels.
1106 const highlighted = highlightedModelKeyRef.current
1107 ? parseModelPickerModelKey(highlightedModelKeyRef.current)
1108 : null;
1109 const pickedNew =
1110 highlighted !== null &&
1111 highlightedModelKeyRef.current !== activeModelKey &&
1112 handleModelSelect(highlighted.slug, highlighted.instanceId) !== null;
1113 if (!pickedNew) props.onFocusEffort();
1114 return;
1116 if (e.key === "Enter" && highlightedModelKeyRef.current) {
1117 (e as typeof e & { preventBaseUIHandler?: () => void }).preventBaseUIHandler?.();
1118 e.preventDefault();
1119 e.stopPropagation();
1120 const legacyInstanceId = parseModelPickerLegacySectionKey(
1121 highlightedModelKeyRef.current,
1122 );
1123 if (legacyInstanceId) {
1124 toggleLegacySection(legacyInstanceId);
1125 return;
1127 if (subProviderSectionByKey.has(highlightedModelKeyRef.current)) {
1128 toggleSubProviderSection(highlightedModelKeyRef.current);
1129 return;
1131 const model = parseModelPickerModelKey(highlightedModelKeyRef.current);
1132 if (model) {
1133 handleModelSelect(model.slug, model.instanceId, e.shiftKey);
1135 return;
1137 e.stopPropagation();
1138 }}
1139 onMouseDown={(e) => e.stopPropagation()}
1140 onTouchStart={(e) => e.stopPropagation()}
1141 />
1142​
1143 <ModelPickerList
1144 listRef={modelListRef}
1145 itemKeys={filteredItemKeys}
1146 extraData={modelListExtraData}
1147 renderItem={({ item: modelKey, index }) => {
1148 if (legacySection?.key === modelKey) {
1149 return (
1150 <ComboboxItem
1151 hideIndicator
1152 index={index}
1153 value={modelKey}
1154 aria-expanded={legacySection.isExpanded}
1155 className="group w-full cursor-pointer"
1157 <span className="text-sm leading-snug text-muted-foreground group-hover:text-foreground group-data-highlighted:text-foreground">
1158 {legacySection.isExpanded
1159 ? gt("Show less", { $context: "collapses the list of older models" })
1160 : gt("Show more", { $context: "expands the list of older models" })}
1161 </span>
1162 </ComboboxItem>
1163 );
1165 const subProviderSection = subProviderSectionByKey.get(modelKey);
1166 if (subProviderSection) {
1167 const unavailable = subProviderSection.unavailableReason !== undefined;
1168 return (
1169 <ComboboxItem
1170 hideIndicator
1171 index={index}
1172 value={modelKey}
1173 disabled={unavailable}
1174 aria-expanded={unavailable ? undefined : subProviderSection.isExpanded}
1175 className="group w-full cursor-pointer"
1177 <div className="min-w-0 flex-1 text-left">
1178 <div className="flex min-w-0 items-center gap-2">
1179 <div className="min-w-0 truncate text-sm font-normal leading-snug">
1180 {subProviderSection.name}
1181 </div>
1182 {unavailable ? (
1183 <Badge variant="outline" size="sm">
1184 {gt("Unavailable", { $context: "backend cannot be used right now" })}
1185 </Badge>
1186 ) : null}
1187 </div>
1188 <div className="mt-1 text-xs font-normal leading-snug text-muted-foreground">
1189 {subProviderSection.unavailableReason ??
1190 gt("{count, plural, one {{count} model} other {{count} models}}", {
1191 count: subProviderSection.models.length,
1192 })}
1193 </div>
1194 </div>
1195 {unavailable ? null : (
1196 <ChevronRightIcon
1197 className={cn(
1198 "size-4 shrink-0 transition-transform",
1199 subProviderSection.isExpanded && "rotate-90",
1200 )}
1201 />
1202 )}
1203 </ComboboxItem>
1204 );
1206 const model = filteredModelByKey.get(modelKey);
1207 if (!model) {
1208 return null;
1210 const disabledReason =
1211 getModelDisabledReason?.(model.instanceId, model.slug) ?? null;
1212 return (
1213 <ModelListRow
1214 key={modelKey}
1215 index={index}
1216 slug={model.slug}
1217 name={model.name}
1218 subProvider={model.subProvider}
1219 instanceId={model.instanceId}
1220 driverKind={model.driverKind}
1221 providerDisplayName={model.instanceDisplayName}
1222 providerAccentColor={model.instanceAccentColor}
1223 acpRegistryAgentId={model.acpRegistryAgentId}
1224 acpRegistryIconUrl={model.acpRegistryIconUrl}
1225 isFavorite={favoritesSet.has(providerModelKey(model.instanceId, model.slug))}
1226 isSelected={
1227 selectedModelKeys !== undefined
1228 ? selectedModelKeySet.has(modelKey)
1229 : modelKey === activeModelKey
1231 favoriteStarOnHover={selectedInstanceId === "favorites" && !isSearching}
1232 showInstanceBadge={badgedInstanceIds.has(model.instanceId)}
1233 showNewBadge={model.badge === "new"}
1234 unavailable={model.isUnavailable === true}
1235 jumpLabel={modelJumpLabelByKey.get(modelKey) ?? null}
1236 disabledReason={disabledReason}
1237 onToggleFavorite={toggleFavorite}
1238 />
1239 );
1240 }}
1241 />
1242 <ModelPickerProviderNotices
1243 setupEntries={providerSetupEntries}
1244 updateRequiredNotices={updateRequiredNotices}
1245 emptyLabel={
1246 selectedInstanceId === "favorites" && !isSearching
1247 ? gt("No favorites yet")
1248 : workspaceModelsScanning
1249 ? gt("Searching project models...")
1250 : gt("No models found")
1252 onRequestClose={onRequestClose}
1253 onOpenProviderSetup={onOpenProviderSetup}
1254 />
1255 {props.listFooter}
1256 </div>
1257 </Combobox>
1258 </div>
1259 </TooltipProvider>
1260 );
1261});