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

ProviderSettingsPanel.tsx

1,447 lines52.1 KB

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