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, useEffect, useMemo, useState } from "react";
6import {
7 ProviderInstanceId,
8 ProviderDriverKind,
9 type ProviderInstanceConfig,
10} from "@t3tools/contracts";
11
12import { useSettings, useUpdateSettings } from "../../hooks/useSettings";
13import { cn } from "../../lib/utils";
14import { normalizeProviderAccentColor } from "../../providerInstances";
15import { Button } from "../ui/button";
16import { ACPRegistryIcon, Gemini, GithubCopilotIcon, 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 `@t3tools/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
91/**
92 * Validate an instance id against the same slug rules the server applies in
93 * `ProviderInstanceId` (see `packages/contracts/src/providerInstance.ts`).
94 * Returns a user-facing error string, or `null` if valid.
95 */
96function validateInstanceId(id: string, existing: ReadonlySet<string>): string | null {
97 if (id.length === 0) return "Instance ID is required.";
98 if (id.length > 64) return "Instance ID must be 64 characters or fewer.";
99 if (!INSTANCE_ID_PATTERN.test(id)) {
100 return "Instance ID must start with a letter and use only letters, digits, '-', or '_'.";
101 }
102 if (existing.has(id)) return `An instance named '${id}' already exists.`;
103 return null;
104}
105
106interface AddProviderInstanceDialogProps {
107 open: boolean;
108 onOpenChange: (open: boolean) => void;
109}
110
111export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderInstanceDialogProps) {
112 const settings = useSettings();
113 const { updateSettings } = useUpdateSettings();
114
115 const [wizardStep, setWizardStep] = useState(0);
116 const [driver, setDriver] = useState<ProviderDriverKind>(DEFAULT_DRIVER_KIND);
117 const [label, setLabel] = useState("");
118 const [accentColor, setAccentColor] = useState<string>("");
119 const [instanceId, setInstanceId] = useState("");
120 const [instanceIdDirty, setInstanceIdDirty] = 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
128 const existingIds = useMemo(
129 () => new Set(Object.keys(settings.providerInstances ?? {})),
130 [settings.providerInstances],
131 );
132
133 // Reset the form every time the dialog opens so each creation starts
134 // from a clean slate.
135 useEffect(() => {
136 if (!open) return;
137 setDriver(DEFAULT_DRIVER_KIND);
138 setLabel("");
139 setAccentColor("");
140 setInstanceId("");
141 setWizardStep(0);
142 setInstanceIdDirty(false);
143 setConfigByDriver({});
144 setHasAttemptedSubmit(false);
145 }, [open]);
146
147 // Auto-derive the instance id from driver + label until the user types
148 // in the Instance ID field directly (after which they own its value).
149 useEffect(() => {
150 if (instanceIdDirty) return;
151 setInstanceId(deriveInstanceId(driver, label));
152 }, [driver, label, instanceIdDirty]);
153
154 const driverOption = DRIVER_OPTION_BY_VALUE[driver] ?? DEFAULT_DRIVER_OPTION;
155 const driverSettingsFields = useMemo(
156 () => deriveProviderSettingsFields(driverOption),
157 [driverOption],
158 );
159 const instanceIdError = validateInstanceId(instanceId, existingIds);
160 const showInstanceIdError = hasAttemptedSubmit && instanceIdError !== null;
161 const previewLabel = label.trim() || `${driverOption.label} Workspace`;
162 const wizardSteps = ["Driver", "Identity", "Config"] as const;
163 const wizardStepSummaries = [driverOption.label, previewLabel, null] as const;
164
165 const configDraft = configByDriver[driver] ?? EMPTY_CONFIG_DRAFT;
166 const setConfigDraft = useCallback(
167 (config: Record<string, unknown> | undefined) => {
168 setConfigByDriver((existing) => {
169 const next = { ...existing };
170 if (config === undefined || Object.keys(config).length === 0) {
171 delete next[driver];
172 } else {
173 next[driver] = config;
174 }
175 return next;
176 });
177 },
178 [driver],
179 );
180
181 const handleSave = useCallback(() => {
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: `${driverOption.label} 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 driver,
222 driverOption,
223 configByDriver,
224 instanceId,
225 instanceIdError,
226 label,
227 accentColor,
228 onOpenChange,
229 settings.providerInstances,
230 updateSettings,
231 ]);
232
233 return (
234 <Dialog open={open} onOpenChange={onOpenChange}>
235 <DialogPopup className="max-w-xl overflow-hidden">
236 <div className="flex min-h-0 flex-col overflow-hidden border-foreground/10 bg-background shadow-2xl">
237 <DialogHeader className="border-b border-border/70 bg-background">
238 <DialogTitle>Add provider instance</DialogTitle>
239 <DialogDescription>
240 Configure an additional provider instance — for example, a second Codex install
241 pointed at a different workspace.
242 </DialogDescription>
243 <div className="grid grid-cols-3 gap-2">
244 {wizardSteps.map((step, index) => (
245 <button
246 key={step}
247 type="button"
248 className={cn(
249 "grid min-w-0 grid-cols-[1rem_minmax(0,1fr)] gap-x-2 rounded-lg border px-3 py-2 text-left",
250 index === wizardStep
251 ? "border-primary bg-primary/10 ring-1 ring-primary/25"
252 : index < wizardStep
253 ? "border-border bg-background"
254 : "border-border bg-muted/40",
255 )}
256 onClick={() => setWizardStep(index)}
257 >
258 <span
259 className={cn(
260 "row-span-2 mt-0.5 grid size-4 place-items-center rounded-full border",
261 index < wizardStep
262 ? "border-primary bg-primary text-primary-foreground"
263 : index === wizardStep
264 ? "border-primary bg-background"
265 : "border-muted-foreground/35 bg-background",
266 )}
267 aria-hidden
268 >
269 {index < wizardStep ? <CheckIcon className="size-3" /> : null}
270 </span>
271 <span className="text-[10px] font-medium uppercase text-muted-foreground">
272 Step {index + 1}
273 </span>
274 <span className="truncate text-xs font-semibold text-foreground">
275 {step}
276 {index < wizardStep && wizardStepSummaries[index]
277 ? `: ${wizardStepSummaries[index]}`
278 : ""}
279 </span>
280 </button>
281 ))}
282 </div>
283 </DialogHeader>
284
285 <div
286 data-slot="dialog-panel"
287 className="space-y-4 border-b border-border/70 bg-muted/20 px-6 py-5"
288 >
289 <AnimatedHeight>
290 <div className={cn("grid gap-2", wizardStep !== 0 && "hidden")}>
291 <span
292 id="add-instance-driver-label"
293 className="text-xs font-medium text-foreground"
294 >
295 Driver
296 </span>
297 <RadioGroup
298 value={driver}
299 onValueChange={(value) => setDriver(ProviderDriverKind.make(value))}
300 aria-labelledby="add-instance-driver-label"
301 className="grid grid-cols-2 gap-2.5"
302 >
303 {DRIVER_OPTIONS.map((option) => {
304 const IconComponent = option.icon;
305 const isSelected = option.value === driver;
306 return (
307 <RadioPrimitive.Root
308 key={option.value}
309 value={option.value}
310 className={cn(
311 "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]",
312 "focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
313 isSelected
314 ? "border-primary bg-background shadow-sm ring-2 ring-primary/35"
315 : "border-border bg-background hover:border-foreground/20 hover:bg-muted/50",
316 )}
317 >
318 <IconComponent className="size-5 shrink-0" aria-hidden />
319 <span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
320 {option.label}
321 </span>
322 {option.badgeLabel ? (
323 <Badge variant="warning" size="sm">
324 {option.badgeLabel}
325 </Badge>
326 ) : null}
327 </RadioPrimitive.Root>
328 );
329 })}
330 {COMING_SOON_DRIVER_OPTIONS.map((option) => {
331 const IconComponent = option.icon;
332 return (
333 <RadioPrimitive.Root
334 key={option.value}
335 value={option.value}
336 disabled
337 className={cn(
338 "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",
339 )}
340 >
341 <IconComponent
342 className="size-5 shrink-0 text-muted-foreground"
343 aria-hidden
344 />
345 <span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
346 {option.label}
347 </span>
348 <Badge variant="warning" size="sm">
349 Coming Soon
350 </Badge>
351 </RadioPrimitive.Root>
352 );
353 })}
354 </RadioGroup>
355 </div>
356
357 <label className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
358 <span className="text-xs font-medium text-foreground">Label</span>
359 <Input
360 className="bg-background"
361 placeholder="e.g. Work"
362 value={label}
363 onChange={(event) => setLabel(event.target.value)}
364 />
365 <span className="text-[11px] text-muted-foreground">
366 Shown in the provider list. Optional.
367 </span>
368 </label>
369
370 <label className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
371 <span className="text-xs font-medium text-foreground">Instance ID</span>
372 <Input
373 className="bg-background"
374 placeholder={`${driver}_work`}
375 value={instanceId}
376 onChange={(event) => {
377 setInstanceIdDirty(true);
378 setInstanceId(event.target.value);
379 }}
380 aria-invalid={showInstanceIdError}
381 />
382 {showInstanceIdError ? (
383 <span className="text-[11px] text-destructive">{instanceIdError}</span>
384 ) : (
385 <span className="text-[11px] text-muted-foreground">
386 Routing key used by threads and sessions. Letters, digits, '-', or '_'.
387 </span>
388 )}
389 </label>
390
391 <div className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
392 <span className="text-xs font-medium text-foreground">Accent color</span>
393 <div className="flex min-w-0 flex-wrap items-center gap-2">
394 <input
395 type="color"
396 value={normalizeProviderAccentColor(accentColor) ?? PROVIDER_ACCENT_SWATCHES[0]}
397 onChange={(event) => setAccentColor(event.target.value)}
398 aria-label="Provider instance accent color"
399 className="h-8 w-10 cursor-pointer rounded-xl border border-input bg-background p-0.5"
400 />
401 <div className="flex flex-wrap gap-1.5">
402 {PROVIDER_ACCENT_SWATCHES.map((swatch) => {
403 const selected = accentColor.toLowerCase() === swatch;
404 return (
405 <button
406 key={swatch}
407 type="button"
408 className={cn(
409 "size-6 cursor-pointer rounded-full border transition",
410 selected
411 ? "scale-110 border-foreground ring-2 ring-ring ring-offset-1 ring-offset-background"
412 : "border-black/10 hover:scale-105 dark:border-white/20",
413 )}
414 style={{ backgroundColor: swatch }}
415 onClick={() => setAccentColor(swatch)}
416 aria-label={`Use ${swatch} accent`}
417 />
418 );
419 })}
420 </div>
421 {accentColor ? (
422 <Button
423 type="button"
424 size="sm"
425 variant="ghost"
426 className="h-7 px-2 text-xs text-muted-foreground"
427 onClick={() => setAccentColor("")}
428 >
429 Clear
430 </Button>
431 ) : null}
432 </div>
433 <span className="text-[11px] text-muted-foreground">
434 Optional marker shown in the picker.
435 </span>
436 </div>
437
438 {driverSettingsFields.length > 0 ? (
439 <div className={cn("grid gap-4", wizardStep !== 2 && "hidden")}>
440 <ProviderSettingsForm
441 definition={driverOption}
442 value={configDraft}
443 idPrefix={`add-provider-${driver}`}
444 variant="dialog"
445 onChange={setConfigDraft}
446 />
447 </div>
448 ) : wizardStep === 2 ? (
449 <div className="grid gap-2">
450 <p className="text-sm text-muted-foreground">
451 This driver has no required configuration. You can add the instance now.
452 </p>
453 </div>
454 ) : null}
455 </AnimatedHeight>
456 </div>
457
458 <DialogFooter className="border-t bg-background">
459 <Button
460 variant="outline"
461 size="sm"
462 onClick={() => {
463 if (wizardStep === 0) {
464 onOpenChange(false);
465 return;
466 }
467 setWizardStep((step) => Math.max(0, step - 1));
468 }}
469 >
470 {wizardStep === 0 ? "Cancel" : "Back"}
471 </Button>
472 {wizardStep < wizardSteps.length - 1 ? (
473 <Button size="sm" onClick={() => setWizardStep((step) => Math.min(2, step + 1))}>
474 Next
475 </Button>
476 ) : (
477 <Button size="sm" onClick={handleSave}>
478 Add instance
479 </Button>
480 )}
481 </DialogFooter>
482 </div>
483 </DialogPopup>
484 </Dialog>
485 );
486}