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

AddProviderInstanceDialog.tsx

445 lines17.5 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 { AnimatedHeight } from "../AnimatedHeight";
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 <div
250 data-slot="dialog-panel"
251 className="space-y-4 bg-zinc-25/80 px-6 py-5 ring-1 ring-black/5 dark:bg-white/2 dark:ring-white/5"
252 >
253 <AnimatedHeight>
254 <div className={cn("grid gap-2", wizardStep !== 0 && "hidden")}>
255 <div id="add-instance-driver-label" className="text-sm font-medium text-foreground">
256 Driver
257 </div>
258 <RadioGroup
259 value={driver}
260 onValueChange={(value) => setDriver(ProviderDriverKind.make(value))}
261 aria-labelledby="add-instance-driver-label"
262 className="grid grid-cols-1 gap-2 sm:grid-cols-2"
263 >
264 {DRIVER_OPTIONS.map((option) => {
265 const IconComponent = option.icon;
266 return (
267 <RadioPrimitive.Root
268 key={option.value}
269 value={option.value}
270 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"
271 >
272 <IconComponent className="size-4 shrink-0" aria-hidden />
273 <span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
274 {option.label}
275 </span>
276 <RadioPrimitive.Indicator
277 className="grid size-5 shrink-0 place-items-center rounded-full bg-primary text-primary-foreground"
278 aria-hidden
279 >
280 <CheckIcon className="size-3.5 shrink-0" />
281 </RadioPrimitive.Indicator>
282 {option.badgeLabel ? (
283 <Badge variant="warning" size="sm">
284 {option.badgeLabel}
285 </Badge>
286 ) : null}
287 </RadioPrimitive.Root>
288 );
289 })}
290 {COMING_SOON_DRIVER_OPTIONS.map((option) => {
291 const IconComponent = option.icon;
292 return (
293 <RadioPrimitive.Root
294 key={option.value}
295 value={option.value}
296 disabled
297 className={cn(
298 "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",
299 )}
300 >
301 <IconComponent
302 className="size-4 shrink-0 text-muted-foreground"
303 aria-hidden
304 />
305 <span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
306 {option.label}
307 </span>
308 <Badge variant="warning" size="sm">
309 Coming Soon
310 </Badge>
311 </RadioPrimitive.Root>
312 );
313 })}
314 </RadioGroup>
315 </div>
316​
317 <label className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
318 <span className="text-xs font-medium text-foreground">Label</span>
319 <Input
320 className="bg-background"
321 placeholder="e.g. Work"
322 value={label}
323 onChange={(event) => setLabel(event.target.value)}
324 />
325 <span className="text-[11px] text-muted-foreground">
326 Shown in the provider list. Optional.
327 </span>
328 </label>
329​
330 <label className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
331 <span className="text-xs font-medium text-foreground">Instance ID</span>
332 <Input
333 className="bg-background"
334 placeholder={`${driver}_work`}
335 value={instanceId}
336 onChange={(event) => {
337 setInstanceIdOverride(event.target.value);
338 }}
339 aria-invalid={showInstanceIdError}
340 />
341 {showInstanceIdError ? (
342 <span className="text-[11px] text-destructive">{instanceIdError}</span>
343 ) : (
344 <span className="text-[11px] text-muted-foreground">
345 Routing key used by threads and sessions. Letters, digits, '-', or '_'.
346 </span>
347 )}
348 </label>
349​
350 <div className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
351 <span className="text-xs font-medium text-foreground">Accent color</span>
352 <div className="flex min-w-0 flex-wrap items-center gap-2">
353 <input
354 type="color"
355 value={normalizeProviderAccentColor(accentColor) ?? PROVIDER_ACCENT_SWATCHES[0]}
356 onChange={(event) => setAccentColor(event.target.value)}
357 aria-label="Provider instance accent color"
358 className="h-8 w-10 cursor-pointer rounded-xl border border-input bg-background p-0.5"
359 />
360 <div className="flex flex-wrap gap-1.5">
361 {PROVIDER_ACCENT_SWATCHES.map((swatch) => {
362 const selected = accentColor.toLowerCase() === swatch;
363 return (
364 <button
365 key={swatch}
366 type="button"
367 className={cn(
368 "size-6 cursor-pointer rounded-full border transition",
369 selected
370 ? "scale-110 border-foreground ring-2 ring-ring ring-offset-1 ring-offset-background"
371 : "border-black/10 hover:scale-105 dark:border-white/20",
372 )}
373 style={{ backgroundColor: swatch }}
374 onClick={() => setAccentColor(swatch)}
375 aria-label={`Use ${swatch} accent`}
376 />
377 );
378 })}
379 </div>
380 {accentColor ? (
381 <Button
382 type="button"
383 size="sm"
384 variant="ghost"
385 className="h-7 px-2 text-xs text-muted-foreground"
386 onClick={() => setAccentColor("")}
387 >
388 Clear
389 </Button>
390 ) : null}
391 </div>
392 <span className="text-[11px] text-muted-foreground">
393 Optional marker shown in the picker.
394 </span>
395 </div>
396​
397 {driverSettingsFields.length > 0 ? (
398 <div className={cn("grid gap-4", wizardStep !== 2 && "hidden")}>
399 <ProviderSettingsForm
400 definition={driverOption}
401 value={configDraft}
402 idPrefix={`add-provider-${driver}`}
403 variant="dialog"
404 onChange={setConfigDraft}
405 />
406 </div>
407 ) : wizardStep === 2 ? (
408 <div className="grid gap-2">
409 <p className="text-sm text-muted-foreground">
410 This driver has no required configuration. You can add the instance now.
411 </p>
412 </div>
413 ) : null}
414 </AnimatedHeight>
415 </div>
416​
417 <DialogFooter variant="bare">
418 <Button
419 variant="outline"
420 size="sm"
421 onClick={() => {
422 if (wizardStep === 0) {
423 onOpenChange(false);
424 return;
425 }
426 setWizardStep((step) => Math.max(0, step - 1));
427 }}
428 >
429 {wizardStep === 0 ? "Cancel" : "Back"}
430 </Button>
431 {wizardStep < ADD_PROVIDER_WIZARD_STEPS.length - 1 ? (
432 <Button size="sm" onClick={() => navigateToStep(wizardStep + 1)}>
433 Next
434 </Button>
435 ) : (
436 <Button size="sm" onClick={handleSave}>
437 Add instance
438 </Button>
439 )}
440 </DialogFooter>
441 </div>
442 </DialogPopup>
443 </Dialog>
444 );