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

AddProviderInstanceDialog.tsx

435 lines17.0 KB

1"use client";
2​
3import { Radio as RadioPrimitive } from "@base-ui/react/radio";
4import { useMemo, useState } from "react";
5import {
6 ProviderInstanceId,
7 ProviderDriverKind,
8 type ProviderInstanceConfig,
9} from "@t3tools/contracts";
10​
11import { usePrimarySettings, useUpdatePrimarySettings } from "../../hooks/useSettings";
12import { cn } from "../../lib/utils";
13import { normalizeProviderAccentColor } from "../../providerInstances";
14import { Button } from "../ui/button";
15import { ACPRegistryIcon, Gemini, GithubCopilotIcon, type Icon } from "../Icons";
16import {
17 Dialog,
18 DialogDescription,
19 DialogFooter,
20 DialogHeader,
21 DialogPopup,
22 DialogTitle,
23} from "../ui/dialog";
24import { Badge } from "../ui/badge";
25import { Input } from "../ui/input";
26import { RadioGroup } from "../ui/radio-group";
27import { toastManager } from "../ui/toast";
28import { DRIVER_OPTION_BY_VALUE, DRIVER_OPTIONS } from "./providerDriverMeta";
29import { ProviderSettingsForm, deriveProviderSettingsFields } from "./ProviderSettingsForm";
30import { AnimatedHeight } from "../AnimatedHeight";
31import {
32 ADD_PROVIDER_WIZARD_STEPS,
33 resolveWizardNavigation,
34 type WizardNavigation,
35} from "./AddProviderInstanceDialog.logic";
36import { AddProviderInstanceWizardSteps } from "./AddProviderInstanceWizardSteps";
37​
38const PROVIDER_ACCENT_SWATCHES = [
39 "#2563eb",
40 "#16a34a",
41 "#ea580c",
42 "#dc2626",
43 "#7c3aed",
44 "#0891b2",
45] as const;
46​
47/**
48 * Normalize a user-provided label into a slug suffix for the instance id.
49 * The full id is formed by prefixing the driver slug — e.g. label "Work" on
50 * driver "codex" becomes `codex_work`. Output is trimmed to 48 chars so the
51 * final composed id stays under the 64-char slug cap enforced by
52 * `ProviderInstanceId` in `@t3tools/contracts`.
53 */
54function slugifyLabel(value: string): string {
55 return value
56 .trim()
57 .toLowerCase()
58 .replace(/[^a-z0-9]+/g, "_")
59 .replace(/^_+|_+$/g, "")
60 .slice(0, 48);
62​
63function deriveInstanceId(driver: ProviderDriverKind, label: string): string {
64 const slug = slugifyLabel(label);
65 return slug ? `${driver}_${slug}` : "";
67​
68const INSTANCE_ID_PATTERN = /^[a-zA-Z][a-zA-Z0-9_-]*$/;
69const DEFAULT_DRIVER_KIND = ProviderDriverKind.make("codex");
70const DEFAULT_DRIVER_OPTION = DRIVER_OPTIONS[0]!;
71const EMPTY_CONFIG_DRAFT: Record<string, unknown> = {};
72interface ComingSoonDriverOption {
73 readonly value: ProviderDriverKind;
74 readonly label: string;
75 readonly icon: Icon;
77​
78const COMING_SOON_DRIVER_OPTIONS: readonly ComingSoonDriverOption[] = [
79 {
80 value: ProviderDriverKind.make("githubCopilot"),
81 label: "Github Copilot",
82 icon: GithubCopilotIcon,
83 },
84 {
85 value: ProviderDriverKind.make("gemini"),
86 label: "Gemini",
87 icon: Gemini,
88 },
89 {
90 value: ProviderDriverKind.make("acpRegistry"),
91 label: "ACP Registry",
92 icon: ACPRegistryIcon,
93 },
94];
95​
96/**
97 * Validate an instance id against the same slug rules the server applies in
98 * `ProviderInstanceId` (see `packages/contracts/src/providerInstance.ts`).
99 * Returns a user-facing error string, or `null` if valid.
100 */
101function validateInstanceId(id: string, existing: ReadonlySet<string>): string | null {
102 if (id.length === 0) return "Instance ID is required.";
103 if (id.length > 64) return "Instance ID must be 64 characters or fewer.";
104 if (!INSTANCE_ID_PATTERN.test(id)) {
105 return "Instance ID must start with a letter and use only letters, digits, '-', or '_'.";
106 }
107 if (existing.has(id)) return `An instance named '${id}' already exists.`;
108 return null;
110​
111interface AddProviderInstanceDialogProps {
112 open: boolean;
113 onOpenChange: (open: boolean) => void;
115​
116export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderInstanceDialogProps) {
117 const settings = usePrimarySettings();
118 const updateSettings = useUpdatePrimarySettings();
119​
120 const [wizardStep, setWizardStep] = useState(0);
121 const [driver, setDriver] = useState<ProviderDriverKind>(DEFAULT_DRIVER_KIND);
122 const [label, setLabel] = useState("");
123 const [accentColor, setAccentColor] = useState<string>("");
124 const [instanceIdOverride, setInstanceIdOverride] = useState<string | null>(null);
125 // Driver-specific config drafts keyed by driver so toggling between drivers
126 // during the same dialog session does not lose in-progress input.
127 const [configByDriver, setConfigByDriver] = useState<Record<string, Record<string, unknown>>>({});
128 // Errors are suppressed until the user has tried to submit once. After that
129 // they update live so fixing the problem clears the message in place.
130 const [hasAttemptedSubmit, setHasAttemptedSubmit] = useState(false);
131​
132 const existingIds = useMemo(
133 () => new Set(Object.keys(settings.providerInstances ?? {})),
134 [settings.providerInstances],
135 );
136​
137 const driverOption = DRIVER_OPTION_BY_VALUE[driver] ?? DEFAULT_DRIVER_OPTION;
138 const instanceId = instanceIdOverride ?? deriveInstanceId(driver, label);
139 const driverSettingsFields = useMemo(
140 () => deriveProviderSettingsFields(driverOption),
141 [driverOption],
142 );
143 const instanceIdError = validateInstanceId(instanceId, existingIds);
144 const showInstanceIdError = hasAttemptedSubmit && instanceIdError !== null;
145 const previewLabel = label.trim() || `${driverOption.label} Workspace`;
146 const wizardStepSummaries = [driverOption.label, previewLabel, null] as const;
147​
148 const configDraft = configByDriver[driver] ?? EMPTY_CONFIG_DRAFT;
149 const setConfigDraft = (config: Record<string, unknown> | undefined) => {
150 setConfigByDriver((existing) => {
151 const next = { ...existing };
152 if (config === undefined || Object.keys(config).length === 0) {
153 delete next[driver];
154 } else {
155 next[driver] = config;
156 }
157 return next;
158 });
159 };
160​
161 const applyWizardNavigation = (navigation: WizardNavigation) => {
162 if (navigation.kind === "blocked") {
163 setHasAttemptedSubmit(true);
164 }
165 setWizardStep(navigation.step);
166 };
167​
168 const navigateToStep = (requestedStep: number) => {
169 applyWizardNavigation(
170 resolveWizardNavigation(wizardStep, requestedStep, ADD_PROVIDER_WIZARD_STEPS.length, {
171 instanceIdError,
172 }),
173 );
174 };
175​
176 const handleSave = () => {
177 setHasAttemptedSubmit(true);
178 if (instanceIdError !== null) return;
179​
180 const config = configByDriver[driver] ?? {};
181 const hasConfig = Object.keys(config).length > 0;
182 const normalizedAccentColor = normalizeProviderAccentColor(accentColor);
183​
184 const nextInstance: ProviderInstanceConfig = {
185 driver,
186 enabled: true,
187 ...(label.trim().length > 0 ? { displayName: label.trim() } : {}),
188 ...(normalizedAccentColor ? { accentColor: normalizedAccentColor } : {}),
189 ...(hasConfig ? { config } : {}),
190 };
191 // `ProviderInstanceId.make` revalidates the slug; we've already checked
192 // it via `validateInstanceId`, but going through the brand constructor
193 // keeps the type boundary honest and guards against any future drift in
194 // the slug rules.
195 const brandedId = ProviderInstanceId.make(instanceId);
196 const nextMap = {
197 ...settings.providerInstances,
198 [brandedId]: nextInstance,
199 };
200 try {
201 updateSettings({ providerInstances: nextMap });
202 toastManager.add({
203 type: "success",
204 title: "Provider instance added",
205 description: `${driverOption.label} instance '${instanceId}' was added.`,
206 });
207 onOpenChange(false);
208 } catch (error) {
209 toastManager.add({
210 type: "error",
211 title: "Could not add provider instance",
212 description: error instanceof Error ? error.message : "Update failed.",
213 });
214 }
215 };
216​
217 return (
218 <Dialog open={open} onOpenChange={onOpenChange}>
219 <DialogPopup className="max-w-xl overflow-hidden">
220 <div className="flex min-h-0 flex-col overflow-hidden">
221 <DialogHeader className="border-b border-border/70">
222 <DialogTitle>Add provider instance</DialogTitle>
223 <DialogDescription>
224 Configure an additional provider instance — for example, a second Codex install
225 pointed at a different workspace.
226 </DialogDescription>
227 <AddProviderInstanceWizardSteps
228 currentStep={wizardStep}
229 summaries={wizardStepSummaries}
230 instanceIdError={instanceIdError}
231 onNavigation={applyWizardNavigation}
232 />
233 </DialogHeader>
234​
235 <div
236 data-slot="dialog-panel"
237 className="space-y-4 border-b border-border/70 bg-foreground/[0.025] px-6 py-5"
238 >
239 <AnimatedHeight>
240 <div className={cn("grid gap-2", wizardStep !== 0 && "hidden")}>
241 <span
242 id="add-instance-driver-label"
243 className="text-xs font-medium text-foreground"
244 >
245 Driver
246 </span>
247 <RadioGroup
248 value={driver}
249 onValueChange={(value) => setDriver(ProviderDriverKind.make(value))}
250 aria-labelledby="add-instance-driver-label"
251 className="grid grid-cols-2 gap-2.5"
252 >
253 {DRIVER_OPTIONS.map((option) => {
254 const IconComponent = option.icon;
255 const isSelected = option.value === driver;
256 return (
257 <RadioPrimitive.Root
258 key={option.value}
259 value={option.value}
260 className={cn(
261 "relative flex cursor-pointer items-center gap-3 rounded-lg border px-3 py-3 text-left outline-none transition-[background-color,border-color,box-shadow]",
262 "focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
263 isSelected
264 ? "border-primary bg-background shadow-sm ring-2 ring-primary/35"
265 : "border-border bg-background hover:border-foreground/20 hover:bg-muted/50",
266 )}
267 >
268 <IconComponent className="size-5 shrink-0" aria-hidden />
269 <span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
270 {option.label}
271 </span>
272 {option.badgeLabel ? (
273 <Badge variant="warning" size="sm">
274 {option.badgeLabel}
275 </Badge>
276 ) : null}
277 </RadioPrimitive.Root>
278 );
279 })}
280 {COMING_SOON_DRIVER_OPTIONS.map((option) => {
281 const IconComponent = option.icon;
282 return (
283 <RadioPrimitive.Root
284 key={option.value}
285 value={option.value}
286 disabled
287 className={cn(
288 "relative flex cursor-not-allowed items-center gap-3 rounded-lg border border-border bg-background px-3 py-3 text-left opacity-55 outline-none",
289 )}
290 >
291 <IconComponent
292 className="size-5 shrink-0 text-muted-foreground"
293 aria-hidden
294 />
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="sm"
374 variant="ghost"
375 className="h-7 px-2 text-xs 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 </AnimatedHeight>
405 </div>
406​
407 <DialogFooter className="border-t bg-transparent">
408 <Button
409 variant="outline"
410 size="sm"
411 onClick={() => {
412 if (wizardStep === 0) {
413 onOpenChange(false);
414 return;
415 }
416 setWizardStep((step) => Math.max(0, step - 1));
417 }}
418 >
419 {wizardStep === 0 ? "Cancel" : "Back"}
420 </Button>
421 {wizardStep < ADD_PROVIDER_WIZARD_STEPS.length - 1 ? (
422 <Button size="sm" onClick={() => navigateToStep(wizardStep + 1)}>
423 Next
424 </Button>
425 ) : (
426 <Button size="sm" onClick={handleSave}>
427 Add instance
428 </Button>
429 )}
430 </DialogFooter>
431 </div>
432 </DialogPopup>
433 </Dialog>
434 );