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

ModelPickerContent.tsx

1,041 lines37.3 KB

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