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