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