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

AddProviderInstanceDialog.tsx

423 lines16.0 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, PiAgentIcon, 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 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 readonly open: boolean;
114 readonly environmentId: EnvironmentId;
115 readonly environmentLabel: string;
116 readonly onOpenChange: (open: boolean) => void;
118​
119export function AddProviderInstanceDialog({
120 open,
121 environmentId,
122 environmentLabel,
123 onOpenChange,
124}: AddProviderInstanceDialogProps) {
125 const settings = useEnvironmentSettings(environmentId);
126 const updateSettings = useUpdateEnvironmentSettings(environmentId);
127​
128 const [wizardStep, setWizardStep] = useState(0);
129 const [driver, setDriver] = useState<ProviderDriverKind>(DEFAULT_DRIVER_KIND);
130 const [label, setLabel] = useState("");
131 const [accentColor, setAccentColor] = useState<string>("");
132 const [instanceIdOverride, setInstanceIdOverride] = useState<string | null>(null);
133 // Driver-specific config drafts keyed by driver so toggling between drivers
134 // during the same dialog session does not lose in-progress input.
135 const [configByDriver, setConfigByDriver] = useState<Record<string, Record<string, unknown>>>({});
136 // Errors are suppressed until the user has tried to submit once. After that
137 // they update live so fixing the problem clears the message in place.
138 const [hasAttemptedSubmit, setHasAttemptedSubmit] = useState(false);
139​
140 const existingIds = useMemo(
141 () => new Set(Object.keys(settings.providerInstances ?? {})),
142 [settings.providerInstances],
143 );
144​
145 const driverOption = DRIVER_OPTION_BY_VALUE[driver] ?? DEFAULT_DRIVER_OPTION;
146 const instanceId = instanceIdOverride ?? deriveInstanceId(driver, label);
147 const driverSettingsFields = useMemo(
148 () => deriveProviderSettingsFields(driverOption),
149 [driverOption],
150 );
151 const instanceIdError = validateInstanceId(instanceId, existingIds);
152 const showInstanceIdError = hasAttemptedSubmit && instanceIdError !== null;
153 const previewLabel = label.trim() || `${driverOption.label} Workspace`;
154 const wizardStepSummaries = [driverOption.label, previewLabel, null] as const;
155​
156 const configDraft = configByDriver[driver] ?? EMPTY_CONFIG_DRAFT;
157 const setConfigDraft = (config: Record<string, unknown> | undefined) => {
158 setConfigByDriver((existing) => {
159 const next = { ...existing };
160 if (config === undefined || Object.keys(config).length === 0) {
161 delete next[driver];
162 } else {
163 next[driver] = config;
164 }
165 return next;
166 });
167 };
168​
169 const applyWizardNavigation = (navigation: WizardNavigation) => {
170 if (navigation.kind === "blocked") {
171 setHasAttemptedSubmit(true);
172 }
173 setWizardStep(navigation.step);
174 };
175​
176 const navigateToStep = (requestedStep: number) => {
177 applyWizardNavigation(
178 resolveWizardNavigation(wizardStep, requestedStep, ADD_PROVIDER_WIZARD_STEPS.length, {
179 instanceIdError,
180 }),
181 );
182 };
183​
184 const handleSave = () => {
185 setHasAttemptedSubmit(true);
186 if (instanceIdError !== null) return;
187​
188 const config = configByDriver[driver] ?? {};
189 const hasConfig = Object.keys(config).length > 0;
190 const normalizedAccentColor = normalizeProviderAccentColor(accentColor);
191​
192 const nextInstance: ProviderInstanceConfig = {
193 driver,
194 enabled: true,
195 ...(label.trim().length > 0 ? { displayName: label.trim() } : {}),
196 ...(normalizedAccentColor ? { accentColor: normalizedAccentColor } : {}),
197 ...(hasConfig ? { config } : {}),
198 };
199 // `ProviderInstanceId.make` revalidates the slug; we've already checked
200 // it via `validateInstanceId`, but going through the brand constructor
201 // keeps the type boundary honest and guards against any future drift in
202 // the slug rules.
203 const brandedId = ProviderInstanceId.make(instanceId);
204 const nextMap = {
205 ...settings.providerInstances,
206 [brandedId]: nextInstance,
207 };
208 try {
209 updateSettings({ providerInstances: nextMap });
210 toastManager.add({
211 type: "success",
212 title: "Provider instance added",
213 description: `${driverOption.label} instance '${instanceId}' was added.`,
214 });
215 onOpenChange(false);
216 } catch (error) {
217 toastManager.add({
218 type: "error",
219 title: "Could not add provider instance",
220 description: error instanceof Error ? error.message : "Update failed.",
221 });
222 }
223 };
224​
225 return (
226 <Dialog open={open} onOpenChange={onOpenChange}>
227 <WizardPopup>
228 <WizardHeader
229 title="Add provider instance"
230 description={
231 <>
232 Configure an additional provider instance on {environmentLabel} — for example, a
233 second Codex install pointed at a different workspace.
234 </>
235 }
236 >
237 <AddProviderInstanceWizardSteps
238 currentStep={wizardStep}
239 summaries={wizardStepSummaries}
240 instanceIdError={instanceIdError}
241 onNavigation={applyWizardNavigation}
242 />
243 </WizardHeader>
244​
245 <WizardPanel>
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 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 className="size-4 shrink-0 text-muted-foreground" aria-hidden />
294 <span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
295 {option.label}
296 </span>
297 <Badge variant="warning" size="sm">
298 Coming Soon
299 </Badge>
300 </RadioPrimitive.Root>
301 );
302 })}
303 </RadioGroup>
304 </div>
305​
306 <label className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
307 <span className="text-xs font-medium text-foreground">Label</span>
308 <Input
309 placeholder="e.g. Work"
310 value={label}
311 onChange={(event) => setLabel(event.target.value)}
312 />
313 <span className="text-[11px] text-muted-foreground">
314 Shown in the provider list. Optional.
315 </span>
316 </label>
317​
318 <label className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
319 <span className="text-xs font-medium text-foreground">Instance ID</span>
320 <Input
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 <ProviderAccentColorPicker
341 displayName={label || driverOption.label}
342 value={accentColor || undefined}
343 onCommit={setAccentColor}
344 layout="inline"
345 />
346 <div className="flex flex-wrap gap-1.5">
347 {PROVIDER_ACCENT_SWATCHES.map((swatch) => {
348 const selected = accentColor.toLowerCase() === swatch;
349 return (
350 <button
351 key={swatch}
352 type="button"
353 className={cn(
354 "size-6 cursor-pointer rounded-full border transition",
355 selected
356 ? "scale-110 border-foreground ring-2 ring-ring ring-offset-1 ring-offset-background"
357 : "border-black/10 hover:scale-105 dark:border-white/20",
358 )}
359 style={{ backgroundColor: swatch }}
360 onClick={() => setAccentColor(swatch)}
361 aria-label={`Use ${swatch} accent`}
362 />
363 );
364 })}
365 </div>
366 {accentColor ? (
367 <Button
368 type="button"
369 size="xs"
370 variant="ghost-muted"
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 );