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

ProviderModelsSection.tsx

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