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

AddProviderInstanceDialog.tsx

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