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