Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ProviderModelsSection.tsx

607 lines22.4 KB

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