Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AddProviderInstanceDialog.tsx

485 lines18.6 KB

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, 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";
31​
32const PROVIDER_ACCENT_SWATCHES = [
33 "#2563eb",
34 "#16a34a",
35 "#ea580c",
36 "#dc2626",
37 "#7c3aed",
38 "#0891b2",
39] as const;
40​
41/**
42 * Normalize a user-provided label into a slug suffix for the instance id.
43 * The full id is formed by prefixing the driver slug — e.g. label "Work" on
44 * driver "codex" becomes `codex_work`. Output is trimmed to 48 chars so the
45 * final composed id stays under the 64-char slug cap enforced by
46 * `ProviderInstanceId` in `@t3tools/contracts`.
47 */
48function slugifyLabel(value: string): string {
49 return value
50 .trim()
51 .toLowerCase()
52 .replace(/[^a-z0-9]+/g, "_")
53 .replace(/^_+|_+$/g, "")
54 .slice(0, 48);
56​
57function deriveInstanceId(driver: ProviderDriverKind, label: string): string {
58 const slug = slugifyLabel(label);
59 return slug ? `${driver}_${slug}` : "";
61​
62const INSTANCE_ID_PATTERN = /^[a-zA-Z][a-zA-Z0-9_-]*$/;
63const DEFAULT_DRIVER_KIND = ProviderDriverKind.make("codex");
64const DEFAULT_DRIVER_OPTION = DRIVER_OPTIONS[0]!;
65const EMPTY_CONFIG_DRAFT: Record<string, unknown> = {};
66interface ComingSoonDriverOption {
67 readonly value: ProviderDriverKind;
68 readonly label: string;
69 readonly icon: Icon;
71​
72const COMING_SOON_DRIVER_OPTIONS: readonly ComingSoonDriverOption[] = [
73 {
74 value: ProviderDriverKind.make("githubCopilot"),
75 label: "Github Copilot",
76 icon: GithubCopilotIcon,
77 },
78 {
79 value: ProviderDriverKind.make("gemini"),
80 label: "Gemini",
81 icon: Gemini,
82 },
83 {
84 value: ProviderDriverKind.make("acpRegistry"),
85 label: "ACP Registry",
86 icon: ACPRegistryIcon,
87 },
88 {
89 value: ProviderDriverKind.make("piAgent"),
90 label: "Pi Agent",
91 icon: PiAgentIcon,
92 },
93];
94​
95/**
96 * Validate an instance id against the same slug rules the server applies in
97 * `ProviderInstanceId` (see `packages/contracts/src/providerInstance.ts`).
98 * Returns a user-facing error string, or `null` if valid.
99 */
100function validateInstanceId(id: string, existing: ReadonlySet<string>): string | null {
101 if (id.length === 0) return "Instance ID is required.";
102 if (id.length > 64) return "Instance ID must be 64 characters or fewer.";
103 if (!INSTANCE_ID_PATTERN.test(id)) {
104 return "Instance ID must start with a letter and use only letters, digits, '-', or '_'.";
105 }
106 if (existing.has(id)) return `An instance named '${id}' already exists.`;
107 return null;
109​
110interface AddProviderInstanceDialogProps {
111 open: boolean;
112 onOpenChange: (open: boolean) => void;
114​
115export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderInstanceDialogProps) {
116 const settings = useSettings();
117 const { updateSettings } = useUpdateSettings();
118​
119 const [wizardStep, setWizardStep] = useState(0);
120 const [driver, setDriver] = useState<ProviderDriverKind>(DEFAULT_DRIVER_KIND);
121 const [label, setLabel] = useState("");
122 const [accentColor, setAccentColor] = useState<string>("");
123 const [instanceId, setInstanceId] = useState("");
124 const [instanceIdDirty, setInstanceIdDirty] = useState(false);
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 // Reset the form every time the dialog opens so each creation starts
138 // from a clean slate.
139 useEffect(() => {
140 if (!open) return;
141 setDriver(DEFAULT_DRIVER_KIND);
142 setLabel("");
143 setAccentColor("");
144 setInstanceId("");
145 setWizardStep(0);
146 setInstanceIdDirty(false);
147 setConfigByDriver({});
148 setHasAttemptedSubmit(false);
149 }, [open]);
150​
151 // Auto-derive the instance id from driver + label until the user types
152 // in the Instance ID field directly (after which they own its value).
153 useEffect(() => {
154 if (instanceIdDirty) return;
155 setInstanceId(deriveInstanceId(driver, label));
156 }, [driver, label, instanceIdDirty]);
157​
158 const driverOption = DRIVER_OPTION_BY_VALUE[driver] ?? DEFAULT_DRIVER_OPTION;
159 const driverSettingsFields = useMemo(
160 () => deriveProviderSettingsFields(driverOption),
161 [driverOption],
162 );
163 const instanceIdError = validateInstanceId(instanceId, existingIds);
164 const showInstanceIdError = hasAttemptedSubmit && instanceIdError !== null;
165 const previewLabel = label.trim() || `${driverOption.label} Workspace`;
166 const wizardSteps = ["Driver", "Identity", "Config"] as const;
167 const wizardStepSummaries = [driverOption.label, previewLabel, null] as const;
168​
169 const configDraft = configByDriver[driver] ?? EMPTY_CONFIG_DRAFT;
170 const setConfigDraft = useCallback(
171 (config: Record<string, unknown> | undefined) => {
172 setConfigByDriver((existing) => {
173 const next = { ...existing };
174 if (config === undefined || Object.keys(config).length === 0) {
175 delete next[driver];
176 } else {
177 next[driver] = config;
178 }
179 return next;
180 });
181 },
182 [driver],
183 );
184​
185 const handleSave = useCallback(() => {
186 setHasAttemptedSubmit(true);
187 if (instanceIdError !== null) return;
188​
189 const config = configByDriver[driver] ?? {};
190 const hasConfig = Object.keys(config).length > 0;
191 const normalizedAccentColor = normalizeProviderAccentColor(accentColor);
192​
193 const nextInstance: ProviderInstanceConfig = {
194 driver,
195 enabled: true,
196 ...(label.trim().length > 0 ? { displayName: label.trim() } : {}),
197 ...(normalizedAccentColor ? { accentColor: normalizedAccentColor } : {}),
198 ...(hasConfig ? { config } : {}),
199 };
200 // `ProviderInstanceId.make` revalidates the slug; we've already checked
201 // it via `validateInstanceId`, but going through the brand constructor
202 // keeps the type boundary honest and guards against any future drift in
203 // the slug rules.
204 const brandedId = ProviderInstanceId.make(instanceId);
205 const nextMap = {
206 ...settings.providerInstances,
207 [brandedId]: nextInstance,
208 };
209 try {
210 updateSettings({ providerInstances: nextMap });
211 toastManager.add({
212 type: "success",
213 title: "Provider instance added",
214 description: `${driverOption.label} instance '${instanceId}' was added.`,
215 });
216 onOpenChange(false);
217 } catch (error) {
218 toastManager.add({
219 type: "error",
220 title: "Could not add provider instance",
221 description: error instanceof Error ? error.message : "Update failed.",
222 });
223 }
224 }, [
225 driver,
226 driverOption,
227 configByDriver,
228 instanceId,
229 instanceIdError,
230 label,
231 accentColor,
232 onOpenChange,
233 settings.providerInstances,
234 updateSettings,
235 ]);
236​
237 return (
238 <Dialog open={open} onOpenChange={onOpenChange}>
239 <DialogPopup className="max-w-xl overflow-hidden">
240 <div className="flex min-h-0 flex-col overflow-hidden border-foreground/10 bg-background shadow-2xl">
241 <DialogHeader className="border-b border-border/70 bg-background">
242 <DialogTitle>Add provider instance</DialogTitle>
243 <DialogDescription>
244 Configure an additional provider instance — for example, a second Codex install
245 pointed at a different workspace.
246 </DialogDescription>
247 <div className="grid grid-cols-3 gap-2">
248 {wizardSteps.map((step, index) => (
249 <button
250 key={step}
251 type="button"
252 className={cn(
253 "grid min-w-0 grid-cols-[1rem_minmax(0,1fr)] gap-x-2 rounded-lg border px-3 py-2 text-left transition",
254 index === wizardStep
255 ? "border-primary bg-primary/10 ring-1 ring-primary/25"
256 : index < wizardStep
257 ? "border-border bg-background"
258 : "border-border bg-muted/40",
259 )}
260 onClick={() => setWizardStep(index)}
261 >
262 <span
263 className={cn(
264 "row-span-2 mt-0.5 grid size-4 place-items-center rounded-full border",
265 index < wizardStep
266 ? "border-primary bg-primary text-primary-foreground"
267 : index === wizardStep
268 ? "border-primary bg-background"
269 : "border-muted-foreground/35 bg-background",
270 )}
271 aria-hidden
272 >
273 {index < wizardStep ? <CheckIcon className="size-3" /> : null}
274 </span>
275 <span className="text-[10px] font-medium uppercase text-muted-foreground">
276 Step {index + 1}
277 </span>
278 <span className="truncate text-xs font-semibold text-foreground">
279 {step}
280 {index < wizardStep && wizardStepSummaries[index]
281 ? `: ${wizardStepSummaries[index]}`
282 : ""}
283 </span>
284 </button>
285 ))}
286 </div>
287 </DialogHeader>
288​
289 <div
290 data-slot="dialog-panel"
291 className="space-y-4 border-b border-border/70 bg-muted/20 px-6 py-5"
292 >
293 <div className={cn("grid gap-2", wizardStep !== 0 && "hidden")}>
294 <span id="add-instance-driver-label" className="text-xs font-medium text-foreground">
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 </div>
456​
457 <DialogFooter className="border-t bg-background">
458 <Button
459 variant="outline"
460 size="sm"
461 onClick={() => {
462 if (wizardStep === 0) {
463 onOpenChange(false);
464 return;
465 }
466 setWizardStep((step) => Math.max(0, step - 1));
467 }}
468 >
469 {wizardStep === 0 ? "Cancel" : "Back"}
470 </Button>
471 {wizardStep < wizardSteps.length - 1 ? (
472 <Button size="sm" onClick={() => setWizardStep((step) => Math.min(2, step + 1))}>
473 Next
474 </Button>
475 ) : (
476 <Button size="sm" onClick={handleSave}>
477 Add instance
478 </Button>
479 )}
480 </DialogFooter>
481 </div>
482 </DialogPopup>
483 </Dialog>
484 );