The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 407 lines 13.7 KB
Raw
1 import { PlusIcon, XIcon } from "lucide-react";
2 import { T, useGT, useMessages } from "gt-react";
3 import { useState, type SetStateAction } from "react";
4 import type { ProviderDriverKind, ServerProviderModel } from "@t3tools/contracts";
5 import type { CustomModelDefinition } from "@t3tools/shared/model";
6
7 import { cn } from "../../lib/utils";
8 import { Button } from "../ui/button";
9 import { Input } from "../ui/input";
10 import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
11 import { Switch } from "../ui/switch";
12 import {
13 DESCRIPTOR_PRESETS_BY_KIND,
14 type CustomModelDraft,
15 type EditorChoice,
16 type EditorDescriptor,
17 choiceFromPreset,
18 definitionFromDraft,
19 descriptorFromPreset,
20 descriptorsFromCapabilities,
21 draftFromDefinition,
22 emptyEditorChoice,
23 emptyEditorDescriptor,
24 validateDraft,
25 } from "./customModelEditor.logic";
26
27 const CUSTOM_ID_VALUE = "__custom__";
28 const START_FROM_NONE = "__none__";
29
30 interface CustomModelEditorProps {
31 readonly instanceId: string;
32 readonly driverKind: ProviderDriverKind | null;
33 readonly entry: CustomModelDefinition;
34 readonly builtInModels: ReadonlyArray<ServerProviderModel>;
35 readonly onSave: (next: CustomModelDefinition) => void;
36 readonly onCancel: () => void;
37 readonly onDraftChange: () => void;
38 }
39
40 export function CustomModelEditor({
41 instanceId,
42 driverKind,
43 entry,
44 builtInModels,
45 onSave,
46 onCancel,
47 onDraftChange,
48 }: CustomModelEditorProps) {
49 const gt = useGT();
50 const m = useMessages();
51 const [draft, setDraft] = useState<CustomModelDraft>(() => draftFromDefinition(entry));
52 const [error, setError] = useState<string | null>(null);
53 const updateDraft = (next: SetStateAction<CustomModelDraft>) => {
54 onDraftChange();
55 setDraft(next);
56 };
57 const presets = (driverKind ? (DESCRIPTOR_PRESETS_BY_KIND[driverKind] ?? []) : []).map(
58 (preset) => ({
59 ...preset,
60 label: m(preset.label),
61 ...(preset.choices
62 ? { choices: preset.choices.map((choice) => ({ ...choice, label: m(choice.label) })) }
63 : {}),
64 }),
65 );
66 const startFromCandidates = builtInModels.filter(
67 (model) => (model.capabilities?.optionDescriptors?.length ?? 0) > 0,
68 );
69 const domId = (suffix: string) => `provider-instance-${instanceId}-custom-model-${suffix}`;
70
71 const updateDescriptor = (key: string, patch: Partial<EditorDescriptor>) => {
72 setError(null);
73 updateDraft((current) => ({
74 ...current,
75 descriptors: current.descriptors.map((descriptor) =>
76 descriptor.key === key ? { ...descriptor, ...patch } : descriptor,
77 ),
78 }));
79 };
80
81 const updateChoice = (descriptorKey: string, choiceKey: string, patch: Partial<EditorChoice>) => {
82 setError(null);
83 updateDraft((current) => ({
84 ...current,
85 descriptors: current.descriptors.map((descriptor) => {
86 if (descriptor.key !== descriptorKey) return descriptor;
87 return {
88 ...descriptor,
89 choices: descriptor.choices.map((choice) => {
90 if (choice.key === choiceKey) return { ...choice, ...patch };
91 return patch.isDefault ? { ...choice, isDefault: false } : choice;
92 }),
93 };
94 }),
95 }));
96 };
97
98 const removeDescriptor = (key: string) => {
99 setError(null);
100 updateDraft((current) => ({
101 ...current,
102 descriptors: current.descriptors.filter((descriptor) => descriptor.key !== key),
103 }));
104 };
105
106 const addDescriptor = (descriptor: EditorDescriptor) => {
107 setError(null);
108 updateDraft((current) => ({ ...current, descriptors: [...current.descriptors, descriptor] }));
109 };
110
111 const applyPresetId = (descriptor: EditorDescriptor, value: string | null) => {
112 if (value === null) return;
113 if (value === CUSTOM_ID_VALUE) {
114 updateDescriptor(descriptor.key, { id: "" });
115 return;
116 }
117 const preset = presets.find((candidate) => candidate.id === value);
118 if (!preset) return;
119 updateDescriptor(descriptor.key, {
120 id: preset.id,
121 label: preset.label,
122 type: preset.type,
123 choices: (preset.choices ?? []).map(choiceFromPreset),
124 currentBooleanValue: undefined,
125 description: undefined,
126 });
127 };
128
129 const handleStartFrom = (slug: string | null) => {
130 if (slug === null || slug === START_FROM_NONE) return;
131 const model = startFromCandidates.find((candidate) => candidate.slug === slug);
132 if (!model) return;
133 setError(null);
134 updateDraft((current) => ({
135 ...current,
136 descriptors: descriptorsFromCapabilities(model.capabilities, driverKind),
137 }));
138 };
139
140 const handleSave = () => {
141 const problem = validateDraft(draft, m);
142 if (problem) {
143 setError(problem);
144 return;
145 }
146 onSave(definitionFromDraft(draft));
147 };
148
149 const idSelectValue = (descriptor: EditorDescriptor) =>
150 presets.some((preset) => preset.id === descriptor.id) ? descriptor.id : CUSTOM_ID_VALUE;
151
152 const renderChoice = (descriptor: EditorDescriptor, choice: EditorChoice) => (
153 <div key={choice.key} className="flex items-center gap-2">
154 <Input
155 size="compact"
156 value={choice.id}
157 onChange={(event) => updateChoice(descriptor.key, choice.key, { id: event.target.value })}
158 placeholder={gt("value", { $context: "placeholder for a choice's stored value" })}
159 font="mono"
160 className="w-28"
161 spellCheck={false}
162 aria-label={gt("Choice value")}
163 />
164 <Input
165 size="compact"
166 value={choice.label}
167 onChange={(event) =>
168 updateChoice(descriptor.key, choice.key, { label: event.target.value })
169 }
170 placeholder={gt("Label", { $context: "noun, display name" })}
171 className="min-w-0 flex-1"
172 aria-label={gt("Choice label")}
173 />
174 <label className="flex shrink-0 items-center gap-1.5 text-2xs text-muted-foreground">
175 <Switch
176 size="sm"
177 checked={choice.isDefault}
178 onCheckedChange={(checked) =>
179 updateChoice(descriptor.key, choice.key, { isDefault: checked })
180 }
181 aria-label={gt("Default choice")}
182 />
183 {gt("Default", { $context: "marks the default choice" })}
184 </label>
185 <Button
186 size="icon-micro"
187 variant="ghost-muted"
188 aria-label={gt("Remove choice")}
189 onClick={() =>
190 updateDescriptor(descriptor.key, {
191 choices: descriptor.choices.filter((candidate) => candidate.key !== choice.key),
192 })
193 }
194 >
195 <XIcon className="size-3" />
196 </Button>
197 </div>
198 );
199
200 const renderDescriptor = (descriptor: EditorDescriptor, index: number) => (
201 <div
202 key={descriptor.key}
203 className="flex flex-col gap-2 rounded-md border border-border/60 bg-background/40 p-2.5"
204 >
205 <div className="flex flex-wrap items-center gap-2">
206 <span className="w-14 shrink-0 text-2xs text-muted-foreground">
207 {gt("Option {number}", { number: index + 1 })}
208 </span>
209 {presets.length > 0 ? (
210 <Select
211 value={idSelectValue(descriptor)}
212 onValueChange={(value) => applyPresetId(descriptor, value)}
213 >
214 <SelectTrigger size="compact" className="w-40" aria-label={gt("Option id")}>
215 <SelectValue>
216 {idSelectValue(descriptor) === CUSTOM_ID_VALUE ? gt("Custom…") : descriptor.id}
217 </SelectValue>
218 </SelectTrigger>
219 <SelectPopup align="start" alignItemWithTrigger={false}>
220 {presets.map((preset) => (
221 <SelectItem key={preset.id} value={preset.id}>
222 <span className="flex items-baseline gap-2">
223 <code className="font-mono text-xs">{preset.id}</code>
224 <span className="text-muted-foreground">{preset.label}</span>
225 </span>
226 </SelectItem>
227 ))}
228 <SelectItem value={CUSTOM_ID_VALUE}>
229 <T>Custom…</T>
230 </SelectItem>
231 </SelectPopup>
232 </Select>
233 ) : null}
234 {idSelectValue(descriptor) === CUSTOM_ID_VALUE ? (
235 <Input
236 size="compact"
237 value={descriptor.id}
238 onChange={(event) => updateDescriptor(descriptor.key, { id: event.target.value })}
239 placeholder="optionId"
240 font="mono"
241 className="w-36"
242 spellCheck={false}
243 aria-label={gt("Option id")}
244 />
245 ) : null}
246 <Input
247 size="compact"
248 value={descriptor.label}
249 onChange={(event) => updateDescriptor(descriptor.key, { label: event.target.value })}
250 placeholder={gt("Label", { $context: "noun, display name" })}
251 className="min-w-0 flex-1"
252 aria-label={gt("Option label")}
253 />
254 <Select
255 value={descriptor.type}
256 onValueChange={(value) =>
257 updateDescriptor(descriptor.key, { type: value === "boolean" ? "boolean" : "select" })
258 }
259 >
260 <SelectTrigger size="compact" className="w-24" aria-label={gt("Option type")}>
261 <SelectValue>
262 {descriptor.type === "boolean"
263 ? gt("Toggle", { $context: "noun, on/off option type" })
264 : gt("Choices")}
265 </SelectValue>
266 </SelectTrigger>
267 <SelectPopup align="end" alignItemWithTrigger={false}>
268 <SelectItem value="select">
269 <T>Choices</T>
270 </SelectItem>
271 <SelectItem value="boolean">
272 {gt("Toggle", { $context: "noun, on/off option type" })}
273 </SelectItem>
274 </SelectPopup>
275 </Select>
276 <Button
277 size="icon-micro"
278 variant="ghost-muted"
279 aria-label={gt("Remove option {number}", { number: index + 1 })}
280 onClick={() => removeDescriptor(descriptor.key)}
281 >
282 <XIcon className="size-3" />
283 </Button>
284 </div>
285 {descriptor.type === "select" ? (
286 <div className="flex flex-col gap-1.5 pl-16">
287 {descriptor.choices.map((choice) => renderChoice(descriptor, choice))}
288 <Button
289 type="button"
290 size="xs"
291 variant="ghost-muted"
292 className="-ml-2 self-start"
293 onClick={() =>
294 updateDescriptor(descriptor.key, {
295 choices: [...descriptor.choices, emptyEditorChoice()],
296 })
297 }
298 >
299 <PlusIcon className="size-3" />
300 <T>Add choice</T>
301 </Button>
302 </div>
303 ) : null}
304 </div>
305 );
306
307 return (
308 <div
309 className="mx-2 mt-1 mb-2 flex flex-col gap-3 rounded-md border border-border bg-muted/20 p-3"
310 onKeyDown={(event) => {
311 if (event.key === "Escape") {
312 event.preventDefault();
313 onCancel();
314 }
315 }}
316 >
317 <div className="flex flex-col gap-1">
318 <label htmlFor={domId("name")} className="text-xs text-muted-foreground">
319 <T>Display name</T>
320 </label>
321 <Input
322 id={domId("name")}
323 size="sm"
324 autoFocus
325 value={draft.name}
326 onChange={(event) => updateDraft((current) => ({ ...current, name: event.target.value }))}
327 placeholder={draft.slug}
328 className="sm:w-72"
329 spellCheck={false}
330 />
331 </div>
332
333 <div className="flex flex-col gap-2">
334 <div className="flex flex-wrap items-center justify-between gap-2">
335 <span className="text-xs text-muted-foreground">
336 <T>Options shown in the composer</T>
337 </span>
338 {startFromCandidates.length > 0 ? (
339 <Select value={START_FROM_NONE} onValueChange={handleStartFrom}>
340 <SelectTrigger
341 size="compact"
342 className="w-44"
343 aria-label={gt("Copy options from a built-in model")}
344 >
345 <SelectValue>
346 <T>Copy from…</T>
347 </SelectValue>
348 </SelectTrigger>
349 <SelectPopup align="end" alignItemWithTrigger={false}>
350 {startFromCandidates.map((model) => (
351 <SelectItem key={model.slug} value={model.slug}>
352 {model.name}
353 </SelectItem>
354 ))}
355 </SelectPopup>
356 </Select>
357 ) : null}
358 </div>
359 {draft.descriptors.length === 0 ? (
360 <p className="text-xs text-muted-foreground/70">
361 <T>No custom options. The composer uses the provider's default options.</T>
362 </p>
363 ) : null}
364 {draft.descriptors.map(renderDescriptor)}
365 <div className="flex flex-wrap gap-1">
366 {presets
367 .filter(
368 (preset) => !draft.descriptors.some((descriptor) => descriptor.id === preset.id),
369 )
370 .map((preset) => (
371 <Button
372 key={preset.id}
373 type="button"
374 size="xs"
375 variant="ghost-muted"
376 className={cn("-ml-2 first:ml-0")}
377 onClick={() => addDescriptor(descriptorFromPreset(preset))}
378 >
379 <PlusIcon className="size-3" />
380 {preset.label}
381 </Button>
382 ))}
383 <Button
384 type="button"
385 size="xs"
386 variant="ghost-muted"
387 onClick={() => addDescriptor(emptyEditorDescriptor())}
388 >
389 <PlusIcon className="size-3" />
390 <T>Custom option</T>
391 </Button>
392 </div>
393 </div>
394
395 {error ? <p className="text-xs text-destructive">{error}</p> : null}
396
397 <div className="flex gap-2">
398 <Button size="sm" variant="outline" onClick={handleSave}>
399 {gt("Save", { $context: "verb" })}
400 </Button>
401 <Button size="sm" variant="ghost" onClick={onCancel}>
402 <T>Cancel</T>
403 </Button>
404 </div>
405 </div>
406 );
407 }