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

ProviderSettingsPanel.tsx

1,453 lines52.5 KB

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