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