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

ProviderSettingsForm.tsx

974 lines35.1 KB

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 { msg, T, useGT, useMessages } from "gt-react";
16import { PlusIcon, XIcon } from "lucide-react";
17​
18import { m, type MessageResolver } from "../../i18n/messages";
19import { cn } from "../../lib/utils";
20import { Button } from "../ui/button";
21import { DraftInput } from "../ui/draft-input";
22import { Input } from "../ui/input";
23import { SecretInput } from "./SecretInput";
24import { SecretSourceInput, useSecretSources } from "./SecretSourceInput";
25import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
26import { Switch } from "../ui/switch";
27import { Textarea } from "../ui/textarea";
28import type { ProviderClientDefinition } from "@t3tools/provider-core/client";
29​
30export type SettingsFormDefinition = Pick<ProviderClientDefinition, "settingsSchema"> & {
31 readonly driverKind?: ProviderClientDefinition["driverKind"];
32};
33import { SettingsRow } from "./settingsLayout";
34​
35export interface ProviderSettingsFieldModel {
36 readonly key: string;
37 readonly control: ProviderSettingsFormControl;
38 readonly label: string;
39 readonly description?: string | undefined;
40 readonly placeholder?: string | undefined;
41 readonly clearWhenEmpty: "omit" | "persist";
42 /** Kept in the server's secret store: a saved value arrives as `SECRET_REDACTED` and never shows. */
43 readonly secret?: boolean | undefined;
44 /** Typed `SettingsSecretValue`: may name a secret provider reference instead of a value. */
45 readonly acceptsSecretReference?: boolean | undefined;
46 readonly defaultBooleanValue?: boolean | undefined;
47 /** Whether the field's schema decodes a typed string; one it rejects is never stored. */
48 readonly accepts?: ((value: string) => boolean) | undefined;
49​
50 readonly options?: ReadonlyArray<ProviderSettingsFormOption> | undefined;
52​
53function titleizeFieldKey(key: string): string {
54 return key
55 .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
56 .replace(/[-_]+/g, " ")
57 .replace(/^./, (char) => char.toUpperCase());
59​
60function readFieldAnnotations(
61 fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string],
62) {
63 return Schema.resolveAnnotationsKey(fieldSchema) ?? Schema.resolveAnnotations(fieldSchema);
65​
66function readFieldAnnotationString(
67 fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string],
68 key: "title" | "description",
69): string | undefined {
70 const annotations = readFieldAnnotations(fieldSchema);
71 const value = annotations?.[key];
72 return typeof value === "string" ? value : undefined;
74​
75function readProviderSettingsFormAnnotation(
76 fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string],
77): ProviderSettingsFormAnnotation {
78 const annotation = readFieldAnnotations(fieldSchema)?.providerSettingsForm;
79 return annotation ?? {};
81​
82function readProviderSettingsFormSchemaAnnotation(
83 definition: SettingsFormDefinition,
84): ProviderSettingsFormSchemaAnnotation {
85 return Schema.resolveAnnotations(definition.settingsSchema)?.providerSettingsFormSchema ?? {};
87​
88function readFieldBooleanDefault(
89 fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string],
90): boolean | undefined {
91 const decodeDefault = Schema.decodeUnknownOption(fieldSchema as Schema.Decoder<unknown>);
92 const decoded = decodeDefault(undefined);
93 return Option.isSome(decoded) && typeof decoded.value === "boolean" ? decoded.value : undefined;
95​
96function fieldAcceptsString(
97 fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string],
98): (value: string) => boolean {
99 const decode = Schema.decodeUnknownOption(fieldSchema as Schema.Decoder<unknown>);
100 return (value) => Option.isSome(decode(value));
102​
103// Field text authored in contracts and the provider and source-control packages, which the server
104// also imports. Keyed by that English; text not listed here shows as authored.
105const PACKAGE_FIELD_TEXT: ReadonlyMap<string, string> = new Map([
106 ["Binary path", msg("Binary path")],
107 ["CODEX_HOME path", msg("CODEX_HOME path")],
108 ["Shadow home path", msg("Shadow home path")],
109 ["Launch arguments", msg("Launch arguments")],
110 ["CLAUDE_CONFIG_DIR path", msg("CLAUDE_CONFIG_DIR path")],
111 ["Auto-compact after", msg("Auto-compact after")],
112 ["Compact idle threads", msg("Compact idle threads")],
113 ["Sign-in method", msg("Sign-in method")],
114 ["API key", msg("API key")],
115 ["GCP project", msg("GCP project")],
116 ["GCP location", msg("GCP location")],
117 ["ACP source", msg("ACP source")],
118 ["Registry agent ID", msg("Registry agent ID")],
119 ["Executable override", msg("Executable override")],
120 ["Authentication method", msg("Authentication method")],
121 ["Server URL", msg("Server URL")],
122 ["Server password", msg("Server password")],
123 ["Access token", msg("Access token")],
124 ["Atlassian account email", msg("Atlassian account email")],
125 ["API token", msg("API token")],
126 ["Token", msg("Token", { $context: "settings field, an access token" })],
127 [
128 "Path to the Codex binary used by this instance.",
129 msg("Path to the Codex binary used by this instance."),
130 ],
131 ["Custom Codex home and config directory.", msg("Custom Codex home and config directory.")],
132 [
133 "Account-specific Codex home. Keeps auth.json separate while sharing state from CODEX_HOME.",
134 msg(
135 "Account-specific Codex home. Keeps auth.json separate while sharing state from CODEX_HOME.",
136 ),
137 ],
138 [
139 "Additional CLI arguments passed to codex app-server on session start.",
140 msg("Additional CLI arguments passed to codex app-server on session start."),
141 ],
142 [
143 "Path to the Claude binary used by this instance.",
144 msg("Path to the Claude binary used by this instance."),
145 ],
146 [
147 "Custom Claude home and config directory. Keeps .claude.json and .claude separate.",
148 msg("Custom Claude home and config directory. Keeps .claude.json and .claude separate."),
149 ],
150 [
151 "Additional CLI arguments passed on session start.",
152 msg("Additional CLI arguments passed on session start."),
153 ],
154 [
155 "Compact after 100,000 to 1,000,000 tokens. Leave empty to use Claude's default.",
156 msg("Compact after 100,000 to 1,000,000 tokens. Leave empty to use Claude's default."),
157 ],
158 [
159 "When to compact an idle thread over 200,000 tokens: after you return, just before its prompt cache expires, or never. Overrides the default in Providers > Advanced.",
160 msg(
161 "When to compact an idle thread over 200,000 tokens: after you return, just before its prompt cache expires, or never. Overrides the default in Providers > Advanced.",
162 ),
163 ],
164 [
165 "Google account and Gemini Enterprise use your existing plan. Gemini API key and Agent Platform charge per use to your key or Google Cloud project.",
166 msg(
167 "Google account and Gemini Enterprise use your existing plan. Gemini API key and Agent Platform charge per use to your key or Google Cloud project.",
168 ),
169 ],
170 [
171 "Gemini or Vertex AI express key. Stored separately on the host.",
172 msg("Gemini or Vertex AI express key. Stored separately on the host."),
173 ],
174 [
175 "Required for Gemini Enterprise. Agent Platform uses it when no API key is set.",
176 msg("Required for Gemini Enterprise. Agent Platform uses it when no API key is set."),
177 ],
178 [
179 "Region for Gemini Enterprise or Agent Platform.",
180 msg("Region for Gemini Enterprise or Agent Platform."),
181 ],
182 [
183 "Custom ACP executable. Leave empty to select automatically.",
184 msg("Custom ACP executable. Leave empty to select automatically."),
185 ],
186 [
187 "Agent identifier from the official ACP Registry, for example 'devin'.",
188 msg("Agent identifier from the official ACP Registry, for example 'devin'."),
189 ],
190 [
191 "Executable on this environment. For registry agents, this overrides the distribution executable while keeping its arguments and environment.",
192 msg(
193 "Executable on this environment. For registry agents, this overrides the distribution executable while keeping its arguments and environment.",
194 ),
195 ],
196 [
197 "Optional ACP authentication method ID. By default, the first agent-managed method is selected.",
198 msg(
199 "Optional ACP authentication method ID. By default, the first agent-managed method is selected.",
200 ),
201 ],
202 [
203 "Path to the fx binary. All fx instances on this machine share its fx login.",
204 msg("Path to the fx binary. All fx instances on this machine share its fx login."),
205 ],
206 ["Path to the Grok CLI binary.", msg("Path to the Grok CLI binary.")],
207 ["Path to the Kiro CLI binary.", msg("Path to the Kiro CLI binary.")],
208 [
209 "Path to the Muse Code binary on this environment. Sign in with muse login on that host.",
210 msg("Path to the Muse Code binary on this environment. Sign in with muse login on that host."),
211 ],
212 ["Path to the OpenCode binary.", msg("Path to the OpenCode binary.")],
213 [
214 "Leave blank to let T3 Code spawn the server when needed.",
215 msg("Leave blank to let T3 Code spawn the server when needed."),
216 ],
217 ["Stored separately on the host.", msg("Stored separately on the host.")],
218 ["Path to the Pi coding agent binary.", msg("Path to the Pi coding agent binary.")],
219 [
220 "Additional CLI arguments passed to pi --mode rpc on session start.",
221 msg("Additional CLI arguments passed to pi --mode rpc on session start."),
222 ],
223 [
224 "Scoped to one repository, project, or workspace. Create it in that item's Bitbucket settings.",
225 msg(
226 "Scoped to one repository, project, or workspace. Create it in that item's Bitbucket settings.",
227 ),
228 ],
229 [
230 "With an API token instead of an access token.",
231 msg("With an API token instead of an access token."),
232 ],
233 [
234 "Reaches every repository your Atlassian account can. Give it read and write access to repositories and pull requests, plus read:user:bitbucket and read:workspace:bitbucket.",
235 msg(
236 "Reaches every repository your Atlassian account can. Give it read and write access to repositories and pull requests, plus read:user:bitbucket and read:workspace:bitbucket.",
237 ),
238 ],
239 [
240 "A git.cafe token, used before CAFE_TOKEN and the cafe login, so GitCafe works without the CLI signed in.",
241 msg(
242 "A git.cafe token, used before CAFE_TOKEN and the cafe login, so GitCafe works without the CLI signed in.",
243 ),
244 ],
245 ["e.g. --chrome", msg("e.g. --chrome")],
246 ["e.g. 300000", msg("e.g. 300000")],
247 ["Optional", msg("Optional", { $context: "placeholder of an optional settings field" })],
248 ["Automatic", msg("Automatic", { $context: "placeholder, chosen automatically when empty" })],
249 ["Registry default", msg("Registry default")],
250 ["When you return", msg("When you return")],
251 ["Before the cache expires (beta)", msg("Before the cache expires (beta)")],
252 ["Never", msg("Never", { $context: "option, never compact idle threads" })],
253 ["Use default", msg("Use default")],
254 ["Google account", msg("Google account")],
255 ["Gemini API key", msg("Gemini API key")],
256 ["Local command", msg("Local command")],
257]);
258​
259function packageFieldText(text: string, resolve: MessageResolver): string {
260 const entry = PACKAGE_FIELD_TEXT.get(text);
261 return entry === undefined ? text : resolve(entry);
263​
264/** An unset select shows, and acts as, its first option. */
265function readSelectValue(
266 config: unknown,
267 key: string,
268 options: ReadonlyArray<ProviderSettingsFormOption> | undefined,
269): string {
270 return readProviderConfigString(config, key) || (options?.[0]?.value ?? "");
272​
273function hasConfiguredValue(config: unknown, key: string): boolean {
274 if (config === null || typeof config !== "object") return false;
275 const value = (config as Record<string, unknown>)[key];
276 return value !== undefined && value !== "";
278​
279/**
280 * Without a `value`, lists every field. With one, a `visibleWhen` field is hidden only while empty:
281 * a leftover value still reaches the server, so it stays visible and clearable.
282 */
283export function deriveProviderSettingsFields(
284 definition: SettingsFormDefinition,
285 value?: unknown,
286 resolve: MessageResolver = m,
287): ReadonlyArray<ProviderSettingsFieldModel> {
288 const isLocalAcp =
289 definition.driverKind === "acpRegistry" &&
290 readProviderConfigString(value, "source") === "local";
291 const schemaAnnotation = readProviderSettingsFormSchemaAnnotation(definition);
292 const orderedKeys = new Map(
293 (schemaAnnotation.order ?? []).map((key, index) => [key, index] as const),
294 );
295 const orderFallbackOffset = orderedKeys.size;
296​
297 return Object.keys(definition.settingsSchema.fields)
298 .map((key, index) => ({ key, index }))
299 .toSorted((left, right) => {
300 return (
301 (orderedKeys.get(left.key) ?? orderFallbackOffset + left.index) -
302 (orderedKeys.get(right.key) ?? orderFallbackOffset + right.index)
303 );
304 })
305 .flatMap(({ key }) => {
306 const fieldSchema = definition.settingsSchema.fields[key]!;
307 const formAnnotation = readProviderSettingsFormAnnotation(fieldSchema);
308 if (formAnnotation.hidden) return [];
309 const visibleWhen = formAnnotation.visibleWhen;
310 const controller =
311 visibleWhen === undefined ? undefined : definition.settingsSchema.fields[visibleWhen.field];
312 if (
313 visibleWhen !== undefined &&
314 value !== undefined &&
315 !hasConfiguredValue(value, key) &&
316 !visibleWhen.values.includes(
317 readSelectValue(
318 value,
319 visibleWhen.field,
320 controller && readProviderSettingsFormAnnotation(controller).options,
321 ),
322 )
323 ) {
324 return [];
325 }
326 if (isLocalAcp && key !== "source" && key !== "commandPath") return [];
327​
328 const annotatedTitle = readFieldAnnotationString(fieldSchema, "title");
329 const annotatedDescription = readFieldAnnotationString(fieldSchema, "description");
330 return [
331 {
332 key,
333 control: formAnnotation.control ?? "text",
334 label:
335 isLocalAcp && key === "commandPath"
336 ? resolve(msg("Executable"))
337 : annotatedTitle !== undefined
338 ? packageFieldText(annotatedTitle, resolve)
339 : titleizeFieldKey(key),
340 ...(isLocalAcp && key === "commandPath"
341 ? { description: resolve(msg("Executable name or path on this environment.")) }
342 : annotatedDescription !== undefined
343 ? { description: packageFieldText(annotatedDescription, resolve) }
344 : {}),
345 ...(isLocalAcp && key === "commandPath"
346 ? { placeholder: resolve(msg("e.g. dsh")) }
347 : formAnnotation.placeholder !== undefined
348 ? { placeholder: packageFieldText(formAnnotation.placeholder, resolve) }
349 : {}),
350 clearWhenEmpty: formAnnotation.clearWhenEmpty ?? "omit",
351 ...(isSecretSetting(fieldSchema) ? { secret: true } : {}),
352 ...(acceptsSecretReference(fieldSchema) ? { acceptsSecretReference: true } : {}),
353 ...(formAnnotation.control === "switch"
354 ? { defaultBooleanValue: readFieldBooleanDefault(fieldSchema) }
355 : {}),
356 accepts: fieldAcceptsString(fieldSchema),
357 ...(formAnnotation.control === "select" && formAnnotation.options
358 ? {
359 options: formAnnotation.options.map((option) => ({
360 ...option,
361 label: packageFieldText(option.label, resolve),
362 })),
363 }
364 : {}),
365 } satisfies ProviderSettingsFieldModel,
366 ];
367 });
369​
370let commandArgumentDraftId = 0;
371/**
372 * Editable rows seeded from a configured value. `seen` is the value the rows
373 * were last reconciled against; `lastPublished` is what the rows last sent to
374 * the owner, so its echo does not reseed rows (and drop their ids) mid-edit.
375 */
376export interface RowsDraft<V, R> {
377 readonly rows: ReadonlyArray<R>;
378 readonly seen: V;
379 readonly lastPublished: V | undefined;
381​
382export function seedRowsDraft<V, R>(
383 value: V,
384 toRows: (value: V) => ReadonlyArray<R>,
385): RowsDraft<V, R> {
386 return { rows: toRows(value), seen: value, lastPublished: undefined };
388​
389/** Reseeds the rows when the configured value changes from outside this editor. */
390export function reconcileRowsDraft<V, R>(
391 draft: RowsDraft<V, R>,
392 incoming: V,
393 equal: (left: V, right: V) => boolean,
394 toRows: (value: V) => ReadonlyArray<R>,
395): RowsDraft<V, R> {
396 if (draft.seen === incoming || equal(draft.seen, incoming)) return draft;
397 const echo = draft.lastPublished !== undefined && equal(draft.lastPublished, incoming);
398 return { rows: echo ? draft.rows : toRows(incoming), seen: incoming, lastPublished: undefined };
400​
401const makeCommandArgumentDraftRow = (value: string) => ({
402 id: `provider-argument-${commandArgumentDraftId++}`,
403 value,
404});
405​
406const toCommandArgumentRows = (args: ReadonlyArray<string>) =>
407 args.map(makeCommandArgumentDraftRow);
408​
409function commandArgumentsEqual(left: ReadonlyArray<string>, right: ReadonlyArray<string>) {
410 return left.length === right.length && left.every((argument, index) => argument === right[index]);
412​
413function configuredCommandArgs(value: ProviderSettingsFormProps["value"]) {
414 const configured =
415 value !== null && typeof value === "object"
416 ? (value as Record<string, unknown>).commandArgs
417 : undefined;
418 return Array.isArray(configured)
419 ? configured.filter((argument): argument is string => typeof argument === "string")
420 : [];
422​
423function ProviderCommandArguments({
424 value,
425 onChange,
426 managedReason,
427}: Pick<ProviderSettingsFormProps, "value" | "onChange"> & {
428 readonly managedReason: string | undefined;
429}) {
430 const gt = useGT();
431 const args = configuredCommandArgs(value);
432 const [storedDraft, setDraft] = useState(() => seedRowsDraft(args, toCommandArgumentRows));
433 const draft = reconcileRowsDraft(storedDraft, args, commandArgumentsEqual, toCommandArgumentRows);
434 if (draft !== storedDraft) setDraft(draft);
435 const rows = draft.rows;
436​
437 const updateArguments = (nextRows: typeof rows) => {
438 const next = nextRows.map((row) => row.value);
439 setDraft({ rows: nextRows, seen: draft.seen, lastPublished: next });
440 const config =
441 value !== null && typeof value === "object" ? { ...(value as Record<string, unknown>) } : {};
442 onChange({ ...config, commandArgs: next });
443 };
444​
445 return (
446 <SettingsRow
447 title={gt("Arguments")}
448 description={gt("One literal argument per row, in launch order.")}
449 managed={managedReason}
450 control={
451 <Button
452 type="button"
453 size="sm"
454 variant="outline"
455 onClick={() => updateArguments([...rows, makeCommandArgumentDraftRow("")])}
456 >
457 <PlusIcon />
458 <T>Add argument</T>
459 </Button>
460 }
461 >
462 {rows.length > 0 ? (
463 <div className="mt-3 min-w-0 space-y-2 pb-2">
464 {rows.map((argument, index) =>
465 managedReason !== undefined ? (
466 <code key={argument.id} className="block min-w-0 truncate text-xs">
467 {argument.value}
468 </code>
469 ) : (
470 <div key={argument.id} className="flex min-w-0 items-center gap-1.5">
471 <DraftInput
472 size="sm"
473 font="mono"
474 value={argument.value}
475 onCommit={(next) =>
476 updateArguments(
477 rows.map((current) =>
478 current.id === argument.id ? { ...current, value: next } : current,
479 ),
480 )
481 }
482 aria-label={gt("Argument {number}", { number: index + 1 })}
483 spellCheck={false}
484 />
485 <Button
486 type="button"
487 size="icon-micro"
488 variant="ghost-destructive"
489 onClick={() =>
490 updateArguments(rows.filter((current) => current.id !== argument.id))
491 }
492 aria-label={gt("Remove argument {number}", { number: index + 1 })}
493 >
494 <XIcon />
495 </Button>
496 </div>
497 ),
498 )}
499 </div>
500 ) : null}
501 </SettingsRow>
502 );
504​
505function readProviderConfigString(config: unknown, key: string): string {
506 if (config === null || typeof config !== "object") return "";
507 const value = (config as Record<string, unknown>)[key];
508 return typeof value === "string" ? value : "";
510​
511function readProviderConfigBoolean(config: unknown, key: string, defaultValue = false): boolean {
512 if (config === null || typeof config !== "object") return defaultValue;
513 const value = (config as Record<string, unknown>)[key];
514 return typeof value === "boolean" ? value : defaultValue;
516​
517export function nextProviderConfigWithFieldValue(
518 config: unknown,
519 field: ProviderSettingsFieldModel,
520 value: string | boolean | SecretReference,
521): Record<string, unknown> | undefined {
522 const base: Record<string, unknown> =
523 config !== null && typeof config === "object" ? { ...(config as Record<string, unknown>) } : {};
524​
525 if (typeof value === "object") {
526 base[field.key] = value;
527 return base;
528 }
529​
530 if (typeof value === "boolean") {
531 const emptyBooleanValue = field.defaultBooleanValue ?? false;
532 if (field.clearWhenEmpty === "omit" && value === emptyBooleanValue) {
533 delete base[field.key];
534 } else {
535 base[field.key] = value;
536 }
537 return Object.keys(base).length > 0 ? base : undefined;
538 }
539​
540 const trimmed = value.trim();
541 if (field.clearWhenEmpty === "omit" && trimmed.length === 0) {
542 delete base[field.key];
543 } else if (field.accepts?.(value) !== false) {
544 base[field.key] = value;
545 }
546 return Object.keys(base).length > 0 ? base : undefined;
548​
549interface ProviderSettingsFormProps {
550 readonly definition: SettingsFormDefinition;
551 readonly value: unknown;
552 readonly idPrefix: string;
553 readonly variant: "card" | "dialog" | "settings";
554 readonly onChange: (nextConfig: Record<string, unknown> | undefined) => void;
555 /** Config keys an administrator's policy pins, shown inert with the reason. */
556 readonly managed?: { readonly keys: ReadonlySet<string>; readonly reason: string } | undefined;
557 /** Where the secret providers offered for `SettingsSecretValue` fields are configured. */
558 readonly environmentId?: EnvironmentId | undefined;
560​
561function SecretSettingsControl({
562 field,
563 value,
564 inputId,
565 descriptionId,
566 environmentId,
567 onChange,
568}: {
569 readonly field: ProviderSettingsFieldModel;
570 readonly value: unknown;
571 readonly inputId: string;
572 readonly descriptionId: string | undefined;
573 readonly environmentId: EnvironmentId;
574 readonly onChange: ProviderSettingsFormProps["onChange"];
575}) {
576 const gt = useGT();
577 const sources = useSecretSources(environmentId);
578 const saved =
579 value !== null && typeof value === "object"
580 ? (value as Record<string, unknown>)[field.key]
581 : undefined;
582 const reference = isSecretReference(saved) ? saved : undefined;
583 const configured = reference !== undefined || (typeof saved === "string" && saved.length > 0);
584 return (
585 <div className="flex w-full min-w-0 items-start gap-2 @min-[32rem]/settings-row:w-80">
586 <SecretSourceInput
587 id={inputId}
588 aria-describedby={descriptionId}
589 aria-label={field.label}
590 size="sm"
591 className="min-w-0 flex-1"
592 value={reference ?? ""}
593 configured={reference === undefined && configured}
594 sources={sources}
595 environmentId={environmentId}
596 onCommit={(next) => onChange(nextProviderConfigWithFieldValue(value, field, next))}
597 onSecretChange={(secret) =>
598 onChange(nextProviderConfigWithFieldValue(value, field, secret ?? ""))
599 }
600 />
601 {configured ? (
602 <Button
603 type="button"
604 size="icon-sm"
605 variant="ghost-destructive"
606 onClick={() => onChange(nextProviderConfigWithFieldValue(value, field, ""))}
607 aria-label={gt("Clear {field}", { field: field.label })}
608 >
609 <XIcon className="size-3.5" />
610 </Button>
611 ) : null}
612 </div>
613 );
615​
616function ProviderSettingsSelect({
617 field,
618 value,
619 inputId,
620 size,
621 className,
622 onChange,
623}: {
624 readonly field: ProviderSettingsFieldModel;
625 readonly value: unknown;
626 readonly inputId: string;
627 readonly size: "sm" | "xs";
628 readonly className?: string | undefined;
629 readonly onChange: ProviderSettingsFormProps["onChange"];
630}) {
631 const options = field.options ?? [];
632 const fallback = options[0]?.value ?? "";
633 const current = readSelectValue(value, field.key, options);
634 const label = options.find((option) => option.value === current)?.label ?? current;
635 return (
636 <Select
637 value={current}
638 onValueChange={(next) => {
639 if (typeof next !== "string") return;
640 onChange(nextProviderConfigWithFieldValue(value, field, next === fallback ? "" : next));
641 }}
642 >
643 <SelectTrigger id={inputId} size={size} className={className} aria-label={field.label}>
644 <SelectValue>{label}</SelectValue>
645 </SelectTrigger>
646 <SelectPopup align="start" alignItemWithTrigger={false}>
647 {options.map((option) => (
648 <SelectItem key={option.value} value={option.value}>
649 {option.label}
650 </SelectItem>
651 ))}
652 </SelectPopup>
653 </Select>
654 );
656​
657function ProviderSettingsTextInput({
658 field,
659 value,
660 inputId,
661 descriptionId,
662 onChange,
663}: {
664 readonly field: ProviderSettingsFieldModel;
665 readonly value: unknown;
666 readonly inputId: string;
667 readonly descriptionId: string | undefined;
668 readonly onChange: ProviderSettingsFormProps["onChange"];
669}) {
670 const [rejected, setRejected] = useState<string | null>(null);
671 return (
672 <div className="flex w-full min-w-0 flex-col gap-1 @min-[32rem]/settings-row:w-56">
673 <DraftInput
674 id={inputId}
675 aria-describedby={descriptionId}
676 size="sm"
677 className="w-full max-w-full"
678 type={field.control === "password" ? "password" : undefined}
679 autoComplete={field.control === "password" ? "off" : undefined}
680 value={rejected ?? readProviderConfigString(value, field.key)}
681 placeholder={field.placeholder}
682 onCommit={(next) => {
683 const clears = field.clearWhenEmpty === "omit" && next.trim().length === 0;
684 if (!clears && field.accepts?.(next) === false) {
685 setRejected(next);
686 return;
687 }
688 setRejected(null);
689 onChange(nextProviderConfigWithFieldValue(value, field, next));
690 }}
691 aria-invalid={rejected !== null || undefined}
692 spellCheck={false}
693 />
694 {rejected !== null ? (
695 <p className="text-2xs text-destructive">
696 <T>Enter a valid value. It was not saved.</T>
697 </p>
698 ) : null}
699 </div>
700 );
702​
703function FieldFrame(props: {
704 readonly variant: ProviderSettingsFormProps["variant"];
705 readonly children: ReactNode;
706}) {
707 if (props.variant === "card") {
708 return <div>{props.children}</div>;
709 }
710 return <div className="grid gap-1.5">{props.children}</div>;
712​
713interface ProviderSettingsFieldRowProps {
714 readonly field: ProviderSettingsFieldModel;
715 readonly value: unknown;
716 readonly idPrefix: string;
717 readonly variant: ProviderSettingsFormProps["variant"];
718 readonly onChange: ProviderSettingsFormProps["onChange"];
719 readonly managedReason?: string | undefined;
720 readonly environmentId: EnvironmentId | undefined;
722​
723function ProviderSettingsFieldRow({
724 field,
725 value,
726 idPrefix,
727 variant,
728 onChange,
729 managedReason,
730 environmentId,
731}: ProviderSettingsFieldRowProps) {
732 const gt = useGT();
733 const inputId = `${idPrefix}-${field.key}`;
734 const descriptionClassName =
735 variant === "dialog"
736 ? "text-2xs text-muted-foreground"
737 : "mt-1 block text-xs text-muted-foreground";
738 const label = <span className="text-xs font-medium text-foreground">{field.label}</span>;
739 const description = field.description ? (
740 <span className={descriptionClassName}>{field.description}</span>
741 ) : null;
742​
743 if (variant === "settings") {
744 const descriptionId = field.description ? `${inputId}-description` : undefined;
745 const secretConfigured =
746 field.secret === true && readProviderConfigString(value, field.key).length > 0;
747 const control =
748 field.control === "switch" ? (
749 <Switch
750 checked={readProviderConfigBoolean(value, field.key, field.defaultBooleanValue)}
751 onCheckedChange={(checked) =>
752 onChange(nextProviderConfigWithFieldValue(value, field, Boolean(checked)))
753 }
754 aria-label={field.label}
755 aria-describedby={descriptionId}
756 />
757 ) : field.control === "select" ? (
758 <ProviderSettingsSelect
759 field={field}
760 value={value}
761 inputId={inputId}
762 size="sm"
763 className="w-full max-w-full @min-[32rem]/settings-row:w-56"
764 onChange={onChange}
765 />
766 ) : field.control === "textarea" ? (
767 <Textarea
768 id={inputId}
769 aria-describedby={descriptionId}
770 className="w-full max-w-full @min-[32rem]/settings-row:w-[min(24rem,50cqw)]"
771 value={readProviderConfigString(value, field.key)}
772 onChange={(event) =>
773 onChange(nextProviderConfigWithFieldValue(value, field, event.target.value))
774 }
775 placeholder={field.placeholder}
776 spellCheck={false}
777 />
778 ) : field.acceptsSecretReference && environmentId !== undefined ? (
779 <SecretSettingsControl
780 field={field}
781 value={value}
782 inputId={inputId}
783 descriptionId={descriptionId}
784 environmentId={environmentId}
785 onChange={onChange}
786 />
787 ) : field.secret ? (
788 <div className="flex w-full min-w-0 items-center gap-2 @min-[32rem]/settings-row:w-56">
789 <SecretInput
790 id={inputId}
791 aria-describedby={descriptionId}
792 size="sm"
793 className="min-w-0 flex-1"
794 configured={secretConfigured}
795 value=""
796 onCommit={(next) => onChange(nextProviderConfigWithFieldValue(value, field, next))}
797 />
798 {secretConfigured ? (
799 <Button
800 type="button"
801 size="icon-sm"
802 variant="ghost-destructive"
803 onClick={() => onChange(nextProviderConfigWithFieldValue(value, field, ""))}
804 aria-label={gt("Clear {field}", { field: field.label })}
805 >
806 <XIcon className="size-3.5" />
807 </Button>
808 ) : null}
809 </div>
810 ) : (
811 <ProviderSettingsTextInput
812 field={field}
813 value={value}
814 inputId={inputId}
815 descriptionId={descriptionId}
816 onChange={onChange}
817 />
818 );
819​
820 return (
821 <SettingsRow
822 title={
823 field.control === "switch" ? field.label : <label htmlFor={inputId}>{field.label}</label>
824 }
825 description={
826 field.description ? <span id={descriptionId}>{field.description}</span> : undefined
827 }
828 control={control}
829 managed={managedReason}
830 />
831 );
832 }
833​
834 if (field.control === "switch") {
835 return (
836 <FieldFrame variant={variant}>
837 <div className="flex items-center justify-between gap-3">
838 <div className="min-w-0">
839 {label}
840 {description}
841 </div>
842 <Switch
843 checked={readProviderConfigBoolean(value, field.key, field.defaultBooleanValue)}
844 onCheckedChange={(checked) =>
845 onChange(nextProviderConfigWithFieldValue(value, field, Boolean(checked)))
846 }
847 aria-label={field.label}
848 />
849 </div>
850 </FieldFrame>
851 );
852 }
853​
854 if (field.control === "select") {
855 return (
856 <FieldFrame variant={variant}>
857 <label htmlFor={inputId} className={cn(variant === "card" && "block")}>
858 {label}
859 <ProviderSettingsSelect
860 field={field}
861 value={value}
862 inputId={inputId}
863 size="sm"
864 className={cn("w-full", variant === "card" && "mt-1.5")}
865 onChange={onChange}
866 />
867 {description}
868 </label>
869 </FieldFrame>
870 );
871 }
872​
873 if (field.control === "textarea") {
874 return (
875 <FieldFrame variant={variant}>
876 <label htmlFor={inputId} className={cn(variant === "card" && "block")}>
877 {label}
878 <Textarea
879 id={inputId}
880 className={cn(variant === "card" && "mt-1.5")}
881 value={readProviderConfigString(value, field.key)}
882 onChange={(event) =>
883 onChange(nextProviderConfigWithFieldValue(value, field, event.target.value))
884 }
885 placeholder={field.placeholder}
886 spellCheck={false}
887 />
888 {description}
889 </label>
890 </FieldFrame>
891 );
892 }
893​
894 const type = field.control === "password" ? "password" : undefined;
895 const BufferedInput = field.secret ? SecretInput : DraftInput;
896 const ControlledInput = field.secret ? SecretInput : Input;
897 return (
898 <FieldFrame variant={variant}>
899 <label htmlFor={inputId} className={cn(variant === "card" && "block")}>
900 {label}
901 {variant === "card" ? (
902 <BufferedInput
903 id={inputId}
904 size="sm"
905 className="mt-1.5"
906 type={field.secret ? undefined : type}
907 autoComplete={!field.secret && field.control === "password" ? "off" : undefined}
908 value={readProviderConfigString(value, field.key)}
909 onCommit={(next) => onChange(nextProviderConfigWithFieldValue(value, field, next))}
910 placeholder={field.placeholder}
911 spellCheck={false}
912 />
913 ) : (
914 <ControlledInput
915 id={inputId}
916 type={field.secret ? undefined : type}
917 autoComplete={!field.secret && field.control === "password" ? "off" : undefined}
918 value={readProviderConfigString(value, field.key)}
919 onChange={(event) =>
920 onChange(nextProviderConfigWithFieldValue(value, field, event.target.value))
921 }
922 placeholder={field.placeholder}
923 spellCheck={false}
924 />
925 )}
926 {description}
927 </label>
928 </FieldFrame>
929 );
931​
932export function ProviderSettingsForm({
933 definition,
934 value,
935 idPrefix,
936 variant,
937 onChange,
938 managed,
939 environmentId,
940}: ProviderSettingsFormProps) {
941 const resolve = useMessages();
942 const fields = deriveProviderSettingsFields(definition, value ?? {}, resolve);
943 const isLocalAcp =
944 definition.driverKind === "acpRegistry" &&
945 readProviderConfigString(value, "source") === "local";
946​
947 if (fields.length === 0) {
948 return null;
949 }
950​
951 return (
952 <>
953 {fields.map((field) => (
954 <ProviderSettingsFieldRow
955 key={field.key}
956 field={field}
957 value={value}
958 idPrefix={idPrefix}
959 variant={variant}
960 onChange={onChange}
961 managedReason={managed?.keys.has(field.key) ? managed.reason : undefined}
962 environmentId={environmentId}
963 />
964 ))}
965 {isLocalAcp ? (
966 <ProviderCommandArguments
967 value={value}
968 onChange={onChange}
969 managedReason={managed?.keys.has("commandArgs") ? managed.reason : undefined}
970 />
971 ) : null}
972 </>
973 );