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

ProviderSettingsPanel.tsx

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