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

ModelPickerContent.tsx

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