Open History to see the last commit
1"use client";
2
3import { ArrowDownIcon, ArrowUpIcon, PencilIcon, PlusIcon, StarIcon, XIcon } from "lucide-react";
4import { useEffect, 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 { useStableCallback } from "../../hooks/useStableCallback";
13import { cn } from "../../lib/utils";
14import { sortModelsForProviderInstance } from "../../modelOrdering";
15import { MAX_CUSTOM_MODEL_LENGTH } from "../../modelSelection";
16import { Button } from "../ui/button";
17import { Input } from "../ui/input";
18import { Switch } from "../ui/switch";
19import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
20import { CustomModelEditor } from "./CustomModelEditor";
21
22const CUSTOM_MODEL_PLACEHOLDER_BY_KIND: Partial<Record<ProviderDriverKind, string>> = {
23 [ProviderDriverKind.make("codex")]: "gpt-6.7-codex-ultra-preview",
24 [ProviderDriverKind.make("claudeAgent")]: "claude-sonnet-5",
25 [ProviderDriverKind.make("cursor")]: "claude-sonnet-4-6",
26 [ProviderDriverKind.make("opencode")]: "openai/gpt-5",
27 [ProviderDriverKind.make("pi")]: "anthropic/claude-sonnet-5",
28};
29
30const FILTER_THRESHOLD = 8;
31
32function describeModelCapabilities(model: ServerProviderModel): string[] {
33 const descriptors = model.capabilities?.optionDescriptors ?? [];
34 const labels: string[] = [];
35 const hasFastMode = descriptors.some(
36 (descriptor) =>
37 descriptor.id === "fastMode" ||
38 (descriptor.id === "serviceTier" &&
39 descriptor.type === "select" &&
40 descriptor.options.some((option) => option.id === "fast" || option.label === "Fast")),
41 );
42 if (hasFastMode) labels.push("Fast mode");
43 if (descriptors.some((descriptor) => descriptor.id === "thinking")) labels.push("Thinking");
44 if (
45 descriptors.some(
46 (descriptor) =>
47 descriptor.type === "select" &&
48 (descriptor.id === "reasoningEffort" ||
49 descriptor.id === "effort" ||
50 descriptor.id === "reasoning" ||
51 descriptor.id === "variant"),
52 )
53 ) {
54 labels.push("Reasoning");
55 }
56 return labels;
57}
58
59export function groupModelsForDisplay<
60 T extends { readonly slug: string; readonly isCustom: boolean },
61>(
62 models: ReadonlyArray<T>,
63 options: {
64 readonly favoriteModels: ReadonlySet<string>;
65 readonly hiddenModels: ReadonlySet<string>;
66 readonly modelOrder: ReadonlyArray<string>;
67 },
68): T[] {
69 const ordered = sortModelsForProviderInstance(models, {
70 favoriteModels: options.favoriteModels,
71 groupFavorites: true,
72 modelOrder: options.modelOrder,
73 });
74 const isHidden = (model: T) => !model.isCustom && options.hiddenModels.has(model.slug);
75 return [
76 ...ordered.filter((model) => options.favoriteModels.has(model.slug)),
77 ...ordered.filter((model) => !options.favoriteModels.has(model.slug) && !isHidden(model)),
78 ...ordered.filter((model) => !options.favoriteModels.has(model.slug) && isHidden(model)),
79 ];
80}
81
82export function nextHiddenModelsForBulkToggle(
83 models: ReadonlyArray<Pick<ServerProviderModel, "slug" | "isCustom">>,
84 hiddenModels: ReadonlyArray<string>,
85): string[] {
86 const builtInSlugs = models.filter((model) => !model.isCustom).map((model) => model.slug);
87 const builtInSlugSet = new Set(builtInSlugs);
88 const allBuiltInModelsHidden = builtInSlugs.every((slug) => hiddenModels.includes(slug));
89
90 if (allBuiltInModelsHidden) {
91 return hiddenModels.filter((slug) => !builtInSlugSet.has(slug));
92 }
93
94 return [...new Set([...hiddenModels, ...builtInSlugs])];
95}
96
97interface ProviderModelsSectionProps {
98 readonly instanceId: ProviderInstanceId;
99 readonly driverKind: ProviderDriverKind | null;
100 readonly models: ReadonlyArray<ServerProviderModel>;
101 readonly customModels: ReadonlyArray<CustomModelDefinition>;
102 readonly canManageCustomModels: boolean;
103 readonly canWritePreferences?: boolean;
104 readonly hiddenModels: ReadonlyArray<string>;
105 readonly favoriteModels: ReadonlyArray<string>;
106 readonly modelOrder: ReadonlyArray<string>;
107 readonly onChange: (next: ReadonlyArray<CustomModelDefinition>) => void;
108 readonly onHiddenModelsChange: (
109 next: ReadonlyArray<string>,
110 affectedModels?: ReadonlyArray<string>,
111 ) => void;
112 readonly onFavoriteModelsChange: (next: ReadonlyArray<string>) => void;
113 readonly onToggleFavorite: (model: string) => void;
114 readonly onModelOrderChange: (next: ReadonlyArray<string>) => void;
115}
116
117export function ProviderModelsSection({
118 instanceId,
119 driverKind,
120 models,
121 customModels,
122 canManageCustomModels,
123 canWritePreferences = true,
124 hiddenModels,
125 favoriteModels,
126 modelOrder,
127 onChange,
128 onHiddenModelsChange,
129 onFavoriteModelsChange,
130 onToggleFavorite,
131 onModelOrderChange,
132}: ProviderModelsSectionProps) {
133 const [input, setInput] = useState("");
134 const [isAdding, setIsAdding] = useState(false);
135 const [filter, setFilter] = useState("");
136 const [error, setError] = useState<string | null>(null);
137 const [editingSlug, setEditingSlug] = useState<string | null>(null);
138 const listRef = useRef<HTMLDivElement>(null);
139 const scrollToSlugRef = useRef<string | null>(null);
140 const hiddenModelSet = new Set(hiddenModels);
141 const favoriteModelSet = new Set(favoriteModels);
142 const displayModels = groupModelsForDisplay(models, {
143 favoriteModels: favoriteModelSet,
144 hiddenModels: hiddenModelSet,
145 modelOrder,
146 });
147 const favoriteCount = displayModels.filter((model) => favoriteModelSet.has(model.slug)).length;
148 const hiddenCount = displayModels.filter(
149 (model) => !model.isCustom && hiddenModelSet.has(model.slug),
150 ).length;
151 const showFilter = models.length > FILTER_THRESHOLD;
152 const normalizedFilter = filter.trim().toLowerCase();
153 const isFiltering = showFilter && normalizedFilter.length > 0;
154 const visibleModels = isFiltering
155 ? displayModels.filter(
156 (model) =>
157 model.name.toLowerCase().includes(normalizedFilter) ||
158 model.slug.toLowerCase().includes(normalizedFilter),
159 )
160 : displayModels;
161
162 // A model added or moved lands in a later commit, so each commit looks for the pending row.
163 useEffect(() => {
164 const slug = scrollToSlugRef.current;
165 if (slug === null) return;
166 const row = listRef.current?.querySelector<HTMLElement>(
167 `[data-model-slug="${CSS.escape(slug)}"]`,
168 );
169 if (!row) return;
170 scrollToSlugRef.current = null;
171 row.scrollIntoView({ block: "nearest" });
172 });
173
174 // CustomModelEditor keys its option list on this array. Derived after the effect and
175 // checked against `hiddenModels` rather than the set built above it, so it stays cached.
176 const builtInModels = models.filter((model) => !model.isCustom);
177 const allBuiltInModelsHidden =
178 builtInModels.length > 0 && builtInModels.every((model) => hiddenModels.includes(model.slug));
179
180 const handleAdd = () => {
181 if (!canManageCustomModels || driverKind === "antigravity") return;
182 const normalized = normalizeCustomModelSlug(input);
183 if (!normalized) {
184 setError("Enter a model slug.");
185 return;
186 }
187 if (models.some((model) => !model.isCustom && model.slug === normalized)) {
188 setError("That model is already built in.");
189 return;
190 }
191 if (normalized.length > MAX_CUSTOM_MODEL_LENGTH) {
192 setError(`Model slugs must be ${MAX_CUSTOM_MODEL_LENGTH} characters or less.`);
193 return;
194 }
195 if (customModels.some((entry) => entry.slug === normalized)) {
196 setError("That custom model is already saved.");
197 return;
198 }
199
200 scrollToSlugRef.current = normalized;
201 setFilter("");
202 onChange([...customModels, { slug: normalized, name: normalized, capabilities: null }]);
203 setInput("");
204 setError(null);
205 setIsAdding(false);
206 };
207
208 const cancelAdd = () => {
209 setInput("");
210 setError(null);
211 setIsAdding(false);
212 };
213
214 const handleRemove = (slug: string) => {
215 if (!canManageCustomModels) return;
216 if (editingSlug === slug) setEditingSlug(null);
217 onChange(customModels.filter((entry) => entry.slug !== slug));
218 onModelOrderChange(modelOrder.filter((model) => model !== slug));
219 onFavoriteModelsChange(favoriteModels.filter((model) => model !== slug));
220 setError(null);
221 };
222
223 const handleSaveEdit = (next: CustomModelDefinition) => {
224 if (!canManageCustomModels) return;
225 onChange(customModels.map((entry) => (entry.slug === next.slug ? next : entry)));
226 setEditingSlug(null);
227 };
228
229 const setHidden = (slug: string, hidden: boolean) => {
230 if (!canWritePreferences || hidden === hiddenModelSet.has(slug)) return;
231 onHiddenModelsChange(
232 hidden ? [...hiddenModels, slug] : hiddenModels.filter((model) => model !== slug),
233 [slug],
234 );
235 };
236
237 const handleToggleFavorite = (slug: string) => {
238 if (!canWritePreferences) return;
239 onToggleFavorite(slug);
240 };
241
242 const groupOf = (model: (typeof displayModels)[number]) =>
243 favoriteModelSet.has(model.slug)
244 ? "favorite"
245 : !model.isCustom && hiddenModelSet.has(model.slug)
246 ? "hidden"
247 : "visible";
248 const handleMove = (slug: string, direction: -1 | 1) => {
249 if (!canWritePreferences) return;
250 const index = displayModels.findIndex((model) => model.slug === slug);
251 const nextIndex = index + direction;
252 if (index < 0 || nextIndex < 0 || nextIndex >= displayModels.length) return;
253 if (groupOf(displayModels[index]!) !== groupOf(displayModels[nextIndex]!)) return;
254 const next = displayModels.map((model) => model.slug);
255 [next[index], next[nextIndex]] = [next[nextIndex]!, next[index]!];
256 onModelOrderChange(next);
257 };
258
259 const handleToggleEdit = useStableCallback((slug: string) => {
260 if (!canManageCustomModels) return;
261 setEditingSlug((current) => (current === slug ? null : slug));
262 });
263 const rowHandlers = {
264 onToggleFavorite: useStableCallback(handleToggleFavorite),
265 onMove: useStableCallback(handleMove),
266 onSetHidden: useStableCallback(setHidden),
267 onToggleEdit: handleToggleEdit,
268 onRemove: useStableCallback(handleRemove),
269 };
270
271 const renderRow = (model: (typeof displayModels)[number]) => {
272 const group = groupOf(model);
273 const index = displayModels.indexOf(model);
274 const previousModel = displayModels[index - 1];
275 const nextModel = displayModels[index + 1];
276 return (
277 <ProviderModelRow
278 key={`${instanceId}:${model.slug}`}
279 model={model}
280 isHidden={!model.isCustom && hiddenModelSet.has(model.slug)}
281 isFavorite={group === "favorite"}
282 canMoveUp={!isFiltering && previousModel !== undefined && groupOf(previousModel) === group}
283 canMoveDown={!isFiltering && nextModel !== undefined && groupOf(nextModel) === group}
284 isFiltering={isFiltering}
285 canWritePreferences={canWritePreferences}
286 canManageCustomModels={canManageCustomModels}
287 {...rowHandlers}
288 />
289 );
290 };
291
292 const groupLabel = (label: string, isFirst: boolean) => (
293 <div className={cn("px-2 pb-1.5 text-2xs text-muted-foreground", isFirst ? "pt-1" : "pt-5")}>
294 {label}
295 </div>
296 );
297
298 return (
299 <div className="lg:flex lg:h-full lg:min-h-0 lg:flex-col">
300 <div className="flex flex-wrap items-center justify-between gap-2">
301 {showFilter ? (
302 <Input
303 value={filter}
304 onChange={(event) => setFilter(event.target.value)}
305 placeholder="Filter models"
306 size="sm"
307 className="w-56 max-w-full"
308 spellCheck={false}
309 aria-label="Filter models"
310 />
311 ) : null}
312 <div className="flex items-center gap-2">
313 {builtInModels.length > 0 ? (
314 <Button
315 type="button"
316 size="xs"
317 variant="ghost-muted"
318 onClick={() =>
319 onHiddenModelsChange(
320 nextHiddenModelsForBulkToggle(models, hiddenModels),
321 builtInModels.map((model) => model.slug),
322 )
323 }
324 >
325 {allBuiltInModelsHidden ? "Enable all" : "Disable all"}
326 </Button>
327 ) : null}
328 <span className="text-xs text-muted-foreground">
329 {models.length} model{models.length === 1 ? "" : "s"}
330 {favoriteCount > 0
331 ? ` · ${favoriteCount} favorite${favoriteCount === 1 ? "" : "s"}`
332 : ""}
333 {hiddenCount > 0 ? ` · ${hiddenCount} hidden` : ""}
334 </span>
335 </div>
336 {driverKind !== "antigravity" && !isAdding ? (
337 <Button
338 type="button"
339 size="xs"
340 variant="ghost-muted"
341 className="ml-auto"
342 onClick={() => setIsAdding(true)}
343 >
344 <PlusIcon className="size-3" />
345 Add custom model
346 </Button>
347 ) : null}
348 </div>
349 <div
350 ref={listRef}
351 className="mt-2 -mx-2 max-h-64 overflow-y-auto lg:max-h-none lg:min-h-0 lg:flex-1"
352 >
353 {visibleModels.length === 0 ? (
354 <p className="px-2 py-2 text-xs text-muted-foreground">
355 {isFiltering ? "No models match." : "No models reported for this provider yet."}
356 </p>
357 ) : null}
358 {visibleModels.map((model, index) => {
359 const group = groupOf(model);
360 const previous = visibleModels[index - 1];
361 const startsGroup = previous === undefined || groupOf(previous) !== group;
362 const editingEntry =
363 canManageCustomModels && model.isCustom && editingSlug === model.slug
364 ? customModels.find((entry) => entry.slug === model.slug)
365 : undefined;
366 return (
367 <div key={`${instanceId}:${model.slug}:group`}>
368 {startsGroup && favoriteCount > 0 && group === "favorite"
369 ? groupLabel("Favorites", index === 0)
370 : null}
371 {startsGroup && favoriteCount > 0 && group === "visible"
372 ? groupLabel("All", index === 0)
373 : null}
374 {startsGroup && group === "hidden"
375 ? groupLabel("Hidden from picker", index === 0)
376 : null}
377 {renderRow(model)}
378 {editingEntry ? (
379 <CustomModelEditor
380 key={`${instanceId}:${model.slug}:editor`}
381 instanceId={instanceId}
382 driverKind={driverKind}
383 entry={editingEntry}
384 builtInModels={builtInModels}
385 onSave={handleSaveEdit}
386 onCancel={() => setEditingSlug(null)}
387 />
388 ) : null}
389 </div>
390 );
391 })}
392 </div>
393
394 {driverKind === "antigravity" || !canManageCustomModels ? null : isAdding ? (
395 <div className="mt-3 flex flex-col gap-2 sm:flex-row">
396 <Input
397 id={`provider-instance-${instanceId}-custom-model`}
398 size="sm"
399 autoFocus
400 value={input}
401 onChange={(event) => {
402 setInput(event.target.value);
403 if (error) setError(null);
404 }}
405 onKeyDown={(event) => {
406 if (event.key === "Escape") {
407 event.preventDefault();
408 cancelAdd();
409 return;
410 }
411 if (event.key !== "Enter") return;
412 event.preventDefault();
413 handleAdd();
414 }}
415 placeholder={driverKind ? CUSTOM_MODEL_PLACEHOLDER_BY_KIND[driverKind] : "model-slug"}
416 spellCheck={false}
417 />
418 <div className="flex shrink-0 gap-2">
419 <Button size="sm" variant="outline" onClick={handleAdd}>
420 Add
421 </Button>
422 <Button size="sm" variant="ghost" onClick={cancelAdd}>
423 Cancel
424 </Button>
425 </div>
426 </div>
427 ) : null}
428
429 {driverKind !== "antigravity" && error ? (
430 <p className="mt-2 text-xs text-destructive">{error}</p>
431 ) : null}
432 </div>
433 );
434}
435
436// A row gets its flags as primitives and handlers that never change, so toggling,
437// starring or moving one model re-renders that row and leaves the others cached.
438function ProviderModelRow({
439 model,
440 isHidden,
441 isFavorite,
442 canMoveUp,
443 canMoveDown,
444 isFiltering,
445 canWritePreferences,
446 canManageCustomModels,
447 onToggleFavorite,
448 onMove,
449 onSetHidden,
450 onToggleEdit,
451 onRemove,
452}: {
453 readonly model: ServerProviderModel;
454 readonly isHidden: boolean;
455 readonly isFavorite: boolean;
456 readonly canMoveUp: boolean;
457 readonly canMoveDown: boolean;
458 readonly isFiltering: boolean;
459 readonly canWritePreferences: boolean;
460 readonly canManageCustomModels: boolean;
461 readonly onToggleFavorite: (slug: string) => void;
462 readonly onMove: (slug: string, direction: -1 | 1) => void;
463 readonly onSetHidden: (slug: string, hidden: boolean) => void;
464 readonly onToggleEdit: (slug: string) => void;
465 readonly onRemove: (slug: string) => void;
466}) {
467 const capLabels = describeModelCapabilities(model);
468 const nameClassName = cn("text-xs", isHidden ? "text-muted-foreground" : "text-foreground/90");
469 const pickerTooltip = model.isCustom
470 ? "Custom models are always shown in the picker"
471 : isHidden
472 ? "Hidden from picker"
473 : "Shown in picker";
474
475 return (
476 <div
477 data-model-slug={model.slug}
478 className={cn(
479 "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",
480 isHidden && "opacity-50",
481 )}
482 >
483 <Tooltip>
484 <TooltipTrigger
485 render={
486 <Button
487 size="icon-micro"
488 variant="ghost-muted"
489 disabled={!canWritePreferences}
490 onClick={() => onToggleFavorite(model.slug)}
491 aria-label={`${isFavorite ? "Remove" : "Add"} ${model.name} ${
492 isFavorite ? "from" : "to"
493 } favorites`}
494 />
495 }
496 >
497 <StarIcon className={cn("size-3", isFavorite && "fill-current text-warning")} />
498 </TooltipTrigger>
499 <TooltipPopup side="top">
500 {isFavorite ? "Remove from favorites" : "Add to favorites"}
501 </TooltipPopup>
502 </Tooltip>
503 <span className="flex min-w-0 items-baseline gap-2">
504 <Tooltip>
505 <TooltipTrigger
506 render={
507 <span tabIndex={0} className="flex min-w-0 items-baseline gap-2 overflow-hidden" />
508 }
509 >
510 <span className={cn(nameClassName, "max-w-full shrink-0 truncate")}>{model.name}</span>
511 {model.name !== model.slug ? (
512 <code className="truncate font-mono text-2xs text-muted-foreground/70">
513 {model.slug}
514 </code>
515 ) : null}
516 </TooltipTrigger>
517 <TooltipPopup side="top" align="start">
518 <div>{model.name}</div>
519 {model.name !== model.slug ? (
520 <code className="font-mono text-2xs text-muted-foreground">{model.slug}</code>
521 ) : null}
522 </TooltipPopup>
523 </Tooltip>
524 {model.isCustom ? (
525 <span className="shrink-0 text-2xs text-muted-foreground/70">custom</span>
526 ) : null}
527 </span>
528 <span className="text-2xs text-muted-foreground/70">
529 {capLabels.length > 0 ? (
530 <span className="hidden sm:inline">{capLabels.join(" · ")}</span>
531 ) : null}
532 </span>
533 <span className="flex shrink-0 items-center justify-end gap-0.5">
534 {!isHidden && !isFiltering ? (
535 <>
536 <Tooltip>
537 <TooltipTrigger
538 render={
539 <Button
540 size="icon-micro"
541 variant="ghost-muted"
542 disabled={!canWritePreferences || !canMoveUp}
543 onClick={() => onMove(model.slug, -1)}
544 aria-label={`Move ${model.name} up`}
545 />
546 }
547 >
548 <ArrowUpIcon className="size-3" />
549 </TooltipTrigger>
550 <TooltipPopup side="top">Move up</TooltipPopup>
551 </Tooltip>
552 <Tooltip>
553 <TooltipTrigger
554 render={
555 <Button
556 size="icon-micro"
557 variant="ghost-muted"
558 disabled={!canWritePreferences || !canMoveDown}
559 onClick={() => onMove(model.slug, 1)}
560 aria-label={`Move ${model.name} down`}
561 />
562 }
563 >
564 <ArrowDownIcon className="size-3" />
565 </TooltipTrigger>
566 <TooltipPopup side="top">Move down</TooltipPopup>
567 </Tooltip>
568 </>
569 ) : null}
570 {model.isCustom ? (
571 <>
572 <Tooltip>
573 <TooltipTrigger
574 render={
575 <Button
576 size="icon-micro"
577 variant="ghost-muted"
578 disabled={!canManageCustomModels}
579 aria-label={`Edit ${model.slug}`}
580 onClick={() => onToggleEdit(model.slug)}
581 />
582 }
583 >
584 <PencilIcon className="size-3" />
585 </TooltipTrigger>
586 <TooltipPopup side="top">Edit name and options</TooltipPopup>
587 </Tooltip>
588 <Tooltip>
589 <TooltipTrigger
590 render={
591 <Button
592 size="icon-micro"
593 variant="ghost-muted"
594 disabled={!canManageCustomModels}
595 aria-label={`Remove ${model.slug}`}
596 onClick={() => onRemove(model.slug)}
597 />
598 }
599 >
600 <XIcon className="size-3" />
601 </TooltipTrigger>
602 <TooltipPopup side="top">Remove custom model</TooltipPopup>
603 </Tooltip>
604 </>
605 ) : null}
606 </span>
607 {/* The trigger is a wrapper span: a disabled switch gets no pointer events,
608 so it could not open the tooltip itself. */}
609 <Tooltip>
610 <TooltipTrigger render={<span className="flex shrink-0 items-center" />}>
611 <Switch
612 size="sm"
613 checked={!isHidden}
614 disabled={!canWritePreferences || model.isCustom}
615 onCheckedChange={(checked) => onSetHidden(model.slug, !checked)}
616 aria-label={`Show ${model.name} in the model picker`}
617 />
618 </TooltipTrigger>
619 <TooltipPopup side="top">{pickerTooltip}</TooltipPopup>
620 </Tooltip>
621 </div>
622 );
623}