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"
316 className={cn(
317 "[--control-icon-color:currentColor]",
318 isFavorite
319 ? "text-yellow-500 hover:text-yellow-600"
320 : "text-muted-foreground/40 hover:text-muted-foreground",
321 )}
322 onClick={() => handleToggleFavorite(model.slug)}
323 aria-label={`${isFavorite ? "Remove" : "Add"} ${model.name} ${
324 isFavorite ? "from" : "to"
325 } favorites`}
326 />
327 }
328 >
329 <StarIcon className={cn("size-3", isFavorite && "fill-current")} />
330 </TooltipTrigger>
331 <TooltipPopup side="top">
332 {isFavorite ? "Remove from favorites" : "Add to favorites"}
333 </TooltipPopup>
334 </Tooltip>
335 );
336
337 // Reorder and remove stay in the row at all times (dimmed when unavailable)
338 // so ordering is discoverable without hovering.
339 const rowActions = (
340 model: DisplayModel,
341 options: {
342 readonly isHidden: boolean;
343 readonly canMoveUp: boolean;
344 readonly canMoveDown: boolean;
345 },
346 ) => (
347 <span className="flex shrink-0 items-center justify-end gap-0.5">
348 {!options.isHidden && !isFiltering ? (
349 <>
350 <Tooltip>
351 <TooltipTrigger
352 render={
353 <Button
354 size="icon-micro"
355 variant="ghost-muted"
356 disabled={!options.canMoveUp}
357 onClick={() => handleMove(model.slug, -1)}
358 aria-label={`Move ${model.name} up`}
359 />
360 }
361 >
362 <ArrowUpIcon className="size-3" />
363 </TooltipTrigger>
364 <TooltipPopup side="top">Move up</TooltipPopup>
365 </Tooltip>
366 <Tooltip>
367 <TooltipTrigger
368 render={
369 <Button
370 size="icon-micro"
371 variant="ghost-muted"
372 disabled={!options.canMoveDown}
373 onClick={() => handleMove(model.slug, 1)}
374 aria-label={`Move ${model.name} down`}
375 />
376 }
377 >
378 <ArrowDownIcon className="size-3" />
379 </TooltipTrigger>
380 <TooltipPopup side="top">Move down</TooltipPopup>
381 </Tooltip>
382 </>
383 ) : null}
384 {model.isCustom ? (
385 <>
386 <Tooltip>
387 <TooltipTrigger
388 render={
389 <Button
390 size="icon-micro"
391 variant="ghost-muted"
392 aria-label={`Edit ${model.slug}`}
393 onClick={() =>
394 setEditingSlug((current) => (current === model.slug ? null : model.slug))
395 }
396 />
397 }
398 >
399 <PencilIcon className="size-3" />
400 </TooltipTrigger>
401 <TooltipPopup side="top">Edit name and options</TooltipPopup>
402 </Tooltip>
403 <Tooltip>
404 <TooltipTrigger
405 render={
406 <Button
407 size="icon-micro"
408 variant="ghost-muted"
409 aria-label={`Remove ${model.slug}`}
410 onClick={() => handleRemove(model.slug)}
411 />
412 }
413 >
414 <XIcon className="size-3" />
415 </TooltipTrigger>
416 <TooltipPopup side="top">Remove custom model</TooltipPopup>
417 </Tooltip>
418 </>
419 ) : null}
420 </span>
421 );
422
423 const pickerTooltip = (model: DisplayModel, isHidden: boolean) =>
424 model.isCustom
425 ? "Custom models are always shown in the picker"
426 : isHidden
427 ? "Hidden from picker"
428 : "Shown in picker";
429
430 // The trigger is a wrapper span: a disabled switch gets no pointer events,
431 // so it could not open the tooltip itself.
432 const pickerSwitch = (model: DisplayModel, isHidden: boolean) => (
433 <Tooltip>
434 <TooltipTrigger render={<span className="flex shrink-0 items-center" />}>
435 <Switch
436 size="sm"
437 checked={!isHidden}
438 disabled={model.isCustom}
439 onCheckedChange={(checked) => setHidden(model.slug, !checked)}
440 aria-label={`Show ${model.name} in the model picker`}
441 />
442 </TooltipTrigger>
443 <TooltipPopup side="top">{pickerTooltip(model, isHidden)}</TooltipPopup>
444 </Tooltip>
445 );
446
447 const renderRow = (model: DisplayModel) => {
448 const capLabels = describeModelCapabilities(model);
449 const group = groupOf(model);
450 // Hidden is read from the preference itself: a favorited model can still be
451 // hidden, and its switch must say so even though it sits in the favorites group.
452 const isHidden = !model.isCustom && hiddenModelSet.has(model.slug);
453 const isFavorite = group === "favorite";
454 const index = displayModels.indexOf(model);
455 const previousModel = displayModels[index - 1];
456 const nextModel = displayModels[index + 1];
457 // Reordering a filtered view would be ambiguous, so arrows only show on
458 // the full list.
459 const canMoveUp =
460 !isFiltering && previousModel !== undefined && groupOf(previousModel) === group;
461 const canMoveDown = !isFiltering && nextModel !== undefined && groupOf(nextModel) === group;
462 const nameClassName = cn("text-xs", isHidden ? "text-muted-foreground" : "text-foreground/90");
463
464 return (
465 <div
466 key={`${instanceId}:${model.slug}`}
467 data-model-slug={model.slug}
468 className={cn(
469 // Actions column is at least wide enough for the four custom-row
470 // buttons so capability labels line up across built-in and custom rows.
471 "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",
472 isHidden && "opacity-50",
473 )}
474 >
475 {starButton(model, isFavorite)}
476 <span className="flex min-w-0 items-baseline gap-2">
477 <span className={cn(nameClassName, "truncate")}>{model.name}</span>
478 {model.name !== model.slug ? (
479 <code className="truncate font-mono text-[11px] text-muted-foreground/70">
480 {model.slug}
481 </code>
482 ) : null}
483 {model.isCustom ? (
484 <span className="text-[11px] text-muted-foreground/70">custom</span>
485 ) : null}
486 </span>
487 {/*
488 Always a grid item so the columns line up across rows; the text
489 itself drops out on phone widths where it would starve the name.
490 */}
491 <span className="text-[11px] text-muted-foreground/70">
492 {capLabels.length > 0 ? (
493 <span className="hidden sm:inline">{capLabels.join(" · ")}</span>
494 ) : null}
495 </span>
496 {rowActions(model, { isHidden, canMoveUp, canMoveDown })}
497 {pickerSwitch(model, isHidden)}
498 </div>
499 );
500 };
501
502 const groupLabel = (label: string, isFirst: boolean) => (
503 <div className={cn("px-2 pb-1.5 text-[11px] text-muted-foreground", isFirst ? "pt-1" : "pt-5")}>
504 {label}
505 </div>
506 );
507
508 return (
509 <div className="lg:flex lg:h-full lg:min-h-0 lg:flex-col">
510 <div className="flex flex-wrap items-center justify-between gap-2">
511 {showFilter ? (
512 <Input
513 value={filter}
514 onChange={(event) => setFilter(event.target.value)}
515 placeholder="Filter models"
516 size="sm"
517 className="w-56"
518 spellCheck={false}
519 aria-label="Filter models"
520 />
521 ) : null}
522 <div className="flex items-center gap-2">
523 {builtInModels.length > 0 ? (
524 <Button
525 type="button"
526 size="xs"
527 variant="ghost-muted"
528 onClick={() =>
529 onHiddenModelsChange(nextHiddenModelsForBulkToggle(models, hiddenModels))
530 }
531 >
532 {allBuiltInModelsHidden ? "Enable all" : "Disable all"}
533 </Button>
534 ) : null}
535 <span className="text-xs text-muted-foreground">
536 {models.length} model{models.length === 1 ? "" : "s"}
537 {favoriteCount > 0
538 ? ` · ${favoriteCount} favorite${favoriteCount === 1 ? "" : "s"}`
539 : ""}
540 {hiddenCount > 0 ? ` · ${hiddenCount} hidden` : ""}
541 </span>
542 </div>
543 </div>
544 <div
545 ref={listRef}
546 className="mt-2 -mx-2 max-h-64 overflow-y-auto lg:max-h-none lg:min-h-0 lg:flex-1"
547 >
548 {visibleModels.length === 0 ? (
549 <p className="px-2 py-2 text-xs text-muted-foreground">
550 {isFiltering ? "No models match." : "No models reported for this provider yet."}
551 </p>
552 ) : null}
553 {visibleModels.map((model, index) => {
554 const group = groupOf(model);
555 const previous = visibleModels[index - 1];
556 const startsGroup = previous === undefined || groupOf(previous) !== group;
557 const editingEntry =
558 model.isCustom && editingSlug === model.slug
559 ? customModels.find((entry) => entry.slug === model.slug)
560 : undefined;
561 return (
562 <div key={`${instanceId}:${model.slug}:group`}>
563 {startsGroup && favoriteCount > 0 && group === "favorite"
564 ? groupLabel("Favorites", index === 0)
565 : null}
566 {startsGroup && favoriteCount > 0 && group === "visible"
567 ? groupLabel("All", index === 0)
568 : null}
569 {startsGroup && group === "hidden"
570 ? groupLabel("Hidden from picker", index === 0)
571 : null}
572 {renderRow(model)}
573 {editingEntry ? (
574 <CustomModelEditor
575 key={`${instanceId}:${model.slug}:editor`}
576 instanceId={instanceId}
577 driverKind={driverKind}
578 entry={editingEntry}
579 builtInModels={builtInModels}
580 onSave={handleSaveEdit}
581 onCancel={() => setEditingSlug(null)}
582 />
583 ) : null}
584 </div>
585 );
586 })}
587 </div>
588
589 {driverKind === "antigravity" ? null : isAdding ? (
590 <div className="mt-3 flex flex-col gap-2 sm:flex-row">
591 <Input
592 id={`provider-instance-${instanceId}-custom-model`}
593 size="sm"
594 autoFocus
595 value={input}
596 onChange={(event) => {
597 setInput(event.target.value);
598 if (error) setError(null);
599 }}
600 onKeyDown={(event) => {
601 if (event.key === "Escape") {
602 event.preventDefault();
603 cancelAdd();
604 return;
605 }
606 if (event.key !== "Enter") return;
607 event.preventDefault();
608 handleAdd();
609 }}
610 placeholder={driverKind ? CUSTOM_MODEL_PLACEHOLDER_BY_KIND[driverKind] : "model-slug"}
611 spellCheck={false}
612 />
613 <div className="flex shrink-0 gap-2">
614 <Button size="sm" variant="outline" onClick={handleAdd}>
615 Add
616 </Button>
617 <Button size="sm" variant="ghost" onClick={cancelAdd}>
618 Cancel
619 </Button>
620 </div>
621 </div>
622 ) : (
623 <Button
624 type="button"
625 size="xs"
626 variant="ghost-muted"
627 className="mt-2 -ml-2"
628 onClick={() => setIsAdding(true)}
629 >
630 <PlusIcon className="size-3" />
631 Add custom model
632 </Button>
633 )}
634
635 {driverKind !== "antigravity" && error ? (
636 <p className="mt-2 text-xs text-destructive">{error}</p>
637 ) : null}
638 </div>
639 );
640}