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

ProviderSettingsPanel.tsx

1,321 lines48.4 KB

1import { SettingsGroup } from "./SettingsGroup";
2import { RefreshIcon } from "~/components/ui/refresh-icon";
3import { useAtomValue } from "@effect/atom-react";
4import { connectionStatusTitle } from "@t3tools/client-runtime/connection";
5import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
6import {
7 isAtomCommandInterrupted,
8 squashAtomCommandFailure,
9} from "@t3tools/client-runtime/state/runtime";
10import {
11 defaultInstanceIdForDriver,
12 type EnvironmentId,
13 type AcpRegistryUrlAuthAction,
14 PROVIDER_DISPLAY_NAMES,
15 ProviderDriverKind,
16 type ProviderInstanceConfig,
17 type ProviderInstanceId,
18 resolveEnvironmentMachineKind,
19 resolveProviderInstanceEnabled,
20} from "@t3tools/contracts";
21import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
22import {
23 getBackgroundActivityPresetSettings,
24 resolveServerBackgroundActivitySettings,
25} from "@t3tools/shared/backgroundActivitySettings";
26import * as Arr from "effect/Array";
27import * as Duration from "effect/Duration";
28import * as Equal from "effect/Equal";
29import * as Result from "effect/Result";
30import { PlusIcon } from "lucide-react";
31import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
32​
33import { isDesktopLocalConnectionTarget } from "../../connection/desktopLocal";
34import { isElectron } from "../../env";
35import { usePrimarySessionState } from "../../environments/primary";
36import {
37 useEnvironmentSettings,
38 usePersistEnvironmentProviderInstanceMutation,
39 useUpdateClientSettings,
40 useUpdateEnvironmentSettings,
41} from "../../hooks/useSettings";
42import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
43import { cn } from "../../lib/utils";
44import { resolveAppModelSelectionState } from "../../modelSelection";
45import {
46 useEnvironments,
47 usePrimaryEnvironmentId,
48 type EnvironmentPresentation,
49} from "../../state/environments";
50import { EMPTY_SERVER_PROVIDERS, serverEnvironment } from "../../state/server";
51import { useEnvironmentSessionState } from "../../state/session";
52import { useProjects } from "../../state/entities";
53import { useAtomCommand } from "../../state/use-atom-command";
54import { getRelativeTimeState } from "../../timestampFormat";
55import {
56 ConnectionStatusDot,
57 connectionPhaseDotClassName,
58 connectionPhasePingClassName,
59} from "../ConnectionStatusDot";
60import {
61 isProviderSettingsUpdateCandidate,
62 isProviderUpdateActive,
63 type ProviderSettingsUpdateCandidate,
64} from "../ProviderUpdateLaunchNotification.logic";
65import { Button } from "../ui/button";
66import {
67 Empty,
68 EmptyContent,
69 EmptyDescription,
70 EmptyHeader,
71 EmptyMedia,
72 EmptyTitle,
73} from "../ui/empty";
74import {
75 NumberField,
76 NumberFieldDecrement,
77 NumberFieldGroup,
78 NumberFieldIncrement,
79 NumberFieldInput,
80} from "../ui/number-field";
81import { ScrollArea } from "../ui/scroll-area";
82import { Toggle, ToggleGroup } from "../ui/toggle-group";
83import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
84import { stackedThreadToast, toastManager } from "../ui/toast";
85import { AddProviderInstanceDialog } from "./AddProviderInstanceDialog";
86import { ExpandableText } from "./ExpandableText";
87import { ProviderInstanceCard } from "./ProviderInstanceCard";
88import { UsageProviderSettings } from "./UsageProviderSettings";
89import { ProviderSetupSection, readAntigravityAuthMethod } from "./ProviderSetupSection";
90import { ProviderAuthenticationSection } from "./ProviderAuthenticationSection";
91import { DRIVER_OPTIONS, getDriverOption } from "./providerDriverMeta";
92import { searchableSetting } from "./settingsSearch";
93import {
94 backgroundActivityOverrideSettings,
95 buildProviderInstanceUpdatePatch,
96 durationToSeconds,
97 normalizeIntervalSeconds,
98 PROVIDER_HEALTH_INTERVAL_STEP_SECONDS,
99} from "./SettingsPanels.logic";
100import {
101 PolicyTooltip,
102 SettingResetButton,
103 SettingsPageContainer,
104 SettingsRow,
105 SettingsSection,
106 useRelativeTimeTick,
107 useSettingsSearchTargetId,
108} from "./settingsLayout";
109import {
110 buildProviderEnvironmentOptions,
111 classifyProviderEnvironmentAccess,
112 isProviderSettingsEnvironmentAvailable,
113 type ProviderEnvironmentAccess,
114 type ProviderOperateAccess,
115 resolvePrimaryOperateAccess,
116 resolveRemoteOperateAccess,
117 resolveSelectedProviderEnvironmentId,
118} from "./ProviderSettingsPanel.logic";
119​
120function withoutProviderInstanceKey<V>(
121 record: Readonly<Record<ProviderInstanceId, V>> | undefined,
122 key: ProviderInstanceId,
123): Record<ProviderInstanceId, V> {
124 const next = { ...record } as Record<ProviderInstanceId, V>;
125 delete next[key];
126 return next;
128​
129function withoutProviderInstanceFavorites(
130 favorites: ReadonlyArray<{ readonly provider: ProviderInstanceId; readonly model: string }>,
131 instanceId: ProviderInstanceId,
132) {
133 return favorites.filter((favorite) => favorite.provider !== instanceId);
135​
136function providerConfigString(config: unknown, key: string): string | null {
137 if (config === null || typeof config !== "object") return null;
138 const value = (config as Record<string, unknown>)[key];
139 return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
141​
142const PROVIDER_SETTINGS = DRIVER_OPTIONS.map((definition) => ({
143 provider: definition.value,
144}));
145​
146function configuredBinaryPath(config: unknown): string {
147 if (config === null || typeof config !== "object" || !("binaryPath" in config)) return "";
148 return typeof config.binaryPath === "string" ? config.binaryPath.trim() : "";
150​
151function ProviderLastChecked({ lastCheckedAt }: { lastCheckedAt: string | null }) {
152 useRelativeTimeTick();
153 const lastCheckedRelative = getRelativeTimeState(lastCheckedAt);
154​
155 if (lastCheckedRelative.status === "missing") {
156 return null;
157 }
158​
159 if (lastCheckedRelative.status === "invalid") {
160 return <span>Checked unavailable</span>;
161 }
162​
163 return (
164 <span>
165 {lastCheckedRelative.suffix ? (
166 <>
167 Checked <span className="font-mono tabular-nums">{lastCheckedRelative.value}</span>{" "}
168 {lastCheckedRelative.suffix}
169 </>
170 ) : (
171 <>Checked {lastCheckedRelative.value}</>
172 )}
173 </span>
174 );
176​
177function providerEnvironmentDetail(environment: EnvironmentPresentation): string {
178 if (environment.entry.target._tag === "PrimaryConnectionTarget") return "Primary device";
179 if (environment.relayManaged) return "T3 Connect";
180 if (environment.entry.target._tag === "SshConnectionTarget") return "SSH";
181 if (isDesktopLocalConnectionTarget(environment.entry.target)) return "Local device";
182 return environment.displayUrl ?? "Remote device";
184​
185// Shared by the editor grid and the placeholder states so switching devices
186// never changes the card's footprint.
187const providerCardHeightClassName =
188 "@min-[48rem]/providers:h-[min(44rem,calc(100dvh-11rem))] @min-[48rem]/providers:min-h-[32rem]";
189​
190/**
191 * Same chrome as the provider editor (section heading, floating device tabs,
192 * tall card) for states that cannot render provider settings yet.
193 */
194function ProviderSettingsPlaceholder({
195 deviceTabs,
196 icon,
197 title,
198 description,
199 children,
200}: {
201 readonly deviceTabs?: ReactNode;
202 readonly icon: ReactNode;
203 readonly title: string;
204 readonly description: string;
205 readonly children?: ReactNode;
206}) {
207 return (
208 <SettingsSection {...searchableSetting("providers")} variant="plain">
209 {deviceTabs ? (
210 <div className="flex min-h-11 min-w-0 items-center px-3 sm:px-4">{deviceTabs}</div>
211 ) : null}
212 <SettingsGroup
213 divided={false}
214 className={cn(providerCardHeightClassName, "flex overflow-x-hidden overflow-y-auto")}
215 >
216 <Empty>
217 <EmptyMedia variant="icon">{icon}</EmptyMedia>
218 <EmptyHeader>
219 <EmptyTitle>{title}</EmptyTitle>
220 <EmptyDescription>{description}</EmptyDescription>
221 </EmptyHeader>
222 {children ? <EmptyContent className="max-w-xl">{children}</EmptyContent> : null}
223 </Empty>
224 </SettingsGroup>
225 </SettingsSection>
226 );
228​
229function EnvironmentUnavailablePlaceholder({
230 environment,
231 access,
232 deviceTabs,
233}: {
234 readonly environment: EnvironmentPresentation;
235 readonly access: Exclude<ProviderEnvironmentAccess, { kind: "editable" | "read-only" }>;
236 readonly deviceTabs?: ReactNode;
237}) {
238 const isLoading = access.kind === "loading";
239 const title = isLoading
240 ? "Loading provider settings"
241 : access.kind === "error"
242 ? "Could not connect to this device"
243 : "Provider settings are unavailable";
244 // Keep the description to a short status; the raw failure can be a
245 // multi-paragraph CLI dump, so it goes below, clamped and expandable.
246 const description = isLoading
247 ? access.reason === "permissions"
248 ? "Checking what this session is allowed to change."
249 : `Waiting for ${environment.label}'s configuration.`
250 : connectionStatusTitle(environment.connection);
251 const error = isLoading ? null : environment.connection.error;
252 // No spinner: this state can persist indefinitely for a wedged device, and a
253 // continuously repainting animation would run the whole time.
254 return (
255 <ProviderSettingsPlaceholder
256 deviceTabs={deviceTabs}
257 icon={
258 <EnvironmentMachineIcon kind={resolveEnvironmentMachineKind(environment.serverConfig)} />
259 }
260 title={title}
261 description={description}
262 >
263 {error ? (
264 <ExpandableText
265 key={environment.environmentId}
266 text={error}
267 className="w-full text-left font-mono text-xs leading-relaxed text-muted-foreground"
268 />
269 ) : null}
270 </ProviderSettingsPlaceholder>
271 );
273​
274interface ProviderSettingsTarget {
275 readonly environmentId?: EnvironmentId;
276 readonly instanceId?: ProviderInstanceId;
277 readonly scoped?: boolean;
279​
280export function ProviderSettingsPanel(target: ProviderSettingsTarget) {
281 return (
282 <SettingsPageContainer width="wide" className="@container/providers gap-8">
283 <ProviderSettingsPanelContent
284 key={`${target.environmentId ?? ""}:${target.instanceId ?? ""}`}
285 {...target}
286 />
287 </SettingsPageContainer>
288 );
290​
291function ProviderSettingsPanelContent(target: ProviderSettingsTarget) {
292 const { environments, isReady } = useEnvironments();
293 const primaryEnvironmentId = usePrimaryEnvironmentId();
294 const searchTargetId = useSettingsSearchTargetId();
295 const options = useMemo(
296 () => buildProviderEnvironmentOptions(environments, primaryEnvironmentId),
297 [environments, primaryEnvironmentId],
298 );
299 // Raw user intent; the effective selection is re-derived every render so a
300 // device that drops out of the catalog falls back without erasing the pick —
301 // if it reappears (e.g. after a reconnect) the selection is restored.
302 const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<EnvironmentId | null>(
303 target.environmentId ?? primaryEnvironmentId,
304 );
305 const targetEnvironmentMissing =
306 target.environmentId !== undefined &&
307 selectedEnvironmentId === target.environmentId &&
308 !options.some((environment) => environment.environmentId === target.environmentId);
309 const effectiveEnvironmentId =
310 target.scoped || targetEnvironmentMissing
311 ? target.environmentId
312 : resolveSelectedProviderEnvironmentId(options, selectedEnvironmentId, primaryEnvironmentId);
313 const selectedEnvironment =
314 options.find((environment) => environment.environmentId === effectiveEnvironmentId) ?? null;
315 const selectedEnvironmentCanRenderSettings =
316 selectedEnvironment !== null &&
317 isProviderSettingsEnvironmentAvailable({
318 connectionPhase: selectedEnvironment.connection.phase,
319 hasServerConfig: selectedEnvironment.serverConfig !== null,
320 });
321 const searchableEnvironmentId = options.find((environment) =>
322 isProviderSettingsEnvironmentAvailable({
323 connectionPhase: environment.connection.phase,
324 hasServerConfig: environment.serverConfig !== null,
325 }),
326 )?.environmentId;
327 useEffect(() => {
328 if (
329 !target.scoped &&
330 (searchTargetId === searchableSetting("provider-health-check-interval").id ||
331 searchTargetId === searchableSetting("usage-providers").id) &&
332 !selectedEnvironmentCanRenderSettings &&
333 searchableEnvironmentId !== undefined
334 ) {
335 setSelectedEnvironmentId(searchableEnvironmentId);
336 }
337 }, [
338 searchTargetId,
339 searchableEnvironmentId,
340 selectedEnvironmentCanRenderSettings,
341 target.scoped,
342 ]);
343 const onlyPrimaryDevice =
344 options.length === 1 && options[0]?.entry.target._tag === "PrimaryConnectionTarget";
345 const deviceTabs =
346 !target.scoped && !onlyPrimaryDevice && options.length > 0 ? (
347 <ScrollArea radius="none" hideScrollbars scrollFade className="h-11 min-w-0 flex-1">
348 <ToggleGroup
349 aria-label="Devices"
350 variant="segmented"
351 className="my-2"
352 value={effectiveEnvironmentId ? [effectiveEnvironmentId] : []}
353 onValueChange={(next) => {
354 const environment = options.find((option) => option.environmentId === next[0]);
355 if (environment) setSelectedEnvironmentId(environment.environmentId);
356 }}
357 >
358 {options.map((environment) => {
359 const machine = resolveEnvironmentMachineKind(environment.serverConfig);
360 const detail = providerEnvironmentDetail(environment);
361 const statusText = connectionStatusTitle(environment.connection);
362 return (
363 <Tooltip key={environment.environmentId}>
364 <TooltipTrigger
365 render={
366 <Toggle value={environment.environmentId}>
367 <EnvironmentMachineIcon
368 kind={machine}
369 className="size-3.5 shrink-0"
370 aria-hidden
371 />
372 <span className="max-w-40 truncate">{environment.label}</span>
373 {environment.connection.phase !== "connected" ? (
374 <ConnectionStatusDot
375 dotClassName={connectionPhaseDotClassName(environment.connection.phase)}
376 pingClassName={connectionPhasePingClassName(environment.connection.phase)}
377 />
378 ) : null}
379 <span className="sr-only">
380 {detail}, {statusText}
381 </span>
382 </Toggle>
383 }
384 />
385 <TooltipPopup side="top">
386 {detail} · {statusText}
387 </TooltipPopup>
388 </Tooltip>
389 );
390 })}
391 </ToggleGroup>
392 </ScrollArea>
393 ) : null;
394​
395 return (
396 <>
397 {targetEnvironmentMissing ? (
398 <ProviderSettingsPlaceholder
399 deviceTabs={deviceTabs}
400 icon={<EnvironmentMachineIcon kind={resolveEnvironmentMachineKind(null)} />}
401 title="Device unavailable"
402 description="Reconnect this device to set up its provider, or select another device."
403 />
404 ) : null}
405 {options.length === 0 && !targetEnvironmentMissing ? (
406 <ProviderSettingsPlaceholder
407 icon={<EnvironmentMachineIcon kind={resolveEnvironmentMachineKind(null)} />}
408 title={isReady ? "No connected devices" : "Loading devices"}
409 description={
410 isReady
411 ? "Connect an execution environment before configuring providers."
412 : "Reading connected execution environments."
413 }
414 />
415 ) : null}
416​
417 {selectedEnvironment ? (
418 <SelectedEnvironmentProviderSettings
419 key={selectedEnvironment.environmentId}
420 environment={selectedEnvironment}
421 deviceTabs={deviceTabs}
422 targetInstanceId={
423 target.environmentId === undefined ||
424 selectedEnvironment.environmentId === target.environmentId
425 ? target.instanceId
426 : undefined
427 }
428 />
429 ) : null}
430 </>
431 );
433​
434function SelectedEnvironmentProviderSettings({
435 environment,
436 deviceTabs,
437 targetInstanceId,
438}: {
439 readonly environment: EnvironmentPresentation;
440 readonly deviceTabs?: ReactNode;
441 readonly targetInstanceId?: ProviderInstanceId | undefined;
442}) {
443 const isPrimary = environment.entry.target._tag === "PrimaryConnectionTarget";
444 if (isPrimary) {
445 // The desktop app owns its primary server outright; a browser session
446 // checks the scopes its cookie session was granted.
447 if (isElectron) {
448 return (
449 <AccessGatedProviderSettings
450 environment={environment}
451 operateAccess="granted"
452 deviceTabs={deviceTabs}
453 targetInstanceId={targetInstanceId}
454 />
455 );
456 }
457 return (
458 <PrimarySessionGatedProviderSettings
459 environment={environment}
460 deviceTabs={deviceTabs}
461 targetInstanceId={targetInstanceId}
462 />
463 );
464 }
465 return (
466 <RemoteSessionGatedProviderSettings
467 environment={environment}
468 deviceTabs={deviceTabs}
469 targetInstanceId={targetInstanceId}
470 />
471 );
473​
474function PrimarySessionGatedProviderSettings({
475 environment,
476 deviceTabs,
477 targetInstanceId,
478}: {
479 readonly environment: EnvironmentPresentation;
480 readonly deviceTabs?: ReactNode;
481 readonly targetInstanceId?: ProviderInstanceId | undefined;
482}) {
483 const primarySessionState = usePrimarySessionState();
484 const operateAccess = resolvePrimaryOperateAccess({
485 isPrimary: true,
486 hasDesktopBridge: false,
487 session: primarySessionState.data,
488 isPending: primarySessionState.isPending,
489 hasError: primarySessionState.error !== null,
490 });
491 return (
492 <AccessGatedProviderSettings
493 environment={environment}
494 operateAccess={operateAccess}
495 deviceTabs={deviceTabs}
496 targetInstanceId={targetInstanceId}
497 />
498 );
500​
501function RemoteSessionGatedProviderSettings({
502 environment,
503 deviceTabs,
504 targetInstanceId,
505}: {
506 readonly environment: EnvironmentPresentation;
507 readonly deviceTabs?: ReactNode;
508 readonly targetInstanceId?: ProviderInstanceId | undefined;
509}) {
510 const sessionState = useEnvironmentSessionState(environment.environmentId);
511 const operateAccess = resolveRemoteOperateAccess({
512 session: sessionState.data,
513 isPending: sessionState.isPending,
514 hasError: sessionState.hasError,
515 });
516 return (
517 <AccessGatedProviderSettings
518 environment={environment}
519 operateAccess={operateAccess}
520 deviceTabs={deviceTabs}
521 targetInstanceId={targetInstanceId}
522 />
523 );
525​
526function AccessGatedProviderSettings({
527 environment,
528 operateAccess,
529 deviceTabs,
530 targetInstanceId,
531}: {
532 readonly environment: EnvironmentPresentation;
533 readonly operateAccess: ProviderOperateAccess;
534 readonly deviceTabs?: ReactNode;
535 readonly targetInstanceId?: ProviderInstanceId | undefined;
536}) {
537 const access = classifyProviderEnvironmentAccess({
538 connectionPhase: environment.connection.phase,
539 hasServerConfig: environment.serverConfig !== null,
540 operateAccess,
541 });
542 if (access.kind !== "editable" && access.kind !== "read-only") {
543 return (
544 <EnvironmentUnavailablePlaceholder
545 environment={environment}
546 access={access}
547 deviceTabs={deviceTabs}
548 />
549 );
550 }
551 return (
552 <EnvironmentProviderSettings
553 environmentId={environment.environmentId}
554 environmentLabel={environment.label}
555 readOnly={access.kind === "read-only"}
556 deviceTabs={deviceTabs}
557 targetInstanceId={targetInstanceId}
558 />
559 );
561​
562export function EnvironmentProviderSettings({
563 environmentId,
564 environmentLabel,
565 readOnly = false,
566 deviceTabs,
567 targetInstanceId,
568}: {
569 readonly environmentId: EnvironmentId;
570 readonly environmentLabel: string;
571 readonly deviceTabs?: ReactNode;
572 readonly targetInstanceId?: ProviderInstanceId | undefined;
573 /**
574 * Grey out and freeze every write control when this session's credential
575 * lacks `orchestration:operate` on the environment. Selecting providers
576 * still works so the real configuration stays readable; switches, forms,
577 * and the health interval are inert so no write is offered and then rejected.
578 */
579 readonly readOnly?: boolean;
580}) {
581 const settings = useEnvironmentSettings(environmentId);
582 // Provider instances hold per-machine credentials and binaries, so this
583 // page always edits exactly the environment it displays.
584 const updateSettings = useUpdateEnvironmentSettings(environmentId);
585 const persistProviderInstance = usePersistEnvironmentProviderInstanceMutation(environmentId);
586 const updateClientSettings = useUpdateClientSettings();
587 const serverProviders =
588 useAtomValue(serverEnvironment.providersValueAtom(environmentId)) ?? EMPTY_SERVER_PROVIDERS;
589 const projects = useProjects().filter((project) => project.environmentId === environmentId);
590 const refreshServerProviders = useAtomCommand(serverEnvironment.refreshProviders, {
591 reportFailure: false,
592 });
593 const updateProvider = useAtomCommand(serverEnvironment.updateProvider, {
594 reportFailure: false,
595 });
596 const uninstallAcpRegistryManagedBinary = useAtomCommand(
597 serverEnvironment.uninstallAcpRegistryManagedBinary,
598 { reportFailure: false },
599 );
600 const acceptAcpRegistryUrlAuth = useAtomCommand(serverEnvironment.acceptAcpRegistryUrlAuth, {
601 reportFailure: false,
602 });
603 const [isRefreshingProviders, setIsRefreshingProviders] = useState(false);
604 const [isAddInstanceDialogOpen, setIsAddInstanceDialogOpen] = useState(false);
605 const [selectedInstanceId, setSelectedInstanceId] = useState<ProviderInstanceId | null>(
606 targetInstanceId ?? null,
607 );
608 const [updatingProviderInstanceIds, setUpdatingProviderInstanceIds] = useState<
609 ReadonlySet<ProviderInstanceId>
610 >(() => new Set());
611 const refreshingRef = useRef(false);
612 const updatingInstanceIdsRef = useRef<Set<ProviderInstanceId>>(new Set());
613​
614 const acceptUrlAuthentication = useCallback(
615 (instanceId: ProviderInstanceId, action: AcpRegistryUrlAuthAction) => {
616 void acceptAcpRegistryUrlAuth({
617 environmentId,
618 input: { instanceId, elicitationId: action.elicitationId },
619 }).then((result) => {
620 if (result._tag === "Success" && !result.value.accepted) {
621 toastManager.add({
622 type: "warning",
623 title: "Authentication request expired",
624 description: "Refresh the provider and start the authentication flow again.",
625 });
626 return;
627 }
628 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
629 const error = squashAtomCommandFailure(result);
630 toastManager.add({
631 type: "error",
632 title: "Could not continue authentication",
633 description:
634 error instanceof Error ? error.message : "The authentication request expired.",
635 });
636 }
637 });
638 },
639 [acceptAcpRegistryUrlAuth, environmentId],
640 );
641​
642 const providerUpdateCandidateByInstanceId = useMemo(
643 () =>
644 new Map(
645 serverProviders
646 .filter(isProviderSettingsUpdateCandidate)
647 .map((candidate) => [candidate.instanceId, candidate]),
648 ),
649 [serverProviders],
650 );
651 const visibleProviderSettings = PROVIDER_SETTINGS.filter(
652 (providerSettings) =>
653 providerSettings.provider !== "cursor" ||
654 serverProviders.some(
655 (provider) =>
656 provider.instanceId === defaultInstanceIdForDriver(ProviderDriverKind.make("cursor")),
657 ),
658 );
659 const textGenerationModelSelection = resolveAppModelSelectionState(settings, serverProviders);
660 const textGenInstanceId = textGenerationModelSelection.instanceId;
661 const resolvedBackgroundActivity = resolveServerBackgroundActivitySettings(settings);
662 const providerHealthPreset = getBackgroundActivityPresetSettings(
663 resolvedBackgroundActivity.profile,
664 ).providerHealthRefreshInterval;
665 const providerHealthRefreshIntervalSeconds = durationToSeconds(
666 resolvedBackgroundActivity.providerHealthRefreshInterval,
667 );
668 const defaultProviderHealthRefreshIntervalSeconds = durationToSeconds(providerHealthPreset);
669 const lastCheckedAt =
670 serverProviders.length > 0
671 ? serverProviders.reduce(
672 (latest, provider) => (provider.checkedAt > latest ? provider.checkedAt : latest),
673 serverProviders[0]!.checkedAt,
674 )
675 : null;
676​
677 const refreshProviders = useCallback(() => {
678 if (refreshingRef.current) return;
679 refreshingRef.current = true;
680 setIsRefreshingProviders(true);
681 void (async () => {
682 const result = await refreshServerProviders({
683 environmentId,
684 input: { refreshModels: true },
685 });
686 refreshingRef.current = false;
687 setIsRefreshingProviders(false);
688 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
689 console.warn("Failed to refresh providers", {
690 operation: "refresh-providers",
691 environmentId,
692 ...safeErrorLogAttributes(squashAtomCommandFailure(result)),
693 });
694 }
695 })();
696 }, [environmentId, refreshServerProviders]);
697​
698 const runProviderUpdate = useCallback(
699 async (
700 candidate: Pick<ProviderSettingsUpdateCandidate, "driver" | "instanceId">,
701 targetVersion?: string,
702 ) => {
703 // Ref-based re-entry guard, mirroring refreshProviders: a state updater
704 // may run after this function returns, so it cannot gate the dispatch.
705 if (updatingInstanceIdsRef.current.has(candidate.instanceId)) {
706 return;
707 }
708 updatingInstanceIdsRef.current.add(candidate.instanceId);
709 setUpdatingProviderInstanceIds((previous) => new Set(previous).add(candidate.instanceId));
710​
711 const result = await updateProvider({
712 environmentId,
713 input: {
714 provider: candidate.driver,
715 instanceId: candidate.instanceId,
716 ...(targetVersion ? { targetVersion } : {}),
717 },
718 });
719 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
720 const error = squashAtomCommandFailure(result);
721 toastManager.add(
722 stackedThreadToast({
723 type: "error",
724 title: `Could not update ${PROVIDER_DISPLAY_NAMES[candidate.driver] ?? candidate.driver}`,
725 description:
726 error instanceof Error
727 ? error.message
728 : "The provider update command could not be started.",
729 }),
730 );
731 }
732 updatingInstanceIdsRef.current.delete(candidate.instanceId);
733 setUpdatingProviderInstanceIds((previous) => {
734 if (!previous.has(candidate.instanceId)) {
735 return previous;
736 }
737 const next = new Set(previous);
738 next.delete(candidate.instanceId);
739 return next;
740 });
741 },
742 [environmentId, updateProvider],
743 );
744​
745 interface InstanceRow {
746 readonly instanceId: ProviderInstanceId;
747 readonly instance: ProviderInstanceConfig;
748 readonly driver: ProviderDriverKind;
749 readonly isDefault: boolean;
750 readonly isDirty?: boolean;
751 }
752​
753 const instancesByDriver = new Map<
754 ProviderDriverKind,
755 Array<[ProviderInstanceId, ProviderInstanceConfig]>
756 >();
757 for (const [rawId, instance] of Object.entries(settings.providerInstances ?? {})) {
758 const driver = instance.driver;
759 const list = instancesByDriver.get(driver) ?? [];
760 list.push([rawId as ProviderInstanceId, instance]);
761 instancesByDriver.set(driver, list);
762 }
763​
764 const defaultSlotIdsBySource = new Set<string>(
765 visibleProviderSettings.map((providerSettings) =>
766 String(defaultInstanceIdForDriver(providerSettings.provider)),
767 ),
768 );
769​
770 const rows: InstanceRow[] = [];
771 const visibleDriverKinds = new Set<ProviderDriverKind>(
772 visibleProviderSettings.map((providerSettings) => providerSettings.provider),
773 );
774​
775 for (const providerSettings of visibleProviderSettings) {
776 type LegacyProviderSettings = (typeof settings.providers)[keyof typeof settings.providers];
777 const legacyProviders = settings.providers as Record<string, LegacyProviderSettings>;
778 const defaultLegacyProviders = DEFAULT_UNIFIED_SETTINGS.providers as Record<
779 string,
780 LegacyProviderSettings
781 >;
782 const driver = providerSettings.provider;
783 const defaultInstanceId = defaultInstanceIdForDriver(driver);
784 const explicitInstance = settings.providerInstances?.[defaultInstanceId];
785 // A remote device may run a server version whose settings predate this
786 // driver, so the legacy mirror can be absent. Without either an explicit
787 // instance or a legacy blob there is nothing to render for the slot.
788 const legacyConfig = legacyProviders[providerSettings.provider];
789 const defaultLegacyConfig = defaultLegacyProviders[providerSettings.provider];
790 // The envelope is the single enabled flag: keep the legacy in-config
791 // flag out of the synthesized blob, or an explicit `enabled: false`
792 // would keep winning over the envelope and the Switch could never
793 // turn a default-off provider on.
794 const synthesizedInstance = (): ProviderInstanceConfig | undefined => {
795 if (legacyConfig === undefined) {
796 return undefined;
797 }
798 const { enabled: legacyEnabled, ...legacyConfigRest } = legacyConfig;
799 return {
800 driver,
801 enabled: legacyEnabled,
802 config: legacyConfigRest,
803 } satisfies ProviderInstanceConfig;
804 };
805 const effectiveInstance: ProviderInstanceConfig | undefined =
806 explicitInstance ?? synthesizedInstance();
807 // Only the default slot depends on the legacy blob; custom instances for
808 // the driver must still render even when the slot has nothing to show.
809 if (effectiveInstance !== undefined) {
810 const isDirty =
811 explicitInstance !== undefined || !Equal.equals(legacyConfig, defaultLegacyConfig);
812 if (
813 driver === "codex" ||
814 driver === "claudeAgent" ||
815 isDirty ||
816 resolveProviderInstanceEnabled(effectiveInstance) ||
817 defaultInstanceId === targetInstanceId
818 ) {
819 rows.push({
820 instanceId: defaultInstanceId,
821 instance: effectiveInstance,
822 driver,
823 isDefault: true,
824 isDirty,
825 });
826 }
827 }
828 for (const [id, instance] of instancesByDriver.get(providerSettings.provider) ?? []) {
829 if (id === defaultInstanceId) continue;
830 rows.push({ instanceId: id, instance, driver: instance.driver, isDefault: false });
831 }
832 }
833 for (const [driver, list] of instancesByDriver) {
834 if (visibleDriverKinds.has(driver)) continue;
835 for (const [id, instance] of list) {
836 rows.push({
837 instanceId: id,
838 instance,
839 driver: instance.driver,
840 isDefault: defaultSlotIdsBySource.has(String(id)),
841 });
842 }
843 }
844​
845 const targetInstanceMissing =
846 targetInstanceId !== undefined &&
847 selectedInstanceId === targetInstanceId &&
848 !rows.some((row) => row.instanceId === targetInstanceId);
849 const selectedRow =
850 rows.find((row) => row.instanceId === selectedInstanceId) ??
851 (targetInstanceMissing ? null : (rows[0] ?? null));
852​
853 const updateProviderInstance = async (
854 row: InstanceRow,
855 next: ProviderInstanceConfig,
856 options?: {
857 readonly textGenerationModelSelection?: Parameters<
858 typeof buildProviderInstanceUpdatePatch
859 >[0]["textGenerationModelSelection"];
860 },
861 ) => {
862 const { providerInstances: _providerInstances, ...patch } = buildProviderInstanceUpdatePatch({
863 settings,
864 instanceId: row.instanceId,
865 instance: next,
866 driver: row.driver,
867 isDefault: row.isDefault,
868 textGenerationModelSelection: options?.textGenerationModelSelection,
869 });
870 const result = await persistProviderInstance(
871 { operation: "upsert", instanceId: row.instanceId, instance: next },
872 patch,
873 );
874 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
875 const error = squashAtomCommandFailure(result);
876 toastManager.add({
877 type: "error",
878 title: "Could not update provider instance",
879 description: error instanceof Error ? error.message : "The settings update failed.",
880 });
881 }
882 };
883​
884 const deleteProviderInstance = async (row: InstanceRow) => {
885 const updateResult = await persistProviderInstance({
886 operation: "remove",
887 instanceId: row.instanceId,
888 });
889 if (updateResult._tag === "Failure") {
890 const error = squashAtomCommandFailure(updateResult);
891 toastManager.add({
892 type: "error",
893 title: "Could not delete provider instance",
894 description: error instanceof Error ? error.message : "The settings update failed.",
895 });
896 return;
897 }
898​
899 if (row.driver !== ProviderDriverKind.make("acpRegistry")) return;
900 const agentId = providerConfigString(row.instance.config, "agentId");
901 if (agentId === null) return;
902​
903 // The server decides from its latest settings whether this was the last
904 // instance using the managed agent. A client-side snapshot check can race
905 // two removals and make both callers skip cleanup.
906 const uninstallResult = await uninstallAcpRegistryManagedBinary({
907 environmentId,
908 input: { agentId },
909 });
910 if (uninstallResult._tag === "Failure" && !isAtomCommandInterrupted(uninstallResult)) {
911 const error = squashAtomCommandFailure(uninstallResult);
912 toastManager.add({
913 type: "warning",
914 title: "Provider deleted, but managed files remain",
915 description: error instanceof Error ? error.message : "Managed binary cleanup failed.",
916 });
917 }
918 };
919​
920 const updateProviderModelPreferences = (
921 instanceId: ProviderInstanceId,
922 next: {
923 readonly hiddenModels: ReadonlyArray<string>;
924 readonly modelOrder: ReadonlyArray<string>;
925 },
926 ) => {
927 const hiddenModels = [...new Set(next.hiddenModels.filter((slug) => slug.trim().length > 0))];
928 const modelOrder = [...new Set(next.modelOrder.filter((slug) => slug.trim().length > 0))];
929 const rest = withoutProviderInstanceKey(settings.providerModelPreferences, instanceId);
930 updateClientSettings({
931 providerModelPreferences:
932 hiddenModels.length === 0 && modelOrder.length === 0
933 ? rest
934 : {
935 ...rest,
936 [instanceId]: {
937 hiddenModels,
938 modelOrder,
939 },
940 },
941 });
942 };
943​
944 const updateProviderFavoriteModels = (
945 instanceId: ProviderInstanceId,
946 nextFavoriteModels: ReadonlyArray<string>,
947 ) => {
948 const favoriteModels = [
949 ...new Set(
950 Arr.filterMap(nextFavoriteModels, (slug) => {
951 const trimmedSlug = slug.trim();
952 return trimmedSlug.length > 0 ? Result.succeed(trimmedSlug) : Result.failVoid;
953 }),
954 ),
955 ];
956 updateClientSettings({
957 favorites: [
958 ...withoutProviderInstanceFavorites(settings.favorites ?? [], instanceId),
959 ...favoriteModels.map((model) => ({ provider: instanceId, model })),
960 ],
961 });
962 };
963​
964 const resetDefaultInstance = async (driverKind: ProviderDriverKind) => {
965 type LegacyProviderSettings = (typeof settings.providers)[keyof typeof settings.providers];
966 const defaultLegacyProviders = DEFAULT_UNIFIED_SETTINGS.providers as Record<
967 string,
968 LegacyProviderSettings | undefined
969 >;
970 const defaultInstanceId = defaultInstanceIdForDriver(driverKind);
971 const defaultLegacyProvider = defaultLegacyProviders[driverKind];
972 if (defaultLegacyProvider === undefined) return;
973 const result = await persistProviderInstance(
974 { operation: "remove", instanceId: defaultInstanceId },
975 {
976 providers: {
977 ...settings.providers,
978 [driverKind]: defaultLegacyProvider,
979 } as typeof settings.providers,
980 },
981 );
982 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
983 const error = squashAtomCommandFailure(result);
984 toastManager.add({
985 type: "error",
986 title: "Could not reset provider instance",
987 description: error instanceof Error ? error.message : "The settings update failed.",
988 });
989 }
990 };
991​
992 const renderProviderInstance = (row: InstanceRow, mode: "list" | "editor") => {
993 const driverOption = getDriverOption(row.driver);
994 const liveProvider = serverProviders.find(
995 (candidate) => candidate.instanceId === row.instanceId,
996 );
997 const updateCandidate = providerUpdateCandidateByInstanceId.get(row.instanceId);
998 const isInstanceUpdateRunning =
999 updatingProviderInstanceIds.has(row.instanceId) ||
1000 (liveProvider !== undefined && isProviderUpdateActive(liveProvider));
1001 const showInlineUpdateButton = updateCandidate !== undefined;
1002 const canRunInlineUpdate = updateCandidate !== undefined && !isInstanceUpdateRunning;
1003 const modelPreferences = settings.providerModelPreferences?.[row.instanceId] ?? {
1004 hiddenModels: [],
1005 modelOrder: [],
1006 };
1007 const favoriteModels = Arr.filterMap(settings.favorites ?? [], (favorite) =>
1008 favorite.provider === row.instanceId ? Result.succeed(favorite.model) : Result.failVoid,
1009 );
1010 const resetLabel = driverOption?.label ?? String(row.driver);
1011​
1012 return (
1013 <ProviderInstanceCard
1014 key={row.instanceId}
1015 environmentId={environmentId}
1016 acpProjects={projects}
1017 onAcceptUrlAuth={
1018 readOnly ? undefined : (action) => acceptUrlAuthentication(row.instanceId, action)
1020 instanceId={row.instanceId}
1021 instance={row.instance}
1022 driverOption={driverOption}
1023 liveProvider={liveProvider}
1024 mode={mode}
1025 selected={mode === "list" && selectedRow?.instanceId === row.instanceId}
1026 onSelect={mode === "list" ? () => setSelectedInstanceId(row.instanceId) : undefined}
1027 readOnly={readOnly}
1028 setup={
1029 mode === "editor" && row.driver === "antigravity" ? (
1030 <ProviderSetupSection
1031 environmentId={environmentId}
1032 environmentLabel={environmentLabel}
1033 instanceId={row.instanceId}
1034 provider={liveProvider}
1035 binaryPath={configuredBinaryPath(row.instance.config)}
1036 authMethod={readAntigravityAuthMethod(row.instance.config)}
1037 enabled={resolveProviderInstanceEnabled(row.instance)}
1038 readOnly={readOnly}
1039 onEnable={() => updateProviderInstance(row, { ...row.instance, enabled: true })}
1040 />
1041 ) : mode === "editor" &&
1042 !readOnly &&
1043 liveProvider &&
1044 (liveProvider.setup?.canAuthenticate ||
1045 (liveProvider.driver === "acpRegistry" && liveProvider.installed)) ? (
1046 <ProviderAuthenticationSection
1047 key={`${environmentId}:${row.instanceId}`}
1048 environmentId={environmentId}
1049 environmentLabel={environmentLabel}
1050 instanceId={row.instanceId}
1051 provider={liveProvider}
1052 readOnly={readOnly}
1053 />
1054 ) : mode === "editor" &&
1055 !readOnly &&
1056 row.driver === "cursor" &&
1057 liveProvider?.setup?.canAuthenticate === false ? (
1058 <SettingsRow
1059 title="Cursor account"
1060 description="Using CURSOR_API_KEY. Remove it from this provider's environment to use browser sign-in."
1061 />
1062 ) : null
1064 onUpdate={(next) => {
1065 const wasEnabled = resolveProviderInstanceEnabled(row.instance);
1066 const isDisabling = next.enabled === false && wasEnabled;
1067 const shouldClearTextGen = isDisabling && textGenInstanceId === row.instanceId;
1068 updateProviderInstance(
1069 row,
1070 next,
1071 shouldClearTextGen
1072 ? {
1073 textGenerationModelSelection:
1074 DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection,
1076 : undefined,
1077 );
1078 }}
1079 onDelete={
1080 mode === "editor" && !row.isDefault ? () => deleteProviderInstance(row) : undefined
1082 headerAction={
1083 mode === "editor" && row.isDefault && row.isDirty ? (
1084 <SettingResetButton
1085 label={`${resetLabel} provider settings`}
1086 onClick={() => resetDefaultInstance(row.driver)}
1087 />
1088 ) : null
1090 hiddenModels={modelPreferences.hiddenModels}
1091 favoriteModels={favoriteModels}
1092 modelOrder={modelPreferences.modelOrder}
1093 onHiddenModelsChange={(hiddenModels) =>
1094 updateProviderModelPreferences(row.instanceId, {
1095 ...modelPreferences,
1096 hiddenModels,
1097 })
1099 onFavoriteModelsChange={(next) => updateProviderFavoriteModels(row.instanceId, next)}
1100 onModelOrderChange={(modelOrder) =>
1101 updateProviderModelPreferences(row.instanceId, {
1102 ...modelPreferences,
1103 modelOrder,
1104 })
1106 onInstallRecommended={
1107 mode === "editor" &&
1108 liveProvider?.compatibilityAdvisory?.message &&
1109 liveProvider.compatibilityAdvisory.recommendedVersion &&
1110 liveProvider.versionAdvisory?.canInstallVersion
1111 ? () => {
1112 void runProviderUpdate(
1113 liveProvider,
1114 liveProvider.compatibilityAdvisory?.recommendedVersion ?? undefined,
1115 );
1117 : undefined
1119 onRunUpdate={
1120 mode === "editor" && showInlineUpdateButton && updateCandidate
1121 ? () => {
1122 if (canRunInlineUpdate) void runProviderUpdate(updateCandidate);
1124 : undefined
1126 isUpdating={mode === "editor" ? isInstanceUpdateRunning : undefined}
1127 />
1128 );
1129 };
1130​
1131 return (
1132 <>
1133 <SettingsSection {...searchableSetting("providers")} variant="plain">
1134 <div className="flex min-h-11 min-w-0 items-center gap-2 px-3 sm:px-4">
1135 {deviceTabs}
1136 <div className="ml-auto flex min-w-0 shrink-0 items-center gap-2">
1137 {readOnly ? (
1138 <span className="min-w-0 truncate text-xs text-muted-foreground">
1139 <ProviderLastChecked lastCheckedAt={lastCheckedAt} />
1140 </span>
1141 ) : (
1142 <>
1143 <Tooltip>
1144 <TooltipTrigger
1145 render={
1146 <Button
1147 size="xs"
1148 variant="ghost-muted"
1149 disabled={isRefreshingProviders}
1150 aria-busy={isRefreshingProviders}
1151 onClick={() => void refreshProviders()}
1153 <RefreshIcon refreshing={isRefreshingProviders} />
1154 <span className="sr-only">Refresh provider status</span>
1155 <span className="hidden min-w-0 truncate sm:inline">
1156 {isRefreshingProviders ? (
1157 "Refreshing providers"
1158 ) : (
1159 <ProviderLastChecked lastCheckedAt={lastCheckedAt} />
1160 )}
1161 </span>
1162 </Button>
1164 />
1165 <TooltipPopup side="top">Refresh provider status</TooltipPopup>
1166 </Tooltip>
1167 <Tooltip>
1168 <TooltipTrigger
1169 render={
1170 <Button
1171 size="icon-xs"
1172 variant="ghost-muted"
1173 onClick={() => setIsAddInstanceDialogOpen(true)}
1174 aria-label="Add provider"
1176 <PlusIcon />
1177 </Button>
1179 />
1180 <TooltipPopup side="top">Add provider</TooltipPopup>
1181 </Tooltip>
1182 </>
1183 )}
1184 </div>
1185 </div>
1186 {readOnly ? (
1187 <SettingsGroup divided={false} className="overflow-hidden">
1188 <SettingsRow
1189 title="Limited permissions"
1190 description={`This session can view ${environmentLabel}'s providers but can't change their settings.`}
1191 />
1192 </SettingsGroup>
1193 ) : null}
1194 <SettingsGroup
1195 divided={false}
1196 className={cn(
1197 providerCardHeightClassName,
1198 "overflow-hidden @min-[48rem]/providers:grid @min-[48rem]/providers:grid-cols-[17rem_minmax(0,1fr)]",
1199 )}
1201 <div className="border-b border-border/60 bg-muted/10 @min-[48rem]/providers:flex @min-[48rem]/providers:min-h-0 @min-[48rem]/providers:flex-col @min-[48rem]/providers:border-r @min-[48rem]/providers:border-b-0">
1202 <ScrollArea
1203 scrollFade
1204 chainVerticalScroll
1205 className="@min-[48rem]/providers:min-h-0 @min-[48rem]/providers:flex-1"
1207 <div className="divide-y divide-border/50">
1208 {rows.map((row) => renderProviderInstance(row, "list"))}
1209 </div>
1210 </ScrollArea>
1211 </div>
1212​
1213 <div className="min-w-0 @min-[48rem]/providers:min-h-0">
1214 {selectedRow ? (
1215 <ScrollArea scrollFade chainVerticalScroll className="@min-[48rem]/providers:h-full">
1216 <div className="space-y-6 p-4">{renderProviderInstance(selectedRow, "editor")}</div>
1217 </ScrollArea>
1218 ) : (
1219 <div className="p-6 text-sm text-muted-foreground">
1220 {targetInstanceMissing
1221 ? "This provider instance is no longer available on this device."
1222 : "No providers configured."}
1223 </div>
1224 )}
1225 </div>
1226 </SettingsGroup>
1227 </SettingsSection>
1228​
1229 <UsageProviderSettings
1230 key={environmentId}
1231 environmentId={environmentId}
1232 environmentLabel={environmentLabel}
1233 sources={settings.usageLimitSources}
1234 readOnly={readOnly}
1235 />
1236​
1237 <SettingsSection title="Advanced">
1238 <SettingsRow
1239 id={searchableSetting("provider-health-check-interval").id}
1240 title={
1241 <span className="inline-flex items-center gap-1.5">
1242 {searchableSetting("provider-health-check-interval").title}
1243 <PolicyTooltip>
1244 This interval is configured here, then the shared Background activity policy decides
1245 whether provider probes may run when the timer fires. Custom intervals appear as
1246 Advanced in General settings.
1247 </PolicyTooltip>
1248 </span>
1250 description="Refresh provider status, versions, and models in the background. Set to 0 to disable."
1251 resetAction={
1252 providerHealthRefreshIntervalSeconds !== defaultProviderHealthRefreshIntervalSeconds ? (
1253 <span inert={readOnly} className={readOnly ? "opacity-50" : undefined}>
1254 <SettingResetButton
1255 label="provider health check interval"
1256 onClick={() =>
1257 updateSettings(
1258 backgroundActivityOverrideSettings(
1259 settings.backgroundActivity,
1260 resolvedBackgroundActivity,
1261 { providerHealthRefreshInterval: undefined },
1262 ),
1265 />
1266 </span>
1267 ) : null
1269 control={
1270 <div
1271 inert={readOnly}
1272 aria-disabled={readOnly || undefined}
1273 className={cn(
1274 "flex shrink-0 items-center gap-2",
1275 readOnly && "opacity-50 select-none",
1276 )}
1278 <NumberField
1279 value={providerHealthRefreshIntervalSeconds}
1280 min={0}
1281 step={PROVIDER_HEALTH_INTERVAL_STEP_SECONDS}
1282 size="sm"
1283 className="w-32"
1284 onValueChange={(value) =>
1285 updateSettings(
1286 backgroundActivityOverrideSettings(
1287 settings.backgroundActivity,
1288 resolvedBackgroundActivity,
1290 providerHealthRefreshInterval: Duration.seconds(
1291 normalizeIntervalSeconds(value),
1292 ),
1293 },
1294 ),
1298 <NumberFieldGroup>
1299 <NumberFieldDecrement aria-label="Decrease provider health check interval" />
1300 <NumberFieldInput aria-label="Provider health check interval in seconds" />
1301 <NumberFieldIncrement aria-label="Increase provider health check interval" />
1302 </NumberFieldGroup>
1303 </NumberField>
1304 <span className="text-xs text-muted-foreground">seconds</span>
1305 </div>
1307 />
1308 </SettingsSection>
1309​
1310 {isAddInstanceDialogOpen ? (
1311 <AddProviderInstanceDialog
1312 open
1313 environmentId={environmentId}
1314 environmentLabel={environmentLabel}
1315 onOpenChange={setIsAddInstanceDialogOpen}
1316 onCreated={setSelectedInstanceId}
1317 />
1318 ) : null}
1319 </>
1320 );