The best way to control Claude Code, Codex and more from any computer or phone

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