Open History to see the last commit
1"use client";
2
3import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
4
5import { Radio as RadioPrimitive } from "@base-ui/react/radio";
6import { CheckIcon } from "lucide-react";
7import { useMemo, useState } from "react";
8import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
9import {
10 type AcpRegistrySearchAgent,
11 ProviderInstanceId,
12 ProviderDriverKind,
13 type EnvironmentId,
14 type ProviderInstanceConfig,
15} from "@t3tools/contracts";
16
17import {
18 useEnvironmentSettings,
19 usePersistEnvironmentProviderInstanceMutation,
20} from "../../hooks/useSettings";
21import { cn } from "../../lib/utils";
22import { normalizeProviderAccentColor } from "../../providerInstances";
23import { Button } from "../ui/button";
24import { Gemini, GithubCopilotIcon, type Icon } from "../Icons";
25import { Dialog } from "../ui/dialog";
26import { Badge } from "../ui/badge";
27import { Input } from "../ui/input";
28import { RadioGroup } from "../ui/radio-group";
29import { toastManager } from "../ui/toast";
30import { DRIVER_OPTION_BY_VALUE, DRIVER_OPTIONS } from "./providerDriverMeta";
31import { ProviderSettingsForm, deriveProviderSettingsFields } from "./ProviderSettingsForm";
32import { WizardPanel, WizardPopup, WizardHeader, WizardFooter } from "../ui/wizard";
33import {
34 ADD_PROVIDER_WIZARD_STEPS,
35 ACP_REGISTRY_WIZARD_STEPS,
36 deriveAvailableInstanceId,
37 getProviderIdentityDraft,
38 resolveAcpRegistryWizardNavigation,
39 resolveWizardNavigation,
40 updateProviderIdentityDraft,
41 type ProviderIdentityDraft,
42 type WizardNavigation,
43} from "./AddProviderInstanceDialog.logic";
44import { AddProviderInstanceWizardSteps } from "./AddProviderInstanceWizardSteps";
45import { AcpRegistrySearchStep } from "./AcpRegistrySearchStep";
46import { resolveOfficialAcpRegistryIconUrl } from "./AcpRegistryIcon";
47
48const PROVIDER_ACCENT_SWATCHES = [
49 "#2563eb",
50 "#16a34a",
51 "#ea580c",
52 "#dc2626",
53 "#7c3aed",
54 "#0891b2",
55] as const;
56
57/**
58 * Normalize a user-provided label into a slug suffix for the instance id.
59 * The full id is formed by prefixing the driver slug. For example, label "Work" on
60 * driver "codex" becomes `codex_work`. Output is trimmed to 48 chars so the
61 * final composed id stays under the 64-char slug cap enforced by
62 * `ProviderInstanceId` in `@t3tools/contracts`.
63 */
64function slugifyLabel(value: string): string {
65 return value
66 .trim()
67 .toLowerCase()
68 .replace(/[^a-z0-9]+/g, "_")
69 .replace(/^_+|_+$/g, "")
70 .slice(0, 48);
71}
72
73function deriveInstanceId(driver: ProviderDriverKind, label: string): string {
74 const slug = slugifyLabel(label);
75 return slug ? `${driver}_${slug}` : "";
76}
77
78const INSTANCE_ID_PATTERN = /^[a-zA-Z][a-zA-Z0-9_-]*$/;
79const DEFAULT_DRIVER_KIND = ProviderDriverKind.make("codex");
80const ACP_REGISTRY_DRIVER_KIND = ProviderDriverKind.make("acpRegistry");
81const DEFAULT_DRIVER_OPTION = DRIVER_OPTIONS[0]!;
82const EMPTY_CONFIG_DRAFT: Record<string, unknown> = {};
83interface ComingSoonDriverOption {
84 readonly value: ProviderDriverKind;
85 readonly label: string;
86 readonly icon: Icon;
87}
88
89const COMING_SOON_DRIVER_OPTIONS: readonly ComingSoonDriverOption[] = [
90 {
91 value: ProviderDriverKind.make("githubCopilot"),
92 label: "Github Copilot",
93 icon: GithubCopilotIcon,
94 },
95 {
96 value: ProviderDriverKind.make("gemini"),
97 label: "Gemini",
98 icon: Gemini,
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;
115}
116
117interface AddProviderInstanceDialogProps {
118 readonly open: boolean;
119 readonly environmentId: EnvironmentId;
120 readonly environmentLabel: string;
121 readonly onOpenChange: (open: boolean) => void;
122}
123
124export function AddProviderInstanceDialog({
125 open,
126 environmentId,
127 environmentLabel,
128 onOpenChange,
129}: AddProviderInstanceDialogProps) {
130 const settings = useEnvironmentSettings(environmentId);
131 const persistProviderInstance = usePersistEnvironmentProviderInstanceMutation(environmentId);
132
133 const [wizardStep, setWizardStep] = useState(0);
134 const [driver, setDriver] = useState<ProviderDriverKind>(DEFAULT_DRIVER_KIND);
135 const [identityByDriver, setIdentityByDriver] = useState<Record<string, ProviderIdentityDraft>>(
136 {},
137 );
138 const [selectedAcp, setSelectedAcp] = useState<AcpRegistrySearchAgent | null>(null);
139 const [isManualAcpConfiguration, setIsManualAcpConfiguration] = useState(false);
140 const [isRegistryLoading, setIsRegistryLoading] = useState(false);
141 // Driver-specific config drafts keyed by driver so toggling between drivers
142 // during the same dialog session does not lose in-progress input.
143 const [configByDriver, setConfigByDriver] = useState<Record<string, Record<string, unknown>>>({});
144 // Errors are suppressed until the user has tried to submit once. After that
145 // they update live so fixing the problem clears the message in place.
146 const [hasAttemptedSubmit, setHasAttemptedSubmit] = useState(false);
147 const [isSaving, setIsSaving] = useState(false);
148
149 const existingIds = useMemo(
150 () => new Set(Object.keys(settings.providerInstances ?? {})),
151 [settings.providerInstances],
152 );
153
154 const driverOption = DRIVER_OPTION_BY_VALUE[driver] ?? DEFAULT_DRIVER_OPTION;
155 const isAcpRegistry = driver === ACP_REGISTRY_DRIVER_KIND;
156 const { label, accentColor, instanceIdOverride } = getProviderIdentityDraft(
157 identityByDriver,
158 driver,
159 );
160 const instanceId = instanceIdOverride ?? deriveInstanceId(driver, label);
161 const driverSettingsFields = useMemo(
162 () => deriveProviderSettingsFields(driverOption),
163 [driverOption],
164 );
165 const instanceIdError = validateInstanceId(instanceId, existingIds);
166 const showInstanceIdError = hasAttemptedSubmit && instanceIdError !== null;
167 const identityStep = isAcpRegistry ? 2 : 1;
168 const previewLabel = label.trim() || `${driverOption.label} Workspace`;
169
170 const configDraft = configByDriver[driver] ?? EMPTY_CONFIG_DRAFT;
171 const manualAgentId = typeof configDraft.agentId === "string" ? configDraft.agentId.trim() : "";
172 const acpSelectionError =
173 selectedAcp !== null || (isManualAcpConfiguration && manualAgentId.length > 0)
174 ? null
175 : "Select an ACP or configure one manually.";
176 const wizardStepSummaries = isAcpRegistry
177 ? ([driverOption.label, selectedAcp?.name ?? (manualAgentId || null), previewLabel] as const)
178 : ([driverOption.label, previewLabel, null] as const);
179 const setConfigDraft = (config: Record<string, unknown> | undefined) => {
180 setConfigByDriver((existing) => {
181 const next = { ...existing };
182 if (config === undefined || Object.keys(config).length === 0) {
183 delete next[driver];
184 } else {
185 next[driver] = config;
186 }
187 return next;
188 });
189 };
190 const setIdentityDraft = (update: Partial<ProviderIdentityDraft>) => {
191 setIdentityByDriver((existing) => updateProviderIdentityDraft(existing, driver, update));
192 };
193
194 const applyWizardNavigation = (navigation: WizardNavigation) => {
195 if (navigation.kind === "blocked") {
196 setHasAttemptedSubmit(true);
197 }
198 setWizardStep(navigation.step);
199 };
200
201 const navigateToStep = (requestedStep: number) => {
202 applyWizardNavigation(
203 isAcpRegistry
204 ? resolveAcpRegistryWizardNavigation(wizardStep, requestedStep, {
205 instanceIdError,
206 selectionError: acpSelectionError,
207 })
208 : resolveWizardNavigation(wizardStep, requestedStep, ADD_PROVIDER_WIZARD_STEPS.length, {
209 instanceIdError,
210 }),
211 );
212 };
213
214 const handleAcpPrepared = (agent: AcpRegistrySearchAgent) => {
215 const nextLabel = agent.name;
216 const registryIconUrl = resolveOfficialAcpRegistryIconUrl(agent.icon);
217 const nextInstanceId = deriveAvailableInstanceId(
218 (candidateLabel) => deriveInstanceId(ACP_REGISTRY_DRIVER_KIND, candidateLabel),
219 nextLabel,
220 existingIds,
221 );
222 setSelectedAcp(agent);
223 setIsManualAcpConfiguration(false);
224 setIdentityByDriver((existing) =>
225 updateProviderIdentityDraft(existing, ACP_REGISTRY_DRIVER_KIND, {
226 label: nextLabel,
227 instanceIdOverride: nextInstanceId,
228 }),
229 );
230 setConfigByDriver((existing) => ({
231 ...existing,
232 [ACP_REGISTRY_DRIVER_KIND]: {
233 agentId: agent.id,
234 distribution: "auto",
235 ...(registryIconUrl ? { registryIconUrl } : {}),
236 },
237 }));
238 setHasAttemptedSubmit(false);
239 setWizardStep(2);
240 };
241
242 const handleManualAcpConfiguration = () => {
243 setSelectedAcp(null);
244 setIsManualAcpConfiguration(true);
245 setConfigDraft(undefined);
246 setIdentityByDriver((existing) =>
247 updateProviderIdentityDraft(existing, ACP_REGISTRY_DRIVER_KIND, {
248 label: "",
249 instanceIdOverride: null,
250 }),
251 );
252 setHasAttemptedSubmit(false);
253 };
254
255 const handleSave = async () => {
256 if (isSaving) return;
257 setHasAttemptedSubmit(true);
258 if (instanceIdError !== null || (isAcpRegistry && acpSelectionError !== null)) return;
259
260 const config = configByDriver[driver] ?? {};
261 const hasConfig = Object.keys(config).length > 0;
262 const normalizedAccentColor = normalizeProviderAccentColor(accentColor);
263
264 const nextInstance: ProviderInstanceConfig = {
265 driver,
266 enabled: true,
267 ...(label.trim().length > 0 ? { displayName: label.trim() } : {}),
268 ...(normalizedAccentColor ? { accentColor: normalizedAccentColor } : {}),
269 ...(hasConfig ? { config } : {}),
270 };
271 // `ProviderInstanceId.make` revalidates the slug; we've already checked
272 // it via `validateInstanceId`, but going through the brand constructor
273 // keeps the type boundary honest and guards against any future drift in
274 // the slug rules.
275 const brandedId = ProviderInstanceId.make(instanceId);
276 setIsSaving(true);
277 const result = await persistProviderInstance({
278 operation: "create",
279 instanceId: brandedId,
280 instance: nextInstance,
281 });
282 if (result._tag === "Failure") {
283 const error = squashAtomCommandFailure(result);
284 setIsSaving(false);
285 toastManager.add({
286 type: "error",
287 title: "Could not add provider instance",
288 description: error instanceof Error ? error.message : "The settings update failed.",
289 });
290 return;
291 }
292 const referenceUrl = selectedAcp?.website ?? selectedAcp?.repository;
293 toastManager.add({
294 type: "success",
295 title: "Provider instance added",
296 description: isAcpRegistry
297 ? `${selectedAcp?.name ?? manualAgentId} was added. Complete the agent's advertised authentication on the server; T3 Code detects it automatically.`
298 : `${driverOption.label} instance '${instanceId}' was added.`,
299 ...(referenceUrl
300 ? {
301 actionProps: {
302 children: selectedAcp?.website ? "Agent docs" : "Agent source",
303 onClick: () => window.open(referenceUrl, "_blank", "noopener,noreferrer"),
304 },
305 }
306 : {}),
307 });
308 onOpenChange(false);
309 };
310
311 return (
312 <Dialog open={open} onOpenChange={onOpenChange}>
313 <WizardPopup>
314 <WizardHeader
315 title="Add provider instance"
316 description={
317 <>
318 Configure an additional provider instance on {environmentLabel}. For example, add a
319 second Codex install pointed at a different workspace.
320 </>
321 }
322 >
323 {isAcpRegistry ? (
324 <AddProviderInstanceWizardSteps
325 currentStep={wizardStep}
326 summaries={wizardStepSummaries}
327 instanceIdError={instanceIdError}
328 steps={ACP_REGISTRY_WIZARD_STEPS}
329 identityStep={2}
330 prerequisite={{ step: 1, error: acpSelectionError }}
331 onNavigation={applyWizardNavigation}
332 />
333 ) : (
334 <AddProviderInstanceWizardSteps
335 currentStep={wizardStep}
336 summaries={wizardStepSummaries}
337 instanceIdError={instanceIdError}
338 onNavigation={applyWizardNavigation}
339 />
340 )}
341 </WizardHeader>
342
343 <WizardPanel
344 holdHeight={
345 isAcpRegistry && wizardStep === 1 && !isManualAcpConfiguration && isRegistryLoading
346 }
347 >
348 <div className={cn("grid gap-2", wizardStep !== 0 && "hidden")}>
349 <div id="add-instance-driver-label" className="text-sm font-medium text-foreground">
350 Driver
351 </div>
352 <RadioGroup
353 value={driver}
354 onValueChange={(value) => {
355 setDriver(ProviderDriverKind.make(value));
356 setHasAttemptedSubmit(false);
357 }}
358 aria-labelledby="add-instance-driver-label"
359 className="grid grid-cols-1 gap-2 sm:grid-cols-2"
360 >
361 {DRIVER_OPTIONS.map((option) => {
362 return (
363 <RadioPrimitive.Root
364 key={option.value}
365 value={option.value}
366 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"
367 >
368 <ProviderInstanceIcon
369 driverKind={option.value}
370 displayName={option.label}
371 iconClassName="size-4"
372 />
373 <span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
374 {option.label}
375 </span>
376 <RadioPrimitive.Indicator
377 className="grid size-5 shrink-0 place-items-center rounded-full bg-primary text-primary-foreground"
378 aria-hidden
379 >
380 <CheckIcon className="size-3.5 shrink-0" />
381 </RadioPrimitive.Indicator>
382 {option.badgeLabel ? (
383 <Badge variant="warning" size="sm">
384 {option.badgeLabel}
385 </Badge>
386 ) : null}
387 </RadioPrimitive.Root>
388 );
389 })}
390 {COMING_SOON_DRIVER_OPTIONS.map((option) => {
391 const IconComponent = option.icon;
392 return (
393 <RadioPrimitive.Root
394 key={option.value}
395 value={option.value}
396 disabled
397 className={cn(
398 "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",
399 )}
400 >
401 <IconComponent className="size-4 shrink-0 text-muted-foreground" aria-hidden />
402 <span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
403 {option.label}
404 </span>
405 <Badge variant="warning" size="sm">
406 Coming Soon
407 </Badge>
408 </RadioPrimitive.Root>
409 );
410 })}
411 </RadioGroup>
412 </div>
413
414 {isAcpRegistry && wizardStep === 1 ? (
415 isManualAcpConfiguration ? (
416 <div className="grid gap-4">
417 <div className="flex items-start justify-between gap-3">
418 <div>
419 <h3 className="text-sm font-medium text-foreground">Configure manually</h3>
420 <p className="mt-0.5 text-xs text-muted-foreground">
421 Enter an official registry ID and any local executable or auth override.
422 </p>
423 </div>
424 <Button
425 onClick={() => {
426 setIsManualAcpConfiguration(false);
427 setHasAttemptedSubmit(false);
428 }}
429 size="xs"
430 variant="ghost"
431 >
432 Search registry
433 </Button>
434 </div>
435 <ProviderSettingsForm
436 definition={driverOption}
437 value={configDraft}
438 idPrefix="add-provider-acpRegistry-manual"
439 variant="dialog"
440 onChange={setConfigDraft}
441 />
442 {hasAttemptedSubmit && acpSelectionError ? (
443 <p className="text-[11px] text-destructive">{acpSelectionError}</p>
444 ) : null}
445 <p className="border-t border-border/70 pt-3 text-[11px] text-muted-foreground">
446 Authentication is completed separately with the configured agent.
447 </p>
448 </div>
449 ) : (
450 <>
451 <AcpRegistrySearchStep
452 environmentId={environmentId}
453 providerInstances={settings.providerInstances}
454 onPrepared={handleAcpPrepared}
455 onManualConfiguration={handleManualAcpConfiguration}
456 onLoadingChange={setIsRegistryLoading}
457 />
458 {hasAttemptedSubmit && acpSelectionError ? (
459 <p className="mt-2 text-[11px] text-destructive">{acpSelectionError}</p>
460 ) : null}
461 </>
462 )
463 ) : null}
464
465 {isAcpRegistry && wizardStep === 2 && selectedAcp ? (
466 <div className="mb-4 flex items-start justify-between gap-3 border-b border-border/70 pb-3">
467 <div className="min-w-0">
468 <p className="truncate text-sm font-medium text-foreground">{selectedAcp.name}</p>
469 <p className="mt-0.5 text-xs text-muted-foreground">
470 v{selectedAcp.version} · {selectedAcp.distribution} · authentication remains
471 user-managed
472 </p>
473 </div>
474 <div className="flex shrink-0 gap-2 text-[11px]">
475 {selectedAcp.website ? (
476 <a
477 aria-label={`Open documentation for ${selectedAcp.name} (${selectedAcp.id})`}
478 className="text-muted-foreground hover:text-foreground"
479 href={selectedAcp.website}
480 rel="noreferrer"
481 target="_blank"
482 >
483 Docs
484 </a>
485 ) : null}
486 {selectedAcp.repository ? (
487 <a
488 aria-label={`Open source for ${selectedAcp.name} (${selectedAcp.id})`}
489 className="text-muted-foreground hover:text-foreground"
490 href={selectedAcp.repository}
491 rel="noreferrer"
492 target="_blank"
493 >
494 Source
495 </a>
496 ) : null}
497 </div>
498 </div>
499 ) : null}
500
501 <label className={cn("grid gap-2", wizardStep !== identityStep && "hidden")}>
502 <span className="text-xs font-medium text-foreground">Label</span>
503 <Input
504 className="bg-background"
505 placeholder="e.g. Work"
506 value={label}
507 onChange={(event) => setIdentityDraft({ label: event.target.value })}
508 />
509 <span className="text-[11px] text-muted-foreground">
510 Shown in the provider list. Optional.
511 </span>
512 </label>
513
514 <label className={cn("grid gap-2", wizardStep !== identityStep && "hidden")}>
515 <span className="text-xs font-medium text-foreground">Instance ID</span>
516 <Input
517 className="bg-background"
518 placeholder={`${driver}_work`}
519 value={instanceId}
520 onChange={(event) => {
521 setIdentityDraft({ instanceIdOverride: event.target.value });
522 }}
523 aria-invalid={showInstanceIdError}
524 />
525 {showInstanceIdError ? (
526 <span className="text-[11px] text-destructive">{instanceIdError}</span>
527 ) : (
528 <span className="text-[11px] text-muted-foreground">
529 Routing key used by threads and sessions. Letters, digits, '-', or '_'.
530 </span>
531 )}
532 </label>
533
534 <div className={cn("grid gap-2", wizardStep !== identityStep && "hidden")}>
535 <span className="text-xs font-medium text-foreground">Accent color</span>
536 <div className="flex min-w-0 flex-wrap items-center gap-2">
537 <input
538 type="color"
539 value={normalizeProviderAccentColor(accentColor) ?? PROVIDER_ACCENT_SWATCHES[0]}
540 onChange={(event) => setIdentityDraft({ accentColor: event.target.value })}
541 aria-label="Provider instance accent color"
542 className="h-8 w-10 cursor-pointer rounded-xl border border-input bg-background p-0.5"
543 />
544 <div className="flex flex-wrap gap-1.5">
545 {PROVIDER_ACCENT_SWATCHES.map((swatch) => {
546 const selected = accentColor.toLowerCase() === swatch;
547 return (
548 <button
549 key={swatch}
550 type="button"
551 className={cn(
552 "size-6 cursor-pointer rounded-full border transition",
553 selected
554 ? "scale-110 border-foreground ring-2 ring-ring ring-offset-1 ring-offset-background"
555 : "border-black/10 hover:scale-105 dark:border-white/20",
556 )}
557 style={{ backgroundColor: swatch }}
558 onClick={() => setIdentityDraft({ accentColor: swatch })}
559 aria-label={`Use ${swatch} accent`}
560 />
561 );
562 })}
563 </div>
564 {accentColor ? (
565 <Button
566 size="xs"
567 variant="ghost"
568 onClick={() => setIdentityDraft({ accentColor: "" })}
569 >
570 Clear
571 </Button>
572 ) : null}
573 </div>
574 <span className="text-[11px] text-muted-foreground">
575 Optional marker shown in the picker.
576 </span>
577 </div>
578
579 {!isAcpRegistry && driverSettingsFields.length > 0 ? (
580 <div className={cn("grid gap-4", wizardStep !== 2 && "hidden")}>
581 <ProviderSettingsForm
582 definition={driverOption}
583 value={configDraft}
584 idPrefix={`add-provider-${driver}`}
585 variant="dialog"
586 onChange={setConfigDraft}
587 />
588 </div>
589 ) : !isAcpRegistry && wizardStep === 2 ? (
590 <div className="grid gap-2">
591 <p className="text-sm text-muted-foreground">
592 This driver has no required configuration. You can add the instance now.
593 </p>
594 </div>
595 ) : null}
596 </WizardPanel>
597
598 <WizardFooter>
599 <Button
600 variant="outline"
601 size="sm"
602 disabled={isSaving}
603 onClick={() => {
604 if (wizardStep === 0) {
605 onOpenChange(false);
606 return;
607 }
608 setWizardStep((step) => Math.max(0, step - 1));
609 }}
610 >
611 {wizardStep === 0 ? "Cancel" : "Back"}
612 </Button>
613 {isAcpRegistry &&
614 wizardStep === 1 &&
615 !isManualAcpConfiguration &&
616 !selectedAcp ? null : wizardStep <
617 (isAcpRegistry ? ACP_REGISTRY_WIZARD_STEPS : ADD_PROVIDER_WIZARD_STEPS).length - 1 ? (
618 <Button size="sm" onClick={() => navigateToStep(wizardStep + 1)}>
619 Next
620 </Button>
621 ) : (
622 <Button size="sm" disabled={isSaving} onClick={() => void handleSave()}>
623 {isSaving ? "Adding..." : "Add instance"}
624 </Button>
625 )}
626 </WizardFooter>
627 </WizardPopup>
628 </Dialog>
629 );
630}