Open History to see the last commit
1"use client";
2
3import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
4import * as Option from "effect/Option";
5import * as Schema from "effect/Schema";
6import {
7 isSecretSetting,
8 type ProviderSettingsFormAnnotation,
9 type ProviderSettingsFormControl,
10 type ProviderSettingsFormOption,
11 type ProviderSettingsFormSchemaAnnotation,
12} from "@t3tools/contracts";
13import { PlusIcon, XIcon } from "lucide-react";
14
15import { cn } from "../../lib/utils";
16import { Button } from "../ui/button";
17import { DraftInput } from "../ui/draft-input";
18import { Input } from "../ui/input";
19import { SecretInput } from "./SecretInput";
20import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
21import { Switch } from "../ui/switch";
22import { Textarea } from "../ui/textarea";
23import type { ProviderClientDefinition } from "@t3tools/provider-core/client";
24
25/** What the form reads from a definition: an agent provider's, or a source control host's. */
26export type SettingsFormDefinition = Pick<ProviderClientDefinition, "settingsSchema"> & {
27 readonly driverKind?: ProviderClientDefinition["driverKind"];
28};
29import { SettingsRow } from "./settingsLayout";
30
31export interface ProviderSettingsFieldModel {
32 readonly key: string;
33 readonly control: ProviderSettingsFormControl;
34 readonly label: string;
35 readonly description?: string | undefined;
36 readonly placeholder?: string | undefined;
37 readonly clearWhenEmpty: "omit" | "persist";
38 /** Kept in the server's secret store: a saved value arrives as `SECRET_REDACTED` and never shows. */
39 readonly secret?: boolean | undefined;
40 readonly defaultBooleanValue?: boolean | undefined;
41 /** Choices for a `select` control. The first entry is the default. */
42 readonly options?: ReadonlyArray<ProviderSettingsFormOption> | undefined;
43}
44
45function titleizeFieldKey(key: string): string {
46 return key
47 .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
48 .replace(/[-_]+/g, " ")
49 .replace(/^./, (char) => char.toUpperCase());
50}
51
52function readFieldAnnotations(
53 fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string],
54) {
55 return Schema.resolveAnnotationsKey(fieldSchema) ?? Schema.resolveAnnotations(fieldSchema);
56}
57
58function readFieldAnnotationString(
59 fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string],
60 key: "title" | "description",
61): string | undefined {
62 const annotations = readFieldAnnotations(fieldSchema);
63 const value = annotations?.[key];
64 return typeof value === "string" ? value : undefined;
65}
66
67function readProviderSettingsFormAnnotation(
68 fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string],
69): ProviderSettingsFormAnnotation {
70 const annotation = readFieldAnnotations(fieldSchema)?.providerSettingsForm;
71 return annotation ?? {};
72}
73
74function readProviderSettingsFormSchemaAnnotation(
75 definition: SettingsFormDefinition,
76): ProviderSettingsFormSchemaAnnotation {
77 return Schema.resolveAnnotations(definition.settingsSchema)?.providerSettingsFormSchema ?? {};
78}
79
80function readFieldBooleanDefault(
81 fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string],
82): boolean | undefined {
83 const decodeDefault = Schema.decodeUnknownOption(fieldSchema as Schema.Decoder<unknown>);
84 const decoded = decodeDefault(undefined);
85 return Option.isSome(decoded) && typeof decoded.value === "boolean" ? decoded.value : undefined;
86}
87
88export function deriveProviderSettingsFields(
89 definition: SettingsFormDefinition,
90 value?: unknown,
91): ReadonlyArray<ProviderSettingsFieldModel> {
92 const isLocalAcp =
93 definition.driverKind === "acpRegistry" &&
94 readProviderConfigString(value, "source") === "local";
95 const schemaAnnotation = readProviderSettingsFormSchemaAnnotation(definition);
96 const orderedKeys = new Map(
97 (schemaAnnotation.order ?? []).map((key, index) => [key, index] as const),
98 );
99 const orderFallbackOffset = orderedKeys.size;
100
101 return Object.keys(definition.settingsSchema.fields)
102 .map((key, index) => ({ key, index }))
103 .toSorted((left, right) => {
104 return (
105 (orderedKeys.get(left.key) ?? orderFallbackOffset + left.index) -
106 (orderedKeys.get(right.key) ?? orderFallbackOffset + right.index)
107 );
108 })
109 .flatMap(({ key }) => {
110 const fieldSchema = definition.settingsSchema.fields[key]!;
111 const formAnnotation = readProviderSettingsFormAnnotation(fieldSchema);
112 if (formAnnotation.hidden) return [];
113 if (isLocalAcp && key !== "source" && key !== "commandPath") return [];
114
115 const annotatedTitle = readFieldAnnotationString(fieldSchema, "title");
116 const annotatedDescription = readFieldAnnotationString(fieldSchema, "description");
117 return [
118 {
119 key,
120 control: formAnnotation.control ?? "text",
121 label:
122 isLocalAcp && key === "commandPath"
123 ? "Executable"
124 : (annotatedTitle ?? titleizeFieldKey(key)),
125 ...(isLocalAcp && key === "commandPath"
126 ? { description: "Executable name or path on this environment." }
127 : annotatedDescription !== undefined
128 ? { description: annotatedDescription }
129 : {}),
130 ...(isLocalAcp && key === "commandPath"
131 ? { placeholder: "e.g. dsh" }
132 : formAnnotation.placeholder !== undefined
133 ? { placeholder: formAnnotation.placeholder }
134 : {}),
135 clearWhenEmpty: formAnnotation.clearWhenEmpty ?? "omit",
136 ...(isSecretSetting(fieldSchema) ? { secret: true } : {}),
137 ...(formAnnotation.control === "switch"
138 ? { defaultBooleanValue: readFieldBooleanDefault(fieldSchema) }
139 : {}),
140 ...(formAnnotation.control === "select" && formAnnotation.options
141 ? { options: formAnnotation.options }
142 : {}),
143 } satisfies ProviderSettingsFieldModel,
144 ];
145 });
146}
147
148let commandArgumentDraftId = 0;
149const makeCommandArgumentDraftRow = (value: string) => ({
150 id: `provider-argument-${commandArgumentDraftId++}`,
151 value,
152});
153
154function commandArgumentsEqual(left: ReadonlyArray<string>, right: ReadonlyArray<string>) {
155 return left.length === right.length && left.every((argument, index) => argument === right[index]);
156}
157
158function ProviderCommandArguments({
159 value,
160 onChange,
161}: Pick<ProviderSettingsFormProps, "value" | "onChange">) {
162 const args = useMemo(() => {
163 const configured =
164 value !== null && typeof value === "object"
165 ? (value as Record<string, unknown>).commandArgs
166 : undefined;
167 return Array.isArray(configured)
168 ? configured.filter((argument): argument is string => typeof argument === "string")
169 : [];
170 }, [value]);
171 const [rows, setRows] = useState(() => args.map(makeCommandArgumentDraftRow));
172 const rowsRef = useRef(rows);
173 const previousArgsRef = useRef(args);
174 const lastPublishedArgsRef = useRef<ReadonlyArray<string> | undefined>(undefined);
175
176 useEffect(() => {
177 const previousArgs = previousArgsRef.current;
178 const lastPublishedArgs = lastPublishedArgsRef.current;
179 previousArgsRef.current = args;
180 lastPublishedArgsRef.current = undefined;
181 if (
182 commandArgumentsEqual(previousArgs, args) ||
183 (lastPublishedArgs !== undefined && commandArgumentsEqual(lastPublishedArgs, args))
184 )
185 return;
186 const nextRows = args.map(makeCommandArgumentDraftRow);
187 rowsRef.current = nextRows;
188 setRows(nextRows);
189 }, [args]);
190
191 const updateArguments = (nextRows: typeof rows) => {
192 rowsRef.current = nextRows;
193 setRows(nextRows);
194 const next = nextRows.map((row) => row.value);
195 lastPublishedArgsRef.current = next;
196 const config =
197 value !== null && typeof value === "object" ? { ...(value as Record<string, unknown>) } : {};
198 onChange({ ...config, commandArgs: next });
199 };
200
201 return (
202 <SettingsRow
203 title="Arguments"
204 description="One literal argument per row, in launch order."
205 control={
206 <Button
207 type="button"
208 size="sm"
209 variant="outline"
210 onClick={() => updateArguments([...rowsRef.current, makeCommandArgumentDraftRow("")])}
211 >
212 <PlusIcon />
213 Add argument
214 </Button>
215 }
216 >
217 {rows.length > 0 ? (
218 <div className="mt-3 min-w-0 space-y-2 pb-2">
219 {rows.map((argument, index) => (
220 <div key={argument.id} className="flex min-w-0 items-center gap-1.5">
221 <DraftInput
222 size="sm"
223 font="mono"
224 value={argument.value}
225 onCommit={(next) =>
226 updateArguments(
227 rowsRef.current.map((current) =>
228 current.id === argument.id ? { ...current, value: next } : current,
229 ),
230 )
231 }
232 aria-label={`Argument ${index + 1}`}
233 spellCheck={false}
234 />
235 <Button
236 type="button"
237 size="icon-micro"
238 variant="ghost-destructive"
239 onClick={() =>
240 updateArguments(rowsRef.current.filter((current) => current.id !== argument.id))
241 }
242 aria-label={`Remove argument ${index + 1}`}
243 >
244 <XIcon />
245 </Button>
246 </div>
247 ))}
248 </div>
249 ) : null}
250 </SettingsRow>
251 );
252}
253
254function readProviderConfigString(config: unknown, key: string): string {
255 if (config === null || typeof config !== "object") return "";
256 const value = (config as Record<string, unknown>)[key];
257 return typeof value === "string" ? value : "";
258}
259
260function readProviderConfigBoolean(config: unknown, key: string, defaultValue = false): boolean {
261 if (config === null || typeof config !== "object") return defaultValue;
262 const value = (config as Record<string, unknown>)[key];
263 return typeof value === "boolean" ? value : defaultValue;
264}
265
266export function nextProviderConfigWithFieldValue(
267 config: unknown,
268 field: ProviderSettingsFieldModel,
269 value: string | boolean,
270): Record<string, unknown> | undefined {
271 const base: Record<string, unknown> =
272 config !== null && typeof config === "object" ? { ...(config as Record<string, unknown>) } : {};
273
274 if (typeof value === "boolean") {
275 const emptyBooleanValue = field.defaultBooleanValue ?? false;
276 if (field.clearWhenEmpty === "omit" && value === emptyBooleanValue) {
277 delete base[field.key];
278 } else {
279 base[field.key] = value;
280 }
281 return Object.keys(base).length > 0 ? base : undefined;
282 }
283
284 const trimmed = value.trim();
285 if (field.clearWhenEmpty === "omit" && trimmed.length === 0) {
286 delete base[field.key];
287 } else {
288 base[field.key] = value;
289 }
290 return Object.keys(base).length > 0 ? base : undefined;
291}
292
293interface ProviderSettingsFormProps {
294 readonly definition: SettingsFormDefinition;
295 readonly value: unknown;
296 readonly idPrefix: string;
297 /**
298 * `card` stacks label over control, `dialog` is the compact wizard layout,
299 * and `settings` renders the shared settings row treatment.
300 */
301 readonly variant: "card" | "dialog" | "settings";
302 readonly onChange: (nextConfig: Record<string, unknown> | undefined) => void;
303}
304
305/** Stores the default choice as an omitted key so unchanged configs stay small. */
306function ProviderSettingsSelect({
307 field,
308 value,
309 inputId,
310 size,
311 className,
312 onChange,
313}: {
314 readonly field: ProviderSettingsFieldModel;
315 readonly value: unknown;
316 readonly inputId: string;
317 readonly size: "sm" | "xs";
318 readonly className?: string | undefined;
319 readonly onChange: ProviderSettingsFormProps["onChange"];
320}) {
321 const options = field.options ?? [];
322 const fallback = options[0]?.value ?? "";
323 const current = readProviderConfigString(value, field.key) || fallback;
324 const label = options.find((option) => option.value === current)?.label ?? current;
325 return (
326 <Select
327 value={current}
328 onValueChange={(next) => {
329 if (typeof next !== "string") return;
330 onChange(nextProviderConfigWithFieldValue(value, field, next === fallback ? "" : next));
331 }}
332 >
333 <SelectTrigger id={inputId} size={size} className={className} aria-label={field.label}>
334 <SelectValue>{label}</SelectValue>
335 </SelectTrigger>
336 <SelectPopup align="start" alignItemWithTrigger={false}>
337 {options.map((option) => (
338 <SelectItem key={option.value} value={option.value}>
339 {option.label}
340 </SelectItem>
341 ))}
342 </SelectPopup>
343 </Select>
344 );
345}
346
347function FieldFrame(props: {
348 readonly variant: ProviderSettingsFormProps["variant"];
349 readonly children: ReactNode;
350}) {
351 if (props.variant === "card") {
352 return <div>{props.children}</div>;
353 }
354 return <div className="grid gap-1.5">{props.children}</div>;
355}
356
357interface ProviderSettingsFieldRowProps {
358 readonly field: ProviderSettingsFieldModel;
359 readonly value: unknown;
360 readonly idPrefix: string;
361 readonly variant: ProviderSettingsFormProps["variant"];
362 readonly onChange: ProviderSettingsFormProps["onChange"];
363}
364
365function ProviderSettingsFieldRow({
366 field,
367 value,
368 idPrefix,
369 variant,
370 onChange,
371}: ProviderSettingsFieldRowProps) {
372 const inputId = `${idPrefix}-${field.key}`;
373 const descriptionClassName =
374 variant === "dialog"
375 ? "text-2xs text-muted-foreground"
376 : "mt-1 block text-xs text-muted-foreground";
377 const label = <span className="text-xs font-medium text-foreground">{field.label}</span>;
378 const description = field.description ? (
379 <span className={descriptionClassName}>{field.description}</span>
380 ) : null;
381
382 if (variant === "settings") {
383 const descriptionId = field.description ? `${inputId}-description` : undefined;
384 const control =
385 field.control === "switch" ? (
386 <Switch
387 checked={readProviderConfigBoolean(value, field.key, field.defaultBooleanValue)}
388 onCheckedChange={(checked) =>
389 onChange(nextProviderConfigWithFieldValue(value, field, Boolean(checked)))
390 }
391 aria-label={field.label}
392 aria-describedby={descriptionId}
393 />
394 ) : field.control === "select" ? (
395 <ProviderSettingsSelect
396 field={field}
397 value={value}
398 inputId={inputId}
399 size="sm"
400 className="w-full max-w-full @min-[32rem]/settings-row:w-56"
401 onChange={onChange}
402 />
403 ) : field.control === "textarea" ? (
404 <Textarea
405 id={inputId}
406 aria-describedby={descriptionId}
407 className="w-full max-w-full @min-[32rem]/settings-row:w-[min(24rem,50cqw)]"
408 value={readProviderConfigString(value, field.key)}
409 onChange={(event) =>
410 onChange(nextProviderConfigWithFieldValue(value, field, event.target.value))
411 }
412 placeholder={field.placeholder}
413 spellCheck={false}
414 />
415 ) : field.secret ? (
416 <SecretInput
417 id={inputId}
418 aria-describedby={descriptionId}
419 size="sm"
420 className="w-full max-w-full @min-[32rem]/settings-row:w-56"
421 configured={readProviderConfigString(value, field.key).length > 0}
422 value=""
423 onCommit={(next) => onChange(nextProviderConfigWithFieldValue(value, field, next))}
424 />
425 ) : (
426 <DraftInput
427 id={inputId}
428 aria-describedby={descriptionId}
429 size="sm"
430 className="w-full max-w-full @min-[32rem]/settings-row:w-56"
431 type={field.control === "password" ? "password" : undefined}
432 autoComplete={field.control === "password" ? "off" : undefined}
433 value={readProviderConfigString(value, field.key)}
434 placeholder={field.placeholder}
435 onCommit={(next) => {
436 onChange(nextProviderConfigWithFieldValue(value, field, next));
437 }}
438 spellCheck={false}
439 />
440 );
441
442 return (
443 <SettingsRow
444 title={
445 field.control === "switch" ? field.label : <label htmlFor={inputId}>{field.label}</label>
446 }
447 description={
448 field.description ? <span id={descriptionId}>{field.description}</span> : undefined
449 }
450 control={control}
451 />
452 );
453 }
454
455 if (field.control === "switch") {
456 return (
457 <FieldFrame variant={variant}>
458 <div className="flex items-center justify-between gap-3">
459 <div className="min-w-0">
460 {label}
461 {description}
462 </div>
463 <Switch
464 checked={readProviderConfigBoolean(value, field.key, field.defaultBooleanValue)}
465 onCheckedChange={(checked) =>
466 onChange(nextProviderConfigWithFieldValue(value, field, Boolean(checked)))
467 }
468 aria-label={field.label}
469 />
470 </div>
471 </FieldFrame>
472 );
473 }
474
475 if (field.control === "select") {
476 return (
477 <FieldFrame variant={variant}>
478 <label htmlFor={inputId} className={cn(variant === "card" && "block")}>
479 {label}
480 <ProviderSettingsSelect
481 field={field}
482 value={value}
483 inputId={inputId}
484 size="sm"
485 className={cn("w-full", variant === "card" && "mt-1.5")}
486 onChange={onChange}
487 />
488 {description}
489 </label>
490 </FieldFrame>
491 );
492 }
493
494 if (field.control === "textarea") {
495 return (
496 <FieldFrame variant={variant}>
497 <label htmlFor={inputId} className={cn(variant === "card" && "block")}>
498 {label}
499 <Textarea
500 id={inputId}
501 className={cn(variant === "card" && "mt-1.5")}
502 value={readProviderConfigString(value, field.key)}
503 onChange={(event) =>
504 onChange(nextProviderConfigWithFieldValue(value, field, event.target.value))
505 }
506 placeholder={field.placeholder}
507 spellCheck={false}
508 />
509 {description}
510 </label>
511 </FieldFrame>
512 );
513 }
514
515 const type = field.control === "password" ? "password" : undefined;
516 const BufferedInput = field.secret ? SecretInput : DraftInput;
517 const ControlledInput = field.secret ? SecretInput : Input;
518 return (
519 <FieldFrame variant={variant}>
520 <label htmlFor={inputId} className={cn(variant === "card" && "block")}>
521 {label}
522 {variant === "card" ? (
523 <BufferedInput
524 id={inputId}
525 size="sm"
526 className="mt-1.5"
527 type={field.secret ? undefined : type}
528 autoComplete={!field.secret && field.control === "password" ? "off" : undefined}
529 value={readProviderConfigString(value, field.key)}
530 onCommit={(next) => onChange(nextProviderConfigWithFieldValue(value, field, next))}
531 placeholder={field.placeholder}
532 spellCheck={false}
533 />
534 ) : (
535 <ControlledInput
536 id={inputId}
537 type={field.secret ? undefined : type}
538 autoComplete={!field.secret && field.control === "password" ? "off" : undefined}
539 value={readProviderConfigString(value, field.key)}
540 onChange={(event) =>
541 onChange(nextProviderConfigWithFieldValue(value, field, event.target.value))
542 }
543 placeholder={field.placeholder}
544 spellCheck={false}
545 />
546 )}
547 {description}
548 </label>
549 </FieldFrame>
550 );
551}
552
553export function ProviderSettingsForm({
554 definition,
555 value,
556 idPrefix,
557 variant,
558 onChange,
559}: ProviderSettingsFormProps) {
560 const fields = useMemo(
561 () => deriveProviderSettingsFields(definition, value),
562 [definition, value],
563 );
564 const isLocalAcp =
565 definition.driverKind === "acpRegistry" &&
566 readProviderConfigString(value, "source") === "local";
567
568 if (fields.length === 0) {
569 return null;
570 }
571
572 return (
573 <>
574 {fields.map((field) => (
575 <ProviderSettingsFieldRow
576 key={field.key}
577 field={field}
578 value={value}
579 idPrefix={idPrefix}
580 variant={variant}
581 onChange={onChange}
582 />
583 ))}
584 {isLocalAcp ? <ProviderCommandArguments value={value} onChange={onChange} /> : null}
585 </>
586 );
587}