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

ProviderModelsSection.tsx

557 lines20.2 KB

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;
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 ];
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;
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 const normalized = normalizeCustomModelSlug(input);
206 if (!normalized) {
207 setError("Enter a model slug.");
208 return;
209 }
210 if (models.some((model) => !model.isCustom && model.slug === normalized)) {
211 setError("That model is already built in.");
212 return;
213 }
214 if (normalized.length > MAX_CUSTOM_MODEL_LENGTH) {
215 setError(`Model slugs must be ${MAX_CUSTOM_MODEL_LENGTH} characters or less.`);
216 return;
217 }
218 if (customModels.includes(normalized)) {
219 setError("That custom model is already saved.");
220 return;
221 }
222​
223 // Clear the filter so the new row renders even when it does not match,
224 // which is also what lets the pending scroll target resolve and clear.
225 scrollToSlugRef.current = normalized;
226 setFilter("");
227 onChange([...customModels, normalized]);
228 setInput("");
229 setError(null);
230 setIsAdding(false);
231 };
232​
233 const cancelAdd = () => {
234 setInput("");
235 setError(null);
236 setIsAdding(false);
237 };
238​
239 const handleRemove = (slug: string) => {
240 onChange(customModels.filter((model) => model !== slug));
241 onModelOrderChange(modelOrder.filter((model) => model !== slug));
242 onFavoriteModelsChange(favoriteModels.filter((model) => model !== slug));
243 setError(null);
244 };
245​
246 const setHidden = (slug: string, hidden: boolean) => {
247 if (hidden === hiddenModelSet.has(slug)) return;
248 onHiddenModelsChange(
249 hidden ? [...hiddenModels, slug] : hiddenModels.filter((model) => model !== slug),
250 );
251 };
252​
253 const handleToggleFavorite = (slug: string) => {
254 if (favoriteModelSet.has(slug)) {
255 onFavoriteModelsChange(favoriteModels.filter((model) => model !== slug));
256 return;
257 }
258 onFavoriteModelsChange([...favoriteModels, slug]);
259 };
260​
261 // Rows only trade places with a neighbour in the same group (favorites,
262 // visible, hidden), and the display order is persisted as the new order.
263 const groupOf = (model: (typeof displayModels)[number]) =>
264 favoriteModelSet.has(model.slug)
265 ? "favorite"
266 : !model.isCustom && hiddenModelSet.has(model.slug)
267 ? "hidden"
268 : "visible";
269 const handleMove = (slug: string, direction: -1 | 1) => {
270 const index = displayModels.findIndex((model) => model.slug === slug);
271 const nextIndex = index + direction;
272 if (index < 0 || nextIndex < 0 || nextIndex >= displayModels.length) return;
273 if (groupOf(displayModels[index]!) !== groupOf(displayModels[nextIndex]!)) return;
274 const next = displayModels.map((model) => model.slug);
275 [next[index], next[nextIndex]] = [next[nextIndex]!, next[index]!];
276 onModelOrderChange(next);
277 };
278​
279 type DisplayModel = (typeof displayModels)[number];
280​
281 const starButton = (model: DisplayModel, isFavorite: boolean) => (
282 <Tooltip>
283 <TooltipTrigger
284 render={
285 <Button
286 size="icon-micro"
287 variant="ghost"
288 className={cn(
289 "[--control-icon-color:currentColor]",
290 isFavorite
291 ? "text-yellow-500 hover:text-yellow-600"
292 : "text-muted-foreground/40 hover:text-muted-foreground",
293 )}
294 onClick={() => handleToggleFavorite(model.slug)}
295 aria-label={`${isFavorite ? "Remove" : "Add"} ${model.name} ${
296 isFavorite ? "from" : "to"
297 } favorites`}
298 />
299 }
300 >
301 <StarIcon className={cn("size-3", isFavorite && "fill-current")} />
302 </TooltipTrigger>
303 <TooltipPopup side="top">
304 {isFavorite ? "Remove from favorites" : "Add to favorites"}
305 </TooltipPopup>
306 </Tooltip>
307 );
308​
309 // Reorder and remove stay in the row at all times (dimmed when unavailable)
310 // so ordering is discoverable without hovering.
311 const rowActions = (
312 model: DisplayModel,
313 options: {
314 readonly isHidden: boolean;
315 readonly canMoveUp: boolean;
316 readonly canMoveDown: boolean;
317 },
318 ) => (
319 <span className="flex shrink-0 items-center justify-end gap-0.5">
320 {!options.isHidden && !isFiltering ? (
321 <>
322 <Tooltip>
323 <TooltipTrigger
324 render={
325 <Button
326 size="icon-micro"
327 variant="ghost-muted"
328 disabled={!options.canMoveUp}
329 onClick={() => handleMove(model.slug, -1)}
330 aria-label={`Move ${model.name} up`}
331 />
332 }
333 >
334 <ArrowUpIcon className="size-3" />
335 </TooltipTrigger>
336 <TooltipPopup side="top">Move up</TooltipPopup>
337 </Tooltip>
338 <Tooltip>
339 <TooltipTrigger
340 render={
341 <Button
342 size="icon-micro"
343 variant="ghost-muted"
344 disabled={!options.canMoveDown}
345 onClick={() => handleMove(model.slug, 1)}
346 aria-label={`Move ${model.name} down`}
347 />
348 }
349 >
350 <ArrowDownIcon className="size-3" />
351 </TooltipTrigger>
352 <TooltipPopup side="top">Move down</TooltipPopup>
353 </Tooltip>
354 </>
355 ) : null}
356 {model.isCustom ? (
357 <Tooltip>
358 <TooltipTrigger
359 render={
360 <Button
361 size="icon-micro"
362 variant="ghost-muted"
363 aria-label={`Remove ${model.slug}`}
364 onClick={() => handleRemove(model.slug)}
365 />
366 }
367 >
368 <XIcon className="size-3" />
369 </TooltipTrigger>
370 <TooltipPopup side="top">Remove custom model</TooltipPopup>
371 </Tooltip>
372 ) : null}
373 </span>
374 );
375​
376 const pickerTooltip = (model: DisplayModel, isHidden: boolean) =>
377 model.isCustom
378 ? "Custom models are always shown in the picker"
379 : isHidden
380 ? "Hidden from picker"
381 : "Shown in picker";
382​
383 // The trigger is a wrapper span: a disabled switch gets no pointer events,
384 // so it could not open the tooltip itself.
385 const pickerSwitch = (model: DisplayModel, isHidden: boolean) => (
386 <Tooltip>
387 <TooltipTrigger render={<span className="flex shrink-0 items-center" />}>
388 <Switch
389 size="sm"
390 checked={!isHidden}
391 disabled={model.isCustom}
392 onCheckedChange={(checked) => setHidden(model.slug, !checked)}
393 aria-label={`Show ${model.name} in the model picker`}
394 />
395 </TooltipTrigger>
396 <TooltipPopup side="top">{pickerTooltip(model, isHidden)}</TooltipPopup>
397 </Tooltip>
398 );
399​
400 const renderRow = (model: DisplayModel) => {
401 const capLabels = describeModelCapabilities(model);
402 const group = groupOf(model);
403 // Hidden is read from the preference itself: a favorited model can still be
404 // hidden, and its switch must say so even though it sits in the favorites group.
405 const isHidden = !model.isCustom && hiddenModelSet.has(model.slug);
406 const isFavorite = group === "favorite";
407 const index = displayModels.indexOf(model);
408 const previousModel = displayModels[index - 1];
409 const nextModel = displayModels[index + 1];
410 // Reordering a filtered view would be ambiguous, so arrows only show on
411 // the full list.
412 const canMoveUp =
413 !isFiltering && previousModel !== undefined && groupOf(previousModel) === group;
414 const canMoveDown = !isFiltering && nextModel !== undefined && groupOf(nextModel) === group;
415 const nameClassName = cn("text-xs", isHidden ? "text-muted-foreground" : "text-foreground/90");
416​
417 return (
418 <div
419 key={`${instanceId}:${model.slug}`}
420 data-model-slug={model.slug}
421 className={cn(
422 "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",
423 isHidden && "opacity-50",
424 )}
425 >
426 {starButton(model, isFavorite)}
427 <span className="flex min-w-0 items-baseline gap-2">
428 <span className={cn(nameClassName, "truncate")}>{model.name}</span>
429 {model.isCustom ? (
430 <span className="text-[11px] text-muted-foreground/70">custom</span>
431 ) : model.name !== model.slug ? (
432 <code className="truncate font-mono text-[11px] text-muted-foreground/70">
433 {model.slug}
434 </code>
435 ) : null}
436 </span>
437 {/*
438 Always a grid item so the columns line up across rows; the text
439 itself drops out on phone widths where it would starve the name.
440 */}
441 <span className="text-[11px] text-muted-foreground/70">
442 {capLabels.length > 0 ? (
443 <span className="hidden sm:inline">{capLabels.join(" · ")}</span>
444 ) : null}
445 </span>
446 {rowActions(model, { isHidden, canMoveUp, canMoveDown })}
447 {pickerSwitch(model, isHidden)}
448 </div>
449 );
450 };
451​
452 const groupLabel = (label: string, isFirst: boolean) => (
453 <div className={cn("px-2 pb-1.5 text-[11px] text-muted-foreground", isFirst ? "pt-1" : "pt-5")}>
454 {label}
455 </div>
456 );
457​
458 return (
459 <div className="lg:flex lg:h-full lg:min-h-0 lg:flex-col">
460 <div className="flex flex-wrap items-center justify-between gap-2">
461 {showFilter ? (
462 <Input
463 value={filter}
464 onChange={(event) => setFilter(event.target.value)}
465 placeholder="Filter models"
466 size="sm"
467 className="w-56"
468 spellCheck={false}
469 aria-label="Filter models"
470 />
471 ) : null}
472 <span className="text-xs text-muted-foreground">
473 {models.length} model{models.length === 1 ? "" : "s"}
474 {favoriteCount > 0 ? ` · ${favoriteCount} favorite${favoriteCount === 1 ? "" : "s"}` : ""}
475 {hiddenCount > 0 ? ` · ${hiddenCount} hidden` : ""}
476 </span>
477 </div>
478 <div
479 ref={listRef}
480 className="mt-2 -mx-2 max-h-64 overflow-y-auto lg:max-h-none lg:min-h-0 lg:flex-1"
481 >
482 {visibleModels.length === 0 ? (
483 <p className="px-2 py-2 text-xs text-muted-foreground">
484 {isFiltering ? "No models match." : "No models reported for this provider yet."}
485 </p>
486 ) : null}
487 {visibleModels.map((model, index) => {
488 const group = groupOf(model);
489 const previous = visibleModels[index - 1];
490 const startsGroup = previous === undefined || groupOf(previous) !== group;
491 return (
492 <div key={`${instanceId}:${model.slug}:group`}>
493 {startsGroup && favoriteCount > 0 && group === "favorite"
494 ? groupLabel("Favorites", index === 0)
495 : null}
496 {startsGroup && favoriteCount > 0 && group === "visible"
497 ? groupLabel("All", index === 0)
498 : null}
499 {startsGroup && group === "hidden"
500 ? groupLabel("Hidden from picker", index === 0)
501 : null}
502 {renderRow(model)}
503 </div>
504 );
505 })}
506 </div>
507​
508 {isAdding ? (
509 <div className="mt-3 flex flex-col gap-2 sm:flex-row">
510 <Input
511 id={`provider-instance-${instanceId}-custom-model`}
512 size="sm"
513 autoFocus
514 value={input}
515 onChange={(event) => {
516 setInput(event.target.value);
517 if (error) setError(null);
518 }}
519 onKeyDown={(event) => {
520 if (event.key === "Escape") {
521 event.preventDefault();
522 cancelAdd();
523 return;
524 }
525 if (event.key !== "Enter") return;
526 event.preventDefault();
527 handleAdd();
528 }}
529 placeholder={driverKind ? CUSTOM_MODEL_PLACEHOLDER_BY_KIND[driverKind] : "model-slug"}
530 spellCheck={false}
531 />
532 <div className="flex shrink-0 gap-2">
533 <Button size="sm" variant="outline" onClick={handleAdd}>
534 Add
535 </Button>
536 <Button size="sm" variant="ghost" onClick={cancelAdd}>
537 Cancel
538 </Button>
539 </div>
540 </div>
541 ) : (
542 <Button
543 type="button"
544 size="xs"
545 variant="ghost-muted"
546 className="mt-2 -ml-2"
547 onClick={() => setIsAdding(true)}
548 >
549 <PlusIcon className="size-3" />
550 Add custom model
551 </Button>
552 )}
553​
554 {error ? <p className="mt-2 text-xs text-destructive">{error}</p> : null}
555 </div>
556 );