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

ProviderModelsSection.tsx

407 lines15.4 KB

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;
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 className="lg:flex lg:h-full lg:min-h-0 lg:flex-col">
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
194 ref={listRef}
195 className="mt-2 max-h-40 overflow-y-auto pb-1 lg:min-h-0 lg:max-h-none lg:flex-1"
196 >
197 {orderedModels.map((model, index) => {
198 const caps = model.capabilities;
199 const capLabels: string[] = [];
200 const isHidden = !model.isCustom && hiddenModelSet.has(model.slug);
201 const isFavorite = favoriteModelSet.has(model.slug);
202 const previousModel = orderedModels[index - 1];
203 const nextModel = orderedModels[index + 1];
204 const canMoveUp =
205 previousModel !== undefined && favoriteModelSet.has(previousModel.slug) === isFavorite;
206 const canMoveDown =
207 nextModel !== undefined && favoriteModelSet.has(nextModel.slug) === isFavorite;
208 const descriptors = caps?.optionDescriptors ?? [];
209 if (descriptors.some((descriptor) => descriptor.id === "fastMode")) {
210 capLabels.push("Fast mode");
211 }
212 if (descriptors.some((descriptor) => descriptor.id === "thinking")) {
213 capLabels.push("Thinking");
214 }
215 if (
216 descriptors.some(
217 (descriptor) =>
218 descriptor.type === "select" &&
219 (descriptor.id === "reasoningEffort" ||
220 descriptor.id === "effort" ||
221 descriptor.id === "reasoning" ||
222 descriptor.id === "variant"),
223 )
224 ) {
225 capLabels.push("Reasoning");
226 }
227 const hasDetails = capLabels.length > 0 || model.name !== model.slug;
228​
229 return (
230 <div
231 key={`${instanceId}:${model.slug}`}
232 className={cn(
233 "grid min-h-7 grid-cols-[minmax(0,1fr)_auto] items-center gap-2 py-1",
234 isHidden && "text-muted-foreground",
235 )}
236 >
237 <div className="flex min-w-0 items-center gap-1">
238 <span
239 className={cn(
240 "min-w-0 truncate text-xs",
241 isHidden ? "text-muted-foreground line-through" : "text-foreground/90",
242 )}
243 >
244 {model.name}
245 </span>
246 {hasDetails ? (
247 <Tooltip>
248 <TooltipTrigger
249 render={
250 <Button
251 size="icon-micro"
252 variant="ghost"
253 className="text-muted-foreground/60 hover:text-muted-foreground"
254 aria-label={`Details for ${model.name}`}
255 />
256 }
257 >
258 <InfoIcon className="size-3" />
259 </TooltipTrigger>
260 <TooltipPopup side="top" className="max-w-56">
261 <div className="space-y-1">
262 <code className="block text-[11px] text-foreground">{model.slug}</code>
263 {capLabels.length > 0 ? (
264 <div className="flex flex-wrap gap-x-2 gap-y-0.5">
265 {capLabels.map((label) => (
266 <span key={label} className="text-[10px] text-muted-foreground">
267 {label}
268 </span>
269 ))}
270 </div>
271 ) : null}
272 </div>
273 </TooltipPopup>
274 </Tooltip>
275 ) : null}
276 {isHidden ? (
277 <span className="text-[10px] text-muted-foreground">hidden</span>
278 ) : null}
279 {model.isCustom ? (
280 <span className="text-[10px] text-muted-foreground">custom</span>
281 ) : null}
282 </div>
283 <div className="flex shrink-0 items-center gap-0.5">
284 <Tooltip>
285 <TooltipTrigger
286 render={
287 <Button
288 size="icon-micro"
289 variant="ghost-muted"
290 className={cn(isFavorite && "text-yellow-500 hover:text-yellow-600")}
291 onClick={() => handleToggleFavorite(model.slug)}
292 aria-label={`${isFavorite ? "Remove" : "Add"} ${model.name} ${
293 isFavorite ? "from" : "to"
294 } favorites`}
295 />
296 }
297 >
298 <StarIcon className={cn("size-3", isFavorite && "fill-current")} />
299 </TooltipTrigger>
300 <TooltipPopup side="top">
301 {isFavorite ? "Remove from favorites" : "Add to favorites"}
302 </TooltipPopup>
303 </Tooltip>
304 <Tooltip>
305 <TooltipTrigger
306 render={
307 <Button
308 size="icon-micro"
309 variant="ghost-muted"
310 disabled={!canMoveUp}
311 onClick={() => handleMove(model.slug, -1)}
312 aria-label={`Move ${model.name} up`}
313 />
314 }
315 >
316 <ArrowUpIcon className="size-3" />
317 </TooltipTrigger>
318 <TooltipPopup side="top">Move up</TooltipPopup>
319 </Tooltip>
320 <Tooltip>
321 <TooltipTrigger
322 render={
323 <Button
324 size="icon-micro"
325 variant="ghost-muted"
326 disabled={!canMoveDown}
327 onClick={() => handleMove(model.slug, 1)}
328 aria-label={`Move ${model.name} down`}
329 />
330 }
331 >
332 <ArrowDownIcon className="size-3" />
333 </TooltipTrigger>
334 <TooltipPopup side="top">Move down</TooltipPopup>
335 </Tooltip>
336 {!model.isCustom ? (
337 <Tooltip>
338 <TooltipTrigger
339 render={
340 <Button
341 size="icon-micro"
342 variant="ghost-muted"
343 onClick={() => handleToggleHidden(model.slug)}
344 aria-label={`${isHidden ? "Show" : "Hide"} ${model.name}`}
345 />
346 }
347 >
348 {isHidden ? (
349 <EyeIcon className="size-3" />
350 ) : (
351 <EyeOffIcon className="size-3" />
352 )}
353 </TooltipTrigger>
354 <TooltipPopup side="top">
355 {isHidden ? "Show in picker" : "Hide from picker"}
356 </TooltipPopup>
357 </Tooltip>
358 ) : null}
359 {model.isCustom ? (
360 <Tooltip>
361 <TooltipTrigger
362 render={
363 <Button
364 size="icon-micro"
365 variant="ghost-muted"
366 aria-label={`Remove ${model.slug}`}
367 onClick={() => handleRemove(model.slug)}
368 />
369 }
370 >
371 <XIcon className="size-3" />
372 </TooltipTrigger>
373 <TooltipPopup side="top">Remove custom model</TooltipPopup>
374 </Tooltip>
375 ) : null}
376 </div>
377 </div>
378 );
379 })}
380 </div>
381​
382 <div className="mt-3 flex flex-col gap-2 sm:flex-row">
383 <Input
384 id={`provider-instance-${instanceId}-custom-model`}
385 value={input}
386 onChange={(event) => {
387 setInput(event.target.value);
388 if (error) setError(null);
389 }}
390 onKeyDown={(event) => {
391 if (event.key !== "Enter") return;
392 event.preventDefault();
393 handleAdd();
394 }}
395 placeholder={driverKind ? CUSTOM_MODEL_PLACEHOLDER_BY_KIND[driverKind] : "model-slug"}
396 spellCheck={false}
397 />
398 <Button className="shrink-0" variant="outline" onClick={handleAdd}>
399 <PlusIcon className="size-3.5" />
400 Add
401 </Button>
402 </div>
403​
404 {error ? <p className="mt-2 text-xs text-destructive">{error}</p> : null}
405 </div>
406 );