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

AddProviderInstanceDialog.tsx

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