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

ModelPickerContent.tsx

1,090 lines39.6 KB

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