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