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