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

ProviderSettingsPanel.tsx

1,386 lines50.8 KB

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