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