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 { ProviderAccentColorPicker } from "./ProviderAccentColorPicker";
25import { ProviderSettingsForm, deriveProviderSettingsFields } from "./ProviderSettingsForm";
26import { WizardPanel, WizardPopup, WizardHeader, WizardFooter } from "../ui/wizard";
27import {
28 ADD_PROVIDER_WIZARD_STEPS,
29 resolveWizardNavigation,
30 type WizardNavigation,
31} from "./AddProviderInstanceDialog.logic";
32import { AddProviderInstanceWizardSteps } from "./AddProviderInstanceWizardSteps";
33
34const PROVIDER_ACCENT_SWATCHES = [
35 "#2563eb",
36 "#16a34a",
37 "#ea580c",
38 "#dc2626",
39 "#7c3aed",
40 "#0891b2",
41] as const;
42
43/**
44 * Normalize a user-provided label into a slug suffix for the instance id.
45 * The full id is formed by prefixing the driver slug — e.g. label "Work" on
46 * driver "codex" becomes `codex_work`. Output is trimmed to 48 chars so the
47 * final composed id stays under the 64-char slug cap enforced by
48 * `ProviderInstanceId` in `@t3tools/contracts`.
49 */
50function slugifyLabel(value: string): string {
51 return value
52 .trim()
53 .toLowerCase()
54 .replace(/[^a-z0-9]+/g, "_")
55 .replace(/^_+|_+$/g, "")
56 .slice(0, 48);
57}
58
59function deriveInstanceId(driver: ProviderDriverKind, label: string): string {
60 const slug = slugifyLabel(label);
61 return slug ? `${driver}_${slug}` : "";
62}
63
64const INSTANCE_ID_PATTERN = /^[a-zA-Z][a-zA-Z0-9_-]*$/;
65const DEFAULT_DRIVER_KIND = ProviderDriverKind.make("codex");
66const DEFAULT_DRIVER_OPTION = DRIVER_OPTIONS[0]!;
67const EMPTY_CONFIG_DRAFT: Record<string, unknown> = {};
68interface ComingSoonDriverOption {
69 readonly value: ProviderDriverKind;
70 readonly label: string;
71 readonly icon: Icon;
72}
73
74const COMING_SOON_DRIVER_OPTIONS: readonly ComingSoonDriverOption[] = [
75 {
76 value: ProviderDriverKind.make("githubCopilot"),
77 label: "Github Copilot",
78 icon: GithubCopilotIcon,
79 },
80 {
81 value: ProviderDriverKind.make("gemini"),
82 label: "Gemini",
83 icon: Gemini,
84 },
85 {
86 value: ProviderDriverKind.make("acpRegistry"),
87 label: "ACP Registry",
88 icon: ACPRegistryIcon,
89 },
90 {
91 value: ProviderDriverKind.make("piAgent"),
92 label: "Pi Agent",
93 icon: PiAgentIcon,
94 },
95];
96
97/**
98 * Validate an instance id against the same slug rules the server applies in
99 * `ProviderInstanceId` (see `packages/contracts/src/providerInstance.ts`).
100 * Returns a user-facing error string, or `null` if valid.
101 */
102function validateInstanceId(id: string, existing: ReadonlySet<string>): string | null {
103 if (id.length === 0) return "Instance ID is required.";
104 if (id.length > 64) return "Instance ID must be 64 characters or fewer.";
105 if (!INSTANCE_ID_PATTERN.test(id)) {
106 return "Instance ID must start with a letter and use only letters, digits, '-', or '_'.";
107 }
108 if (existing.has(id)) return `An instance named '${id}' already exists.`;
109 return null;
110}
111
112interface AddProviderInstanceDialogProps {
113 readonly open: boolean;
114 readonly environmentId: EnvironmentId;
115 readonly environmentLabel: string;
116 readonly onOpenChange: (open: boolean) => void;
117}
118
119export function AddProviderInstanceDialog({
120 open,
121 environmentId,
122 environmentLabel,
123 onOpenChange,
124}: AddProviderInstanceDialogProps) {
125 const settings = useEnvironmentSettings(environmentId);
126 const updateSettings = useUpdateEnvironmentSettings(environmentId);
127
128 const [wizardStep, setWizardStep] = useState(0);
129 const [driver, setDriver] = useState<ProviderDriverKind>(DEFAULT_DRIVER_KIND);
130 const [label, setLabel] = useState("");
131 const [accentColor, setAccentColor] = useState<string>("");
132 const [instanceIdOverride, setInstanceIdOverride] = useState<string | null>(null);
133 // Driver-specific config drafts keyed by driver so toggling between drivers
134 // during the same dialog session does not lose in-progress input.
135 const [configByDriver, setConfigByDriver] = useState<Record<string, Record<string, unknown>>>({});
136 // Errors are suppressed until the user has tried to submit once. After that
137 // they update live so fixing the problem clears the message in place.
138 const [hasAttemptedSubmit, setHasAttemptedSubmit] = useState(false);
139
140 const existingIds = useMemo(
141 () => new Set(Object.keys(settings.providerInstances ?? {})),
142 [settings.providerInstances],
143 );
144
145 const driverOption = DRIVER_OPTION_BY_VALUE[driver] ?? DEFAULT_DRIVER_OPTION;
146 const instanceId = instanceIdOverride ?? deriveInstanceId(driver, label);
147 const driverSettingsFields = useMemo(
148 () => deriveProviderSettingsFields(driverOption),
149 [driverOption],
150 );
151 const instanceIdError = validateInstanceId(instanceId, existingIds);
152 const showInstanceIdError = hasAttemptedSubmit && instanceIdError !== null;
153 const previewLabel = label.trim() || `${driverOption.label} Workspace`;
154 const wizardStepSummaries = [driverOption.label, previewLabel, null] as const;
155
156 const configDraft = configByDriver[driver] ?? EMPTY_CONFIG_DRAFT;
157 const setConfigDraft = (config: Record<string, unknown> | undefined) => {
158 setConfigByDriver((existing) => {
159 const next = { ...existing };
160 if (config === undefined || Object.keys(config).length === 0) {
161 delete next[driver];
162 } else {
163 next[driver] = config;
164 }
165 return next;
166 });
167 };
168
169 const applyWizardNavigation = (navigation: WizardNavigation) => {
170 if (navigation.kind === "blocked") {
171 setHasAttemptedSubmit(true);
172 }
173 setWizardStep(navigation.step);
174 };
175
176 const navigateToStep = (requestedStep: number) => {
177 applyWizardNavigation(
178 resolveWizardNavigation(wizardStep, requestedStep, ADD_PROVIDER_WIZARD_STEPS.length, {
179 instanceIdError,
180 }),
181 );
182 };
183
184 const handleSave = () => {
185 setHasAttemptedSubmit(true);
186 if (instanceIdError !== null) return;
187
188 const config = configByDriver[driver] ?? {};
189 const hasConfig = Object.keys(config).length > 0;
190 const normalizedAccentColor = normalizeProviderAccentColor(accentColor);
191
192 const nextInstance: ProviderInstanceConfig = {
193 driver,
194 enabled: true,
195 ...(label.trim().length > 0 ? { displayName: label.trim() } : {}),
196 ...(normalizedAccentColor ? { accentColor: normalizedAccentColor } : {}),
197 ...(hasConfig ? { config } : {}),
198 };
199 // `ProviderInstanceId.make` revalidates the slug; we've already checked
200 // it via `validateInstanceId`, but going through the brand constructor
201 // keeps the type boundary honest and guards against any future drift in
202 // the slug rules.
203 const brandedId = ProviderInstanceId.make(instanceId);
204 const nextMap = {
205 ...settings.providerInstances,
206 [brandedId]: nextInstance,
207 };
208 try {
209 updateSettings({ providerInstances: nextMap });
210 toastManager.add({
211 type: "success",
212 title: "Provider instance added",
213 description: `${driverOption.label} instance '${instanceId}' was added.`,
214 });
215 onOpenChange(false);
216 } catch (error) {
217 toastManager.add({
218 type: "error",
219 title: "Could not add provider instance",
220 description: error instanceof Error ? error.message : "Update failed.",
221 });
222 }
223 };
224
225 return (
226 <Dialog open={open} onOpenChange={onOpenChange}>
227 <WizardPopup>
228 <WizardHeader
229 title="Add provider instance"
230 description={
231 <>
232 Configure an additional provider instance on {environmentLabel} — for example, a
233 second Codex install pointed at a different workspace.
234 </>
235 }
236 >
237 <AddProviderInstanceWizardSteps
238 currentStep={wizardStep}
239 summaries={wizardStepSummaries}
240 instanceIdError={instanceIdError}
241 onNavigation={applyWizardNavigation}
242 />
243 </WizardHeader>
244
245 <WizardPanel>
246 <div className={cn("grid gap-2", wizardStep !== 0 && "hidden")}>
247 <div id="add-instance-driver-label" className="text-sm font-medium text-foreground">
248 Driver
249 </div>
250 <RadioGroup
251 value={driver}
252 onValueChange={(value) => setDriver(ProviderDriverKind.make(value))}
253 aria-labelledby="add-instance-driver-label"
254 className="grid grid-cols-1 gap-2 sm:grid-cols-2"
255 >
256 {DRIVER_OPTIONS.map((option) => {
257 const IconComponent = option.icon;
258 return (
259 <RadioPrimitive.Root
260 key={option.value}
261 value={option.value}
262 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"
263 >
264 <IconComponent className="size-4 shrink-0" aria-hidden />
265 <span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
266 {option.label}
267 </span>
268 <RadioPrimitive.Indicator
269 className="grid size-5 shrink-0 place-items-center rounded-full bg-primary text-primary-foreground"
270 aria-hidden
271 >
272 <CheckIcon className="size-3.5 shrink-0" />
273 </RadioPrimitive.Indicator>
274 {option.badgeLabel ? (
275 <Badge variant="warning" size="sm">
276 {option.badgeLabel}
277 </Badge>
278 ) : null}
279 </RadioPrimitive.Root>
280 );
281 })}
282 {COMING_SOON_DRIVER_OPTIONS.map((option) => {
283 const IconComponent = option.icon;
284 return (
285 <RadioPrimitive.Root
286 key={option.value}
287 value={option.value}
288 disabled
289 className={cn(
290 "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",
291 )}
292 >
293 <IconComponent className="size-4 shrink-0 text-muted-foreground" aria-hidden />
294 <span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
295 {option.label}
296 </span>
297 <Badge variant="warning" size="sm">
298 Coming Soon
299 </Badge>
300 </RadioPrimitive.Root>
301 );
302 })}
303 </RadioGroup>
304 </div>
305
306 <label className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
307 <span className="text-xs font-medium text-foreground">Label</span>
308 <Input
309 className="bg-background"
310 placeholder="e.g. Work"
311 value={label}
312 onChange={(event) => setLabel(event.target.value)}
313 />
314 <span className="text-[11px] text-muted-foreground">
315 Shown in the provider list. Optional.
316 </span>
317 </label>
318
319 <label className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
320 <span className="text-xs font-medium text-foreground">Instance ID</span>
321 <Input
322 className="bg-background"
323 placeholder={`${driver}_work`}
324 value={instanceId}
325 onChange={(event) => {
326 setInstanceIdOverride(event.target.value);
327 }}
328 aria-invalid={showInstanceIdError}
329 />
330 {showInstanceIdError ? (
331 <span className="text-[11px] text-destructive">{instanceIdError}</span>
332 ) : (
333 <span className="text-[11px] text-muted-foreground">
334 Routing key used by threads and sessions. Letters, digits, '-', or '_'.
335 </span>
336 )}
337 </label>
338
339 <div className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
340 <span className="text-xs font-medium text-foreground">Accent color</span>
341 <div className="flex min-w-0 flex-wrap items-center gap-2">
342 <ProviderAccentColorPicker
343 displayName={label || driverOption.label}
344 value={accentColor || undefined}
345 onCommit={setAccentColor}
346 layout="inline"
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}