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