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

AddProviderInstanceDialog.tsx

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