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