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 {
7 ACP_FEATURED_AGENTS,
8 type AcpRegistryCatalogIconKey,
9 ProviderInstanceId,
10 ProviderDriverKind,
11 type EnvironmentId,
12 type ProviderInstanceConfig,
13} from "@t3tools/contracts";
14
15import { useEnvironmentSettings, useUpdateEnvironmentSettings } from "../../hooks/useSettings";
16import { cn } from "../../lib/utils";
17import { normalizeProviderAccentColor } from "../../providerInstances";
18import { Button } from "../ui/button";
19import { ACPRegistryIcon, Gemini, GithubCopilotIcon, PiAgentIcon, type Icon } from "../Icons";
20import {
21 Dialog,
22 DialogDescription,
23 DialogFooter,
24 DialogHeader,
25 DialogPopup,
26 DialogTitle,
27} 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, NATIVE_DRIVER_OPTIONS } from "./providerDriverMeta";
33import { ProviderSettingsForm, deriveProviderSettingsFields } from "./ProviderSettingsForm";
34import { AnimatedHeight } from "../AnimatedHeight";
35import {
36 ACP_REGISTRY_DRIVER,
37 ADD_PROVIDER_WIZARD_STEPS,
38 acpPickerValue,
39 configDraftForFeaturedAgent,
40 parseAddProviderPickerValue,
41 resolveWizardNavigation,
42 type WizardNavigation,
43} from "./AddProviderInstanceDialog.logic";
44import { AddProviderInstanceWizardSteps } from "./AddProviderInstanceWizardSteps";
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 — e.g. 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 DEFAULT_DRIVER_OPTION = NATIVE_DRIVER_OPTIONS[0]!;
79const EMPTY_CONFIG_DRAFT: Record<string, unknown> = {};
80
81function iconForCatalogKey(iconKey: AcpRegistryCatalogIconKey): Icon {
82 if (iconKey === "gemini") return Gemini;
83 if (iconKey === "githubCopilot") return GithubCopilotIcon;
84 if (iconKey === "piAgent") return PiAgentIcon;
85 return ACPRegistryIcon;
86}
87
88/**
89 * Validate an instance id against the same slug rules the server applies in
90 * `ProviderInstanceId` (see `packages/contracts/src/providerInstance.ts`).
91 * Returns a user-facing error string, or `null` if valid.
92 */
93function validateInstanceId(id: string, existing: ReadonlySet<string>): string | null {
94 if (id.length === 0) return "Instance ID is required.";
95 if (id.length > 64) return "Instance ID must be 64 characters or fewer.";
96 if (!INSTANCE_ID_PATTERN.test(id)) {
97 return "Instance ID must start with a letter and use only letters, digits, '-', or '_'.";
98 }
99 if (existing.has(id)) return `An instance named '${id}' already exists.`;
100 return null;
101}
102
103interface AddProviderInstanceDialogProps {
104 readonly open: boolean;
105 readonly environmentId: EnvironmentId;
106 readonly environmentLabel: string;
107 readonly onOpenChange: (open: boolean) => void;
108}
109
110export function AddProviderInstanceDialog({
111 open,
112 environmentId,
113 environmentLabel,
114 onOpenChange,
115}: AddProviderInstanceDialogProps) {
116 const settings = useEnvironmentSettings(environmentId);
117 const updateSettings = useUpdateEnvironmentSettings(environmentId);
118
119 const [wizardStep, setWizardStep] = useState(0);
120 const [driver, setDriver] = useState<ProviderDriverKind>(DEFAULT_DRIVER_KIND);
121 const [catalogId, setCatalogId] = useState<string | undefined>(undefined);
122 const [label, setLabel] = useState("");
123 const [accentColor, setAccentColor] = useState<string>("");
124 const [instanceIdOverride, setInstanceIdOverride] = useState<string | null>(null);
125 // Driver-specific config drafts keyed by driver so toggling between drivers
126 // during the same dialog session does not lose in-progress input.
127 const [configByDriver, setConfigByDriver] = useState<Record<string, Record<string, unknown>>>({});
128 // Errors are suppressed until the user has tried to submit once. After that
129 // they update live so fixing the problem clears the message in place.
130 const [hasAttemptedSubmit, setHasAttemptedSubmit] = useState(false);
131
132 const existingIds = useMemo(
133 () => new Set(Object.keys(settings.providerInstances ?? {})),
134 [settings.providerInstances],
135 );
136
137 const driverOption = DRIVER_OPTION_BY_VALUE[driver] ?? DEFAULT_DRIVER_OPTION;
138 const featuredAgent = catalogId
139 ? ACP_FEATURED_AGENTS.find((agent) => agent.id === catalogId)
140 : undefined;
141 const pickerLabel = featuredAgent?.label ?? driverOption.label;
142 const instanceId = instanceIdOverride ?? deriveInstanceId(driver, label);
143 const driverSettingsFields = useMemo(
144 () => deriveProviderSettingsFields(driverOption),
145 [driverOption],
146 );
147 const instanceIdError = validateInstanceId(instanceId, existingIds);
148 const showInstanceIdError = hasAttemptedSubmit && instanceIdError !== null;
149 const previewLabel = label.trim() || `${pickerLabel} Workspace`;
150 const wizardStepSummaries = [pickerLabel, previewLabel, null] as const;
151 const pickerValue = catalogId ? acpPickerValue(catalogId) : driver;
152
153 const configDraft = configByDriver[driver] ?? EMPTY_CONFIG_DRAFT;
154 const setConfigDraft = (config: Record<string, unknown> | undefined) => {
155 setConfigByDriver((existing) => {
156 const next = { ...existing };
157 if (config === undefined || Object.keys(config).length === 0) {
158 delete next[driver];
159 } else {
160 next[driver] = config;
161 }
162 return next;
163 });
164 };
165
166 const applyWizardNavigation = (navigation: WizardNavigation) => {
167 if (navigation.kind === "blocked") {
168 setHasAttemptedSubmit(true);
169 }
170 setWizardStep(navigation.step);
171 };
172
173 const navigateToStep = (requestedStep: number) => {
174 applyWizardNavigation(
175 resolveWizardNavigation(wizardStep, requestedStep, ADD_PROVIDER_WIZARD_STEPS.length, {
176 instanceIdError,
177 }),
178 );
179 };
180
181 const handleSave = () => {
182 setHasAttemptedSubmit(true);
183 if (instanceIdError !== null) return;
184
185 const config = configByDriver[driver] ?? {};
186 const hasConfig = Object.keys(config).length > 0;
187 const normalizedAccentColor = normalizeProviderAccentColor(accentColor);
188
189 const nextInstance: ProviderInstanceConfig = {
190 driver,
191 enabled: true,
192 ...(label.trim().length > 0 ? { displayName: label.trim() } : {}),
193 ...(normalizedAccentColor ? { accentColor: normalizedAccentColor } : {}),
194 ...(hasConfig ? { config } : {}),
195 };
196 // `ProviderInstanceId.make` revalidates the slug; we've already checked
197 // it via `validateInstanceId`, but going through the brand constructor
198 // keeps the type boundary honest and guards against any future drift in
199 // the slug rules.
200 const brandedId = ProviderInstanceId.make(instanceId);
201 const nextMap = {
202 ...settings.providerInstances,
203 [brandedId]: nextInstance,
204 };
205 try {
206 updateSettings({ providerInstances: nextMap });
207 toastManager.add({
208 type: "success",
209 title: "Provider instance added",
210 description: `${pickerLabel} instance '${instanceId}' was added.`,
211 });
212 onOpenChange(false);
213 } catch (error) {
214 toastManager.add({
215 type: "error",
216 title: "Could not add provider instance",
217 description: error instanceof Error ? error.message : "Update failed.",
218 });
219 }
220 };
221
222 return (
223 <Dialog open={open} onOpenChange={onOpenChange}>
224 <DialogPopup className="max-w-xl overflow-hidden">
225 <div className="flex min-h-0 flex-col overflow-hidden">
226 <DialogHeader>
227 <DialogTitle>Add provider instance</DialogTitle>
228 <DialogDescription>
229 Configure an additional provider instance on {environmentLabel} — native drivers, or
230 any ACP-speaking CLI such as Gemini, Copilot, or Pi.
231 </DialogDescription>
232 <AddProviderInstanceWizardSteps
233 currentStep={wizardStep}
234 summaries={wizardStepSummaries}
235 instanceIdError={instanceIdError}
236 onNavigation={applyWizardNavigation}
237 />
238 </DialogHeader>
239
240 <div
241 data-slot="dialog-panel"
242 className="space-y-4 bg-zinc-25/80 px-6 py-5 ring-1 ring-black/5 dark:bg-white/2 dark:ring-white/5"
243 >
244 <AnimatedHeight>
245 <div className={cn("grid gap-2", wizardStep !== 0 && "hidden")}>
246 <div id="add-instance-driver-label" className="text-sm font-medium text-foreground">
247 Driver
248 </div>
249 <RadioGroup
250 value={pickerValue}
251 onValueChange={(value) => {
252 const parsed = parseAddProviderPickerValue(value);
253 setDriver(parsed.driver);
254 setCatalogId(parsed.catalogId);
255 if (parsed.catalogId) {
256 const agent = ACP_FEATURED_AGENTS.find(
257 (entry) => entry.id === parsed.catalogId,
258 );
259 setLabel(agent?.label ?? "");
260 const nextConfig = configDraftForFeaturedAgent(parsed.catalogId);
261 setConfigByDriver((existing) => {
262 const next = { ...existing };
263 if (Object.keys(nextConfig).length === 0) {
264 delete next[parsed.driver];
265 } else {
266 next[parsed.driver] = nextConfig;
267 }
268 return next;
269 });
270 return;
271 }
272 if (parsed.driver !== ACP_REGISTRY_DRIVER) {
273 setLabel("");
274 }
275 }}
276 aria-labelledby="add-instance-driver-label"
277 className="grid grid-cols-1 gap-2 sm:grid-cols-2"
278 >
279 {NATIVE_DRIVER_OPTIONS.map((option) => {
280 const IconComponent = option.icon;
281 return (
282 <RadioPrimitive.Root
283 key={option.value}
284 value={option.value}
285 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"
286 >
287 <IconComponent className="size-4 shrink-0" aria-hidden />
288 <span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
289 {option.label}
290 </span>
291 <RadioPrimitive.Indicator
292 className="grid size-5 shrink-0 place-items-center rounded-full bg-primary text-primary-foreground"
293 aria-hidden
294 >
295 <CheckIcon className="size-3.5 shrink-0" />
296 </RadioPrimitive.Indicator>
297 {option.badgeLabel ? (
298 <Badge variant="warning" size="sm">
299 {option.badgeLabel}
300 </Badge>
301 ) : null}
302 </RadioPrimitive.Root>
303 );
304 })}
305 {ACP_FEATURED_AGENTS.map((agent) => {
306 const IconComponent = iconForCatalogKey(agent.iconKey);
307 return (
308 <RadioPrimitive.Root
309 key={agent.id}
310 value={acpPickerValue(agent.id)}
311 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"
312 >
313 <IconComponent className="size-4 shrink-0" aria-hidden />
314 <span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
315 {agent.label}
316 </span>
317 <RadioPrimitive.Indicator
318 className="grid size-5 shrink-0 place-items-center rounded-full bg-primary text-primary-foreground"
319 aria-hidden
320 >
321 <CheckIcon className="size-3.5 shrink-0" />
322 </RadioPrimitive.Indicator>
323 <Badge variant="warning" size="sm">
324 ACP
325 </Badge>
326 </RadioPrimitive.Root>
327 );
328 })}
329 </RadioGroup>
330 </div>
331
332 <label className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
333 <span className="text-xs font-medium text-foreground">Label</span>
334 <Input
335 className="bg-background"
336 placeholder="e.g. Work"
337 value={label}
338 onChange={(event) => setLabel(event.target.value)}
339 />
340 <span className="text-[11px] text-muted-foreground">
341 Shown in the provider list. Optional.
342 </span>
343 </label>
344
345 <label className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
346 <span className="text-xs font-medium text-foreground">Instance ID</span>
347 <Input
348 className="bg-background"
349 placeholder={`${driver}_work`}
350 value={instanceId}
351 onChange={(event) => {
352 setInstanceIdOverride(event.target.value);
353 }}
354 aria-invalid={showInstanceIdError}
355 />
356 {showInstanceIdError ? (
357 <span className="text-[11px] text-destructive">{instanceIdError}</span>
358 ) : (
359 <span className="text-[11px] text-muted-foreground">
360 Routing key used by threads and sessions. Letters, digits, '-', or '_'.
361 </span>
362 )}
363 </label>
364
365 <div className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
366 <span className="text-xs font-medium text-foreground">Accent color</span>
367 <div className="flex min-w-0 flex-wrap items-center gap-2">
368 <input
369 type="color"
370 value={normalizeProviderAccentColor(accentColor) ?? PROVIDER_ACCENT_SWATCHES[0]}
371 onChange={(event) => setAccentColor(event.target.value)}
372 aria-label="Provider instance accent color"
373 className="h-8 w-10 cursor-pointer rounded-xl border border-input bg-background p-0.5"
374 />
375 <div className="flex flex-wrap gap-1.5">
376 {PROVIDER_ACCENT_SWATCHES.map((swatch) => {
377 const selected = accentColor.toLowerCase() === swatch;
378 return (
379 <button
380 key={swatch}
381 type="button"
382 className={cn(
383 "size-6 cursor-pointer rounded-full border transition",
384 selected
385 ? "scale-110 border-foreground ring-2 ring-ring ring-offset-1 ring-offset-background"
386 : "border-black/10 hover:scale-105 dark:border-white/20",
387 )}
388 style={{ backgroundColor: swatch }}
389 onClick={() => setAccentColor(swatch)}
390 aria-label={`Use ${swatch} accent`}
391 />
392 );
393 })}
394 </div>
395 {accentColor ? (
396 <Button
397 type="button"
398 size="sm"
399 variant="ghost"
400 className="h-7 px-2 text-xs text-muted-foreground"
401 onClick={() => setAccentColor("")}
402 >
403 Clear
404 </Button>
405 ) : null}
406 </div>
407 <span className="text-[11px] text-muted-foreground">
408 Optional marker shown in the picker.
409 </span>
410 </div>
411
412 {driverSettingsFields.length > 0 ? (
413 <div className={cn("grid gap-4", wizardStep !== 2 && "hidden")}>
414 <ProviderSettingsForm
415 definition={driverOption}
416 value={configDraft}
417 idPrefix={`add-provider-${driver}`}
418 variant="dialog"
419 onChange={setConfigDraft}
420 />
421 </div>
422 ) : wizardStep === 2 ? (
423 <div className="grid gap-2">
424 <p className="text-sm text-muted-foreground">
425 This driver has no required configuration. You can add the instance now.
426 </p>
427 </div>
428 ) : null}
429 </AnimatedHeight>
430 </div>
431
432 <DialogFooter variant="bare">
433 <Button
434 variant="outline"
435 size="sm"
436 onClick={() => {
437 if (wizardStep === 0) {
438 onOpenChange(false);
439 return;
440 }
441 setWizardStep((step) => Math.max(0, step - 1));
442 }}
443 >
444 {wizardStep === 0 ? "Cancel" : "Back"}
445 </Button>
446 {wizardStep < ADD_PROVIDER_WIZARD_STEPS.length - 1 ? (
447 <Button size="sm" onClick={() => navigateToStep(wizardStep + 1)}>
448 Next
449 </Button>
450 ) : (
451 <Button size="sm" onClick={handleSave}>
452 Add instance
453 </Button>
454 )}
455 </DialogFooter>
456 </div>
457 </DialogPopup>
458 </Dialog>
459 );
460}