Open History to see the last commit
1"use client";
2
3import { ArrowDownIcon, ArrowUpIcon, PencilIcon, PlusIcon, StarIcon, XIcon } from "lucide-react";
4import { useEffect, useRef, useState } from "react";
5import {
6 ProviderDriverKind,
7 type ProviderInstanceId,
8 type ServerProviderModel,
9} from "@t3tools/contracts";
10import { type CustomModelDefinition, normalizeCustomModelSlug } from "@t3tools/shared/model";
11
12import { cn } from "../../lib/utils";
13import { sortModelsForProviderInstance } from "../../modelOrdering";
14import { MAX_CUSTOM_MODEL_LENGTH } from "../../modelSelection";
15import { Button } from "../ui/button";
16import { Input } from "../ui/input";
17import { Switch } from "../ui/switch";
18import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
19import { CustomModelEditor } from "./CustomModelEditor";
20
21const CUSTOM_MODEL_PLACEHOLDER_BY_KIND: Partial<Record<ProviderDriverKind, string>> = {
22 [ProviderDriverKind.make("codex")]: "gpt-6.7-codex-ultra-preview",
23 [ProviderDriverKind.make("claudeAgent")]: "claude-sonnet-5",
24 [ProviderDriverKind.make("cursor")]: "claude-sonnet-4-6",
25 [ProviderDriverKind.make("opencode")]: "openai/gpt-5",
26 [ProviderDriverKind.make("pi")]: "anthropic/claude-sonnet-5",
27};
28
29const FILTER_THRESHOLD = 8;
30
31function describeModelCapabilities(model: ServerProviderModel): string[] {
32 const descriptors = model.capabilities?.optionDescriptors ?? [];
33 const labels: string[] = [];
34 const hasFastMode = descriptors.some(
35 (descriptor) =>
36 descriptor.id === "fastMode" ||
37 (descriptor.id === "serviceTier" &&
38 descriptor.type === "select" &&
39 descriptor.options.some((option) => option.id === "fast" || option.label === "Fast")),
40 );
41 if (hasFastMode) labels.push("Fast mode");
42 if (descriptors.some((descriptor) => descriptor.id === "thinking")) labels.push("Thinking");
43 if (
44 descriptors.some(
45 (descriptor) =>
46 descriptor.type === "select" &&
47 (descriptor.id === "reasoningEffort" ||
48 descriptor.id === "effort" ||
49 descriptor.id === "reasoning" ||
50 descriptor.id === "variant"),
51 )
52 ) {
53 labels.push("Reasoning");
54 }
55 return labels;
56}
57
58export function groupModelsForDisplay<
59 T extends { readonly slug: string; readonly isCustom: boolean },
60>(
61 models: ReadonlyArray<T>,
62 options: {
63 readonly favoriteModels: ReadonlySet<string>;
64 readonly hiddenModels: ReadonlySet<string>;
65 readonly modelOrder: ReadonlyArray<string>;
66 },
67): T[] {
68 const ordered = sortModelsForProviderInstance(models, {
69 favoriteModels: options.favoriteModels,
70 groupFavorites: true,
71 modelOrder: options.modelOrder,
72 });
73 const isHidden = (model: T) => !model.isCustom && options.hiddenModels.has(model.slug);
74 return [
75 ...ordered.filter((model) => options.favoriteModels.has(model.slug)),
76 ...ordered.filter((model) => !options.favoriteModels.has(model.slug) && !isHidden(model)),
77 ...ordered.filter((model) => !options.favoriteModels.has(model.slug) && isHidden(model)),
78 ];
79}
80
81export function nextHiddenModelsForBulkToggle(
82 models: ReadonlyArray<Pick<ServerProviderModel, "slug" | "isCustom">>,
83 hiddenModels: ReadonlyArray<string>,
84): string[] {
85 const builtInSlugs = models.filter((model) => !model.isCustom).map((model) => model.slug);
86 const builtInSlugSet = new Set(builtInSlugs);
87 const allBuiltInModelsHidden = builtInSlugs.every((slug) => hiddenModels.includes(slug));
88
89 if (allBuiltInModelsHidden) {
90 return hiddenModels.filter((slug) => !builtInSlugSet.has(slug));
91 }
92
93 return [...new Set([...hiddenModels, ...builtInSlugs])];
94}
95
96interface ProviderModelsSectionProps {
97 readonly instanceId: ProviderInstanceId;
98 readonly driverKind: ProviderDriverKind | null;
99 readonly models: ReadonlyArray<ServerProviderModel>;
100 readonly customModels: ReadonlyArray<CustomModelDefinition>;
101 readonly canManageCustomModels: boolean;
102 readonly canWritePreferences?: boolean;
103 readonly hiddenModels: ReadonlyArray<string>;
104 readonly favoriteModels: ReadonlyArray<string>;
105 readonly modelOrder: ReadonlyArray<string>;
106 readonly onChange: (next: ReadonlyArray<CustomModelDefinition>) => void;
107 readonly onHiddenModelsChange: (
108 next: ReadonlyArray<string>,
109 affectedModels?: ReadonlyArray<string>,
110 ) => void;
111 readonly onFavoriteModelsChange: (next: ReadonlyArray<string>) => void;
112 readonly onToggleFavorite: (model: string) => void;
113 readonly onModelOrderChange: (next: ReadonlyArray<string>) => void;
114}
115
116export function ProviderModelsSection({
117 instanceId,
118 driverKind,
119 models,
120 customModels,
121 canManageCustomModels,
122 canWritePreferences = true,
123 hiddenModels,
124 favoriteModels,
125 modelOrder,
126 onChange,
127 onHiddenModelsChange,
128 onFavoriteModelsChange,
129 onToggleFavorite,
130 onModelOrderChange,
131}: ProviderModelsSectionProps) {
132 const [input, setInput] = useState("");
133 const [isAdding, setIsAdding] = useState(false);
134 const [filter, setFilter] = useState("");
135 const [error, setError] = useState<string | null>(null);
136 const [editingSlug, setEditingSlug] = useState<string | null>(null);
137 const listRef = useRef<HTMLDivElement>(null);
138 const scrollToSlugRef = useRef<string | null>(null);
139 const hiddenModelSet = new Set(hiddenModels);
140 const favoriteModelSet = new Set(favoriteModels);
141 const displayModels = groupModelsForDisplay(models, {
142 favoriteModels: favoriteModelSet,
143 hiddenModels: hiddenModelSet,
144 modelOrder,
145 });
146 const favoriteCount = displayModels.filter((model) => favoriteModelSet.has(model.slug)).length;
147 const hiddenCount = displayModels.filter(
148 (model) => !model.isCustom && hiddenModelSet.has(model.slug),
149 ).length;
150 const showFilter = models.length > FILTER_THRESHOLD;
151 const normalizedFilter = filter.trim().toLowerCase();
152 const isFiltering = showFilter && normalizedFilter.length > 0;
153 const visibleModels = isFiltering
154 ? displayModels.filter(
155 (model) =>
156 model.name.toLowerCase().includes(normalizedFilter) ||
157 model.slug.toLowerCase().includes(normalizedFilter),
158 )
159 : displayModels;
160
161 // A model added or moved lands in a later commit, so each commit looks for the pending row.
162 useEffect(() => {
163 const slug = scrollToSlugRef.current;
164 if (slug === null) return;
165 const row = listRef.current?.querySelector<HTMLElement>(
166 `[data-model-slug="${CSS.escape(slug)}"]`,
167 );
168 if (!row) return;
169 scrollToSlugRef.current = null;
170 row.scrollIntoView({ block: "nearest" });
171 });
172
173 // CustomModelEditor keys its option list on this array. Derived after the effect and
174 // checked against `hiddenModels` rather than the set built above it, so it stays cached.
175 const builtInModels = models.filter((model) => !model.isCustom);
176 const allBuiltInModelsHidden =
177 builtInModels.length > 0 && builtInModels.every((model) => hiddenModels.includes(model.slug));
178
179 const handleAdd = () => {
180 if (!canManageCustomModels || driverKind === "antigravity") return;
181 const normalized = normalizeCustomModelSlug(input);
182 if (!normalized) {
183 setError("Enter a model slug.");
184 return;
185 }
186 if (models.some((model) => !model.isCustom && model.slug === normalized)) {
187 setError("That model is already built in.");
188 return;
189 }
190 if (normalized.length > MAX_CUSTOM_MODEL_LENGTH) {
191 setError(`Model slugs must be ${MAX_CUSTOM_MODEL_LENGTH} characters or less.`);
192 return;
193 }
194 if (customModels.some((entry) => entry.slug === normalized)) {
195 setError("That custom model is already saved.");
196 return;
197 }
198
199 scrollToSlugRef.current = normalized;
200 setFilter("");
201 onChange([...customModels, { slug: normalized, name: normalized, capabilities: null }]);
202 setInput("");
203 setError(null);
204 setIsAdding(false);
205 };
206
207 const cancelAdd = () => {
208 setInput("");
209 setError(null);
210 setIsAdding(false);
211 };
212
213 const handleRemove = (slug: string) => {
214 if (!canManageCustomModels) return;
215 if (editingSlug === slug) setEditingSlug(null);
216 onChange(customModels.filter((entry) => entry.slug !== slug));
217 onModelOrderChange(modelOrder.filter((model) => model !== slug));
218 onFavoriteModelsChange(favoriteModels.filter((model) => model !== slug));
219 setError(null);
220 };
221
222 const handleSaveEdit = (next: CustomModelDefinition) => {
223 if (!canManageCustomModels) return;
224 onChange(customModels.map((entry) => (entry.slug === next.slug ? next : entry)));
225 setEditingSlug(null);
226 };
227
228 const setHidden = (slug: string, hidden: boolean) => {
229 if (!canWritePreferences || hidden === hiddenModelSet.has(slug)) return;
230 onHiddenModelsChange(
231 hidden ? [...hiddenModels, slug] : hiddenModels.filter((model) => model !== slug),
232 [slug],
233 );
234 };
235
236 const handleToggleFavorite = (slug: string) => {
237 if (!canWritePreferences) return;
238 onToggleFavorite(slug);
239 };
240
241 const groupOf = (model: (typeof displayModels)[number]) =>
242 favoriteModelSet.has(model.slug)
243 ? "favorite"
244 : !model.isCustom && hiddenModelSet.has(model.slug)
245 ? "hidden"
246 : "visible";
247 const handleMove = (slug: string, direction: -1 | 1) => {
248 if (!canWritePreferences) return;
249 const index = displayModels.findIndex((model) => model.slug === slug);
250 const nextIndex = index + direction;
251 if (index < 0 || nextIndex < 0 || nextIndex >= displayModels.length) return;
252 if (groupOf(displayModels[index]!) !== groupOf(displayModels[nextIndex]!)) return;
253 const next = displayModels.map((model) => model.slug);
254 [next[index], next[nextIndex]] = [next[nextIndex]!, next[index]!];
255 onModelOrderChange(next);
256 };
257
258 type DisplayModel = (typeof displayModels)[number];
259
260 const starButton = (model: DisplayModel, isFavorite: boolean) => (
261 <Tooltip>
262 <TooltipTrigger
263 render={
264 <Button
265 size="icon-micro"
266 variant="ghost-muted"
267 disabled={!canWritePreferences}
268 onClick={() => handleToggleFavorite(model.slug)}
269 aria-label={`${isFavorite ? "Remove" : "Add"} ${model.name} ${
270 isFavorite ? "from" : "to"
271 } favorites`}
272 />
273 }
274 >
275 <StarIcon className={cn("size-3", isFavorite && "fill-current text-warning")} />
276 </TooltipTrigger>
277 <TooltipPopup side="top">
278 {isFavorite ? "Remove from favorites" : "Add to favorites"}
279 </TooltipPopup>
280 </Tooltip>
281 );
282
283 const rowActions = (
284 model: DisplayModel,
285 options: {
286 readonly isHidden: boolean;
287 readonly canMoveUp: boolean;
288 readonly canMoveDown: boolean;
289 },
290 ) => (
291 <span className="flex shrink-0 items-center justify-end gap-0.5">
292 {!options.isHidden && !isFiltering ? (
293 <>
294 <Tooltip>
295 <TooltipTrigger
296 render={
297 <Button
298 size="icon-micro"
299 variant="ghost-muted"
300 disabled={!canWritePreferences || !options.canMoveUp}
301 onClick={() => handleMove(model.slug, -1)}
302 aria-label={`Move ${model.name} up`}
303 />
304 }
305 >
306 <ArrowUpIcon className="size-3" />
307 </TooltipTrigger>
308 <TooltipPopup side="top">Move up</TooltipPopup>
309 </Tooltip>
310 <Tooltip>
311 <TooltipTrigger
312 render={
313 <Button
314 size="icon-micro"
315 variant="ghost-muted"
316 disabled={!canWritePreferences || !options.canMoveDown}
317 onClick={() => handleMove(model.slug, 1)}
318 aria-label={`Move ${model.name} down`}
319 />
320 }
321 >
322 <ArrowDownIcon className="size-3" />
323 </TooltipTrigger>
324 <TooltipPopup side="top">Move down</TooltipPopup>
325 </Tooltip>
326 </>
327 ) : null}
328 {model.isCustom ? (
329 <>
330 <Tooltip>
331 <TooltipTrigger
332 render={
333 <Button
334 size="icon-micro"
335 variant="ghost-muted"
336 disabled={!canManageCustomModels}
337 aria-label={`Edit ${model.slug}`}
338 onClick={() => {
339 if (!canManageCustomModels) return;
340 setEditingSlug((current) => (current === model.slug ? null : model.slug));
341 }}
342 />
343 }
344 >
345 <PencilIcon className="size-3" />
346 </TooltipTrigger>
347 <TooltipPopup side="top">Edit name and options</TooltipPopup>
348 </Tooltip>
349 <Tooltip>
350 <TooltipTrigger
351 render={
352 <Button
353 size="icon-micro"
354 variant="ghost-muted"
355 disabled={!canManageCustomModels}
356 aria-label={`Remove ${model.slug}`}
357 onClick={() => handleRemove(model.slug)}
358 />
359 }
360 >
361 <XIcon className="size-3" />
362 </TooltipTrigger>
363 <TooltipPopup side="top">Remove custom model</TooltipPopup>
364 </Tooltip>
365 </>
366 ) : null}
367 </span>
368 );
369
370 const pickerTooltip = (model: DisplayModel, isHidden: boolean) =>
371 model.isCustom
372 ? "Custom models are always shown in the picker"
373 : isHidden
374 ? "Hidden from picker"
375 : "Shown in picker";
376
377 // The trigger is a wrapper span: a disabled switch gets no pointer events,
378 // so it could not open the tooltip itself.
379 const pickerSwitch = (model: DisplayModel, isHidden: boolean) => (
380 <Tooltip>
381 <TooltipTrigger render={<span className="flex shrink-0 items-center" />}>
382 <Switch
383 size="sm"
384 checked={!isHidden}
385 disabled={!canWritePreferences || model.isCustom}
386 onCheckedChange={(checked) => setHidden(model.slug, !checked)}
387 aria-label={`Show ${model.name} in the model picker`}
388 />
389 </TooltipTrigger>
390 <TooltipPopup side="top">{pickerTooltip(model, isHidden)}</TooltipPopup>
391 </Tooltip>
392 );
393
394 const renderRow = (model: DisplayModel) => {
395 const capLabels = describeModelCapabilities(model);
396 const group = groupOf(model);
397 const isHidden = !model.isCustom && hiddenModelSet.has(model.slug);
398 const isFavorite = group === "favorite";
399 const index = displayModels.indexOf(model);
400 const previousModel = displayModels[index - 1];
401 const nextModel = displayModels[index + 1];
402 const canMoveUp =
403 !isFiltering && previousModel !== undefined && groupOf(previousModel) === group;
404 const canMoveDown = !isFiltering && nextModel !== undefined && groupOf(nextModel) === group;
405 const nameClassName = cn("text-xs", isHidden ? "text-muted-foreground" : "text-foreground/90");
406
407 return (
408 <div
409 key={`${instanceId}:${model.slug}`}
410 data-model-slug={model.slug}
411 className={cn(
412 "grid h-7 grid-cols-[1.5rem_minmax(0,1fr)_auto_minmax(5.5rem,auto)_auto] items-center gap-2 rounded-md px-2 transition-colors hover:bg-muted/30",
413 isHidden && "opacity-50",
414 )}
415 >
416 {starButton(model, isFavorite)}
417 <span className="flex min-w-0 items-baseline gap-2">
418 <span className={cn(nameClassName, "truncate")}>{model.name}</span>
419 {model.name !== model.slug ? (
420 <code className="truncate font-mono text-2xs text-muted-foreground/70">
421 {model.slug}
422 </code>
423 ) : null}
424 {model.isCustom ? (
425 <span className="text-2xs text-muted-foreground/70">custom</span>
426 ) : null}
427 </span>
428 <span className="text-2xs text-muted-foreground/70">
429 {capLabels.length > 0 ? (
430 <span className="hidden sm:inline">{capLabels.join(" · ")}</span>
431 ) : null}
432 </span>
433 {rowActions(model, { isHidden, canMoveUp, canMoveDown })}
434 {pickerSwitch(model, isHidden)}
435 </div>
436 );
437 };
438
439 const groupLabel = (label: string, isFirst: boolean) => (
440 <div className={cn("px-2 pb-1.5 text-2xs text-muted-foreground", isFirst ? "pt-1" : "pt-5")}>
441 {label}
442 </div>
443 );
444
445 return (
446 <div className="lg:flex lg:h-full lg:min-h-0 lg:flex-col">
447 <div className="flex flex-wrap items-center justify-between gap-2">
448 {showFilter ? (
449 <Input
450 value={filter}
451 onChange={(event) => setFilter(event.target.value)}
452 placeholder="Filter models"
453 size="sm"
454 className="w-56 max-w-full"
455 spellCheck={false}
456 aria-label="Filter models"
457 />
458 ) : null}
459 <div className="flex items-center gap-2">
460 {builtInModels.length > 0 ? (
461 <Button
462 type="button"
463 size="xs"
464 variant="ghost-muted"
465 onClick={() =>
466 onHiddenModelsChange(
467 nextHiddenModelsForBulkToggle(models, hiddenModels),
468 builtInModels.map((model) => model.slug),
469 )
470 }
471 >
472 {allBuiltInModelsHidden ? "Enable all" : "Disable all"}
473 </Button>
474 ) : null}
475 <span className="text-xs text-muted-foreground">
476 {models.length} model{models.length === 1 ? "" : "s"}
477 {favoriteCount > 0
478 ? ` · ${favoriteCount} favorite${favoriteCount === 1 ? "" : "s"}`
479 : ""}
480 {hiddenCount > 0 ? ` · ${hiddenCount} hidden` : ""}
481 </span>
482 </div>
483 {driverKind !== "antigravity" && !isAdding ? (
484 <Button
485 type="button"
486 size="xs"
487 variant="ghost-muted"
488 className="ml-auto"
489 onClick={() => setIsAdding(true)}
490 >
491 <PlusIcon className="size-3" />
492 Add custom model
493 </Button>
494 ) : null}
495 </div>
496 <div
497 ref={listRef}
498 className="mt-2 -mx-2 max-h-64 overflow-y-auto lg:max-h-none lg:min-h-0 lg:flex-1"
499 >
500 {visibleModels.length === 0 ? (
501 <p className="px-2 py-2 text-xs text-muted-foreground">
502 {isFiltering ? "No models match." : "No models reported for this provider yet."}
503 </p>
504 ) : null}
505 {visibleModels.map((model, index) => {
506 const group = groupOf(model);
507 const previous = visibleModels[index - 1];
508 const startsGroup = previous === undefined || groupOf(previous) !== group;
509 const editingEntry =
510 canManageCustomModels && model.isCustom && editingSlug === model.slug
511 ? customModels.find((entry) => entry.slug === model.slug)
512 : undefined;
513 return (
514 <div key={`${instanceId}:${model.slug}:group`}>
515 {startsGroup && favoriteCount > 0 && group === "favorite"
516 ? groupLabel("Favorites", index === 0)
517 : null}
518 {startsGroup && favoriteCount > 0 && group === "visible"
519 ? groupLabel("All", index === 0)
520 : null}
521 {startsGroup && group === "hidden"
522 ? groupLabel("Hidden from picker", index === 0)
523 : null}
524 {renderRow(model)}
525 {editingEntry ? (
526 <CustomModelEditor
527 key={`${instanceId}:${model.slug}:editor`}
528 instanceId={instanceId}
529 driverKind={driverKind}
530 entry={editingEntry}
531 builtInModels={builtInModels}
532 onSave={handleSaveEdit}
533 onCancel={() => setEditingSlug(null)}
534 />
535 ) : null}
536 </div>
537 );
538 })}
539 </div>
540
541 {driverKind === "antigravity" || !canManageCustomModels ? null : isAdding ? (
542 <div className="mt-3 flex flex-col gap-2 sm:flex-row">
543 <Input
544 id={`provider-instance-${instanceId}-custom-model`}
545 size="sm"
546 autoFocus
547 value={input}
548 onChange={(event) => {
549 setInput(event.target.value);
550 if (error) setError(null);
551 }}
552 onKeyDown={(event) => {
553 if (event.key === "Escape") {
554 event.preventDefault();
555 cancelAdd();
556 return;
557 }
558 if (event.key !== "Enter") return;
559 event.preventDefault();
560 handleAdd();
561 }}
562 placeholder={driverKind ? CUSTOM_MODEL_PLACEHOLDER_BY_KIND[driverKind] : "model-slug"}
563 spellCheck={false}
564 />
565 <div className="flex shrink-0 gap-2">
566 <Button size="sm" variant="outline" onClick={handleAdd}>
567 Add
568 </Button>
569 <Button size="sm" variant="ghost" onClick={cancelAdd}>
570 Cancel
571 </Button>
572 </div>
573 </div>
574 ) : null}
575
576 {driverKind !== "antigravity" && error ? (
577 <p className="mt-2 text-xs text-destructive">{error}</p>
578 ) : null}
579 </div>
580 );
581}