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

AddProviderInstanceDialog.tsx

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