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