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