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

AddProviderInstanceDialog.tsx

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