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 if (providerConfigString(row.instance.config, "source") === "local") return;
926 const agentId = providerConfigString(row.instance.config, "agentId");
927 if (agentId === null) return;
928
929 // The server decides from its latest settings whether this was the last
930 // instance using the managed agent. A client-side snapshot check can race
931 // two removals and make both callers skip cleanup.
932 const uninstallResult = await uninstallAcpRegistryManagedBinary({
933 environmentId,
934 input: { agentId },
935 });
936 if (uninstallResult._tag === "Failure" && !isAtomCommandInterrupted(uninstallResult)) {
937 const error = squashAtomCommandFailure(uninstallResult);
938 toastManager.add({
939 type: "warning",
940 title: "Provider deleted, but managed files remain",
941 description: error instanceof Error ? error.message : "Managed binary cleanup failed.",
942 });
943 }
944 };
945
946 const updateProviderModelPreferences = (
947 instanceId: ProviderInstanceId,
948 next: {
949 readonly hiddenModels: ReadonlyArray<string>;
950 readonly modelOrder: ReadonlyArray<string>;
951 },
952 ) => {
953 const hiddenModels = [...new Set(next.hiddenModels.filter((slug) => slug.trim().length > 0))];
954 const modelOrder = [...new Set(next.modelOrder.filter((slug) => slug.trim().length > 0))];
955 const rest = withoutProviderInstanceKey(settings.providerModelPreferences, instanceId);
956 updateClientSettings({
957 providerModelPreferences:
958 hiddenModels.length === 0 && modelOrder.length === 0
959 ? rest
960 : {
961 ...rest,
962 [instanceId]: {
963 hiddenModels,
964 modelOrder,
965 },
966 },
967 });
968 };
969
970 const updateProviderFavoriteModels = (
971 instanceId: ProviderInstanceId,
972 nextFavoriteModels: ReadonlyArray<string>,
973 ) => {
974 const favoriteModels = [
975 ...new Set(
976 Arr.filterMap(nextFavoriteModels, (slug) => {
977 const trimmedSlug = slug.trim();
978 return trimmedSlug.length > 0 ? Result.succeed(trimmedSlug) : Result.failVoid;
979 }),
980 ),
981 ];
982 updateClientSettings({
983 favorites: [
984 ...withoutProviderInstanceFavorites(settings.favorites ?? [], instanceId),
985 ...favoriteModels.map((model) => ({ provider: instanceId, model })),
986 ],
987 });
988 };
989
990 const resetDefaultInstance = async (driverKind: ProviderDriverKind) => {
991 type LegacyProviderSettings = (typeof settings.providers)[keyof typeof settings.providers];
992 const defaultLegacyProviders = DEFAULT_UNIFIED_SETTINGS.providers as Record<
993 string,
994 LegacyProviderSettings | undefined
995 >;
996 const defaultInstanceId = defaultInstanceIdForDriver(driverKind);
997 const defaultLegacyProvider = defaultLegacyProviders[driverKind];
998 if (defaultLegacyProvider === undefined) return;
999 const result = await persistProviderInstance(
1000 { operation: "remove", instanceId: defaultInstanceId },
1001 {
1002 providers: {
1003 ...settings.providers,
1004 [driverKind]: defaultLegacyProvider,
1005 } as typeof settings.providers,
1006 },
1007 );
1008 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
1009 const error = squashAtomCommandFailure(result);
1010 toastManager.add({
1011 type: "error",
1012 title: "Could not reset provider instance",
1013 description: error instanceof Error ? error.message : "The settings update failed.",
1014 });
1015 }
1016 };
1017
1018 const renderProviderInstance = (row: InstanceRow, mode: "list" | "editor") => {
1019 const driverOption = getDriverOption(row.driver);
1020 const liveProvider = serverProviders.find(
1021 (candidate) => candidate.instanceId === row.instanceId,
1022 );
1023 const updateCandidate = providerUpdateCandidateByInstanceId.get(row.instanceId);
1024 const isInstanceUpdateRunning =
1025 updatingProviderInstanceIds.has(row.instanceId) ||
1026 (liveProvider !== undefined && isProviderUpdateActive(liveProvider));
1027 const showInlineUpdateButton = updateCandidate !== undefined;
1028 const canRunInlineUpdate = updateCandidate !== undefined && !isInstanceUpdateRunning;
1029 const modelPreferences = settings.providerModelPreferences?.[row.instanceId] ?? {
1030 hiddenModels: [],
1031 modelOrder: [],
1032 };
1033 const favoriteModels = Arr.filterMap(settings.favorites ?? [], (favorite) =>
1034 favorite.provider === row.instanceId ? Result.succeed(favorite.model) : Result.failVoid,
1035 );
1036 const resetLabel = driverOption?.label ?? String(row.driver);
1037
1038 return (
1039 <ProviderInstanceCard
1040 key={row.instanceId}
1041 environmentId={environmentId}
1042 acpProjects={projects}
1043 onAcceptUrlAuth={
1044 readOnly ? undefined : (action) => acceptUrlAuthentication(row.instanceId, action)
1045 }
1046 instanceId={row.instanceId}
1047 instance={row.instance}
1048 driverOption={driverOption}
1049 liveProvider={liveProvider}
1050 mode={mode}
1051 selected={mode === "list" && selectedRow?.instanceId === row.instanceId}
1052 onSelect={mode === "list" ? () => setSelectedInstanceId(row.instanceId) : undefined}
1053 readOnly={readOnly}
1054 runtime={
1055 mode === "editor" &&
1056 row.driver === "codex" &&
1057 readCodexSetupMode(row.instance.config) === "managed" ? (
1058 <CodexManagedRuntimeFields
1059 environmentId={environmentId}
1060 instanceId={row.instanceId}
1061 provider={liveProvider}
1062 />
1063 ) : undefined
1064 }
1065 setup={
1066 mode === "editor" && row.driver === "antigravity" ? (
1067 <ProviderSetupSection
1068 environmentId={environmentId}
1069 environmentLabel={environmentLabel}
1070 instanceId={row.instanceId}
1071 provider={liveProvider}
1072 binaryPath={configuredBinaryPath(row.instance.config)}
1073 authMethod={readAntigravityAuthMethod(row.instance.config)}
1074 enabled={resolveProviderInstanceEnabled(row.instance)}
1075 readOnly={readOnly}
1076 onEnable={() => updateProviderInstance(row, { ...row.instance, enabled: true })}
1077 />
1078 ) : mode === "editor" &&
1079 row.driver === "codex" &&
1080 readCodexSetupMode(row.instance.config) === "managed" ? (
1081 <CodexSetupSection
1082 environmentId={environmentId}
1083 instanceId={row.instanceId}
1084 provider={liveProvider}
1085 mode={readCodexSetupMode(row.instance.config)}
1086 enabled={resolveProviderInstanceEnabled(row.instance)}
1087 readOnly={readOnly}
1088 onModeChange={(setupMode) =>
1089 updateProviderInstance(row, {
1090 ...row.instance,
1091 enabled: true,
1092 config: {
1093 ...(row.instance.config !== null && typeof row.instance.config === "object"
1094 ? row.instance.config
1095 : {}),
1096 enabled: true,
1097 setupMode,
1098 },
1099 })
1100 }
1101 />
1102 ) : mode === "editor" &&
1103 !readOnly &&
1104 liveProvider &&
1105 (liveProvider.setup?.canAuthenticate ||
1106 (liveProvider.driver === "acpRegistry" && liveProvider.installed)) ? (
1107 <ProviderAuthenticationSection
1108 key={`${environmentId}:${row.instanceId}`}
1109 environmentId={environmentId}
1110 environmentLabel={environmentLabel}
1111 instanceId={row.instanceId}
1112 provider={liveProvider}
1113 readOnly={readOnly}
1114 />
1115 ) : mode === "editor" &&
1116 !readOnly &&
1117 row.driver === "cursor" &&
1118 liveProvider?.setup?.canAuthenticate === false ? (
1119 <SettingsRow
1120 title="Cursor account"
1121 description="Using CURSOR_API_KEY. Remove it from this provider's environment to use browser sign-in."
1122 />
1123 ) : null
1124 }
1125 onUpdate={(next) => {
1126 const wasEnabled = resolveProviderInstanceEnabled(row.instance);
1127 const isDisabling = next.enabled === false && wasEnabled;
1128 const shouldClearTextGen = isDisabling && textGenInstanceId === row.instanceId;
1129 updateProviderInstance(
1130 row,
1131 next,
1132 shouldClearTextGen
1133 ? {
1134 textGenerationModelSelection:
1135 DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection,
1136 }
1137 : undefined,
1138 );
1139 }}
1140 onDelete={
1141 mode === "editor" && !row.isDefault ? () => deleteProviderInstance(row) : undefined
1142 }
1143 headerAction={
1144 mode === "editor" && row.isDefault && row.isDirty ? (
1145 <SettingResetButton
1146 label={`${resetLabel} provider settings`}
1147 onClick={() => resetDefaultInstance(row.driver)}
1148 />
1149 ) : null
1150 }
1151 hiddenModels={modelPreferences.hiddenModels}
1152 favoriteModels={favoriteModels}
1153 modelOrder={modelPreferences.modelOrder}
1154 onHiddenModelsChange={(hiddenModels) =>
1155 updateProviderModelPreferences(row.instanceId, {
1156 ...modelPreferences,
1157 hiddenModels,
1158 })
1159 }
1160 onFavoriteModelsChange={(next) => updateProviderFavoriteModels(row.instanceId, next)}
1161 onModelOrderChange={(modelOrder) =>
1162 updateProviderModelPreferences(row.instanceId, {
1163 ...modelPreferences,
1164 modelOrder,
1165 })
1166 }
1167 onInstallRecommended={
1168 !readOnly &&
1169 liveProvider?.compatibilityAdvisory?.message &&
1170 liveProvider.compatibilityAdvisory.recommendedVersion &&
1171 liveProvider.versionAdvisory?.canInstallVersion
1172 ? () => {
1173 void runProviderUpdate(
1174 liveProvider,
1175 liveProvider.compatibilityAdvisory?.recommendedVersion ?? undefined,
1176 );
1177 }
1178 : undefined
1179 }
1180 onRunUpdate={
1181 !readOnly && showInlineUpdateButton && updateCandidate
1182 ? () => {
1183 if (canRunInlineUpdate) void runProviderUpdate(updateCandidate);
1184 }
1185 : undefined
1186 }
1187 isUpdating={isInstanceUpdateRunning}
1188 />
1189 );
1190 };
1191
1192 return (
1193 <>
1194 <SettingsSection
1195 {...searchableSetting("providers")}
1196 variant="plain"
1197 headerAction={
1198 <div className="flex min-w-0 items-center gap-2">
1199 <ProviderUpdatesAction />
1200 {readOnly ? (
1201 <span className="min-w-0 truncate text-xs text-muted-foreground">
1202 <ProviderLastChecked lastCheckedAt={lastCheckedAt} />
1203 </span>
1204 ) : (
1205 <>
1206 <Tooltip>
1207 <TooltipTrigger
1208 render={
1209 <Button
1210 size="xs"
1211 variant="ghost-muted"
1212 disabled={isRefreshingProviders}
1213 aria-busy={isRefreshingProviders}
1214 onClick={() => void refreshProviders()}
1215 >
1216 <RefreshIcon refreshing={isRefreshingProviders} />
1217 <span className="sr-only">Refresh provider status</span>
1218 <span className="hidden min-w-0 truncate sm:inline">
1219 {isRefreshingProviders ? (
1220 "Refreshing providers"
1221 ) : (
1222 <ProviderLastChecked lastCheckedAt={lastCheckedAt} />
1223 )}
1224 </span>
1225 </Button>
1226 }
1227 />
1228 <TooltipPopup side="top">Refresh provider status</TooltipPopup>
1229 </Tooltip>
1230 <Tooltip>
1231 <TooltipTrigger
1232 render={
1233 <Button
1234 size="icon-xs"
1235 variant="ghost-muted"
1236 onClick={() => setIsAddInstanceDialogOpen(true)}
1237 aria-label="Add provider"
1238 >
1239 <PlusIcon />
1240 </Button>
1241 }
1242 />
1243 <TooltipPopup side="top">Add provider</TooltipPopup>
1244 </Tooltip>
1245 </>
1246 )}
1247 </div>
1248 }
1249 >
1250 {deviceTabs ? (
1251 <div className="flex min-h-11 min-w-0 items-center gap-2 px-3 sm:px-4">{deviceTabs}</div>
1252 ) : null}
1253 {readOnly ? (
1254 <SettingsGroup divided={false} className="overflow-hidden">
1255 <SettingsRow
1256 title="Limited permissions"
1257 description={`This session can view ${environmentLabel}'s providers but can't change their settings.`}
1258 />
1259 </SettingsGroup>
1260 ) : null}
1261 <SettingsGroup
1262 divided={false}
1263 className={cn(
1264 providerCardHeightClassName,
1265 "overflow-hidden @min-[48rem]/providers:grid @min-[48rem]/providers:grid-cols-[17rem_minmax(0,1fr)]",
1266 )}
1267 >
1268 <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">
1269 <ScrollArea
1270 scrollFade
1271 chainVerticalScroll
1272 className="@min-[48rem]/providers:min-h-0 @min-[48rem]/providers:flex-1"
1273 >
1274 <div className="divide-y divide-border/50">
1275 {rows.map((row) => renderProviderInstance(row, "list"))}
1276 </div>
1277 </ScrollArea>
1278 </div>
1279
1280 <div className="min-w-0 @min-[48rem]/providers:min-h-0">
1281 {selectedRow ? (
1282 <ScrollArea scrollFade chainVerticalScroll className="@min-[48rem]/providers:h-full">
1283 <div className="space-y-6 p-4">{renderProviderInstance(selectedRow, "editor")}</div>
1284 </ScrollArea>
1285 ) : (
1286 <div className="p-6 text-sm text-muted-foreground">
1287 {targetInstanceMissing
1288 ? "This provider instance is no longer available on this device."
1289 : "No providers configured."}
1290 </div>
1291 )}
1292 </div>
1293 </SettingsGroup>
1294 </SettingsSection>
1295
1296 <UsageProviderSettings
1297 key={environmentId}
1298 environmentId={environmentId}
1299 environmentLabel={environmentLabel}
1300 sources={settings.usageLimitSources}
1301 cursorKeychainUsageEnabled={settings.cursorKeychainUsageEnabled}
1302 readOnly={readOnly}
1303 />
1304
1305 <SettingsSection title="Advanced">
1306 <SettingsRow
1307 id={searchableSetting("provider-health-check-interval").id}
1308 title={
1309 <span className="inline-flex items-center gap-1.5">
1310 {searchableSetting("provider-health-check-interval").title}
1311 <PolicyTooltip>
1312 This interval is configured here, then the shared Background activity policy decides
1313 whether provider probes may run when the timer fires. Custom intervals appear as
1314 Advanced in General settings.
1315 </PolicyTooltip>
1316 </span>
1317 }
1318 description="Refresh provider status, versions, and models in the background. Set to 0 to disable."
1319 resetAction={
1320 providerHealthRefreshIntervalSeconds !== defaultProviderHealthRefreshIntervalSeconds ? (
1321 <span inert={readOnly} className={readOnly ? "opacity-50" : undefined}>
1322 <SettingResetButton
1323 label="provider health check interval"
1324 onClick={() =>
1325 updateSettings(
1326 backgroundActivityOverrideSettings(
1327 settings.backgroundActivity,
1328 resolvedBackgroundActivity,
1329 { providerHealthRefreshInterval: undefined },
1330 ),
1331 )
1332 }
1333 />
1334 </span>
1335 ) : null
1336 }
1337 control={
1338 <div
1339 inert={readOnly}
1340 aria-disabled={readOnly || undefined}
1341 className={cn(
1342 "flex shrink-0 items-center gap-2",
1343 readOnly && "opacity-50 select-none",
1344 )}
1345 >
1346 <NumberField
1347 value={providerHealthRefreshIntervalSeconds}
1348 min={0}
1349 step={PROVIDER_HEALTH_INTERVAL_STEP_SECONDS}
1350 size="sm"
1351 className="w-32"
1352 onValueChange={(value) =>
1353 updateSettings(
1354 backgroundActivityOverrideSettings(
1355 settings.backgroundActivity,
1356 resolvedBackgroundActivity,
1357 {
1358 providerHealthRefreshInterval: Duration.seconds(
1359 normalizeIntervalSeconds(value),
1360 ),
1361 },
1362 ),
1363 )
1364 }
1365 >
1366 <NumberFieldGroup>
1367 <NumberFieldDecrement aria-label="Decrease provider health check interval" />
1368 <NumberFieldInput aria-label="Provider health check interval in seconds" />
1369 <NumberFieldIncrement aria-label="Increase provider health check interval" />
1370 </NumberFieldGroup>
1371 </NumberField>
1372 <span className="text-xs text-muted-foreground">seconds</span>
1373 </div>
1374 }
1375 />
1376 </SettingsSection>
1377
1378 {isAddInstanceDialogOpen ? (
1379 <AddProviderInstanceDialog
1380 open
1381 environmentId={environmentId}
1382 environmentLabel={environmentLabel}
1383 onOpenChange={setIsAddInstanceDialogOpen}
1384 onCreated={setSelectedInstanceId}
1385 />
1386 ) : null}
1387 </>
1388 );
1389}