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

ModelPickerContent.tsx

1,261 lines46.0 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 { InlineButton } from "../ui/button";
68import { Badge } from "../ui/badge";
69import {
70 isProviderInstancePickerReady,
71 isProviderInstancePickerVisible,
72 shouldShowInstanceBadge,
73 type ProviderInstanceEntry,
74} from "../../providerInstances";
75import { providerModelKey, sortProviderModelItems } from "../../modelOrdering";
76import { hasRuntimeModelCatalog } from "../../providerModels";
77​
78type ModelPickerItem = {
79 slug: string;
80 name: string;
81 shortName?: string;
82 subProvider?: string;
83 badge?: "new";
84 instanceId: ProviderInstanceId;
85 driverKind: ProviderDriverKind;
86 instanceDisplayName: string;
87 instanceAccentColor?: string | undefined;
88 acpRegistryAgentId?: string | undefined;
89 acpRegistryIconUrl?: string | undefined;
90 continuationGroupKey?: string | undefined;
91 isLegacy?: boolean | undefined;
92 isUnavailable?: boolean | undefined;
93};
94​
95export function resolveModelPickerSelectedModel(input: {
96 driverKind: ProviderDriverKind | undefined;
97 model: string;
98 options: ReadonlyArray<ModelEsque>;
99}) {
100 if (input.driverKind === "antigravity" && input.model === ANTIGRAVITY_DEFAULT_MODEL) {
101 const availableModels = input.options.filter(
102 (option) => option.slug !== ANTIGRAVITY_DEFAULT_MODEL && !option.isUnavailable,
103 );
104 return (
105 availableModels.find((option) => option.aliases?.includes(ANTIGRAVITY_DEFAULT_MODEL)) ??
106 availableModels.find((option) => option.isDefault)
107 );
108 }
109 return input.options.find((option) => option.slug === input.model);
111​
112function shouldIncludeModelPickerOption(input: {
113 readonly entry: ProviderInstanceEntry;
114 readonly option: ModelEsque;
115 readonly activeInstanceId: ProviderInstanceId;
116 readonly activeModel: string;
117}): boolean {
118 if (input.entry.driverKind === "antigravity" && input.option.slug === ANTIGRAVITY_DEFAULT_MODEL) {
119 return false;
120 }
121 if (isProviderInstancePickerReady(input.entry)) return true;
122 return (
123 input.entry.enabled &&
124 hasRuntimeModelCatalog(input.entry.driverKind) &&
125 input.entry.instanceId === input.activeInstanceId &&
126 input.option.slug === input.activeModel &&
127 input.option.isUnavailable === true
128 );
130​
131function shouldOfferModelPickerSetup(
132 entry: ProviderInstanceEntry,
133 options: ReadonlyArray<ModelEsque>,
134): boolean {
135 return (
136 entry.enabled &&
137 entry.status !== "disabled" &&
138 hasProviderSetup(entry.snapshot) &&
139 (!isProviderInstancePickerReady(entry) ||
140 !entry.installed ||
141 entry.snapshot.auth.status === "unauthenticated" ||
142 !options.some((option) => !option.isUnavailable))
143 );
145​
146function adjacentModelPickerProvider(input: {
147 entries: ReadonlyArray<ProviderInstanceEntry>;
148 selectedInstanceId: ProviderInstanceId | "favorites";
149 direction: 1 | -1;
150 disabledInstanceIds: ReadonlySet<ProviderInstanceId> | undefined;
151 selectableUnavailableInstanceIds: ReadonlySet<ProviderInstanceId> | undefined;
152}) {
153 const providers: Array<ProviderInstanceId | "favorites"> = [
154 "favorites",
155 ...input.entries
156 .filter(
157 (entry) =>
158 !input.disabledInstanceIds?.has(entry.instanceId) &&
159 (isProviderInstancePickerReady(entry) ||
160 input.selectableUnavailableInstanceIds?.has(entry.instanceId)),
161 )
162 .map((entry) => entry.instanceId),
163 ];
164 const index = providers.indexOf(input.selectedInstanceId);
165 return providers[
166 index < 0
167 ? input.direction === 1
168 ? 0
169 : providers.length - 1
170 : (index + input.direction + providers.length) % providers.length
171 ]!;
173​
174const EMPTY_MODEL_JUMP_LABELS = new Map<string, string>();
175const MODEL_LIST_ESTIMATED_ITEM_SIZE = 32;
176// Rendered heights in `--spacing` units. Chrome is the search box and list padding, plus a 1px border.
177const ROW_UNITS = 8;
178const ROW_SEPARATOR_UNITS = 0.5;
179const LIST_CHROME_UNITS = 15.5;
180​
181function ModelListSeparator() {
182 return <div className="h-0.5" />;
184​
185function modelJumpLabelsByKey(
186 modelKeys: ReadonlyArray<string>,
187 keybindings: ResolvedKeybindingsConfig,
188 terminalOpen: boolean,
189): ReadonlyMap<string, string> {
190 const shortcutLabelOptions = {
191 platform: navigator.platform,
192 context: { terminalFocus: false, terminalOpen, modelPickerOpen: true },
193 };
194 const mapping = new Map<string, string>();
195 for (const [index, modelKey] of modelKeys.entries()) {
196 const command = modelPickerJumpCommandForIndex(index);
197 const label = command && shortcutLabelForCommand(keybindings, command, shortcutLabelOptions);
198 if (label) {
199 mapping.set(modelKey, label);
200 }
201 }
202 return mapping.size > 0 ? mapping : EMPTY_MODEL_JUMP_LABELS;
204​
205function ModelPickerProviderNotices({
206 setupEntries,
207 updateRequiredNotices,
208 emptyLabel,
209 onRequestClose,
210 onOpenProviderSetup,
211}: {
212 setupEntries: ReadonlyArray<ProviderInstanceEntry>;
213 emptyLabel: string;
214 updateRequiredNotices: ReadonlyArray<{
215 instanceId: ProviderInstanceId;
216 notice: string;
217 canUpdateInSettings: boolean;
218 }>;
219 onRequestClose: (() => void) | undefined;
220 onOpenProviderSetup: ((instanceId: ProviderInstanceId) => void) | undefined;
221}) {
222 const gt = useGT();
223 const messages = useMessages();
224 const navigate = useNavigate();
225 return (
226 <>
227 {setupEntries.length > 0 ? (
228 <div className="max-h-44 shrink-0 overflow-y-auto border-t border-border/70 p-2">
229 {setupEntries.map((entry) => (
230 <div key={entry.instanceId} className="px-1 py-1.5 text-xs leading-snug">
231 <p className="line-clamp-3 text-muted-foreground">
232 {getProviderStatusMessage(entry.snapshot, messages)}
233 </p>
234 <InlineButton
235 className="mt-1"
236 onClick={() => {
237 onRequestClose?.();
238 onOpenProviderSetup?.(entry.instanceId);
239 }}
240 >
241 {setupEntries.length > 1
242 ? gt("Set up {provider}", { provider: entry.displayName })
243 : gt("Open provider setup")}
244 </InlineButton>
245 </div>
246 ))}
247 </div>
248 ) : (
249 <ComboboxEmpty className="empty:h-0">{emptyLabel}</ComboboxEmpty>
250 )}
251 {updateRequiredNotices.map(({ instanceId, notice, canUpdateInSettings }) => (
252 <p
253 key={instanceId}
254 className="shrink-0 border-t border-border/70 px-3 py-2 text-xs leading-snug text-muted-foreground"
255 >
256 {notice}
257 {canUpdateInSettings ? (
258 <>
259 {" "}
260 <InlineButton
261 onClick={() => {
262 onRequestClose?.();
263 void navigate({ to: "/settings/providers" });
264 }}
265 >
266 <T>Provider settings</T>
267 </InlineButton>
268 </>
269 ) : null}
270 </p>
271 ))}
272 </>
273 );
275​
276function ModelPickerList({
277 listRef,
278 itemKeys,
279 extraData,
280 renderItem,
281}: {
282 listRef: RefObject<LegendListRef | null>;
283 itemKeys: ReadonlyArray<string>;
284 extraData: unknown;
285 renderItem: (props: { item: string; index: number }) => ReactNode;
286}) {
287 const [showTopScrollFade, setShowTopScrollFade] = useState(false);
288 const [showBottomScrollFade, setShowBottomScrollFade] = useState(false);
289 const updateScrollFades = () => {
290 const metrics = listRef.current?.getState();
291 if (!metrics) return;
292 setShowTopScrollFade(!metrics.isAtStart);
293 setShowBottomScrollFade(!metrics.isAtEnd);
294 };
295 const scrollRef = useLegendListRef(listRef, updateScrollFades);
296​
297 return (
298 <div
299 className={cn(
300 "relative min-h-0 overflow-hidden pr-px",
301 itemKeys.length > 0 ? "flex-1" : "h-0",
302 )}
303 >
304 <ComboboxListVirtualized>
305 <LegendList<string>
306 ref={scrollRef}
307 data={itemKeys}
308 extraData={extraData}
309 keyExtractor={(modelKey) => modelKey}
310 renderItem={renderItem}
311 estimatedItemSize={MODEL_LIST_ESTIMATED_ITEM_SIZE}
312 drawDistance={480}
313 recycleItems
314 contentContainerClassName="pl-2 pr-px"
315 ItemSeparatorComponent={ModelListSeparator}
316 onLayout={updateScrollFades}
317 onScroll={updateScrollFades}
318 onReady={updateScrollFades}
319 className={cn(
320 "scrollbar-gutter-stable h-full overflow-x-hidden overscroll-y-contain py-1.5 [&::-webkit-scrollbar-track]:my-2",
321 getVirtualizedScrollFadeClassName({
322 top: showTopScrollFade,
323 bottom: showBottomScrollFade,
324 }),
325 )}
326 />
327 </ComboboxListVirtualized>
328 </div>
329 );
331​
332// Capture gives picker shortcuts priority over the composer.
333function WindowKeyDownListener({ onKeyDown }: { onKeyDown: (event: KeyboardEvent) => void }) {
334 const handleKeyDown = useEffectEvent(onKeyDown);
335 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes a capture-phase window keydown listener for the picker's lifetime
336 useEffect(() => {
337 const listener = (event: KeyboardEvent) => handleKeyDown(event);
338 window.addEventListener("keydown", listener, true);
339 return () => {
340 window.removeEventListener("keydown", listener, true);
341 };
342 }, []);
343 return null;
345​
346export const ModelPickerContent = memo(function ModelPickerContent(props: {
347 environmentId: EnvironmentId | null;
348 /** Keeps the open provider tab's catalog fresh for this directory. */
349 workspaceCwd?: string | null;
350 activeInstanceId: ProviderInstanceId;
351 model: string;
352 selectedModels?: ReadonlyArray<{ instanceId: ProviderInstanceId; model: string }>;
353 onToggleModel?: (instanceId: ProviderInstanceId, model: string) => void;
354 lockedProvider: ProviderDriverKind | null;
355 lockedContinuationGroupKey?: string | null;
356 instanceEntries: ReadonlyArray<ProviderInstanceEntry>;
357 keybindings?: ResolvedKeybindingsConfig;
358 modelOptionsByInstance: ReadonlyMap<ProviderInstanceId, ReadonlyArray<ModelEsque>>;
359 terminalOpen: boolean;
360 onRequestClose?: () => void;
361 onOpenProviderSetup?: (instanceId: ProviderInstanceId) => void;
362 getModelDisabledReason?: (instanceId: ProviderInstanceId, model: string) => string | null;
363 onInstanceModelChange: (instanceId: ProviderInstanceId, model: string) => void;
364 /** The owning popup moves focus here when it opens (its `initialFocus`). */
365 searchInputRef: RefObject<HTMLInputElement | null>;
366 /** Sits beside an effort column: fills the shared row, and stacks above it on narrow screens. */
367 docked?: boolean;
368 /** Right at the end of the search text moves into the popup's effort column. */
369 onFocusEffort?: () => void;
370 /** Closes the list column, inside the popup's fixed height. */
371 listFooter?: ReactNode;
372}) {
373 const gt = useGT();
374 const messages = useMessages();
375 const locale = useLocale();
376 const {
377 searchInputRef,
378 keybindings: providedKeybindings,
379 modelOptionsByInstance,
380 instanceEntries,
381 getModelDisabledReason,
382 onInstanceModelChange,
383 onToggleModel,
384 onRequestClose,
385 onOpenProviderSetup,
386 } = props;
387 const [searchQuery, setSearchQuery] = useState("");
388 const modelListRef = useRef<LegendListRef | null>(null);
389 const pickerContentRef = useRef<HTMLDivElement>(null);
390 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes this picker's mount to global keydown handlers
391 useLayoutEffect(() => registerModelPickerContent(), []);
392 const highlightedModelKeyRef = useRef<string | null>(null);
393 const { favorites } = useEnvironmentModelPreferences(props.environmentId);
394 const activeEntry = props.instanceEntries.find(
395 (entry) => entry.instanceId === props.activeInstanceId,
396 );
397 const activeModel = resolveModelPickerSelectedModel({
398 driverKind: activeEntry?.driverKind,
399 model: props.model,
400 options: modelOptionsByInstance.get(props.activeInstanceId) ?? [],
401 });
402 const activeModelSlug =
403 activeModel?.slug ?? (props.model === ANTIGRAVITY_DEFAULT_MODEL ? "" : props.model);
404 const activeModelKey = activeModelSlug
405 ? modelPickerModelKey(props.activeInstanceId, activeModelSlug)
406 : null;
407 const selectedModelKeys = props.selectedModels?.map((selection) => {
408 const entry = instanceEntries.find((entry) => entry.instanceId === selection.instanceId);
409 const model = resolveModelPickerSelectedModel({
410 driverKind: entry?.driverKind,
411 model: selection.model,
412 options: modelOptionsByInstance.get(selection.instanceId) ?? [],
413 });
414 return modelPickerModelKey(selection.instanceId, model?.slug ?? selection.model);
415 });
416 const selectedModelKeySet = new Set(
417 selectedModelKeys ?? (activeModelKey ? [activeModelKey] : []),
418 );
419 const activeInstanceHasSelectableUnavailableModel =
420 activeEntry !== undefined &&
421 (modelOptionsByInstance.get(props.activeInstanceId) ?? []).some((option) =>
422 shouldIncludeModelPickerOption({
423 entry: activeEntry,
424 option,
425 activeInstanceId: props.activeInstanceId,
426 activeModel: activeModelSlug,
427 }),
428 ) &&
429 !isProviderInstancePickerReady(activeEntry);
430 const activeInstanceNeedsSetup =
431 onOpenProviderSetup !== undefined &&
432 activeEntry !== undefined &&
433 shouldOfferModelPickerSetup(
434 activeEntry,
435 modelOptionsByInstance.get(props.activeInstanceId) ?? [],
436 );
437 const [selectedInstanceId, setSelectedInstanceId] = useState<ProviderInstanceId | "favorites">(
438 () => {
439 if (
440 props.lockedProvider !== null ||
441 activeInstanceHasSelectableUnavailableModel ||
442 activeInstanceNeedsSetup
443 ) {
444 return props.activeInstanceId;
445 }
446 const hasPickableFavorite = favorites.some((favorite) => {
447 const entry = instanceEntries.find((entry) => entry.instanceId === favorite.provider);
448 return (
449 entry !== undefined &&
450 (modelOptionsByInstance.get(favorite.provider) ?? []).some(
451 (option) =>
452 option.slug === favorite.model &&
453 shouldIncludeModelPickerOption({
454 entry,
455 option,
456 activeInstanceId: props.activeInstanceId,
457 activeModel: activeModelSlug,
458 }),
459 )
460 );
461 });
462 return hasPickableFavorite ? "favorites" : props.activeInstanceId;
463 },
464 );
465 const { scanning: workspaceModelsScanning } = useProviderWorkspaceSnapshotRefresh({
466 environmentId: props.environmentId,
467 gitCwd: props.workspaceCwd ?? null,
468 instanceId: selectedInstanceId === "favorites" ? undefined : selectedInstanceId,
469 });
470 const favoritesSet = new Set(favorites.map((fav) => providerModelKey(fav.provider, fav.model)));
471 const [expandedLegacyInstances, setExpandedLegacyInstances] = useState(
472 () =>
473 new Set<ProviderInstanceId>(
474 activeModel?.isLegacy &&
475 !favoritesSet.has(providerModelKey(props.activeInstanceId, activeModelSlug))
476 ? [props.activeInstanceId]
477 : [],
478 ),
479 );
480 // The thread's backend opens expanded, so its models show without a click.
481 const [expandedSubProviderKeys, setExpandedSubProviderKeys] = useState(
482 () =>
483 new Set<string>(
484 activeModel?.subProvider
485 ? [modelPickerSubProviderSectionKey(props.activeInstanceId, activeModel.subProvider)]
486 : [],
487 ),
488 );
489 const serverKeybindings = useAtomValue(primaryServerKeybindingsAtom);
490 const keybindings = providedKeybindings ?? serverKeybindings;
491 const [searchHeight, setSearchHeight] = useState(0);
492 const toggleFavorite = useToggleEnvironmentModelFavorite(props.environmentId);
493​
494 const focusSearchInput = () => {
495 searchInputRef.current?.focus({ preventScroll: true });
496 };
497​
498 const handleSelectInstance = (instanceId: ProviderInstanceId | "favorites") => {
499 setSelectedInstanceId(instanceId);
500 // Focusing the search on touch raises the on-screen keyboard on every provider tap.
501 if (window.matchMedia("(pointer: coarse)").matches) return;
502 window.requestAnimationFrame(() => {
503 focusSearchInput();
504 });
505 };
506​
507 const toggleLegacySection = (instanceId: ProviderInstanceId) => {
508 setExpandedLegacyInstances((expanded) => {
509 const next = new Set(expanded);
510 if (next.has(instanceId)) {
511 next.delete(instanceId);
512 } else {
513 next.add(instanceId);
514 }
515 return next;
516 });
517 };
518​
519 const toggleSubProviderSection = (key: string) => {
520 setExpandedSubProviderKeys((expanded) => {
521 const next = new Set(expanded);
522 if (!next.delete(key)) next.add(key);
523 return next;
524 });
525 };
526​
527 const handleModelSelect = (
528 modelSlug: string,
529 instanceId: ProviderInstanceId,
530 additive = false,
531 ): string | null => {
532 if (getModelDisabledReason?.(instanceId, modelSlug)) {
533 return null;
534 }
535 const options = modelOptionsByInstance.get(instanceId);
536 if (!options) {
537 return null;
538 }
539 const entry = instanceEntries.find((candidate) => candidate.instanceId === instanceId);
540 if (!entry) {
541 return null;
542 }
543 const resolvedModel = resolveSelectableModel(entry.driverKind, modelSlug, options);
544 if (!resolvedModel) return null;
545 if (additive && onToggleModel) {
546 onToggleModel(instanceId, resolvedModel);
547 } else {
548 onInstanceModelChange(instanceId, resolvedModel);
549 }
550 return resolvedModel;
551 };
552​
553 const modelJumpShortcutContext = {
554 terminalFocus: false,
555 terminalOpen: props.terminalOpen,
556 modelPickerOpen: true,
557 } as const;
558 const lockedProvider = props.lockedProvider;
559 const lockedContinuationGroupKey = props.lockedContinuationGroupKey;
560 const canOpenProviderSetup = onOpenProviderSetup !== undefined;
561​
562 const entryByInstanceId = new Map(instanceEntries.map((entry) => [entry.instanceId, entry]));
563 const matchesLockedProvider = (
564 entry: Pick<ProviderInstanceEntry, "driverKind" | "continuationGroupKey">,
565 ): boolean => {
566 if (lockedProvider === null) return true;
567 if (entry.driverKind !== lockedProvider) return false;
568 if (!lockedContinuationGroupKey) return true;
569 return entry.continuationGroupKey === lockedContinuationGroupKey;
570 };
571​
572 const selectableUnavailableInstanceIds = (() => {
573 const instanceIds = new Set<ProviderInstanceId>();
574 if (activeInstanceHasSelectableUnavailableModel) {
575 instanceIds.add(props.activeInstanceId);
576 }
577 if (canOpenProviderSetup) {
578 for (const entry of instanceEntries) {
579 if (
580 shouldOfferModelPickerSetup(entry, modelOptionsByInstance.get(entry.instanceId) ?? [])
581 ) {
582 instanceIds.add(entry.instanceId);
583 }
584 }
585 }
586 return instanceIds.size > 0 ? instanceIds : undefined;
587 })();
588​
589 const flatModels = (() => {
590 const out: ModelPickerItem[] = [];
591 const seenKeys = new Set<string>();
592 for (const [instanceId, models] of modelOptionsByInstance) {
593 const entry = entryByInstanceId.get(instanceId);
594 if (!entry) {
595 continue;
596 }
597 for (const model of models) {
598 const key = modelPickerModelKey(instanceId, model.slug);
599 if (
600 seenKeys.has(key) ||
601 !shouldIncludeModelPickerOption({
602 entry,
603 option: model,
604 activeInstanceId: props.activeInstanceId,
605 activeModel: activeModelSlug,
606 })
607 ) {
608 continue;
609 }
610 seenKeys.add(key);
611 out.push({
612 slug: model.slug,
613 name: model.name,
614 ...(model.shortName ? { shortName: model.shortName } : {}),
615 ...(model.subProvider ? { subProvider: model.subProvider } : {}),
616 ...(model.badge ? { badge: model.badge } : {}),
617 ...(model.isLegacy ? { isLegacy: true } : {}),
618 ...(model.isUnavailable ? { isUnavailable: true } : {}),
619 instanceId,
620 driverKind: entry.driverKind,
621 instanceDisplayName: entry.displayName,
622 ...(entry.accentColor ? { instanceAccentColor: entry.accentColor } : {}),
623 ...(entry.acpRegistryAgentId ? { acpRegistryAgentId: entry.acpRegistryAgentId } : {}),
624 ...(entry.acpRegistryIconUrl ? { acpRegistryIconUrl: entry.acpRegistryIconUrl } : {}),
625 ...(entry.continuationGroupKey
626 ? { continuationGroupKey: entry.continuationGroupKey }
627 : {}),
628 });
629 }
630 }
631 return out;
632 })();
633​
634 const subProvidersByInstance = new Map(
635 instanceEntries.flatMap((entry) =>
636 entry.snapshot.subProviders?.length
637 ? [[entry.instanceId, entry.snapshot.subProviders] as const]
638 : [],
639 ),
640 );
641 const isLocked = lockedProvider !== null;
642 const isSearching = searchQuery.trim().length > 0;
643 // Fit the tallest tab so switching tabs never resizes the popup and moves the rail under the cursor.
644 const tallestTabUnits = (() => {
645 const unitsByTab = new Map<ProviderInstanceId | "favorites", number>();
646 const addRow = (tab: ProviderInstanceId | "favorites") => {
647 const previous = unitsByTab.get(tab);
648 unitsByTab.set(
649 tab,
650 previous === undefined ? ROW_UNITS : previous + ROW_SEPARATOR_UNITS + ROW_UNITS,
651 );
652 };
653 const tabsWithLegacyRow = new Set<ProviderInstanceId>();
654 for (const model of flatModels) {
655 if (!matchesLockedProvider(model)) continue;
656 const isFavorite = favoritesSet.has(providerModelKey(model.instanceId, model.slug));
657 if (isFavorite) addRow("favorites");
658 if (model.isLegacy && !isFavorite) {
659 tabsWithLegacyRow.add(model.instanceId);
660 } else {
661 addRow(model.instanceId);
662 }
663 }
664 for (const instanceId of tabsWithLegacyRow) addRow(instanceId);
665 for (const [instanceId, subProviders] of subProvidersByInstance) {
666 for (const _subProvider of subProviders) addRow(instanceId);
667 }
668 return Math.max(0, ...unitsByTab.values());
669 })();
670 const lockedDisabledInstanceIds = (() => {
671 if (!isLocked) {
672 return undefined;
673 }
674 const disabled = new Set<ProviderInstanceId>();
675 for (const entry of instanceEntries) {
676 if (!matchesLockedProvider(entry)) {
677 disabled.add(entry.instanceId);
678 }
679 }
680 return disabled;
681 })();
682 const sidebarInstanceEntries = (() => {
683 const enabledEntries = instanceEntries.filter(isProviderInstancePickerVisible);
684 if (!isLocked) {
685 return enabledEntries;
686 }
687 const available: ProviderInstanceEntry[] = [];
688 const disabled: ProviderInstanceEntry[] = [];
689 for (const entry of enabledEntries) {
690 if (matchesLockedProvider(entry)) {
691 available.push(entry);
692 } else {
693 disabled.push(entry);
694 }
695 }
696 return [...available, ...disabled];
697 })();
698 const showSidebar = !isSearching && sidebarInstanceEntries.length > 0;
699 const instanceOrder = instanceEntries.map((entry) => entry.instanceId);
700​
701 const filteredModels = (() => {
702 let result = flatModels;
703​
704 if (searchQuery.trim()) {
705 const candidates =
706 lockedProvider !== null ? result.filter((m) => matchesLockedProvider(m)) : result;
707 return rankModelPickerSearch(candidates, searchQuery, (model) => ({
708 name: model.name,
709 slug: model.slug,
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 <>
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 </>
1260 );
1261});