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

AddProviderInstanceDialog.tsx

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