Open History to see the last commit
1"use client";
2
3import { ArrowDownIcon, ArrowUpIcon, PencilIcon, PlusIcon, StarIcon, XIcon } from "lucide-react";
4import { useEffect, useMemo, 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
21/**
22 * Placeholder text for the "add a custom model" input, keyed by driver
23 * kind. Mirrors the prior hardcoded switch in `SettingsPanels.tsx` so the
24 * UX is unchanged — only the owning component has moved.
25 */
26const CUSTOM_MODEL_PLACEHOLDER_BY_KIND: Partial<Record<ProviderDriverKind, string>> = {
27 [ProviderDriverKind.make("codex")]: "gpt-6.7-codex-ultra-preview",
28 [ProviderDriverKind.make("claudeAgent")]: "claude-sonnet-5",
29 [ProviderDriverKind.make("cursor")]: "claude-sonnet-4-6",
30 [ProviderDriverKind.make("opencode")]: "openai/gpt-5",
31};
32
33/** Above this many models the list gets a filter input. */
34const FILTER_THRESHOLD = 8;
35
36/**
37 * Short capability words shown after a model's slug. Claude and Cursor report
38 * fast mode as a boolean `fastMode` option; Codex reports it as a
39 * `serviceTier` select whose fast tier is labelled "Fast" (catalog id
40 * `priority`, or `fast` from the speed-tier fallback), matching the composer.
41 */
42function describeModelCapabilities(model: ServerProviderModel): string[] {
43 const descriptors = model.capabilities?.optionDescriptors ?? [];
44 const labels: string[] = [];
45 const hasFastMode = descriptors.some(
46 (descriptor) =>
47 descriptor.id === "fastMode" ||
48 (descriptor.id === "serviceTier" &&
49 descriptor.type === "select" &&
50 descriptor.options.some((option) => option.id === "fast" || option.label === "Fast")),
51 );
52 if (hasFastMode) labels.push("Fast mode");
53 if (descriptors.some((descriptor) => descriptor.id === "thinking")) labels.push("Thinking");
54 if (
55 descriptors.some(
56 (descriptor) =>
57 descriptor.type === "select" &&
58 (descriptor.id === "reasoningEffort" ||
59 descriptor.id === "effort" ||
60 descriptor.id === "reasoning" ||
61 descriptor.id === "variant"),
62 )
63 ) {
64 labels.push("Reasoning");
65 }
66 return labels;
67}
68
69/**
70 * Display order for the models list: favorites first (in user order), then
71 * visible models, then hidden ones. Hidden models sink so the list reads
72 * top-down as "what the picker shows"; moves only swap rows within the same
73 * group, and the resulting display order is what gets persisted as
74 * `modelOrder`.
75 */
76export function groupModelsForDisplay<
77 T extends { readonly slug: string; readonly isCustom: boolean },
78>(
79 models: ReadonlyArray<T>,
80 options: {
81 readonly favoriteModels: ReadonlySet<string>;
82 readonly hiddenModels: ReadonlySet<string>;
83 readonly modelOrder: ReadonlyArray<string>;
84 },
85): T[] {
86 const ordered = sortModelsForProviderInstance(models, {
87 favoriteModels: options.favoriteModels,
88 groupFavorites: true,
89 modelOrder: options.modelOrder,
90 });
91 const isHidden = (model: T) => !model.isCustom && options.hiddenModels.has(model.slug);
92 return [
93 ...ordered.filter((model) => options.favoriteModels.has(model.slug)),
94 ...ordered.filter((model) => !options.favoriteModels.has(model.slug) && !isHidden(model)),
95 ...ordered.filter((model) => !options.favoriteModels.has(model.slug) && isHidden(model)),
96 ];
97}
98
99export function nextHiddenModelsForBulkToggle(
100 models: ReadonlyArray<Pick<ServerProviderModel, "slug" | "isCustom">>,
101 hiddenModels: ReadonlyArray<string>,
102): string[] {
103 const builtInSlugs = models.filter((model) => !model.isCustom).map((model) => model.slug);
104 const builtInSlugSet = new Set(builtInSlugs);
105 const allBuiltInModelsHidden = builtInSlugs.every((slug) => hiddenModels.includes(slug));
106
107 if (allBuiltInModelsHidden) {
108 return hiddenModels.filter((slug) => !builtInSlugSet.has(slug));
109 }
110
111 return [...new Set([...hiddenModels, ...builtInSlugs])];
112}
113
114interface ProviderModelsSectionProps {
115 /** Identifier used to namespace input ids within the DOM. */
116 readonly instanceId: ProviderInstanceId;
117 /**
118 * Driver kind for slug normalization + input placeholder. `null` when
119 * the section is rendered without enough provider metadata.
120 */
121 readonly driverKind: ProviderDriverKind | null;
122 /**
123 * The live model list to display. Includes both built-in (probe-reported)
124 * and custom entries, distinguished by `isCustom`.
125 */
126 readonly models: ReadonlyArray<ServerProviderModel>;
127 /**
128 * The persisted custom-model list for this instance, resolved. Drives
129 * dedup, and is the list we hand back (with an entry appended / replaced /
130 * removed) via `onChange`.
131 */
132 readonly customModels: ReadonlyArray<CustomModelDefinition>;
133 /** Server-returned model slugs hidden from the model picker. */
134 readonly hiddenModels: ReadonlyArray<string>;
135 /** Model slugs favorited for this provider instance. */
136 readonly favoriteModels: ReadonlyArray<string>;
137 /** Explicit user-authored model ordering for this provider instance. */
138 readonly modelOrder: ReadonlyArray<string>;
139 /**
140 * Commit the new custom-model list. Caller is responsible for routing the
141 * write to the correct storage (legacy `settings.providers[kind]` vs.
142 * `providerInstances[id].config`).
143 */
144 readonly onChange: (next: ReadonlyArray<CustomModelDefinition>) => void;
145 readonly onHiddenModelsChange: (next: ReadonlyArray<string>) => void;
146 readonly onFavoriteModelsChange: (next: ReadonlyArray<string>) => void;
147 readonly onModelOrderChange: (next: ReadonlyArray<string>) => void;
148}
149
150/**
151 * Shared "Models" section rendered on both the built-in default and custom
152 * provider-instance cards. Owns its own input + error local state so two
153 * cards on screen don't fight over the input value.
154 *
155 * Validation mirrors the pre-consolidation logic in `SettingsPanels`:
156 * - empty / whitespace → "Enter a model slug."
157 * - duplicate of a non-custom (probe-reported) slug → "already built in"
158 * - exceeds `MAX_CUSTOM_MODEL_LENGTH` → length error
159 * - duplicate of an already-saved custom slug → already-saved error
160 */
161export function ProviderModelsSection({
162 instanceId,
163 driverKind,
164 models,
165 customModels,
166 hiddenModels,
167 favoriteModels,
168 modelOrder,
169 onChange,
170 onHiddenModelsChange,
171 onFavoriteModelsChange,
172 onModelOrderChange,
173}: ProviderModelsSectionProps) {
174 const [input, setInput] = useState("");
175 const [isAdding, setIsAdding] = useState(false);
176 const [filter, setFilter] = useState("");
177 const [error, setError] = useState<string | null>(null);
178 // Slug of the custom model whose inline editor is open, if any.
179 const [editingSlug, setEditingSlug] = useState<string | null>(null);
180 const listRef = useRef<HTMLDivElement>(null);
181 // Slug of a just-added custom model, scrolled into view once its row exists.
182 const scrollToSlugRef = useRef<string | null>(null);
183 const hiddenModelSet = useMemo(() => new Set(hiddenModels), [hiddenModels]);
184 const favoriteModelSet = useMemo(() => new Set(favoriteModels), [favoriteModels]);
185 const displayModels = useMemo(
186 () =>
187 groupModelsForDisplay(models, {
188 favoriteModels: favoriteModelSet,
189 hiddenModels: hiddenModelSet,
190 modelOrder,
191 }),
192 [favoriteModelSet, hiddenModelSet, modelOrder, models],
193 );
194 const favoriteCount = displayModels.filter((model) => favoriteModelSet.has(model.slug)).length;
195 const hiddenCount = displayModels.filter(
196 (model) => !model.isCustom && hiddenModelSet.has(model.slug),
197 ).length;
198 const builtInModels = useMemo(() => models.filter((model) => !model.isCustom), [models]);
199 const allBuiltInModelsHidden =
200 builtInModels.length > 0 && builtInModels.every((model) => hiddenModelSet.has(model.slug));
201 const showFilter = models.length > FILTER_THRESHOLD;
202 const normalizedFilter = filter.trim().toLowerCase();
203 const isFiltering = showFilter && normalizedFilter.length > 0;
204 const visibleModels = isFiltering
205 ? displayModels.filter(
206 (model) =>
207 model.name.toLowerCase().includes(normalizedFilter) ||
208 model.slug.toLowerCase().includes(normalizedFilter),
209 )
210 : displayModels;
211
212 // The parent commits the new custom model and hands back an updated
213 // `models` list, so the row can only be scrolled to after that render.
214 useEffect(() => {
215 const slug = scrollToSlugRef.current;
216 if (slug === null) return;
217 const row = listRef.current?.querySelector<HTMLElement>(
218 `[data-model-slug="${CSS.escape(slug)}"]`,
219 );
220 if (!row) return;
221 scrollToSlugRef.current = null;
222 row.scrollIntoView({ block: "nearest" });
223 }, [displayModels]);
224
225 const handleAdd = () => {
226 if (driverKind === "antigravity") return;
227 const normalized = normalizeCustomModelSlug(input);
228 if (!normalized) {
229 setError("Enter a model slug.");
230 return;
231 }
232 if (models.some((model) => !model.isCustom && model.slug === normalized)) {
233 setError("That model is already built in.");
234 return;
235 }
236 if (normalized.length > MAX_CUSTOM_MODEL_LENGTH) {
237 setError(`Model slugs must be ${MAX_CUSTOM_MODEL_LENGTH} characters or less.`);
238 return;
239 }
240 if (customModels.some((entry) => entry.slug === normalized)) {
241 setError("That custom model is already saved.");
242 return;
243 }
244
245 // Clear the filter so the new row renders even when it does not match,
246 // which is also what lets the pending scroll target resolve and clear.
247 scrollToSlugRef.current = normalized;
248 setFilter("");
249 onChange([...customModels, { slug: normalized, name: normalized, capabilities: null }]);
250 setInput("");
251 setError(null);
252 setIsAdding(false);
253 };
254
255 const cancelAdd = () => {
256 setInput("");
257 setError(null);
258 setIsAdding(false);
259 };
260
261 const handleRemove = (slug: string) => {
262 if (editingSlug === slug) setEditingSlug(null);
263 onChange(customModels.filter((entry) => entry.slug !== slug));
264 onModelOrderChange(modelOrder.filter((model) => model !== slug));
265 onFavoriteModelsChange(favoriteModels.filter((model) => model !== slug));
266 setError(null);
267 };
268
269 const handleSaveEdit = (next: CustomModelDefinition) => {
270 onChange(customModels.map((entry) => (entry.slug === next.slug ? next : entry)));
271 setEditingSlug(null);
272 };
273
274 const setHidden = (slug: string, hidden: boolean) => {
275 if (hidden === hiddenModelSet.has(slug)) return;
276 onHiddenModelsChange(
277 hidden ? [...hiddenModels, slug] : hiddenModels.filter((model) => model !== slug),
278 );
279 };
280
281 const handleToggleFavorite = (slug: string) => {
282 if (favoriteModelSet.has(slug)) {
283 onFavoriteModelsChange(favoriteModels.filter((model) => model !== slug));
284 return;
285 }
286 onFavoriteModelsChange([...favoriteModels, slug]);
287 };
288
289 // Rows only trade places with a neighbour in the same group (favorites,
290 // visible, hidden), and the display order is persisted as the new order.
291 const groupOf = (model: (typeof displayModels)[number]) =>
292 favoriteModelSet.has(model.slug)
293 ? "favorite"
294 : !model.isCustom && hiddenModelSet.has(model.slug)
295 ? "hidden"
296 : "visible";
297 const handleMove = (slug: string, direction: -1 | 1) => {
298 const index = displayModels.findIndex((model) => model.slug === slug);
299 const nextIndex = index + direction;
300 if (index < 0 || nextIndex < 0 || nextIndex >= displayModels.length) return;
301 if (groupOf(displayModels[index]!) !== groupOf(displayModels[nextIndex]!)) return;
302 const next = displayModels.map((model) => model.slug);
303 [next[index], next[nextIndex]] = [next[nextIndex]!, next[index]!];
304 onModelOrderChange(next);
305 };
306
307 type DisplayModel = (typeof displayModels)[number];
308
309 const starButton = (model: DisplayModel, isFavorite: boolean) => (
310 <Tooltip>
311 <TooltipTrigger
312 render={
313 <Button
314 size="icon-micro"
315 variant="ghost-muted"
316 onClick={() => handleToggleFavorite(model.slug)}
317 aria-label={`${isFavorite ? "Remove" : "Add"} ${model.name} ${
318 isFavorite ? "from" : "to"
319 } favorites`}
320 />
321 }
322 >
323 <StarIcon className={cn("size-3", isFavorite && "fill-current text-warning")} />
324 </TooltipTrigger>
325 <TooltipPopup side="top">
326 {isFavorite ? "Remove from favorites" : "Add to favorites"}
327 </TooltipPopup>
328 </Tooltip>
329 );
330
331 // Reorder and remove stay in the row at all times (dimmed when unavailable)
332 // so ordering is discoverable without hovering.
333 const rowActions = (
334 model: DisplayModel,
335 options: {
336 readonly isHidden: boolean;
337 readonly canMoveUp: boolean;
338 readonly canMoveDown: boolean;
339 },
340 ) => (
341 <span className="flex shrink-0 items-center justify-end gap-0.5">
342 {!options.isHidden && !isFiltering ? (
343 <>
344 <Tooltip>
345 <TooltipTrigger
346 render={
347 <Button
348 size="icon-micro"
349 variant="ghost-muted"
350 disabled={!options.canMoveUp}
351 onClick={() => handleMove(model.slug, -1)}
352 aria-label={`Move ${model.name} up`}
353 />
354 }
355 >
356 <ArrowUpIcon className="size-3" />
357 </TooltipTrigger>
358 <TooltipPopup side="top">Move up</TooltipPopup>
359 </Tooltip>
360 <Tooltip>
361 <TooltipTrigger
362 render={
363 <Button
364 size="icon-micro"
365 variant="ghost-muted"
366 disabled={!options.canMoveDown}
367 onClick={() => handleMove(model.slug, 1)}
368 aria-label={`Move ${model.name} down`}
369 />
370 }
371 >
372 <ArrowDownIcon className="size-3" />
373 </TooltipTrigger>
374 <TooltipPopup side="top">Move down</TooltipPopup>
375 </Tooltip>
376 </>
377 ) : null}
378 {model.isCustom ? (
379 <>
380 <Tooltip>
381 <TooltipTrigger
382 render={
383 <Button
384 size="icon-micro"
385 variant="ghost-muted"
386 aria-label={`Edit ${model.slug}`}
387 onClick={() =>
388 setEditingSlug((current) => (current === model.slug ? null : model.slug))
389 }
390 />
391 }
392 >
393 <PencilIcon className="size-3" />
394 </TooltipTrigger>
395 <TooltipPopup side="top">Edit name and options</TooltipPopup>
396 </Tooltip>
397 <Tooltip>
398 <TooltipTrigger
399 render={
400 <Button
401 size="icon-micro"
402 variant="ghost-muted"
403 aria-label={`Remove ${model.slug}`}
404 onClick={() => handleRemove(model.slug)}
405 />
406 }
407 >
408 <XIcon className="size-3" />
409 </TooltipTrigger>
410 <TooltipPopup side="top">Remove custom model</TooltipPopup>
411 </Tooltip>
412 </>
413 ) : null}
414 </span>
415 );
416
417 const pickerTooltip = (model: DisplayModel, isHidden: boolean) =>
418 model.isCustom
419 ? "Custom models are always shown in the picker"
420 : isHidden
421 ? "Hidden from picker"
422 : "Shown in picker";
423
424 // The trigger is a wrapper span: a disabled switch gets no pointer events,
425 // so it could not open the tooltip itself.
426 const pickerSwitch = (model: DisplayModel, isHidden: boolean) => (
427 <Tooltip>
428 <TooltipTrigger render={<span className="flex shrink-0 items-center" />}>
429 <Switch
430 size="sm"
431 checked={!isHidden}
432 disabled={model.isCustom}
433 onCheckedChange={(checked) => setHidden(model.slug, !checked)}
434 aria-label={`Show ${model.name} in the model picker`}
435 />
436 </TooltipTrigger>
437 <TooltipPopup side="top">{pickerTooltip(model, isHidden)}</TooltipPopup>
438 </Tooltip>
439 );
440
441 const renderRow = (model: DisplayModel) => {
442 const capLabels = describeModelCapabilities(model);
443 const group = groupOf(model);
444 // Hidden is read from the preference itself: a favorited model can still be
445 // hidden, and its switch must say so even though it sits in the favorites group.
446 const isHidden = !model.isCustom && hiddenModelSet.has(model.slug);
447 const isFavorite = group === "favorite";
448 const index = displayModels.indexOf(model);
449 const previousModel = displayModels[index - 1];
450 const nextModel = displayModels[index + 1];
451 // Reordering a filtered view would be ambiguous, so arrows only show on
452 // the full list.
453 const canMoveUp =
454 !isFiltering && previousModel !== undefined && groupOf(previousModel) === group;
455 const canMoveDown = !isFiltering && nextModel !== undefined && groupOf(nextModel) === group;
456 const nameClassName = cn("text-xs", isHidden ? "text-muted-foreground" : "text-foreground/90");
457
458 return (
459 <div
460 key={`${instanceId}:${model.slug}`}
461 data-model-slug={model.slug}
462 className={cn(
463 // Actions column is at least wide enough for the four custom-row
464 // buttons so capability labels line up across built-in and custom rows.
465 "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",
466 isHidden && "opacity-50",
467 )}
468 >
469 {starButton(model, isFavorite)}
470 <span className="flex min-w-0 items-baseline gap-2">
471 <span className={cn(nameClassName, "truncate")}>{model.name}</span>
472 {model.name !== model.slug ? (
473 <code className="truncate font-mono text-[11px] text-muted-foreground/70">
474 {model.slug}
475 </code>
476 ) : null}
477 {model.isCustom ? (
478 <span className="text-[11px] text-muted-foreground/70">custom</span>
479 ) : null}
480 </span>
481 {/*
482 Always a grid item so the columns line up across rows; the text
483 itself drops out on phone widths where it would starve the name.
484 */}
485 <span className="text-[11px] text-muted-foreground/70">
486 {capLabels.length > 0 ? (
487 <span className="hidden sm:inline">{capLabels.join(" · ")}</span>
488 ) : null}
489 </span>
490 {rowActions(model, { isHidden, canMoveUp, canMoveDown })}
491 {pickerSwitch(model, isHidden)}
492 </div>
493 );
494 };
495
496 const groupLabel = (label: string, isFirst: boolean) => (
497 <div className={cn("px-2 pb-1.5 text-[11px] text-muted-foreground", isFirst ? "pt-1" : "pt-5")}>
498 {label}
499 </div>
500 );
501
502 return (
503 <div className="lg:flex lg:h-full lg:min-h-0 lg:flex-col">
504 <div className="flex flex-wrap items-center justify-between gap-2">
505 {showFilter ? (
506 <Input
507 value={filter}
508 onChange={(event) => setFilter(event.target.value)}
509 placeholder="Filter models"
510 size="sm"
511 className="w-56 max-w-full"
512 spellCheck={false}
513 aria-label="Filter models"
514 />
515 ) : null}
516 <div className="flex items-center gap-2">
517 {builtInModels.length > 0 ? (
518 <Button
519 type="button"
520 size="xs"
521 variant="ghost-muted"
522 onClick={() =>
523 onHiddenModelsChange(nextHiddenModelsForBulkToggle(models, hiddenModels))
524 }
525 >
526 {allBuiltInModelsHidden ? "Enable all" : "Disable all"}
527 </Button>
528 ) : null}
529 <span className="text-xs text-muted-foreground">
530 {models.length} model{models.length === 1 ? "" : "s"}
531 {favoriteCount > 0
532 ? ` · ${favoriteCount} favorite${favoriteCount === 1 ? "" : "s"}`
533 : ""}
534 {hiddenCount > 0 ? ` · ${hiddenCount} hidden` : ""}
535 </span>
536 </div>
537 {driverKind !== "antigravity" && !isAdding ? (
538 <Button
539 type="button"
540 size="xs"
541 variant="ghost-muted"
542 className="ml-auto"
543 onClick={() => setIsAdding(true)}
544 >
545 <PlusIcon className="size-3" />
546 Add custom model
547 </Button>
548 ) : null}
549 </div>
550 <div
551 ref={listRef}
552 className="mt-2 -mx-2 max-h-64 overflow-y-auto lg:max-h-none lg:min-h-0 lg:flex-1"
553 >
554 {visibleModels.length === 0 ? (
555 <p className="px-2 py-2 text-xs text-muted-foreground">
556 {isFiltering ? "No models match." : "No models reported for this provider yet."}
557 </p>
558 ) : null}
559 {visibleModels.map((model, index) => {
560 const group = groupOf(model);
561 const previous = visibleModels[index - 1];
562 const startsGroup = previous === undefined || groupOf(previous) !== group;
563 const editingEntry =
564 model.isCustom && editingSlug === model.slug
565 ? customModels.find((entry) => entry.slug === model.slug)
566 : undefined;
567 return (
568 <div key={`${instanceId}:${model.slug}:group`}>
569 {startsGroup && favoriteCount > 0 && group === "favorite"
570 ? groupLabel("Favorites", index === 0)
571 : null}
572 {startsGroup && favoriteCount > 0 && group === "visible"
573 ? groupLabel("All", index === 0)
574 : null}
575 {startsGroup && group === "hidden"
576 ? groupLabel("Hidden from picker", index === 0)
577 : null}
578 {renderRow(model)}
579 {editingEntry ? (
580 <CustomModelEditor
581 key={`${instanceId}:${model.slug}:editor`}
582 instanceId={instanceId}
583 driverKind={driverKind}
584 entry={editingEntry}
585 builtInModels={builtInModels}
586 onSave={handleSaveEdit}
587 onCancel={() => setEditingSlug(null)}
588 />
589 ) : null}
590 </div>
591 );
592 })}
593 </div>
594
595 {driverKind === "antigravity" ? null : isAdding ? (
596 <div className="mt-3 flex flex-col gap-2 sm:flex-row">
597 <Input
598 id={`provider-instance-${instanceId}-custom-model`}
599 size="sm"
600 autoFocus
601 value={input}
602 onChange={(event) => {
603 setInput(event.target.value);
604 if (error) setError(null);
605 }}
606 onKeyDown={(event) => {
607 if (event.key === "Escape") {
608 event.preventDefault();
609 cancelAdd();
610 return;
611 }
612 if (event.key !== "Enter") return;
613 event.preventDefault();
614 handleAdd();
615 }}
616 placeholder={driverKind ? CUSTOM_MODEL_PLACEHOLDER_BY_KIND[driverKind] : "model-slug"}
617 spellCheck={false}
618 />
619 <div className="flex shrink-0 gap-2">
620 <Button size="sm" variant="outline" onClick={handleAdd}>
621 Add
622 </Button>
623 <Button size="sm" variant="ghost" onClick={cancelAdd}>
624 Cancel
625 </Button>
626 </div>
627 </div>
628 ) : null}
629
630 {driverKind !== "antigravity" && error ? (
631 <p className="mt-2 text-xs text-destructive">{error}</p>
632 ) : null}
633 </div>
634 );
635}