Open History to see the last commit
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) }));
140}
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;
146}
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() : "";
156}
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 );
191}
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";
199}
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 );
240}
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 );
282}
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[];
290}
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 );
301}
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 );
461}
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 );
482}
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 );
510}
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 );
549}
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
1001 }
1002 headerAction={
1003 // The ghost button's padding would inset its label; the New design aligns the text to the card edge.
1004 <div className="flex min-w-0 items-center gap-2 redesign:-me-2">
1005 <ProviderUpdatesAction />
1006 <Tooltip>
1007 <TooltipTrigger
1008 render={
1009 <Button
1010 size="xs"
1011 variant="ghost-muted"
1012 disabled={isRefreshingProviders || !canRefreshProviders}
1013 aria-busy={isRefreshingProviders}
1014 onClick={() => void refreshProviders()}
1015 >
1016 <RefreshIcon refreshing={isRefreshingProviders} />
1017 <span className="sr-only">Refresh provider status</span>
1018 <span className="hidden min-w-0 truncate sm:inline">
1019 {isRefreshingProviders ? (
1020 "Refreshing providers"
1021 ) : (
1022 <ProviderLastChecked environmentId={environmentId} />
1023 )}
1024 </span>
1025 </Button>
1026 }
1027 />
1028 <TooltipPopup side="top">Refresh provider status</TooltipPopup>
1029 </Tooltip>
1030 </div>
1031 }
1032 >
1033 {deviceTabs ? (
1034 <div className="flex min-h-11 min-w-0 items-center gap-2 px-3 sm:px-4">{deviceTabs}</div>
1035 ) : null}
1036 {readOnly ? (
1037 <SettingsGroup divided={false} className="overflow-hidden">
1038 <SettingsRow
1039 title="Limited permissions"
1040 description={`This session can view ${environmentLabel}'s providers but can't change their settings.`}
1041 />
1042 </SettingsGroup>
1043 ) : null}
1044 <SettingsGroup
1045 divided={false}
1046 className={cn(
1047 providerCardHeightClassName,
1048 "overflow-hidden @min-[48rem]/providers:grid @min-[48rem]/providers:grid-cols-[17rem_minmax(0,1fr)]",
1049 )}
1050 >
1051 <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">
1052 <ScrollArea
1053 scrollFade
1054 chainVerticalScroll
1055 className="@min-[48rem]/providers:min-h-0 @min-[48rem]/providers:flex-1"
1056 >
1057 <div className="divide-y divide-border/50">
1058 {rows.map((row) => renderProviderInstance(row, "list"))}
1059 {!readOnly ? (
1060 <button
1061 type="button"
1062 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"
1063 onClick={() => setIsAddInstanceDialogOpen(true)}
1064 >
1065 <PlusIcon className="size-4 shrink-0" />
1066 Add provider
1067 </button>
1068 ) : null}
1069 </div>
1070 </ScrollArea>
1071 </div>
1072
1073 <div data-provider-detail className="min-w-0 @min-[48rem]/providers:min-h-0">
1074 {selectedRow ? (
1075 <ScrollArea scrollFade chainVerticalScroll className="@min-[48rem]/providers:h-full">
1076 {/* Flat sections run dividers edge to edge and inset text like the list beside them. */}
1077 <div className="space-y-6 p-4 redesign:px-0">
1078 {renderProviderInstance(selectedRow, "editor")}
1079 </div>
1080 </ScrollArea>
1081 ) : (
1082 <div className="p-6 text-sm text-muted-foreground">
1083 {targetInstanceMissing
1084 ? "This provider instance is no longer available on this device."
1085 : "No providers configured."}
1086 </div>
1087 )}
1088 </div>
1089 </SettingsGroup>
1090 </SettingsSection>
1091
1092 <UsageProviderSettings
1093 key={environmentId}
1094 environmentId={environmentId}
1095 environmentLabel={environmentLabel}
1096 sources={settings.usageLimitSources}
1097 cursorKeychainUsageEnabled={settings.cursorKeychainUsageEnabled}
1098 readOnly={readOnly}
1099 />
1100
1101 <SettingsSection title="Advanced">
1102 <SettingsRow
1103 id={searchableSetting("provider-health-check-interval").id}
1104 title={
1105 <span className="inline-flex items-center gap-1.5">
1106 {searchableSetting("provider-health-check-interval").title}
1107 <PolicyTooltip>
1108 This interval is configured here, then the shared Background activity policy decides
1109 whether provider probes may run when the timer fires. Custom intervals appear as
1110 Advanced in General settings.
1111 </PolicyTooltip>
1112 </span>
1113 }
1114 description="Refresh provider status, versions, and models in the background. Set to 0 to disable."
1115 resetAction={
1116 providerHealthRefreshIntervalSeconds !== defaultProviderHealthRefreshIntervalSeconds ? (
1117 <span
1118 inert={!canWriteSettings}
1119 className={!canWriteSettings ? "opacity-50" : undefined}
1120 >
1121 <SettingResetButton
1122 label="provider health check interval"
1123 onClick={() =>
1124 updateSettings(
1125 backgroundActivityOverrideSettings(
1126 settings.backgroundActivity,
1127 resolvedBackgroundActivity,
1128 { providerHealthRefreshInterval: undefined },
1129 ),
1130 )
1131 }
1132 />
1133 </span>
1134 ) : null
1135 }
1136 control={
1137 <div
1138 inert={!canWriteSettings}
1139 aria-disabled={!canWriteSettings || undefined}
1140 className={cn(
1141 "flex shrink-0 items-center gap-2",
1142 !canWriteSettings && "opacity-50 select-none",
1143 )}
1144 >
1145 <NumberField
1146 value={providerHealthRefreshIntervalSeconds}
1147 min={0}
1148 step={PROVIDER_HEALTH_INTERVAL_STEP_SECONDS}
1149 size="sm"
1150 className="w-32"
1151 onValueChange={(value) =>
1152 updateSettings(
1153 backgroundActivityOverrideSettings(
1154 settings.backgroundActivity,
1155 resolvedBackgroundActivity,
1156 {
1157 providerHealthRefreshInterval: Duration.seconds(
1158 normalizeIntervalSeconds(value),
1159 ),
1160 },
1161 ),
1162 )
1163 }
1164 >
1165 <NumberFieldGroup>
1166 <NumberFieldDecrement aria-label="Decrease provider health check interval" />
1167 <NumberFieldInput aria-label="Provider health check interval in seconds" />
1168 <NumberFieldIncrement aria-label="Increase provider health check interval" />
1169 </NumberFieldGroup>
1170 </NumberField>
1171 <span className="text-xs text-muted-foreground">seconds</span>
1172 </div>
1173 }
1174 />
1175 </SettingsSection>
1176
1177 {isAddInstanceDialogOpen && !readOnly ? (
1178 <AddProviderInstanceDialog
1179 open
1180 environmentId={environmentId}
1181 environmentLabel={environmentLabel}
1182 onOpenChange={setIsAddInstanceDialogOpen}
1183 onCreated={setSelectedInstanceId}
1184 />
1185 ) : null}
1186 </>
1187 );
1188}
1189
1190interface ProviderInstanceRowActions {
1191 readonly acceptUrlAuthentication: (
1192 instanceId: ProviderInstanceId,
1193 action: AcpRegistryUrlAuthAction,
1194 ) => void;
1195 readonly runProviderUpdate: (
1196 candidate: Pick<ProviderSettingsUpdateCandidate, "driver" | "instanceId">,
1197 targetVersion?: string,
1198 ) => Promise<void>;
1199 readonly updateInstance: (
1200 instanceId: ProviderInstanceId,
1201 previous: ProviderInstanceConfig,
1202 next: ProviderInstanceConfig,
1203 ) => void;
1204 readonly enableInstance: (
1205 instanceId: ProviderInstanceId,
1206 next: ProviderInstanceConfig,
1207 ) => Promise<void>;
1208 readonly deleteInstance: (
1209 instanceId: ProviderInstanceId,
1210 instance: ProviderInstanceConfig,
1211 ) => Promise<void>;
1212 readonly resetDefaultInstance: (driverKind: ProviderDriverKind) => Promise<void>;
1213 readonly writeProjectOverride: (
1214 instanceId: ProviderInstanceId,
1215 next: boolean | undefined,
1216 ) => void;
1217 readonly updateModelPreferences: ReturnType<typeof useUpdateEnvironmentModelPreferences>;
1218 readonly toggleModelFavorite: ReturnType<typeof useToggleEnvironmentModelFavorite>;
1219 readonly selectInstance: (instanceId: ProviderInstanceId) => void;
1220}
1221
1222const NO_MODELS: ReadonlyArray<string> = [];
1223
1224/** Stable props let this boundary return cached cards even when settings rebuild parent row elements. */
1225function ProviderInstanceRow({
1226 environmentId,
1227 environmentLabel,
1228 instanceId,
1229 driver,
1230 explicitInstance,
1231 isDefault,
1232 isDirty,
1233 mode,
1234 selected,
1235 readOnly,
1236 canWriteSettings,
1237 liveProvider,
1238 isUpdateDispatching,
1239 showProjectOverride,
1240 projectOverrideValue,
1241 projectOverrideEffectiveEnabled,
1242 modelPreferences,
1243 favorites,
1244 actions,
1245}: {
1246 readonly environmentId: EnvironmentId;
1247 readonly environmentLabel: string;
1248 readonly instanceId: ProviderInstanceId;
1249 readonly driver: ProviderDriverKind;
1250 readonly explicitInstance: ProviderInstanceConfig | undefined;
1251 readonly isDefault: boolean;
1252 readonly isDirty: boolean;
1253 readonly mode: "list" | "editor";
1254 readonly selected: boolean;
1255 readonly readOnly: boolean;
1256 readonly canWriteSettings: boolean;
1257 readonly liveProvider: ServerProvider | undefined;
1258 readonly isUpdateDispatching: boolean;
1259 readonly showProjectOverride: boolean;
1260 readonly projectOverrideValue: boolean | undefined;
1261 readonly projectOverrideEffectiveEnabled: boolean;
1262 readonly modelPreferences:
1263 | { readonly hiddenModels: ReadonlyArray<string>; readonly modelOrder: ReadonlyArray<string> }
1264 | undefined;
1265 readonly favorites: UnifiedSettings["favorites"];
1266 readonly actions: ProviderInstanceRowActions;
1267}) {
1268 const allProjects = useProjects();
1269 const acpProjects =
1270 mode === "editor" && liveProvider?.driver === "acpRegistry"
1271 ? allProjects.filter((project) => project.environmentId === environmentId)
1272 : undefined;
1273 const instance = explicitInstance ?? { driver };
1274 const driverOption = providerClients.get(driver);
1275 const updateCandidate =
1276 liveProvider !== undefined && isProviderSettingsUpdateCandidate(liveProvider)
1277 ? liveProvider
1278 : undefined;
1279 const isInstanceUpdateRunning =
1280 isUpdateDispatching || (liveProvider !== undefined && isProviderUpdateActive(liveProvider));
1281 const hiddenModels = modelPreferences?.hiddenModels ?? NO_MODELS;
1282 const modelOrder = modelPreferences?.modelOrder ?? NO_MODELS;
1283 const favoriteModels = Arr.filterMap(favorites, (favorite) =>
1284 favorite.provider === instanceId ? Result.succeed(favorite.model) : Result.failVoid,
1285 );
1286 const resetLabel = driverOption?.label ?? String(driver);
1287 const projectOverride = showProjectOverride
1288 ? {
1289 value: projectOverrideValue,
1290 effectiveEnabled: projectOverrideEffectiveEnabled,
1291 onChange: (next: boolean) => actions.writeProjectOverride(instanceId, next),
1292 onReset: () => actions.writeProjectOverride(instanceId, undefined),
1293 }
1294 : undefined;
1295 const codexSetupMode = driver === "codex" ? readCodexSetupMode(instance.config) : null;
1296 const recommendedVersion = liveProvider?.compatibilityAdvisory?.recommendedVersion;
1297 const canInstallRecommended =
1298 !readOnly &&
1299 liveProvider !== undefined &&
1300 Boolean(liveProvider.compatibilityAdvisory?.message) &&
1301 Boolean(recommendedVersion) &&
1302 liveProvider.versionAdvisory?.canInstallVersion === true;
1303
1304 return (
1305 <ProviderInstanceCard
1306 environmentId={environmentId}
1307 acpProjects={acpProjects}
1308 projectOverride={projectOverride}
1309 onAcceptUrlAuth={
1310 readOnly ? undefined : (action) => actions.acceptUrlAuthentication(instanceId, action)
1311 }
1312 instanceId={instanceId}
1313 instance={instance}
1314 driverOption={driverOption}
1315 liveProvider={liveProvider}
1316 mode={mode}
1317 selected={selected}
1318 onSelect={mode === "list" ? () => actions.selectInstance(instanceId) : undefined}
1319 readOnly={readOnly}
1320 runtime={
1321 mode === "editor" && codexSetupMode === "managed" ? (
1322 <CodexManagedRuntimeFields
1323 environmentId={environmentId}
1324 instanceId={instanceId}
1325 provider={liveProvider}
1326 />
1327 ) : undefined
1328 }
1329 canWriteSettings={canWriteSettings}
1330 setup={
1331 mode === "editor" && driver === "antigravity" ? (
1332 <ProviderSetupSection
1333 environmentId={environmentId}
1334 environmentLabel={environmentLabel}
1335 instanceId={instanceId}
1336 provider={liveProvider}
1337 binaryPath={configuredBinaryPath(instance.config)}
1338 authMethod={readAntigravityAuthMethod(instance.config)}
1339 enabled={resolveProviderInstanceEnabled(instance)}
1340 readOnly={readOnly}
1341 onEnable={() => actions.enableInstance(instanceId, { ...instance, enabled: true })}
1342 />
1343 ) : mode === "editor" && codexSetupMode === "managed" ? (
1344 <CodexSetupSection
1345 environmentId={environmentId}
1346 instanceId={instanceId}
1347 provider={liveProvider}
1348 mode={codexSetupMode}
1349 enabled={resolveProviderInstanceEnabled(instance)}
1350 readOnly={readOnly}
1351 onModeChange={(setupMode) =>
1352 actions.enableInstance(instanceId, {
1353 ...instance,
1354 enabled: true,
1355 config: {
1356 ...(instance.config !== null && typeof instance.config === "object"
1357 ? instance.config
1358 : {}),
1359 enabled: true,
1360 setupMode,
1361 },
1362 })
1363 }
1364 />
1365 ) : mode === "editor" &&
1366 !readOnly &&
1367 liveProvider &&
1368 (liveProvider.setup?.canAuthenticate ||
1369 (liveProvider.driver === "acpRegistry" && liveProvider.installed)) ? (
1370 <ProviderAuthenticationSection
1371 key={`${environmentId}:${instanceId}`}
1372 environmentId={environmentId}
1373 environmentLabel={environmentLabel}
1374 instanceId={instanceId}
1375 provider={liveProvider}
1376 readOnly={readOnly}
1377 />
1378 ) : mode === "editor" &&
1379 !readOnly &&
1380 driver === "cursor" &&
1381 liveProvider?.setup?.canAuthenticate === false ? (
1382 <SettingsRow
1383 title="Cursor account"
1384 description="Using CURSOR_API_KEY. Remove it from this provider's environment to use browser sign-in."
1385 />
1386 ) : null
1387 }
1388 onUpdate={(next) => actions.updateInstance(instanceId, instance, next)}
1389 onDelete={
1390 mode === "editor" && !isDefault
1391 ? () => actions.deleteInstance(instanceId, instance)
1392 : undefined
1393 }
1394 headerAction={
1395 mode === "editor" && isDefault && isDirty ? (
1396 <SettingResetButton
1397 label={`${resetLabel} provider settings`}
1398 onClick={() => actions.resetDefaultInstance(driver)}
1399 />
1400 ) : null
1401 }
1402 hiddenModels={hiddenModels}
1403 favoriteModels={favoriteModels}
1404 modelOrder={modelOrder}
1405 onHiddenModelsChange={(next, affectedModels) => {
1406 const hidden = new Set(next);
1407 const models =
1408 affectedModels ?? modelListChanges(hiddenModels, next).map((change) => change.model);
1409 void actions.updateModelPreferences({
1410 setModelsHidden: models.map((model) => ({
1411 provider: instanceId,
1412 model,
1413 hidden: hidden.has(model),
1414 })),
1415 });
1416 }}
1417 onToggleFavorite={(model) => {
1418 void actions.toggleModelFavorite(instanceId, model);
1419 }}
1420 onFavoriteModelsChange={(next) => {
1421 void actions.updateModelPreferences({
1422 setModelFavorites: modelListChanges(favoriteModels, next).map(({ model, selected }) => ({
1423 provider: instanceId,
1424 model,
1425 favorite: selected,
1426 })),
1427 });
1428 }}
1429 onModelOrderChange={(nextOrder) => {
1430 void actions.updateModelPreferences({
1431 setProviderModelOrder: { provider: instanceId, modelOrder: nextOrder },
1432 });
1433 }}
1434 onInstallRecommended={
1435 canInstallRecommended
1436 ? () => {
1437 void actions.runProviderUpdate(liveProvider, recommendedVersion ?? undefined);
1438 }
1439 : undefined
1440 }
1441 onRunUpdate={
1442 !readOnly && updateCandidate
1443 ? () => {
1444 if (!isInstanceUpdateRunning) void actions.runProviderUpdate(updateCandidate);
1445 }
1446 : undefined
1447 }
1448 isUpdating={isInstanceUpdateRunning}
1449 />
1450 );
1451}