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

AddProviderInstanceDialog.tsx

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