Open History to see the last commit
1"use client";
2
3import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
4
5import { Radio as RadioPrimitive } from "@base-ui/react/radio";
6import { CheckIcon } from "lucide-react";
7import { useMemo, useState } from "react";
8import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
9import {
10 DEFAULT_UNIFIED_SETTINGS,
11 type AcpRegistrySearchAgent,
12 AuthProvidersManageScope,
13 ProviderInstanceId,
14 ProviderDriverKind,
15 type EnvironmentId,
16 type ProviderInstanceConfig,
17 type ProviderInstanceEnvironmentVariable,
18} from "@t3tools/contracts";
19
20import {
21 useEnvironmentSettings,
22 usePersistEnvironmentProviderInstanceMutation,
23} from "../../hooks/useSettings";
24import * as Equal from "effect/Equal";
25
26import { cn } from "../../lib/utils";
27import { normalizeProviderAccentColor } from "../../providerInstances";
28import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
29import { Button } from "../ui/button";
30import { ChatGptConnectionButton } from "./ChatGptConnectionButton";
31import { Dialog } from "../ui/dialog";
32import { Badge } from "../ui/badge";
33import { Input } from "../ui/input";
34import { RadioGroup } from "../ui/radio-group";
35import { toastManager } from "../ui/toast";
36import { DRIVER_OPTION_BY_VALUE, DRIVER_OPTIONS } from "./providerDriverMeta";
37import { ProviderAccentColorPicker } from "./ProviderAccentColorPicker";
38import { SettingsGroup } from "./SettingsGroup";
39import { SettingsRow } from "./settingsLayout";
40import { ProviderSettingsForm, deriveProviderSettingsFields } from "./ProviderSettingsForm";
41import { WizardPanel, WizardPopup, WizardHeader, WizardFooter } from "../ui/wizard";
42import {
43 ADD_PROVIDER_WIZARD_STEPS,
44 ACP_REGISTRY_WIZARD_STEPS,
45 LOCAL_ACP_WIZARD_STEPS,
46 deriveAvailableInstanceId,
47 resolveAcpRegistryWizardNavigation,
48 resolveWizardNavigation,
49 updateProviderIdentityDraft,
50 type ProviderIdentityDraft,
51 type WizardNavigation,
52} from "./AddProviderInstanceDialog.logic";
53import { AddProviderInstanceWizardSteps } from "./AddProviderInstanceWizardSteps";
54import { AcpRegistrySearchStep } from "./AcpRegistrySearchStep";
55import { ProviderWizardAuthenticationStep } from "./ProviderWizardAuthenticationStep";
56import { resolveOfficialAcpRegistryIconUrl } from "./AcpRegistryIcon";
57import { AddManagedCodexAccountDialog } from "./CodexSetupSection";
58import { ProviderEnvironmentSection } from "./ProviderInstanceCard";
59
60/**
61 * Normalize a user-provided label into a slug suffix for the instance id.
62 * The full id is formed by prefixing the driver slug. For example, label "Work" on
63 * driver "codex" becomes `codex_work`. Output is trimmed to 48 chars so the
64 * final composed id stays under the 64-char slug cap enforced by
65 * `ProviderInstanceId` in `@t3tools/contracts`.
66 */
67function slugifyLabel(value: string): string {
68 return value
69 .trim()
70 .toLowerCase()
71 .replace(/[^a-z0-9]+/g, "_")
72 .replace(/^_+|_+$/g, "")
73 .slice(0, 48);
74}
75
76function deriveInstanceId(driver: ProviderDriverKind, label: string): string {
77 const slug = slugifyLabel(label);
78 return slug ? `${driver}_${slug}` : "";
79}
80
81const INSTANCE_ID_PATTERN = /^[a-zA-Z][a-zA-Z0-9_-]*$/;
82const DEFAULT_DRIVER_KIND = ProviderDriverKind.make("codex");
83const ACP_REGISTRY_DRIVER_KIND = ProviderDriverKind.make("acpRegistry");
84const DEFAULT_DRIVER_OPTION = DRIVER_OPTIONS[0]!;
85const EMPTY_CONFIG_DRAFT: Record<string, unknown> = {};
86/**
87 * Validate an instance id against the same slug rules the server applies in
88 * `ProviderInstanceId` (see `packages/contracts/src/providerInstance.ts`).
89 * Returns a user-facing error string, or `null` if valid.
90 */
91function validateInstanceId(id: string, existing: ReadonlySet<string>): string | null {
92 if (id.length === 0) return "Instance ID is required.";
93 if (id.length > 64) return "Instance ID must be 64 characters or fewer.";
94 if (!INSTANCE_ID_PATTERN.test(id)) {
95 return "Instance ID must start with a letter and use only letters, digits, '-', or '_'.";
96 }
97 if (existing.has(id)) return `An instance named '${id}' already exists.`;
98 return null;
99}
100
101interface AddProviderInstanceDialogProps {
102 readonly open: boolean;
103 readonly environmentId: EnvironmentId;
104 readonly environmentLabel: string;
105 readonly onOpenChange: (open: boolean) => void;
106 readonly onCreated?: (instanceId: ProviderInstanceId) => void;
107}
108
109export function AddProviderInstanceDialog({
110 open,
111 environmentId,
112 environmentLabel,
113 onOpenChange,
114 onCreated,
115}: AddProviderInstanceDialogProps) {
116 const settings = useEnvironmentSettings(environmentId);
117 const persistProviderInstance = usePersistEnvironmentProviderInstanceMutation(environmentId);
118 const canManageProviders = useEnvironmentScope(environmentId, AuthProvidersManageScope);
119
120 const [wizardStep, setWizardStep] = useState(0);
121 const [addingChatGptAccount, setAddingChatGptAccount] = useState(false);
122 const [driver, setDriver] = useState<ProviderDriverKind>(DEFAULT_DRIVER_KIND);
123 const [identityByDriver, setIdentityByDriver] = useState<Record<string, ProviderIdentityDraft>>(
124 {},
125 );
126 const [selectedAcp, setSelectedAcp] = useState<AcpRegistrySearchAgent | null>(null);
127 const [localEnvironment, setLocalEnvironment] = useState<
128 ReadonlyArray<ProviderInstanceEnvironmentVariable>
129 >([]);
130 const [isManualAcpConfiguration, setIsManualAcpConfiguration] = useState(false);
131 const [isRegistryLoading, setIsRegistryLoading] = useState(false);
132 const [isPreparingRegistryAgent, setIsPreparingRegistryAgent] = useState(false);
133 // Driver-specific config drafts keyed by driver so toggling between drivers
134 // during the same dialog session does not lose in-progress input.
135 const [configByDriver, setConfigByDriver] = useState<Record<string, Record<string, unknown>>>({});
136 // Errors are suppressed until the user has tried to submit once. After that
137 // they update live so fixing the problem clears the message in place.
138 const [hasAttemptedSubmit, setHasAttemptedSubmit] = useState(false);
139 const [isSaving, setIsSaving] = useState(false);
140 const [createdInstanceId, setCreatedInstanceId] = useState<ProviderInstanceId | null>(null);
141
142 const existingIds = useMemo(() => {
143 const ids = new Set(["codex", "claudeAgent", ...Object.keys(settings.providerInstances ?? {})]);
144 const defaults = DEFAULT_UNIFIED_SETTINGS.providers as Record<string, unknown>;
145 // Reserve configured legacy slots too, so adding an account cannot replace them.
146 for (const [kind, config] of Object.entries(settings.providers ?? {})) {
147 if (!Equal.equals(config, defaults[kind])) ids.add(kind);
148 }
149 return ids;
150 }, [settings.providerInstances, settings.providers]);
151
152 const driverOption = DRIVER_OPTION_BY_VALUE[driver] ?? DEFAULT_DRIVER_OPTION;
153 const isAcpRegistry = driver === ACP_REGISTRY_DRIVER_KIND;
154 const defaultIdentity: ProviderIdentityDraft = {
155 label: driverOption.label,
156 accentColor: "",
157 instanceIdOverride: null,
158 };
159 const { label, accentColor, instanceIdOverride } = identityByDriver[driver] ?? defaultIdentity;
160 const instanceId =
161 instanceIdOverride ??
162 deriveAvailableInstanceId(
163 (candidateLabel) => {
164 if (!candidateLabel.trim() || candidateLabel === driverOption.label) {
165 return isAcpRegistry ? `${driver}_custom` : driver;
166 }
167 return deriveInstanceId(driver, candidateLabel);
168 },
169 label,
170 existingIds,
171 );
172 const driverSettingsFields = useMemo(
173 () => deriveProviderSettingsFields(driverOption),
174 [driverOption],
175 );
176 const instanceIdError = validateInstanceId(instanceId, existingIds);
177 const showInstanceIdError = hasAttemptedSubmit && instanceIdError !== null;
178 const identityStep = 1;
179 const previewLabel = label.trim() || `${driverOption.label} Workspace`;
180
181 const configDraft = configByDriver[driver] ?? EMPTY_CONFIG_DRAFT;
182 const isLocalAcp = isAcpRegistry && isManualAcpConfiguration && configDraft.source === "local";
183 const localCommandPath =
184 typeof configDraft.commandPath === "string" ? configDraft.commandPath.trim() : "";
185 const manualAgentId = typeof configDraft.agentId === "string" ? configDraft.agentId.trim() : "";
186 const acpSelectionError = isLocalAcp
187 ? localCommandPath.length > 0
188 ? null
189 : "Executable is required."
190 : selectedAcp !== null || (isManualAcpConfiguration && manualAgentId.length > 0)
191 ? null
192 : "Select an ACP or configure one manually.";
193 const wizardStepSummaries = isAcpRegistry
194 ? ([
195 isLocalAcp ? "Local ACP command" : (selectedAcp?.name ?? (manualAgentId || null)),
196 previewLabel,
197 null,
198 ] as const)
199 : ([driverOption.label, previewLabel, null] as const);
200 const setConfigDraft = (config: Record<string, unknown> | undefined) => {
201 setConfigByDriver((existing) => {
202 const next = { ...existing };
203 if (config === undefined || Object.keys(config).length === 0) {
204 delete next[driver];
205 } else {
206 next[driver] = config;
207 }
208 return next;
209 });
210 };
211 const setIdentityDraft = (update: Partial<ProviderIdentityDraft>) => {
212 setIdentityByDriver((existing) => ({
213 ...existing,
214 [driver]: { ...(existing[driver] ?? defaultIdentity), ...update },
215 }));
216 };
217
218 const applyWizardNavigation = (navigation: WizardNavigation) => {
219 if (isSaving || isPreparingRegistryAgent || createdInstanceId) return;
220 if (navigation.kind === "blocked") {
221 setHasAttemptedSubmit(true);
222 }
223 if (isAcpRegistry && !isLocalAcp && navigation.kind === "navigate" && navigation.step === 2) {
224 void handleSave();
225 return;
226 }
227 setWizardStep(navigation.step);
228 };
229
230 const navigateToStep = (requestedStep: number) => {
231 applyWizardNavigation(
232 isAcpRegistry
233 ? isLocalAcp
234 ? resolveWizardNavigation(wizardStep, requestedStep, LOCAL_ACP_WIZARD_STEPS.length, {
235 instanceIdError,
236 prerequisite: { step: 0, error: acpSelectionError },
237 })
238 : resolveAcpRegistryWizardNavigation(wizardStep, requestedStep, {
239 instanceIdError,
240 selectionError: acpSelectionError,
241 })
242 : resolveWizardNavigation(wizardStep, requestedStep, ADD_PROVIDER_WIZARD_STEPS.length, {
243 instanceIdError,
244 }),
245 );
246 };
247
248 const handleAcpPrepared = (agent: AcpRegistrySearchAgent) => {
249 setDriver(ACP_REGISTRY_DRIVER_KIND);
250 const nextLabel = agent.name;
251 const registryIconUrl = resolveOfficialAcpRegistryIconUrl(agent.icon);
252 const nextInstanceId = deriveAvailableInstanceId(
253 (candidateLabel) => deriveInstanceId(ACP_REGISTRY_DRIVER_KIND, candidateLabel),
254 nextLabel,
255 existingIds,
256 );
257 setSelectedAcp(agent);
258 setIsManualAcpConfiguration(false);
259 setIdentityByDriver((existing) =>
260 updateProviderIdentityDraft(existing, ACP_REGISTRY_DRIVER_KIND, {
261 label: nextLabel,
262 instanceIdOverride: nextInstanceId,
263 }),
264 );
265 setConfigByDriver((existing) => ({
266 ...existing,
267 [ACP_REGISTRY_DRIVER_KIND]: {
268 agentId: agent.id,
269 distribution: "auto",
270 ...(registryIconUrl ? { registryIconUrl } : {}),
271 },
272 }));
273 setHasAttemptedSubmit(false);
274 setWizardStep(1);
275 };
276
277 const handleManualAcpConfiguration = () => {
278 setDriver(ACP_REGISTRY_DRIVER_KIND);
279 setSelectedAcp(null);
280 setIsManualAcpConfiguration(true);
281 setConfigByDriver((existing) => {
282 const next = { ...existing };
283 delete next[ACP_REGISTRY_DRIVER_KIND];
284 return next;
285 });
286 setIdentityByDriver((existing) =>
287 updateProviderIdentityDraft(existing, ACP_REGISTRY_DRIVER_KIND, {
288 label: "",
289 instanceIdOverride: null,
290 }),
291 );
292 setHasAttemptedSubmit(false);
293 };
294
295 const handleLocalAcpConfiguration = () => {
296 setDriver(ACP_REGISTRY_DRIVER_KIND);
297 setSelectedAcp(null);
298 setIsManualAcpConfiguration(true);
299 setConfigByDriver((existing) => ({
300 ...existing,
301 [ACP_REGISTRY_DRIVER_KIND]: { source: "local", commandArgs: [] },
302 }));
303 setIdentityByDriver((existing) =>
304 updateProviderIdentityDraft(existing, ACP_REGISTRY_DRIVER_KIND, {
305 label: "Local ACP",
306 instanceIdOverride: null,
307 }),
308 );
309 setLocalEnvironment([]);
310 setHasAttemptedSubmit(false);
311 };
312
313 const handleSave = async () => {
314 if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
315 if (isSaving || createdInstanceId) return;
316 setHasAttemptedSubmit(true);
317 if (instanceIdError !== null || (isAcpRegistry && acpSelectionError !== null)) return;
318
319 const config =
320 driver === "codex"
321 ? { ...configByDriver[driver], setupMode: "existing" }
322 : (configByDriver[driver] ?? {});
323 const hasConfig = Object.keys(config).length > 0;
324 const normalizedAccentColor = normalizeProviderAccentColor(accentColor);
325
326 const nextInstance: ProviderInstanceConfig = {
327 driver,
328 enabled: true,
329 ...(label.trim().length > 0 ? { displayName: label.trim() } : {}),
330 ...(normalizedAccentColor ? { accentColor: normalizedAccentColor } : {}),
331 ...(hasConfig ? { config } : {}),
332 ...(isLocalAcp && localEnvironment.length > 0 ? { environment: localEnvironment } : {}),
333 };
334 // `ProviderInstanceId.make` revalidates the slug; we've already checked
335 // it via `validateInstanceId`, but going through the brand constructor
336 // keeps the type boundary honest and guards against any future drift in
337 // the slug rules.
338 const brandedId = ProviderInstanceId.make(instanceId);
339 setIsSaving(true);
340 const result = await persistProviderInstance({
341 operation: "create",
342 instanceId: brandedId,
343 instance: nextInstance,
344 });
345 if (result._tag === "Failure") {
346 const error = squashAtomCommandFailure(result);
347 setIsSaving(false);
348 toastManager.add({
349 type: "error",
350 title: "Could not add provider instance",
351 description: error instanceof Error ? error.message : "The settings update failed.",
352 });
353 return;
354 }
355 onCreated?.(brandedId);
356 if (isAcpRegistry && !isLocalAcp) {
357 setCreatedInstanceId(brandedId);
358 setIsSaving(false);
359 setWizardStep(2);
360 return;
361 }
362 toastManager.add({
363 type: "success",
364 title: "Provider instance added",
365 description: `${driverOption.label} instance '${instanceId}' was added.`,
366 });
367 onOpenChange(false);
368 };
369
370 if (addingChatGptAccount) {
371 return (
372 <AddManagedCodexAccountDialog
373 environmentId={environmentId}
374 onClose={() => onOpenChange(false)}
375 />
376 );
377 }
378
379 return (
380 <Dialog open={open} onOpenChange={onOpenChange}>
381 <WizardPopup size="wide">
382 <WizardHeader
383 title="Add provider"
384 description={<>Add an account or configure a provider on {environmentLabel}.</>}
385 >
386 {isAcpRegistry ? (
387 <AddProviderInstanceWizardSteps
388 currentStep={wizardStep}
389 summaries={wizardStepSummaries}
390 instanceIdError={instanceIdError}
391 steps={isLocalAcp ? LOCAL_ACP_WIZARD_STEPS : ACP_REGISTRY_WIZARD_STEPS}
392 disabled={isSaving || isPreparingRegistryAgent || createdInstanceId !== null}
393 identityStep={1}
394 prerequisite={{ step: 0, error: acpSelectionError }}
395 onNavigation={applyWizardNavigation}
396 />
397 ) : (
398 <AddProviderInstanceWizardSteps
399 currentStep={wizardStep}
400 summaries={wizardStepSummaries}
401 instanceIdError={instanceIdError}
402 disabled={isSaving || isPreparingRegistryAgent}
403 onNavigation={applyWizardNavigation}
404 />
405 )}
406 </WizardHeader>
407
408 {createdInstanceId ? (
409 <ProviderWizardAuthenticationStep
410 environmentId={environmentId}
411 environmentLabel={environmentLabel}
412 instanceId={createdInstanceId}
413 onFinish={() => onOpenChange(false)}
414 />
415 ) : (
416 <>
417 <WizardPanel
418 className={cn(isAcpRegistry && wizardStep === identityStep && "min-h-72")}
419 holdHeight={wizardStep === 0 && !isManualAcpConfiguration && isRegistryLoading}
420 >
421 <div className={cn("grid gap-2", wizardStep !== 0 && "hidden")}>
422 <div id="add-instance-driver-label" className="text-sm font-medium text-foreground">
423 Provider
424 </div>
425 <RadioGroup
426 disabled={isPreparingRegistryAgent}
427 value={driver}
428 onValueChange={(value) => {
429 setDriver(ProviderDriverKind.make(value));
430 setIsManualAcpConfiguration(false);
431 setHasAttemptedSubmit(false);
432 }}
433 aria-labelledby="add-instance-driver-label"
434 className="grid grid-cols-1 sm:grid-cols-2"
435 >
436 {DRIVER_OPTIONS.filter((option) => option.value !== ACP_REGISTRY_DRIVER_KIND).map(
437 (option) => {
438 return (
439 <RadioPrimitive.Root
440 key={option.value}
441 value={option.value}
442 className="relative flex cursor-pointer items-center gap-3 rounded-lg bg-card px-3 py-3 text-left text-muted-foreground outline-none ring-1 ring-black/5 hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring data-checked:bg-primary/8 data-checked:text-foreground data-checked:ring-2 data-checked:ring-primary data-checked:hover:bg-primary/8 dark:bg-white/3 dark:ring-white/5 dark:hover:bg-white/5 dark:data-checked:bg-primary/15 dark:data-checked:ring-primary dark:data-checked:hover:bg-primary/15"
443 >
444 <ProviderInstanceIcon
445 driverKind={option.value}
446 displayName={option.label}
447 iconClassName="size-4"
448 />
449 <span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
450 {option.label}
451 </span>
452 <RadioPrimitive.Indicator
453 className="grid size-5 shrink-0 place-items-center rounded-full bg-primary text-primary-foreground"
454 aria-hidden
455 >
456 <CheckIcon className="size-3.5 shrink-0" />
457 </RadioPrimitive.Indicator>
458 {option.badgeLabel ? (
459 <Badge variant="warning" size="sm">
460 {option.badgeLabel}
461 </Badge>
462 ) : null}
463 </RadioPrimitive.Root>
464 );
465 },
466 )}
467 </RadioGroup>
468 </div>
469
470 {wizardStep === 0 ? (
471 <div className="space-y-4 pt-4">
472 <div className="flex items-center gap-3 text-xs text-muted-foreground">
473 <div aria-hidden className="flex-1 border-t border-border/70" />
474 <span>Or choose from ACP Registry</span>
475 <div aria-hidden className="flex-1 border-t border-border/70" />
476 </div>
477 {isAcpRegistry && isManualAcpConfiguration ? (
478 <div className="grid gap-4">
479 <div className="flex items-start justify-between gap-3">
480 <div>
481 <h3 className="text-sm font-medium text-foreground">
482 {isLocalAcp ? "Local ACP command" : "Enter manually"}
483 </h3>
484 <p className="mt-0.5 text-xs text-muted-foreground">
485 {isLocalAcp
486 ? `Run an installed ACP executable on ${environmentLabel}.`
487 : "Enter an official registry ID and any local executable or auth override."}
488 </p>
489 </div>
490 <Button
491 onClick={() => {
492 setIsManualAcpConfiguration(false);
493 setHasAttemptedSubmit(false);
494 }}
495 size="xs"
496 variant="ghost"
497 >
498 Search registry
499 </Button>
500 </div>
501 <SettingsGroup variant="plain">
502 <ProviderSettingsForm
503 definition={driverOption}
504 value={configDraft}
505 idPrefix="add-provider-acpRegistry-manual"
506 variant="settings"
507 onChange={setConfigDraft}
508 />
509 {isLocalAcp ? (
510 <ProviderEnvironmentSection
511 environment={localEnvironment}
512 onChange={setLocalEnvironment}
513 />
514 ) : null}
515 </SettingsGroup>
516 {isAcpRegistry && hasAttemptedSubmit && acpSelectionError ? (
517 <p className="text-2xs text-destructive">{acpSelectionError}</p>
518 ) : null}
519 </div>
520 ) : (
521 <>
522 <AcpRegistrySearchStep
523 environmentId={environmentId}
524 providerInstances={settings.providerInstances}
525 onPrepared={handleAcpPrepared}
526 onManualConfiguration={handleManualAcpConfiguration}
527 onLocalConfiguration={handleLocalAcpConfiguration}
528 onLoadingChange={setIsRegistryLoading}
529 onPreparingChange={setIsPreparingRegistryAgent}
530 />
531 {isAcpRegistry && hasAttemptedSubmit && acpSelectionError ? (
532 <p className="mt-2 text-2xs text-destructive">{acpSelectionError}</p>
533 ) : null}
534 </>
535 )}
536 </div>
537 ) : null}
538
539 {isAcpRegistry && wizardStep === 1 && selectedAcp ? (
540 <div className="mb-4 flex items-start justify-between gap-3 border-b border-border/70 pb-3">
541 <div className="min-w-0">
542 <p className="truncate text-sm font-medium text-foreground">
543 {selectedAcp.name}
544 </p>
545 <p className="mt-0.5 text-xs text-muted-foreground">
546 v{selectedAcp.version} · {selectedAcp.distribution}
547 </p>
548 </div>
549 <div className="flex shrink-0 gap-2 text-2xs">
550 {selectedAcp.website ? (
551 <a
552 aria-label={`Open documentation for ${selectedAcp.name} (${selectedAcp.id})`}
553 className="text-muted-foreground hover:text-foreground"
554 href={selectedAcp.website}
555 rel="noreferrer"
556 target="_blank"
557 >
558 Docs
559 </a>
560 ) : null}
561 {selectedAcp.repository ? (
562 <a
563 aria-label={`Open source for ${selectedAcp.name} (${selectedAcp.id})`}
564 className="text-muted-foreground hover:text-foreground"
565 href={selectedAcp.repository}
566 rel="noreferrer"
567 target="_blank"
568 >
569 Source
570 </a>
571 ) : null}
572 </div>
573 </div>
574 ) : null}
575
576 <SettingsGroup
577 variant="plain"
578 className={cn(wizardStep !== identityStep && "hidden")}
579 >
580 <SettingsRow
581 title={<label htmlFor="add-provider-label">Label</label>}
582 description={
583 <span id="add-provider-label-description">Shown in the provider list.</span>
584 }
585 control={
586 <Input
587 id="add-provider-label"
588 aria-describedby="add-provider-label-description"
589 size="sm"
590 className="w-full @min-[32rem]/settings-row:w-56"
591 placeholder="e.g. Work"
592 value={label}
593 onChange={(event) => setIdentityDraft({ label: event.target.value })}
594 />
595 }
596 />
597 <SettingsRow
598 title={<label htmlFor="add-provider-instance-id">Instance ID</label>}
599 description={
600 <span id="add-provider-instance-id-description">
601 Letters, digits, '-', or '_'.
602 </span>
603 }
604 status={
605 showInstanceIdError ? (
606 <span
607 id="add-provider-instance-id-error"
608 role="alert"
609 className="text-destructive"
610 >
611 {instanceIdError}
612 </span>
613 ) : undefined
614 }
615 control={
616 <Input
617 id="add-provider-instance-id"
618 aria-describedby={
619 showInstanceIdError
620 ? "add-provider-instance-id-description add-provider-instance-id-error"
621 : "add-provider-instance-id-description"
622 }
623 size="sm"
624 className="w-full @min-[32rem]/settings-row:w-56"
625 placeholder={`${driver}_work`}
626 value={instanceId}
627 onChange={(event) => {
628 setIdentityDraft({ instanceIdOverride: event.target.value });
629 }}
630 aria-invalid={showInstanceIdError}
631 />
632 }
633 />
634 <SettingsRow
635 title="Accent color"
636 description="Optional marker shown in the picker."
637 control={
638 <ProviderAccentColorPicker
639 displayName={label || driverOption.label}
640 value={accentColor || undefined}
641 onCommit={(value) => setIdentityDraft({ accentColor: value })}
642 layout="inline"
643 />
644 }
645 />
646 </SettingsGroup>
647
648 {!isAcpRegistry && driverSettingsFields.length > 0 ? (
649 <SettingsGroup variant="plain" className={cn(wizardStep !== 2 && "hidden")}>
650 <ProviderSettingsForm
651 definition={driverOption}
652 value={configDraft}
653 idPrefix={`add-provider-${driver}`}
654 variant="settings"
655 onChange={setConfigDraft}
656 />
657 </SettingsGroup>
658 ) : !isAcpRegistry && wizardStep === 2 ? (
659 <div className="grid gap-2">
660 <p className="text-sm text-muted-foreground">
661 This driver has no required configuration. You can add the instance now.
662 </p>
663 </div>
664 ) : null}
665 </WizardPanel>
666
667 <WizardFooter>
668 <Button
669 variant={wizardStep === 0 ? "ghost-muted" : "outline"}
670 size="sm"
671 disabled={isSaving || isPreparingRegistryAgent}
672 onClick={() => {
673 if (wizardStep === 0) {
674 onOpenChange(false);
675 return;
676 }
677 setWizardStep((step) => Math.max(0, step - 1));
678 }}
679 >
680 {wizardStep === 0 ? "Cancel" : "Back"}
681 </Button>
682 {wizardStep === 0 && driver === "codex" ? (
683 <>
684 <Button variant="outline" size="sm" onClick={() => navigateToStep(1)}>
685 Configure manually
686 </Button>
687 <ChatGptConnectionButton
688 size="sm"
689 onClick={() => setAddingChatGptAccount(true)}
690 />
691 </>
692 ) : wizardStep < (isAcpRegistry ? 1 : 2) ? (
693 <Button
694 size="sm"
695 disabled={isPreparingRegistryAgent}
696 onClick={() => navigateToStep(wizardStep + 1)}
697 >
698 Next
699 </Button>
700 ) : (
701 <Button
702 size="sm"
703 disabled={isSaving || !canManageProviders}
704 onClick={() => void handleSave()}
705 >
706 {isSaving
707 ? "Adding..."
708 : isAcpRegistry && !isLocalAcp
709 ? "Continue to sign-in"
710 : "Add instance"}
711 </Button>
712 )}
713 </WizardFooter>
714 </>
715 )}
716 </WizardPopup>
717 </Dialog>
718 );
719}