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