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

AddProviderInstanceDialog.tsx

440 lines17.4 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 { 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("piAgent"),
93 label: "Pi Agent",
94 icon: PiAgentIcon,
95 },
96];
97​
98/**
99 * Validate an instance id against the same slug rules the server applies in
100 * `ProviderInstanceId` (see `packages/contracts/src/providerInstance.ts`).
101 * Returns a user-facing error string, or `null` if valid.
102 */
103function validateInstanceId(id: string, existing: ReadonlySet<string>): string | null {
104 if (id.length === 0) return "Instance ID is required.";
105 if (id.length > 64) return "Instance ID must be 64 characters or fewer.";
106 if (!INSTANCE_ID_PATTERN.test(id)) {
107 return "Instance ID must start with a letter and use only letters, digits, '-', or '_'.";
108 }
109 if (existing.has(id)) return `An instance named '${id}' already exists.`;
110 return null;
112​
113interface AddProviderInstanceDialogProps {
114 readonly open: boolean;
115 readonly environmentId: EnvironmentId;
116 readonly environmentLabel: string;
117 readonly onOpenChange: (open: boolean) => void;
119​
120export function AddProviderInstanceDialog({
121 open,
122 environmentId,
123 environmentLabel,
124 onOpenChange,
125}: AddProviderInstanceDialogProps) {
126 const settings = useEnvironmentSettings(environmentId);
127 const updateSettings = useUpdateEnvironmentSettings(environmentId);
128​
129 const [wizardStep, setWizardStep] = useState(0);
130 const [driver, setDriver] = useState<ProviderDriverKind>(DEFAULT_DRIVER_KIND);
131 const [label, setLabel] = useState("");
132 const [accentColor, setAccentColor] = useState<string>("");
133 const [instanceIdOverride, setInstanceIdOverride] = useState<string | null>(null);
134 // Driver-specific config drafts keyed by driver so toggling between drivers
135 // during the same dialog session does not lose in-progress input.
136 const [configByDriver, setConfigByDriver] = useState<Record<string, Record<string, unknown>>>({});
137 // Errors are suppressed until the user has tried to submit once. After that
138 // they update live so fixing the problem clears the message in place.
139 const [hasAttemptedSubmit, setHasAttemptedSubmit] = useState(false);
140​
141 const existingIds = useMemo(
142 () => new Set(Object.keys(settings.providerInstances ?? {})),
143 [settings.providerInstances],
144 );
145​
146 const driverOption = DRIVER_OPTION_BY_VALUE[driver] ?? DEFAULT_DRIVER_OPTION;
147 const instanceId = instanceIdOverride ?? deriveInstanceId(driver, label);
148 const driverSettingsFields = useMemo(
149 () => deriveProviderSettingsFields(driverOption),
150 [driverOption],
151 );
152 const instanceIdError = validateInstanceId(instanceId, existingIds);
153 const showInstanceIdError = hasAttemptedSubmit && instanceIdError !== null;
154 const previewLabel = label.trim() || `${driverOption.label} Workspace`;
155 const wizardStepSummaries = [driverOption.label, previewLabel, null] as const;
156​
157 const configDraft = configByDriver[driver] ?? EMPTY_CONFIG_DRAFT;
158 const setConfigDraft = (config: Record<string, unknown> | undefined) => {
159 setConfigByDriver((existing) => {
160 const next = { ...existing };
161 if (config === undefined || Object.keys(config).length === 0) {
162 delete next[driver];
163 } else {
164 next[driver] = config;
165 }
166 return next;
167 });
168 };
169​
170 const applyWizardNavigation = (navigation: WizardNavigation) => {
171 if (navigation.kind === "blocked") {
172 setHasAttemptedSubmit(true);
173 }
174 setWizardStep(navigation.step);
175 };
176​
177 const navigateToStep = (requestedStep: number) => {
178 applyWizardNavigation(
179 resolveWizardNavigation(wizardStep, requestedStep, ADD_PROVIDER_WIZARD_STEPS.length, {
180 instanceIdError,
181 }),
182 );
183 };
184​
185 const handleSave = () => {
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​
226 return (
227 <Dialog open={open} onOpenChange={onOpenChange}>
228 <DialogPopup className="max-w-xl overflow-hidden">
229 <div className="flex min-h-0 flex-col overflow-hidden">
230 <DialogHeader>
231 <DialogTitle>Add provider instance</DialogTitle>
232 <DialogDescription>
233 Configure an additional provider instance on {environmentLabel} — for example, a
234 second Codex install pointed at a different workspace.
235 </DialogDescription>
236 <AddProviderInstanceWizardSteps
237 currentStep={wizardStep}
238 summaries={wizardStepSummaries}
239 instanceIdError={instanceIdError}
240 onNavigation={applyWizardNavigation}
241 />
242 </DialogHeader>
243​
244 <div
245 data-slot="dialog-panel"
246 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"
247 >
248 <AnimatedHeight>
249 <div className={cn("grid gap-2", wizardStep !== 0 && "hidden")}>
250 <div id="add-instance-driver-label" className="text-sm font-medium text-foreground">
251 Driver
252 </div>
253 <RadioGroup
254 value={driver}
255 onValueChange={(value) => setDriver(ProviderDriverKind.make(value))}
256 aria-labelledby="add-instance-driver-label"
257 className="grid grid-cols-1 gap-2 sm:grid-cols-2"
258 >
259 {DRIVER_OPTIONS.map((option) => {
260 const IconComponent = option.icon;
261 return (
262 <RadioPrimitive.Root
263 key={option.value}
264 value={option.value}
265 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"
266 >
267 <IconComponent className="size-4 shrink-0" aria-hidden />
268 <span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
269 {option.label}
270 </span>
271 <RadioPrimitive.Indicator
272 className="grid size-5 shrink-0 place-items-center rounded-full bg-primary text-primary-foreground"
273 aria-hidden
274 >
275 <CheckIcon className="size-3.5 shrink-0" />
276 </RadioPrimitive.Indicator>
277 {option.badgeLabel ? (
278 <Badge variant="warning" size="sm">
279 {option.badgeLabel}
280 </Badge>
281 ) : null}
282 </RadioPrimitive.Root>
283 );
284 })}
285 {COMING_SOON_DRIVER_OPTIONS.map((option) => {
286 const IconComponent = option.icon;
287 return (
288 <RadioPrimitive.Root
289 key={option.value}
290 value={option.value}
291 disabled
292 className={cn(
293 "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",
294 )}
295 >
296 <IconComponent
297 className="size-4 shrink-0 text-muted-foreground"
298 aria-hidden
299 />
300 <span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
301 {option.label}
302 </span>
303 <Badge variant="warning" size="sm">
304 Coming Soon
305 </Badge>
306 </RadioPrimitive.Root>
307 );
308 })}
309 </RadioGroup>
310 </div>
311​
312 <label className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
313 <span className="text-xs font-medium text-foreground">Label</span>
314 <Input
315 className="bg-background"
316 placeholder="e.g. Work"
317 value={label}
318 onChange={(event) => setLabel(event.target.value)}
319 />
320 <span className="text-[11px] text-muted-foreground">
321 Shown in the provider list. Optional.
322 </span>
323 </label>
324​
325 <label className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
326 <span className="text-xs font-medium text-foreground">Instance ID</span>
327 <Input
328 className="bg-background"
329 placeholder={`${driver}_work`}
330 value={instanceId}
331 onChange={(event) => {
332 setInstanceIdOverride(event.target.value);
333 }}
334 aria-invalid={showInstanceIdError}
335 />
336 {showInstanceIdError ? (
337 <span className="text-[11px] text-destructive">{instanceIdError}</span>
338 ) : (
339 <span className="text-[11px] text-muted-foreground">
340 Routing key used by threads and sessions. Letters, digits, '-', or '_'.
341 </span>
342 )}
343 </label>
344​
345 <div className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
346 <span className="text-xs font-medium text-foreground">Accent color</span>
347 <div className="flex min-w-0 flex-wrap items-center gap-2">
348 <input
349 type="color"
350 value={normalizeProviderAccentColor(accentColor) ?? PROVIDER_ACCENT_SWATCHES[0]}
351 onChange={(event) => setAccentColor(event.target.value)}
352 aria-label="Provider instance accent color"
353 className="h-8 w-10 cursor-pointer rounded-xl border border-input bg-background p-0.5"
354 />
355 <div className="flex flex-wrap gap-1.5">
356 {PROVIDER_ACCENT_SWATCHES.map((swatch) => {
357 const selected = accentColor.toLowerCase() === swatch;
358 return (
359 <button
360 key={swatch}
361 type="button"
362 className={cn(
363 "size-6 cursor-pointer rounded-full border transition",
364 selected
365 ? "scale-110 border-foreground ring-2 ring-ring ring-offset-1 ring-offset-background"
366 : "border-black/10 hover:scale-105 dark:border-white/20",
367 )}
368 style={{ backgroundColor: swatch }}
369 onClick={() => setAccentColor(swatch)}
370 aria-label={`Use ${swatch} accent`}
371 />
372 );
373 })}
374 </div>
375 {accentColor ? (
376 <Button
377 type="button"
378 size="sm"
379 variant="ghost"
380 className="h-7 px-2 text-xs text-muted-foreground"
381 onClick={() => setAccentColor("")}
382 >
383 Clear
384 </Button>
385 ) : null}
386 </div>
387 <span className="text-[11px] text-muted-foreground">
388 Optional marker shown in the picker.
389 </span>
390 </div>
391​
392 {driverSettingsFields.length > 0 ? (
393 <div className={cn("grid gap-4", wizardStep !== 2 && "hidden")}>
394 <ProviderSettingsForm
395 definition={driverOption}
396 value={configDraft}
397 idPrefix={`add-provider-${driver}`}
398 variant="dialog"
399 onChange={setConfigDraft}
400 />
401 </div>
402 ) : wizardStep === 2 ? (
403 <div className="grid gap-2">
404 <p className="text-sm text-muted-foreground">
405 This driver has no required configuration. You can add the instance now.
406 </p>
407 </div>
408 ) : null}
409 </AnimatedHeight>
410 </div>
411​
412 <DialogFooter variant="bare">
413 <Button
414 variant="outline"
415 size="sm"
416 onClick={() => {
417 if (wizardStep === 0) {
418 onOpenChange(false);
419 return;
420 }
421 setWizardStep((step) => Math.max(0, step - 1));
422 }}
423 >
424 {wizardStep === 0 ? "Cancel" : "Back"}
425 </Button>
426 {wizardStep < ADD_PROVIDER_WIZARD_STEPS.length - 1 ? (
427 <Button size="sm" onClick={() => navigateToStep(wizardStep + 1)}>
428 Next
429 </Button>
430 ) : (
431 <Button size="sm" onClick={handleSave}>
432 Add instance
433 </Button>
434 )}
435 </DialogFooter>
436 </div>
437 </DialogPopup>
438 </Dialog>
439 );