Open History to see the last commit
1"use client";
2
3import { CheckIcon } from "lucide-react";
4import { Radio as RadioPrimitive } from "@base-ui/react/radio";
5import { useCallback, useMemo, useState } from "react";
6import {
7 ProviderInstanceId,
8 ProviderDriverKind,
9 type ProviderInstanceConfig,
10} from "@v12/contracts";
11
12import { usePrimarySettings, useUpdatePrimarySettings } from "../../hooks/useSettings";
13import { cn } from "../../lib/utils";
14import { normalizeProviderAccentColor } from "../../providerInstances";
15import { Button } from "../ui/button";
16import { ACPRegistryIcon, Gemini, GithubCopilotIcon, PiAgentIcon, type Icon } from "../Icons";
17import {
18 Dialog,
19 DialogDescription,
20 DialogFooter,
21 DialogHeader,
22 DialogPopup,
23 DialogTitle,
24} from "../ui/dialog";
25import { Badge } from "../ui/badge";
26import { Input } from "../ui/input";
27import { RadioGroup } from "../ui/radio-group";
28import { toastManager } from "../ui/toast";
29import { DRIVER_OPTION_BY_VALUE, DRIVER_OPTIONS } from "./providerDriverMeta";
30import { ProviderSettingsForm, deriveProviderSettingsFields } from "./ProviderSettingsForm";
31import { AnimatedHeight } from "../AnimatedHeight";
32
33const PROVIDER_ACCENT_SWATCHES = [
34 "#2563eb",
35 "#16a34a",
36 "#ea580c",
37 "#dc2626",
38 "#7c3aed",
39 "#0891b2",
40] as const;
41
42/**
43 * Normalize a user-provided label into a slug suffix for the instance id.
44 * The full id is formed by prefixing the driver slug — e.g. label "Work" on
45 * driver "codex" becomes `codex_work`. Output is trimmed to 48 chars so the
46 * final composed id stays under the 64-char slug cap enforced by
47 * `ProviderInstanceId` in `@v12/contracts`.
48 */
49function slugifyLabel(value: string): string {
50 return value
51 .trim()
52 .toLowerCase()
53 .replace(/[^a-z0-9]+/g, "_")
54 .replace(/^_+|_+$/g, "")
55 .slice(0, 48);
56}
57
58function deriveInstanceId(driver: ProviderDriverKind, label: string): string {
59 const slug = slugifyLabel(label);
60 return slug ? `${driver}_${slug}` : "";
61}
62
63const INSTANCE_ID_PATTERN = /^[a-zA-Z][a-zA-Z0-9_-]*$/;
64const DEFAULT_DRIVER_KIND = ProviderDriverKind.make("codex");
65const DEFAULT_DRIVER_OPTION = DRIVER_OPTIONS[0]!;
66const EMPTY_CONFIG_DRAFT: Record<string, unknown> = {};
67interface ComingSoonDriverOption {
68 readonly value: ProviderDriverKind;
69 readonly label: string;
70 readonly icon: Icon;
71}
72
73const COMING_SOON_DRIVER_OPTIONS: readonly ComingSoonDriverOption[] = [
74 {
75 value: ProviderDriverKind.make("githubCopilot"),
76 label: "Github Copilot",
77 icon: GithubCopilotIcon,
78 },
79 {
80 value: ProviderDriverKind.make("gemini"),
81 label: "Gemini",
82 icon: Gemini,
83 },
84 {
85 value: ProviderDriverKind.make("acpRegistry"),
86 label: "ACP Registry",
87 icon: ACPRegistryIcon,
88 },
89 {
90 value: ProviderDriverKind.make("piAgent"),
91 label: "Pi Agent",
92 icon: PiAgentIcon,
93 },
94];
95
96/**
97 * Validate an instance id against the same slug rules the server applies in
98 * `ProviderInstanceId` (see `packages/contracts/src/providerInstance.ts`).
99 * Returns a user-facing error string, or `null` if valid.
100 */
101function validateInstanceId(id: string, existing: ReadonlySet<string>): string | null {
102 if (id.length === 0) return "Instance ID is required.";
103 if (id.length > 64) return "Instance ID must be 64 characters or fewer.";
104 if (!INSTANCE_ID_PATTERN.test(id)) {
105 return "Instance ID must start with a letter and use only letters, digits, '-', or '_'.";
106 }
107 if (existing.has(id)) return `An instance named '${id}' already exists.`;
108 return null;
109}
110
111interface AddProviderInstanceDialogProps {
112 open: boolean;
113 onOpenChange: (open: boolean) => void;
114}
115
116export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderInstanceDialogProps) {
117 const settings = usePrimarySettings();
118 const updateSettings = useUpdatePrimarySettings();
119
120 const [wizardStep, setWizardStep] = useState(0);
121 const [driver, setDriver] = useState<ProviderDriverKind>(DEFAULT_DRIVER_KIND);
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 instanceId = instanceIdOverride ?? deriveInstanceId(driver, label);
139 const driverSettingsFields = useMemo(
140 () => deriveProviderSettingsFields(driverOption),
141 [driverOption],
142 );
143 const instanceIdError = validateInstanceId(instanceId, existingIds);
144 const showInstanceIdError = hasAttemptedSubmit && instanceIdError !== null;
145 const previewLabel = label.trim() || `${driverOption.label} Workspace`;
146 const wizardSteps = ["Driver", "Identity", "Config"] as const;
147 const wizardStepSummaries = [driverOption.label, previewLabel, null] as const;
148
149 const configDraft = configByDriver[driver] ?? EMPTY_CONFIG_DRAFT;
150 const setConfigDraft = useCallback(
151 (config: Record<string, unknown> | undefined) => {
152 setConfigByDriver((existing) => {
153 const next = { ...existing };
154 if (config === undefined || Object.keys(config).length === 0) {
155 delete next[driver];
156 } else {
157 next[driver] = config;
158 }
159 return next;
160 });
161 },
162 [driver],
163 );
164
165 const handleSave = useCallback(() => {
166 setHasAttemptedSubmit(true);
167 if (instanceIdError !== null) return;
168
169 const config = configByDriver[driver] ?? {};
170 const hasConfig = Object.keys(config).length > 0;
171 const normalizedAccentColor = normalizeProviderAccentColor(accentColor);
172
173 const nextInstance: ProviderInstanceConfig = {
174 driver,
175 enabled: true,
176 ...(label.trim().length > 0 ? { displayName: label.trim() } : {}),
177 ...(normalizedAccentColor ? { accentColor: normalizedAccentColor } : {}),
178 ...(hasConfig ? { config } : {}),
179 };
180 // `ProviderInstanceId.make` revalidates the slug; we've already checked
181 // it via `validateInstanceId`, but going through the brand constructor
182 // keeps the type boundary honest and guards against any future drift in
183 // the slug rules.
184 const brandedId = ProviderInstanceId.make(instanceId);
185 const nextMap = {
186 ...settings.providerInstances,
187 [brandedId]: nextInstance,
188 };
189 try {
190 updateSettings({ providerInstances: nextMap });
191 toastManager.add({
192 type: "success",
193 title: "Provider instance added",
194 description: `${driverOption.label} instance '${instanceId}' was added.`,
195 });
196 onOpenChange(false);
197 } catch (error) {
198 toastManager.add({
199 type: "error",
200 title: "Could not add provider instance",
201 description: error instanceof Error ? error.message : "Update failed.",
202 });
203 }
204 }, [
205 driver,
206 driverOption,
207 configByDriver,
208 instanceId,
209 instanceIdError,
210 label,
211 accentColor,
212 onOpenChange,
213 settings.providerInstances,
214 updateSettings,
215 ]);
216
217 return (
218 <Dialog open={open} onOpenChange={onOpenChange}>
219 <DialogPopup className="max-w-xl overflow-hidden">
220 <div className="flex min-h-0 flex-col overflow-hidden border-foreground/10 bg-background shadow-2xl">
221 <DialogHeader className="border-b border-border/70 bg-background">
222 <DialogTitle>Add provider instance</DialogTitle>
223 <DialogDescription>
224 Configure an additional provider instance — for example, a second Codex install
225 pointed at a different workspace.
226 </DialogDescription>
227 <div className="grid grid-cols-3 gap-2">
228 {wizardSteps.map((step, index) => (
229 <button
230 key={step}
231 type="button"
232 className={cn(
233 "grid min-w-0 grid-cols-[1rem_minmax(0,1fr)] gap-x-2 rounded-lg border px-3 py-2 text-left",
234 index === wizardStep
235 ? "border-primary bg-primary/10 ring-1 ring-primary/25"
236 : index < wizardStep
237 ? "border-border bg-background"
238 : "border-border bg-muted/40",
239 )}
240 onClick={() => setWizardStep(index)}
241 >
242 <span
243 className={cn(
244 "row-span-2 mt-0.5 grid size-4 place-items-center rounded-full border",
245 index < wizardStep
246 ? "border-primary bg-primary text-primary-foreground"
247 : index === wizardStep
248 ? "border-primary bg-background"
249 : "border-muted-foreground/35 bg-background",
250 )}
251 aria-hidden
252 >
253 {index < wizardStep ? <CheckIcon className="size-3" /> : null}
254 </span>
255 <span className="text-[10px] font-medium uppercase text-muted-foreground">
256 Step {index + 1}
257 </span>
258 <span className="truncate text-xs font-semibold text-foreground">
259 {step}
260 {index < wizardStep && wizardStepSummaries[index]
261 ? `: ${wizardStepSummaries[index]}`
262 : ""}
263 </span>
264 </button>
265 ))}
266 </div>
267 </DialogHeader>
268
269 <div
270 data-slot="dialog-panel"
271 className="space-y-4 border-b border-border/70 bg-muted/20 px-6 py-5"
272 >
273 <AnimatedHeight>
274 <div className={cn("grid gap-2", wizardStep !== 0 && "hidden")}>
275 <span
276 id="add-instance-driver-label"
277 className="text-xs font-medium text-foreground"
278 >
279 Driver
280 </span>
281 <RadioGroup
282 value={driver}
283 onValueChange={(value) => setDriver(ProviderDriverKind.make(value))}
284 aria-labelledby="add-instance-driver-label"
285 className="grid grid-cols-2 gap-2.5"
286 >
287 {DRIVER_OPTIONS.map((option) => {
288 const IconComponent = option.icon;
289 const isSelected = option.value === driver;
290 return (
291 <RadioPrimitive.Root
292 key={option.value}
293 value={option.value}
294 className={cn(
295 "relative flex cursor-pointer items-center gap-3 rounded-lg border px-3 py-3 text-left outline-none transition-[background-color,border-color,box-shadow]",
296 "focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
297 isSelected
298 ? "border-primary bg-background shadow-sm ring-2 ring-primary/35"
299 : "border-border bg-background hover:border-foreground/20 hover:bg-muted/50",
300 )}
301 >
302 <IconComponent className="size-5 shrink-0" aria-hidden />
303 <span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
304 {option.label}
305 </span>
306 {option.badgeLabel ? (
307 <Badge variant="warning" size="sm">
308 {option.badgeLabel}
309 </Badge>
310 ) : null}
311 </RadioPrimitive.Root>
312 );
313 })}
314 {COMING_SOON_DRIVER_OPTIONS.map((option) => {
315 const IconComponent = option.icon;
316 return (
317 <RadioPrimitive.Root
318 key={option.value}
319 value={option.value}
320 disabled
321 className={cn(
322 "relative flex cursor-not-allowed items-center gap-3 rounded-lg border border-border bg-background px-3 py-3 text-left opacity-55 outline-none",
323 )}
324 >
325 <IconComponent
326 className="size-5 shrink-0 text-muted-foreground"
327 aria-hidden
328 />
329 <span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
330 {option.label}
331 </span>
332 <Badge variant="warning" size="sm">
333 Coming Soon
334 </Badge>
335 </RadioPrimitive.Root>
336 );
337 })}
338 </RadioGroup>
339 </div>
340
341 <label className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
342 <span className="text-xs font-medium text-foreground">Label</span>
343 <Input
344 className="bg-background"
345 placeholder="e.g. Work"
346 value={label}
347 onChange={(event) => setLabel(event.target.value)}
348 />
349 <span className="text-[11px] text-muted-foreground">
350 Shown in the provider list. Optional.
351 </span>
352 </label>
353
354 <label className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
355 <span className="text-xs font-medium text-foreground">Instance ID</span>
356 <Input
357 className="bg-background"
358 placeholder={`${driver}_work`}
359 value={instanceId}
360 onChange={(event) => {
361 setInstanceIdOverride(event.target.value);
362 }}
363 aria-invalid={showInstanceIdError}
364 />
365 {showInstanceIdError ? (
366 <span className="text-[11px] text-destructive">{instanceIdError}</span>
367 ) : (
368 <span className="text-[11px] text-muted-foreground">
369 Routing key used by threads and sessions. Letters, digits, '-', or '_'.
370 </span>
371 )}
372 </label>
373
374 <div className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
375 <span className="text-xs font-medium text-foreground">Accent color</span>
376 <div className="flex min-w-0 flex-wrap items-center gap-2">
377 <input
378 type="color"
379 value={normalizeProviderAccentColor(accentColor) ?? PROVIDER_ACCENT_SWATCHES[0]}
380 onChange={(event) => setAccentColor(event.target.value)}
381 aria-label="Provider instance accent color"
382 className="h-8 w-10 cursor-pointer rounded-xl border border-input bg-background p-0.5"
383 />
384 <div className="flex flex-wrap gap-1.5">
385 {PROVIDER_ACCENT_SWATCHES.map((swatch) => {
386 const selected = accentColor.toLowerCase() === swatch;
387 return (
388 <button
389 key={swatch}
390 type="button"
391 className={cn(
392 "size-6 cursor-pointer rounded-full border transition",
393 selected
394 ? "scale-110 border-foreground ring-2 ring-ring ring-offset-1 ring-offset-background"
395 : "border-black/10 hover:scale-105 dark:border-white/20",
396 )}
397 style={{ backgroundColor: swatch }}
398 onClick={() => setAccentColor(swatch)}
399 aria-label={`Use ${swatch} accent`}
400 />
401 );
402 })}
403 </div>
404 {accentColor ? (
405 <Button
406 type="button"
407 size="sm"
408 variant="ghost"
409 className="h-7 px-2 text-xs text-muted-foreground"
410 onClick={() => setAccentColor("")}
411 >
412 Clear
413 </Button>
414 ) : null}
415 </div>
416 <span className="text-[11px] text-muted-foreground">
417 Optional marker shown in the picker.
418 </span>
419 </div>
420
421 {driverSettingsFields.length > 0 ? (
422 <div className={cn("grid gap-4", wizardStep !== 2 && "hidden")}>
423 <ProviderSettingsForm
424 definition={driverOption}
425 value={configDraft}
426 idPrefix={`add-provider-${driver}`}
427 variant="dialog"
428 onChange={setConfigDraft}
429 />
430 </div>
431 ) : wizardStep === 2 ? (
432 <div className="grid gap-2">
433 <p className="text-sm text-muted-foreground">
434 This driver has no required configuration. You can add the instance now.
435 </p>
436 </div>
437 ) : null}
438 </AnimatedHeight>
439 </div>
440
441 <DialogFooter className="border-t bg-background">
442 <Button
443 variant="outline"
444 size="sm"
445 onClick={() => {
446 if (wizardStep === 0) {
447 onOpenChange(false);
448 return;
449 }
450 setWizardStep((step) => Math.max(0, step - 1));
451 }}
452 >
453 {wizardStep === 0 ? "Cancel" : "Back"}
454 </Button>
455 {wizardStep < wizardSteps.length - 1 ? (
456 <Button size="sm" onClick={() => setWizardStep((step) => Math.min(2, step + 1))}>
457 Next
458 </Button>
459 ) : (
460 <Button size="sm" onClick={handleSave}>
461 Add instance
462 </Button>
463 )}
464 </DialogFooter>
465 </div>
466 </DialogPopup>
467 </Dialog>
468 );
469}