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