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

ProviderSettingsPanel.tsx

1,361 lines50.3 KB

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