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