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