Open History to see the last commit
1"use client";
2
3import {
4 ArrowDownIcon,
5 ArrowUpIcon,
6 EyeIcon,
7 EyeOffIcon,
8 InfoIcon,
9 PlusIcon,
10 StarIcon,
11 XIcon,
12} from "lucide-react";
13import { useMemo, useRef, useState } from "react";
14import {
15 ProviderDriverKind,
16 type ProviderInstanceId,
17 type ServerProviderModel,
18} from "@t3tools/contracts";
19import { normalizeCustomModelSlug } from "@t3tools/shared/model";
20
21import { cn } from "../../lib/utils";
22import { sortModelsForProviderInstance } from "../../modelOrdering";
23import { MAX_CUSTOM_MODEL_LENGTH } from "../../modelSelection";
24import { Button } from "../ui/button";
25import { Input } from "../ui/input";
26import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
27
28/**
29 * Placeholder text for the "add a custom model" input, keyed by driver
30 * kind. Mirrors the prior hardcoded switch in `SettingsPanels.tsx` so the
31 * UX is unchanged — only the owning component has moved.
32 */
33const CUSTOM_MODEL_PLACEHOLDER_BY_KIND: Partial<Record<ProviderDriverKind, string>> = {
34 [ProviderDriverKind.make("codex")]: "gpt-6.7-codex-ultra-preview",
35 [ProviderDriverKind.make("claudeAgent")]: "claude-sonnet-5",
36 [ProviderDriverKind.make("cursor")]: "claude-sonnet-4-6",
37 [ProviderDriverKind.make("opencode")]: "openai/gpt-5",
38};
39
40interface ProviderModelsSectionProps {
41 /** Identifier used to namespace input ids within the DOM. */
42 readonly instanceId: ProviderInstanceId;
43 /**
44 * Driver kind for slug normalization + input placeholder. `null` when
45 * the section is rendered without enough provider metadata.
46 */
47 readonly driverKind: ProviderDriverKind | null;
48 /**
49 * The live model list to display. Includes both built-in (probe-reported)
50 * and custom entries, distinguished by `isCustom`.
51 */
52 readonly models: ReadonlyArray<ServerProviderModel>;
53 /**
54 * The persisted custom-model slug list for this instance. Drives dedup,
55 * and is the array we hand back verbatim (with the new slug appended /
56 * removed) via `onChange`.
57 */
58 readonly customModels: ReadonlyArray<string>;
59 /** Server-returned model slugs hidden from the model picker. */
60 readonly hiddenModels: ReadonlyArray<string>;
61 /** Model slugs favorited for this provider instance. */
62 readonly favoriteModels: ReadonlyArray<string>;
63 /** Explicit user-authored model ordering for this provider instance. */
64 readonly modelOrder: ReadonlyArray<string>;
65 /**
66 * Commit the new custom-model list. Caller is responsible for routing the
67 * write to the correct storage (legacy `settings.providers[kind]` vs.
68 * `providerInstances[id].config`).
69 */
70 readonly onChange: (next: ReadonlyArray<string>) => void;
71 readonly onHiddenModelsChange: (next: ReadonlyArray<string>) => void;
72 readonly onFavoriteModelsChange: (next: ReadonlyArray<string>) => void;
73 readonly onModelOrderChange: (next: ReadonlyArray<string>) => void;
74}
75
76/**
77 * Shared "Models" section rendered on both the built-in default and custom
78 * provider-instance cards. Owns its own input + error local state so two
79 * cards on screen don't fight over the input value.
80 *
81 * Validation mirrors the pre-consolidation logic in `SettingsPanels`:
82 * - empty / whitespace → "Enter a model slug."
83 * - duplicate of a non-custom (probe-reported) slug → "already built in"
84 * - exceeds `MAX_CUSTOM_MODEL_LENGTH` → length error
85 * - duplicate of an already-saved custom slug → already-saved error
86 */
87export function ProviderModelsSection({
88 instanceId,
89 driverKind,
90 models,
91 customModels,
92 hiddenModels,
93 favoriteModels,
94 modelOrder,
95 onChange,
96 onHiddenModelsChange,
97 onFavoriteModelsChange,
98 onModelOrderChange,
99}: ProviderModelsSectionProps) {
100 const [input, setInput] = useState("");
101 const [error, setError] = useState<string | null>(null);
102 const listRef = useRef<HTMLDivElement | null>(null);
103 const hiddenModelSet = useMemo(() => new Set(hiddenModels), [hiddenModels]);
104 const favoriteModelSet = useMemo(() => new Set(favoriteModels), [favoriteModels]);
105 const orderedModels = useMemo(() => {
106 return sortModelsForProviderInstance(models, {
107 favoriteModels: favoriteModelSet,
108 groupFavorites: true,
109 modelOrder,
110 });
111 }, [favoriteModelSet, modelOrder, models]);
112
113 const handleAdd = () => {
114 const normalized = normalizeCustomModelSlug(input);
115 if (!normalized) {
116 setError("Enter a model slug.");
117 return;
118 }
119 if (models.some((model) => !model.isCustom && model.slug === normalized)) {
120 setError("That model is already built in.");
121 return;
122 }
123 if (normalized.length > MAX_CUSTOM_MODEL_LENGTH) {
124 setError(`Model slugs must be ${MAX_CUSTOM_MODEL_LENGTH} characters or less.`);
125 return;
126 }
127 if (customModels.includes(normalized)) {
128 setError("That custom model is already saved.");
129 return;
130 }
131
132 onChange([...customModels, normalized]);
133 setInput("");
134 setError(null);
135
136 // Scroll the new row into view once the DOM reflects the commit.
137 // `MutationObserver` handles the one-frame gap between `onChange` and
138 // the `models` prop update; the `requestAnimationFrame` covers the
139 // common case where the parent updates synchronously.
140 const el = listRef.current;
141 if (!el) return;
142 const scrollToEnd = () => el.scrollTo({ top: el.scrollHeight, behavior: "smooth" });
143 requestAnimationFrame(scrollToEnd);
144 const observer = new MutationObserver(() => {
145 scrollToEnd();
146 observer.disconnect();
147 });
148 observer.observe(el, { childList: true, subtree: true });
149 setTimeout(() => observer.disconnect(), 2_000);
150 };
151
152 const handleRemove = (slug: string) => {
153 onChange(customModels.filter((model) => model !== slug));
154 onModelOrderChange(modelOrder.filter((model) => model !== slug));
155 onFavoriteModelsChange(favoriteModels.filter((model) => model !== slug));
156 setError(null);
157 };
158
159 const handleToggleHidden = (slug: string) => {
160 if (hiddenModelSet.has(slug)) {
161 onHiddenModelsChange(hiddenModels.filter((model) => model !== slug));
162 return;
163 }
164 onHiddenModelsChange([...hiddenModels, slug]);
165 };
166
167 const handleToggleFavorite = (slug: string) => {
168 if (favoriteModelSet.has(slug)) {
169 onFavoriteModelsChange(favoriteModels.filter((model) => model !== slug));
170 return;
171 }
172 onFavoriteModelsChange([...favoriteModels, slug]);
173 };
174
175 const handleMove = (slug: string, direction: -1 | 1) => {
176 const slugs = orderedModels.map((model) => model.slug);
177 const index = slugs.indexOf(slug);
178 const nextIndex = index + direction;
179 if (index < 0 || nextIndex < 0 || nextIndex >= slugs.length) {
180 return;
181 }
182 const next = [...slugs];
183 [next[index], next[nextIndex]] = [next[nextIndex]!, next[index]!];
184 onModelOrderChange(next);
185 };
186
187 return (
188 <div>
189 <div className="text-xs font-medium text-foreground">Models</div>
190 <div className="mt-1 text-xs text-muted-foreground">
191 {models.length} model{models.length === 1 ? "" : "s"} available.
192 </div>
193 <div ref={listRef} className="mt-2 max-h-40 overflow-y-auto pb-1">
194 {orderedModels.map((model, index) => {
195 const caps = model.capabilities;
196 const capLabels: string[] = [];
197 const isHidden = !model.isCustom && hiddenModelSet.has(model.slug);
198 const isFavorite = favoriteModelSet.has(model.slug);
199 const previousModel = orderedModels[index - 1];
200 const nextModel = orderedModels[index + 1];
201 const canMoveUp =
202 previousModel !== undefined && favoriteModelSet.has(previousModel.slug) === isFavorite;
203 const canMoveDown =
204 nextModel !== undefined && favoriteModelSet.has(nextModel.slug) === isFavorite;
205 const descriptors = caps?.optionDescriptors ?? [];
206 if (descriptors.some((descriptor) => descriptor.id === "fastMode")) {
207 capLabels.push("Fast mode");
208 }
209 if (descriptors.some((descriptor) => descriptor.id === "thinking")) {
210 capLabels.push("Thinking");
211 }
212 if (
213 descriptors.some(
214 (descriptor) =>
215 descriptor.type === "select" &&
216 (descriptor.id === "reasoningEffort" ||
217 descriptor.id === "effort" ||
218 descriptor.id === "reasoning" ||
219 descriptor.id === "variant"),
220 )
221 ) {
222 capLabels.push("Reasoning");
223 }
224 const hasDetails = capLabels.length > 0 || model.name !== model.slug;
225
226 return (
227 <div
228 key={`${instanceId}:${model.slug}`}
229 className={cn(
230 "grid min-h-7 grid-cols-[minmax(0,1fr)_auto] items-center gap-2 py-1",
231 isHidden && "text-muted-foreground",
232 )}
233 >
234 <div className="flex min-w-0 items-center gap-1">
235 <span
236 className={cn(
237 "min-w-0 truncate text-xs",
238 isHidden ? "text-muted-foreground line-through" : "text-foreground/90",
239 )}
240 >
241 {model.name}
242 </span>
243 {hasDetails ? (
244 <Tooltip>
245 <TooltipTrigger
246 render={
247 <Button
248 size="icon-micro"
249 variant="ghost"
250 className="text-muted-foreground/60 hover:text-muted-foreground"
251 aria-label={`Details for ${model.name}`}
252 />
253 }
254 >
255 <InfoIcon className="size-3" />
256 </TooltipTrigger>
257 <TooltipPopup side="top" className="max-w-56">
258 <div className="space-y-1">
259 <code className="block text-[11px] text-foreground">{model.slug}</code>
260 {capLabels.length > 0 ? (
261 <div className="flex flex-wrap gap-x-2 gap-y-0.5">
262 {capLabels.map((label) => (
263 <span key={label} className="text-[10px] text-muted-foreground">
264 {label}
265 </span>
266 ))}
267 </div>
268 ) : null}
269 </div>
270 </TooltipPopup>
271 </Tooltip>
272 ) : null}
273 {isHidden ? (
274 <span className="text-[10px] text-muted-foreground">hidden</span>
275 ) : null}
276 {model.isCustom ? (
277 <span className="text-[10px] text-muted-foreground">custom</span>
278 ) : null}
279 </div>
280 <div className="flex shrink-0 items-center gap-0.5">
281 <Tooltip>
282 <TooltipTrigger
283 render={
284 <Button
285 size="icon-micro"
286 variant="ghost-muted"
287 className={cn(isFavorite && "text-yellow-500 hover:text-yellow-600")}
288 onClick={() => handleToggleFavorite(model.slug)}
289 aria-label={`${isFavorite ? "Remove" : "Add"} ${model.name} ${
290 isFavorite ? "from" : "to"
291 } favorites`}
292 />
293 }
294 >
295 <StarIcon className={cn("size-3", isFavorite && "fill-current")} />
296 </TooltipTrigger>
297 <TooltipPopup side="top">
298 {isFavorite ? "Remove from favorites" : "Add to favorites"}
299 </TooltipPopup>
300 </Tooltip>
301 <Tooltip>
302 <TooltipTrigger
303 render={
304 <Button
305 size="icon-micro"
306 variant="ghost-muted"
307 disabled={!canMoveUp}
308 onClick={() => handleMove(model.slug, -1)}
309 aria-label={`Move ${model.name} up`}
310 />
311 }
312 >
313 <ArrowUpIcon className="size-3" />
314 </TooltipTrigger>
315 <TooltipPopup side="top">Move up</TooltipPopup>
316 </Tooltip>
317 <Tooltip>
318 <TooltipTrigger
319 render={
320 <Button
321 size="icon-micro"
322 variant="ghost-muted"
323 disabled={!canMoveDown}
324 onClick={() => handleMove(model.slug, 1)}
325 aria-label={`Move ${model.name} down`}
326 />
327 }
328 >
329 <ArrowDownIcon className="size-3" />
330 </TooltipTrigger>
331 <TooltipPopup side="top">Move down</TooltipPopup>
332 </Tooltip>
333 {!model.isCustom ? (
334 <Tooltip>
335 <TooltipTrigger
336 render={
337 <Button
338 size="icon-micro"
339 variant="ghost-muted"
340 onClick={() => handleToggleHidden(model.slug)}
341 aria-label={`${isHidden ? "Show" : "Hide"} ${model.name}`}
342 />
343 }
344 >
345 {isHidden ? (
346 <EyeIcon className="size-3" />
347 ) : (
348 <EyeOffIcon className="size-3" />
349 )}
350 </TooltipTrigger>
351 <TooltipPopup side="top">
352 {isHidden ? "Show in picker" : "Hide from picker"}
353 </TooltipPopup>
354 </Tooltip>
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 </div>
374 </div>
375 );
376 })}
377 </div>
378
379 <div className="mt-3 flex flex-col gap-2 sm:flex-row">
380 <Input
381 id={`provider-instance-${instanceId}-custom-model`}
382 value={input}
383 onChange={(event) => {
384 setInput(event.target.value);
385 if (error) setError(null);
386 }}
387 onKeyDown={(event) => {
388 if (event.key !== "Enter") return;
389 event.preventDefault();
390 handleAdd();
391 }}
392 placeholder={driverKind ? CUSTOM_MODEL_PLACEHOLDER_BY_KIND[driverKind] : "model-slug"}
393 spellCheck={false}
394 />
395 <Button className="shrink-0" variant="outline" onClick={handleAdd}>
396 <PlusIcon className="size-3.5" />
397 Add
398 </Button>
399 </div>
400
401 {error ? <p className="mt-2 text-xs text-destructive">{error}</p> : null}
402 </div>
403 );
404}