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

AddProviderInstanceDialog.tsx

435 lines16.9 KB

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