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 "@t3tools/contracts";
11
12import { usePrimarySettings, useUpdatePrimarySettings } from "../../hooks/useSettings";
13import { cn } from "../../lib/utils";
14import { normalizeProviderAccentColor } from "../../providerInstances";
15import { Button } from "../ui/button";
16import { 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 `@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("piAgent"),
86 label: "Pi Agent",
87 icon: PiAgentIcon,
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 = usePrimarySettings();
113 const updateSettings = useUpdatePrimarySettings();
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 [instanceIdOverride, setInstanceIdOverride] = useState<string | null>(null);
120 // Driver-specific config drafts keyed by driver so toggling between drivers
121 // during the same dialog session does not lose in-progress input.
122 const [configByDriver, setConfigByDriver] = useState<Record<string, Record<string, unknown>>>({});
123 // Errors are suppressed until the user has tried to submit once. After that
124 // they update live so fixing the problem clears the message in place.
125 const [hasAttemptedSubmit, setHasAttemptedSubmit] = useState(false);
126
127 const existingIds = useMemo(
128 () => new Set(Object.keys(settings.providerInstances ?? {})),
129 [settings.providerInstances],
130 );
131
132 const driverOption = DRIVER_OPTION_BY_VALUE[driver] ?? DEFAULT_DRIVER_OPTION;
133 const instanceId = instanceIdOverride ?? deriveInstanceId(driver, label);
134 const driverSettingsFields = useMemo(
135 () => deriveProviderSettingsFields(driverOption),
136 [driverOption],
137 );
138 const instanceIdError = validateInstanceId(instanceId, existingIds);
139 const showInstanceIdError = hasAttemptedSubmit && instanceIdError !== null;
140 const previewLabel = label.trim() || `${driverOption.label} Workspace`;
141 const wizardSteps = ["Driver", "Identity", "Config"] as const;
142 const wizardStepSummaries = [driverOption.label, previewLabel, null] as const;
143
144 const configDraft = configByDriver[driver] ?? EMPTY_CONFIG_DRAFT;
145 const setConfigDraft = useCallback(
146 (config: Record<string, unknown> | undefined) => {
147 setConfigByDriver((existing) => {
148 const next = { ...existing };
149 if (config === undefined || Object.keys(config).length === 0) {
150 delete next[driver];
151 } else {
152 next[driver] = config;
153 }
154 return next;
155 });
156 },
157 [driver],
158 );
159
160 const handleSave = useCallback(() => {
161 setHasAttemptedSubmit(true);
162 if (instanceIdError !== null) return;
163
164 const config = configByDriver[driver] ?? {};
165 const hasConfig = Object.keys(config).length > 0;
166 const normalizedAccentColor = normalizeProviderAccentColor(accentColor);
167
168 const nextInstance: ProviderInstanceConfig = {
169 driver,
170 enabled: true,
171 ...(label.trim().length > 0 ? { displayName: label.trim() } : {}),
172 ...(normalizedAccentColor ? { accentColor: normalizedAccentColor } : {}),
173 ...(hasConfig ? { config } : {}),
174 };
175 // `ProviderInstanceId.make` revalidates the slug; we've already checked
176 // it via `validateInstanceId`, but going through the brand constructor
177 // keeps the type boundary honest and guards against any future drift in
178 // the slug rules.
179 const brandedId = ProviderInstanceId.make(instanceId);
180 const nextMap = {
181 ...settings.providerInstances,
182 [brandedId]: nextInstance,
183 };
184 try {
185 updateSettings({ providerInstances: nextMap });
186 toastManager.add({
187 type: "success",
188 title: "Provider instance added",
189 description: `${driverOption.label} instance '${instanceId}' was added.`,
190 });
191 onOpenChange(false);
192 } catch (error) {
193 toastManager.add({
194 type: "error",
195 title: "Could not add provider instance",
196 description: error instanceof Error ? error.message : "Update failed.",
197 });
198 }
199 }, [
200 driver,
201 driverOption,
202 configByDriver,
203 instanceId,
204 instanceIdError,
205 label,
206 accentColor,
207 onOpenChange,
208 settings.providerInstances,
209 updateSettings,
210 ]);
211
212 return (
213 <Dialog open={open} onOpenChange={onOpenChange}>
214 <DialogPopup className="max-w-xl overflow-hidden">
215 <div className="flex min-h-0 flex-col overflow-hidden border-foreground/10 bg-background shadow-2xl">
216 <DialogHeader className="border-b border-border/70 bg-background">
217 <DialogTitle>Add provider instance</DialogTitle>
218 <DialogDescription>
219 Configure an additional provider instance — for example, a second Codex install
220 pointed at a different workspace.
221 </DialogDescription>
222 <div className="grid grid-cols-3 gap-2">
223 {wizardSteps.map((step, index) => (
224 <button
225 key={step}
226 type="button"
227 className={cn(
228 "grid min-w-0 grid-cols-[1rem_minmax(0,1fr)] gap-x-2 rounded-lg border px-3 py-2 text-left",
229 index === wizardStep
230 ? "border-primary bg-primary/10 ring-1 ring-primary/25"
231 : index < wizardStep
232 ? "border-border bg-background"
233 : "border-border bg-muted/40",
234 )}
235 onClick={() => setWizardStep(index)}
236 >
237 <span
238 className={cn(
239 "row-span-2 mt-0.5 grid size-4 place-items-center rounded-full border",
240 index < wizardStep
241 ? "border-primary bg-primary text-primary-foreground"
242 : index === wizardStep
243 ? "border-primary bg-background"
244 : "border-muted-foreground/35 bg-background",
245 )}
246 aria-hidden
247 >
248 {index < wizardStep ? <CheckIcon className="size-3" /> : null}
249 </span>
250 <span className="text-[10px] font-medium uppercase text-muted-foreground">
251 Step {index + 1}
252 </span>
253 <span className="truncate text-xs font-semibold text-foreground">
254 {step}
255 {index < wizardStep && wizardStepSummaries[index]
256 ? `: ${wizardStepSummaries[index]}`
257 : ""}
258 </span>
259 </button>
260 ))}
261 </div>
262 </DialogHeader>
263
264 <div
265 data-slot="dialog-panel"
266 className="space-y-4 border-b border-border/70 bg-muted/20 px-6 py-5"
267 >
268 <AnimatedHeight>
269 <div className={cn("grid gap-2", wizardStep !== 0 && "hidden")}>
270 <span
271 id="add-instance-driver-label"
272 className="text-xs font-medium text-foreground"
273 >
274 Driver
275 </span>
276 <RadioGroup
277 value={driver}
278 onValueChange={(value) => setDriver(ProviderDriverKind.make(value))}
279 aria-labelledby="add-instance-driver-label"
280 className="grid grid-cols-2 gap-2.5"
281 >
282 {DRIVER_OPTIONS.map((option) => {
283 const IconComponent = option.icon;
284 const isSelected = option.value === driver;
285 return (
286 <RadioPrimitive.Root
287 key={option.value}
288 value={option.value}
289 className={cn(
290 "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]",
291 "focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
292 isSelected
293 ? "border-primary bg-background shadow-sm ring-2 ring-primary/35"
294 : "border-border bg-background hover:border-foreground/20 hover:bg-muted/50",
295 )}
296 >
297 <IconComponent className="size-5 shrink-0" aria-hidden />
298 <span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
299 {option.label}
300 </span>
301 {option.badgeLabel ? (
302 <Badge variant="warning" size="sm">
303 {option.badgeLabel}
304 </Badge>
305 ) : null}
306 </RadioPrimitive.Root>
307 );
308 })}
309 {COMING_SOON_DRIVER_OPTIONS.map((option) => {
310 const IconComponent = option.icon;
311 return (
312 <RadioPrimitive.Root
313 key={option.value}
314 value={option.value}
315 disabled
316 className={cn(
317 "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",
318 )}
319 >
320 <IconComponent
321 className="size-5 shrink-0 text-muted-foreground"
322 aria-hidden
323 />
324 <span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
325 {option.label}
326 </span>
327 <Badge variant="warning" size="sm">
328 Coming Soon
329 </Badge>
330 </RadioPrimitive.Root>
331 );
332 })}
333 </RadioGroup>
334 </div>
335
336 <label className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
337 <span className="text-xs font-medium text-foreground">Label</span>
338 <Input
339 className="bg-background"
340 placeholder="e.g. Work"
341 value={label}
342 onChange={(event) => setLabel(event.target.value)}
343 />
344 <span className="text-[11px] text-muted-foreground">
345 Shown in the provider list. Optional.
346 </span>
347 </label>
348
349 <label className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
350 <span className="text-xs font-medium text-foreground">Instance ID</span>
351 <Input
352 className="bg-background"
353 placeholder={`${driver}_work`}
354 value={instanceId}
355 onChange={(event) => {
356 setInstanceIdOverride(event.target.value);
357 }}
358 aria-invalid={showInstanceIdError}
359 />
360 {showInstanceIdError ? (
361 <span className="text-[11px] text-destructive">{instanceIdError}</span>
362 ) : (
363 <span className="text-[11px] text-muted-foreground">
364 Routing key used by threads and sessions. Letters, digits, '-', or '_'.
365 </span>
366 )}
367 </label>
368
369 <div className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
370 <span className="text-xs font-medium text-foreground">Accent color</span>
371 <div className="flex min-w-0 flex-wrap items-center gap-2">
372 <input
373 type="color"
374 value={normalizeProviderAccentColor(accentColor) ?? PROVIDER_ACCENT_SWATCHES[0]}
375 onChange={(event) => setAccentColor(event.target.value)}
376 aria-label="Provider instance accent color"
377 className="h-8 w-10 cursor-pointer rounded-xl border border-input bg-background p-0.5"
378 />
379 <div className="flex flex-wrap gap-1.5">
380 {PROVIDER_ACCENT_SWATCHES.map((swatch) => {
381 const selected = accentColor.toLowerCase() === swatch;
382 return (
383 <button
384 key={swatch}
385 type="button"
386 className={cn(
387 "size-6 cursor-pointer rounded-full border transition",
388 selected
389 ? "scale-110 border-foreground ring-2 ring-ring ring-offset-1 ring-offset-background"
390 : "border-black/10 hover:scale-105 dark:border-white/20",
391 )}
392 style={{ backgroundColor: swatch }}
393 onClick={() => setAccentColor(swatch)}
394 aria-label={`Use ${swatch} accent`}
395 />
396 );
397 })}
398 </div>
399 {accentColor ? (
400 <Button
401 type="button"
402 size="sm"
403 variant="ghost"
404 className="h-7 px-2 text-xs text-muted-foreground"
405 onClick={() => setAccentColor("")}
406 >
407 Clear
408 </Button>
409 ) : null}
410 </div>
411 <span className="text-[11px] text-muted-foreground">
412 Optional marker shown in the picker.
413 </span>
414 </div>
415
416 {driverSettingsFields.length > 0 ? (
417 <div className={cn("grid gap-4", wizardStep !== 2 && "hidden")}>
418 <ProviderSettingsForm
419 definition={driverOption}
420 value={configDraft}
421 idPrefix={`add-provider-${driver}`}
422 variant="dialog"
423 onChange={setConfigDraft}
424 />
425 </div>
426 ) : wizardStep === 2 ? (
427 <div className="grid gap-2">
428 <p className="text-sm text-muted-foreground">
429 This driver has no required configuration. You can add the instance now.
430 </p>
431 </div>
432 ) : null}
433 </AnimatedHeight>
434 </div>
435
436 <DialogFooter className="border-t bg-background">
437 <Button
438 variant="outline"
439 size="sm"
440 onClick={() => {
441 if (wizardStep === 0) {
442 onOpenChange(false);
443 return;
444 }
445 setWizardStep((step) => Math.max(0, step - 1));
446 }}
447 >
448 {wizardStep === 0 ? "Cancel" : "Back"}
449 </Button>
450 {wizardStep < wizardSteps.length - 1 ? (
451 <Button size="sm" onClick={() => setWizardStep((step) => Math.min(2, step + 1))}>
452 Next
453 </Button>
454 ) : (
455 <Button size="sm" onClick={handleSave}>
456 Add instance
457 </Button>
458 )}
459 </DialogFooter>
460 </div>
461 </DialogPopup>
462 </Dialog>
463 );
464}