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