Open History to see the last commit
1import { SettingsGroup } from "./SettingsGroup";
2import { RefreshIcon } from "~/components/ui/refresh-icon";
3import {
4 AuthSettingsWriteScope,
5 AuthProvidersManageScope,
6 AuthOrchestrationReadScope,
7} from "@t3tools/contracts";
8import { useEnvironmentScope, readEnvironmentScope } from "../../state/session";
9import { useAtomValue } from "@effect/atom-react";
10import { connectionStatusTitle } from "@t3tools/client-runtime/connection";
11import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
12import {
13 isAtomCommandInterrupted,
14 squashAtomCommandFailure,
15} from "@t3tools/client-runtime/state/runtime";
16import {
17 defaultInstanceIdForDriver,
18 type EnvironmentId,
19 type AcpRegistryUrlAuthAction,
20 PROVIDER_DISPLAY_NAMES,
21 ProviderDriverKind,
22 type ProjectId,
23 type ProviderInstanceConfig,
24 type ProviderInstanceId,
25 type ServerProvider,
26 resolveEnvironmentMachineKind,
27 resolveProjectProviderInstanceEnabled,
28 resolveProviderInstanceEnabled,
29} from "@t3tools/contracts";
30import { DEFAULT_UNIFIED_SETTINGS, type UnifiedSettings } from "@t3tools/contracts/settings";
31import {
32 getBackgroundActivityPresetSettings,
33 resolveServerBackgroundActivitySettings,
34} from "@t3tools/shared/backgroundActivitySettings";
35import * as Arr from "effect/Array";
36import * as Duration from "effect/Duration";
37import * as Result from "effect/Result";
38import { PlusIcon } from "lucide-react";
39import { useRef, useState, type ReactNode } from "react";
40
41import { isDesktopLocalConnectionTarget } from "../../connection/desktopLocal";
42import {
43 useEnvironmentSettings,
44 usePersistEnvironmentProviderInstanceMutation,
45 useUpdateEnvironmentSettings,
46 useUpdateEnvironmentModelPreferences,
47 useToggleEnvironmentModelFavorite,
48} from "../../hooks/useSettings";
49import { useStableCallback } from "../../hooks/useStableCallback";
50import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
51import { cn } from "../../lib/utils";
52import { resolveAppModelSelectionState } from "../../modelSelection";
53import {
54 useEnvironments,
55 usePrimaryEnvironmentId,
56 type EnvironmentPresentation,
57} from "../../state/environments";
58import {
59 EMPTY_SERVER_PROVIDERS,
60 providersIgnoringCheckedAtAtom,
61 serverEnvironment,
62} from "../../state/server";
63import { useEnvironmentSessionState } from "../../state/session";
64import { useProjects } from "../../state/entities";
65import { useAtomCommand } from "../../state/use-atom-command";
66import { useRelativeTimeState } from "../../hooks/useRelativeTimeState";
67import {
68 ConnectionStatusDot,
69 connectionPhaseDotClassName,
70 connectionPhasePingClassName,
71} from "../ConnectionStatusDot";
72import {
73 isProviderSettingsUpdateCandidate,
74 isProviderUpdateActive,
75 type ProviderSettingsUpdateCandidate,
76} from "../ProviderUpdateLaunchNotification.logic";
77import { ProviderUpdatesAction } from "../ProviderUpdatesAction";
78import { Button } from "../ui/button";
79import {
80 Empty,
81 EmptyContent,
82 EmptyDescription,
83 EmptyHeader,
84 EmptyMedia,
85 EmptyTitle,
86} from "../ui/empty";
87import {
88 NumberField,
89 NumberFieldDecrement,
90 NumberFieldGroup,
91 NumberFieldIncrement,
92 NumberFieldInput,
93} from "../ui/number-field";
94import { ScrollArea } from "../ui/scroll-area";
95import { Toggle, ToggleGroup } from "../ui/toggle-group";
96import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
97import { stackedThreadToast, toastManager } from "../ui/toast";
98import { AddProviderInstanceDialog } from "./AddProviderInstanceDialog";
99import { ExpandableText } from "./ExpandableText";
100import { ProviderInstanceCard } from "./ProviderInstanceCard";
101import { UsageProviderSettings } from "./UsageProviderSettings";
102import { ProviderSetupSection, readAntigravityAuthMethod } from "./ProviderSetupSection";
103import { ProviderAuthenticationSection } from "./ProviderAuthenticationSection";
104import { CodexSetupSection, CodexManagedRuntimeFields } from "./CodexSetupSection";
105import { readCodexSetupMode } from "./CodexSetupSection.logic";
106import { providerClients } from "./providerDriverMeta";
107import { searchableSetting } from "./settingsSearch";
108import { 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) }));
141}
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;
147}
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() : "";
157}
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 );
192}
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";
200}
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 );
241}
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 );
283}
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[];
291}
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 );
302}
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 <RemoteSessionGatedProviderSettings
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 );
462}
463
464function RemoteSessionGatedProviderSettings({
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 const sessionState = useEnvironmentSessionState(environment.environmentId);
476 const operateAccess = resolveRemoteOperateAccess({
477 session: sessionState.data,
478 isPending: sessionState.isPending,
479 hasError: sessionState.hasError,
480 });
481 return (
482 <AccessGatedProviderSettings
483 environment={environment}
484 operateAccess={operateAccess}
485 deviceTabs={deviceTabs}
486 targetInstanceId={targetInstanceId}
487 projectIds={projectIds}
488 />
489 );
490}
491
492function AccessGatedProviderSettings({
493 environment,
494 operateAccess,
495 deviceTabs,
496 targetInstanceId,
497 projectIds,
498}: {
499 readonly environment: EnvironmentPresentation;
500 readonly operateAccess: ProviderOperateAccess;
501 readonly deviceTabs?: ReactNode;
502 readonly targetInstanceId?: ProviderInstanceId | undefined;
503 readonly projectIds: readonly ProjectId[];
504}) {
505 const access = classifyProviderEnvironmentAccess({
506 connectionPhase: environment.connection.phase,
507 hasServerConfig: environment.serverConfig !== null,
508 operateAccess,
509 });
510 if (access.kind !== "editable" && access.kind !== "read-only") {
511 return (
512 <EnvironmentUnavailablePlaceholder
513 environment={environment}
514 access={access}
515 deviceTabs={deviceTabs}
516 />
517 );
518 }
519 return (
520 <EnvironmentProviderSettings
521 environmentId={environment.environmentId}
522 environmentLabel={environment.label}
523 readOnly={access.kind === "read-only"}
524 deviceTabs={deviceTabs}
525 targetInstanceId={targetInstanceId}
526 projectIds={projectIds}
527 />
528 );
529}
530
531const NO_PROJECT_IDS: readonly ProjectId[] = [];
532const NO_FAVORITES: UnifiedSettings["favorites"] = [];
533
534export function EnvironmentProviderSettings({
535 environmentId,
536 environmentLabel,
537 readOnly = false,
538 deviceTabs,
539 targetInstanceId,
540 projectIds = NO_PROJECT_IDS,
541}: {
542 readonly environmentId: EnvironmentId;
543 readonly environmentLabel: string;
544 readonly deviceTabs?: ReactNode;
545 readonly targetInstanceId?: ProviderInstanceId | undefined;
546 readonly projectIds?: readonly ProjectId[];
547 readonly readOnly?: boolean;
548}) {
549 const settings = useEnvironmentSettings(environmentId);
550 const canWriteSettings = useEnvironmentScope(environmentId, AuthSettingsWriteScope);
551 const canRefreshProviders = useEnvironmentScope(environmentId, AuthOrchestrationReadScope);
552 const updateSettings = useUpdateEnvironmentSettings(environmentId);
553 const updateModelPreferences = useUpdateEnvironmentModelPreferences(environmentId);
554 const toggleModelFavorite = useToggleEnvironmentModelFavorite(environmentId);
555 const persistProviderInstance = usePersistEnvironmentProviderInstanceMutation(environmentId);
556 const serverProviders = useAtomValue(providersIgnoringCheckedAtAtom(environmentId));
557 // Hide overrides on older servers that silently ignore providerInstances patches.
558 const supportsProjectProviderOverrides = useAtomValue(
559 serverEnvironment.configValueAtom(environmentId),
560 (config) => config?.environment.capabilities.projectProviderInstanceOverrides === true,
561 );
562 const refreshServerProviders = useAtomCommand(serverEnvironment.refreshProviders, {
563 reportFailure: false,
564 });
565 const updateProvider = useAtomCommand(serverEnvironment.updateProvider, {
566 reportFailure: false,
567 });
568 const uninstallAcpRegistryManagedBinary = useAtomCommand(
569 serverEnvironment.uninstallAcpRegistryManagedBinary,
570 { reportFailure: false },
571 );
572 const acceptAcpRegistryUrlAuth = useAtomCommand(serverEnvironment.acceptAcpRegistryUrlAuth, {
573 reportFailure: false,
574 });
575 const [isRefreshingProviders, setIsRefreshingProviders] = useState(false);
576 const [isAddInstanceDialogOpen, setIsAddInstanceDialogOpen] = useState(false);
577 const [selectedInstanceId, setSelectedInstanceId] = useState<ProviderInstanceId | null>(
578 targetInstanceId ?? null,
579 );
580 const [updatingProviderInstanceIds, setUpdatingProviderInstanceIds] = useState<
581 ReadonlySet<ProviderInstanceId>
582 >(() => new Set());
583 const refreshingRef = useRef(false);
584 const updatingInstanceIdsRef = useRef<Set<ProviderInstanceId>>(new Set());
585
586 const acceptUrlAuthentication = useStableCallback(
587 (instanceId: ProviderInstanceId, action: AcpRegistryUrlAuthAction) => {
588 void acceptAcpRegistryUrlAuth({
589 environmentId,
590 input: { instanceId, elicitationId: action.elicitationId },
591 }).then((result) => {
592 if (result._tag === "Success" && !result.value.accepted) {
593 toastManager.add({
594 type: "warning",
595 title: "Authentication request expired",
596 description: "Refresh the provider and start the authentication flow again.",
597 });
598 return;
599 }
600 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
601 const error = squashAtomCommandFailure(result);
602 toastManager.add({
603 type: "error",
604 title: "Could not continue authentication",
605 description:
606 error instanceof Error ? error.message : "The authentication request expired.",
607 });
608 }
609 });
610 },
611 );
612
613 const visibleProviderSettings = PROVIDER_SETTINGS.filter(
614 (providerSettings) =>
615 providerSettings.provider !== "cursor" ||
616 serverProviders.some(
617 (provider) =>
618 provider.instanceId === defaultInstanceIdForDriver(ProviderDriverKind.make("cursor")),
619 ),
620 );
621 const resolvedBackgroundActivity = resolveServerBackgroundActivitySettings(settings);
622 const providerHealthPreset = getBackgroundActivityPresetSettings(
623 resolvedBackgroundActivity.profile,
624 ).providerHealthRefreshInterval;
625 const providerHealthRefreshIntervalSeconds = durationToSeconds(
626 resolvedBackgroundActivity.providerHealthRefreshInterval,
627 );
628 const defaultProviderHealthRefreshIntervalSeconds = durationToSeconds(providerHealthPreset);
629
630 const refreshProviders = () => {
631 if (refreshingRef.current || !readEnvironmentScope(environmentId, AuthOrchestrationReadScope))
632 return;
633 refreshingRef.current = true;
634 setIsRefreshingProviders(true);
635 void (async () => {
636 const result = await refreshServerProviders({
637 environmentId,
638 input: { refreshModels: true },
639 });
640 refreshingRef.current = false;
641 setIsRefreshingProviders(false);
642 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
643 console.warn("Failed to refresh providers", {
644 operation: "refresh-providers",
645 environmentId,
646 ...safeErrorLogAttributes(squashAtomCommandFailure(result)),
647 });
648 }
649 })();
650 };
651
652 const runProviderUpdate = useStableCallback(
653 async (
654 candidate: Pick<ProviderSettingsUpdateCandidate, "driver" | "instanceId">,
655 targetVersion?: string,
656 ) => {
657 if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
658 // Guard re-entry with a ref; deferred state updates cannot gate dispatch.
659 if (updatingInstanceIdsRef.current.has(candidate.instanceId)) {
660 return;
661 }
662 updatingInstanceIdsRef.current.add(candidate.instanceId);
663 setUpdatingProviderInstanceIds((previous) => new Set(previous).add(candidate.instanceId));
664
665 const result = await updateProvider({
666 environmentId,
667 input: {
668 provider: candidate.driver,
669 instanceId: candidate.instanceId,
670 ...(targetVersion ? { targetVersion } : {}),
671 },
672 });
673 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
674 const error = squashAtomCommandFailure(result);
675 toastManager.add(
676 stackedThreadToast({
677 type: "error",
678 title: `Could not update ${PROVIDER_DISPLAY_NAMES[candidate.driver] ?? candidate.driver}`,
679 description:
680 error instanceof Error
681 ? error.message
682 : "The provider update command could not be started.",
683 }),
684 );
685 }
686 updatingInstanceIdsRef.current.delete(candidate.instanceId);
687 setUpdatingProviderInstanceIds((previous) => {
688 if (!previous.has(candidate.instanceId)) {
689 return previous;
690 }
691 const next = new Set(previous);
692 next.delete(candidate.instanceId);
693 return next;
694 });
695 },
696 );
697
698 interface InstanceRow {
699 readonly instanceId: ProviderInstanceId;
700 /** Undefined for a default slot the user never configured. */
701 readonly explicitInstance: ProviderInstanceConfig | undefined;
702 readonly driver: ProviderDriverKind;
703 readonly isDefault: boolean;
704 readonly isDirty?: boolean;
705 }
706
707 const instancesByDriver = new Map<
708 ProviderDriverKind,
709 Array<[ProviderInstanceId, ProviderInstanceConfig]>
710 >();
711 for (const [rawId, instance] of Object.entries(settings.providerInstances ?? {})) {
712 const driver = instance.driver;
713 const list = instancesByDriver.get(driver) ?? [];
714 list.push([rawId as ProviderInstanceId, instance]);
715 instancesByDriver.set(driver, list);
716 }
717
718 const defaultSlotIdsBySource = new Set<string>(
719 visibleProviderSettings.map((providerSettings) =>
720 String(defaultInstanceIdForDriver(providerSettings.provider)),
721 ),
722 );
723
724 const rows: InstanceRow[] = [];
725 const visibleDriverKinds = new Set<ProviderDriverKind>(
726 visibleProviderSettings.map((providerSettings) => providerSettings.provider),
727 );
728
729 for (const providerSettings of visibleProviderSettings) {
730 const driver = providerSettings.provider;
731 const defaultInstanceId = defaultInstanceIdForDriver(driver);
732 const explicitInstance = settings.providerInstances?.[defaultInstanceId];
733 const isDirty = explicitInstance !== undefined;
734 const hasDefaultSlot = providerSettings.hasDefaultInstance || explicitInstance !== undefined;
735 if (
736 hasDefaultSlot &&
737 (driver === "codex" ||
738 driver === "claudeAgent" ||
739 isDirty ||
740 resolveProviderInstanceEnabled(explicitInstance ?? { driver }) ||
741 defaultInstanceId === targetInstanceId)
742 ) {
743 rows.push({
744 instanceId: defaultInstanceId,
745 explicitInstance,
746 driver,
747 isDefault: true,
748 isDirty,
749 });
750 }
751 for (const [id, instance] of instancesByDriver.get(providerSettings.provider) ?? []) {
752 if (id === defaultInstanceId) continue;
753 rows.push({
754 instanceId: id,
755 explicitInstance: instance,
756 driver: instance.driver,
757 isDefault: false,
758 });
759 }
760 }
761 for (const [driver, list] of instancesByDriver) {
762 if (visibleDriverKinds.has(driver)) continue;
763 for (const [id, instance] of list) {
764 rows.push({
765 instanceId: id,
766 explicitInstance: instance,
767 driver: instance.driver,
768 isDefault: defaultSlotIdsBySource.has(String(id)),
769 });
770 }
771 }
772
773 const targetInstanceMissing =
774 targetInstanceId !== undefined &&
775 selectedInstanceId === targetInstanceId &&
776 !rows.some((row) => row.instanceId === targetInstanceId);
777 const selectedRow =
778 rows.find((row) => row.instanceId === selectedInstanceId) ??
779 (targetInstanceMissing ? null : (rows[0] ?? null));
780
781 const persistInstance = async (
782 instanceId: ProviderInstanceId,
783 next: ProviderInstanceConfig,
784 textGenerationModelSelection?: Parameters<
785 typeof buildProviderInstanceUpdatePatch
786 >[0]["textGenerationModelSelection"],
787 ) => {
788 const { providerInstances: _providerInstances, ...patch } = buildProviderInstanceUpdatePatch({
789 settings,
790 instanceId,
791 instance: next,
792 textGenerationModelSelection,
793 });
794 const result = await persistProviderInstance(
795 { operation: "upsert", instanceId, instance: next },
796 patch,
797 );
798 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
799 const error = squashAtomCommandFailure(result);
800 toastManager.add({
801 type: "error",
802 title: "Could not update provider instance",
803 description: error instanceof Error ? error.message : "The settings update failed.",
804 });
805 }
806 };
807
808 const updateInstance = useStableCallback(
809 (
810 instanceId: ProviderInstanceId,
811 previous: ProviderInstanceConfig,
812 next: ProviderInstanceConfig,
813 ) => {
814 const isDisabling = next.enabled === false && resolveProviderInstanceEnabled(previous);
815 const shouldClearTextGen =
816 isDisabling &&
817 resolveAppModelSelectionState(settings, serverProviders).instanceId === instanceId &&
818 readEnvironmentScope(environmentId, AuthSettingsWriteScope);
819 void persistInstance(
820 instanceId,
821 next,
822 shouldClearTextGen ? DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection : undefined,
823 );
824 },
825 );
826
827 const enableInstance = useStableCallback(
828 (instanceId: ProviderInstanceId, next: ProviderInstanceConfig) =>
829 persistInstance(instanceId, next),
830 );
831
832 const deleteInstance = useStableCallback(
833 async (instanceId: ProviderInstanceId, instance: ProviderInstanceConfig) => {
834 const updateResult = await persistProviderInstance({
835 operation: "remove",
836 instanceId,
837 });
838 if (updateResult._tag === "Failure") {
839 const error = squashAtomCommandFailure(updateResult);
840 toastManager.add({
841 type: "error",
842 title: "Could not delete provider instance",
843 description: error instanceof Error ? error.message : "The settings update failed.",
844 });
845 return;
846 }
847
848 if (instance.driver !== ProviderDriverKind.make("acpRegistry")) return;
849 if (providerConfigString(instance.config, "source") === "local") return;
850 const agentId = providerConfigString(instance.config, "agentId");
851 if (agentId === null) return;
852
853 // Concurrent removals race client snapshots; let the server decide whether the agent remains in use.
854 const uninstallResult = await uninstallAcpRegistryManagedBinary({
855 environmentId,
856 input: { agentId },
857 });
858 if (uninstallResult._tag === "Failure" && !isAtomCommandInterrupted(uninstallResult)) {
859 const error = squashAtomCommandFailure(uninstallResult);
860 toastManager.add({
861 type: "warning",
862 title: "Provider deleted, but managed files remain",
863 description: error instanceof Error ? error.message : "Managed binary cleanup failed.",
864 });
865 }
866 },
867 );
868
869 const resetDefaultInstance = useStableCallback(async (driverKind: ProviderDriverKind) => {
870 const result = await persistProviderInstance({
871 operation: "remove",
872 instanceId: defaultInstanceIdForDriver(driverKind),
873 });
874 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
875 const error = squashAtomCommandFailure(result);
876 toastManager.add({
877 type: "error",
878 title: "Could not reset provider instance",
879 description: error instanceof Error ? error.message : "The settings update failed.",
880 });
881 }
882 });
883
884 const writeProjectOverride = useStableCallback(
885 (instanceId: ProviderInstanceId, next: boolean | undefined) => {
886 updateSettings({
887 projectSettingsOverrides: buildProviderInstanceOverridePatch(
888 settings,
889 projectIds,
890 instanceId,
891 next,
892 ),
893 });
894 },
895 );
896
897 const stableUpdateModelPreferences = useStableCallback(updateModelPreferences);
898 const stableToggleModelFavorite = useStableCallback(toggleModelFavorite);
899 const actions: ProviderInstanceRowActions = {
900 acceptUrlAuthentication,
901 runProviderUpdate,
902 updateInstance,
903 enableInstance,
904 deleteInstance,
905 resetDefaultInstance,
906 writeProjectOverride,
907 updateModelPreferences: stableUpdateModelPreferences,
908 toggleModelFavorite: stableToggleModelFavorite,
909 selectInstance: setSelectedInstanceId,
910 };
911 // resolveModelPreferences falls back to a fresh `[]`; keep it stable for the rows.
912 const favorites = settings.favorites.length > 0 ? settings.favorites : NO_FAVORITES;
913
914 const representativeProjectId = projectIds[0];
915 const renderProviderInstance = (row: InstanceRow, mode: "list" | "editor") => {
916 const showProjectOverride =
917 representativeProjectId !== undefined && supportsProjectProviderOverrides;
918 return (
919 <ProviderInstanceRow
920 key={row.instanceId}
921 environmentId={environmentId}
922 environmentLabel={environmentLabel}
923 instanceId={row.instanceId}
924 driver={row.driver}
925 explicitInstance={row.explicitInstance}
926 isDefault={row.isDefault}
927 isDirty={row.isDirty === true}
928 mode={mode}
929 selected={mode === "list" && selectedRow?.instanceId === row.instanceId}
930 readOnly={readOnly}
931 canWriteSettings={canWriteSettings}
932 liveProvider={serverProviders.find((candidate) => candidate.instanceId === row.instanceId)}
933 isUpdateDispatching={updatingProviderInstanceIds.has(row.instanceId)}
934 showProjectOverride={showProjectOverride}
935 projectOverrideValue={
936 showProjectOverride
937 ? settings.projectSettingsOverrides[representativeProjectId]?.providerInstances?.[
938 row.instanceId
939 ]?.enabled
940 : undefined
941 }
942 projectOverrideEffectiveEnabled={
943 showProjectOverride
944 ? resolveProjectProviderInstanceEnabled(
945 settings,
946 representativeProjectId,
947 row.instanceId,
948 )
949 : false
950 }
951 modelPreferences={settings.providerModelPreferences?.[row.instanceId]}
952 favorites={favorites}
953 actions={actions}
954 />
955 );
956 };
957
958 return (
959 <>
960 <SettingsSection
961 {...searchableSetting("providers")}
962 variant="plain"
963 titleAction={
964 !readOnly ? (
965 <Tooltip>
966 <TooltipTrigger
967 render={
968 <Button
969 size="icon-xs"
970 variant="ghost-muted"
971 onClick={() => setIsAddInstanceDialogOpen(true)}
972 aria-label="Add provider"
973 >
974 <PlusIcon />
975 </Button>
976 }
977 />
978 <TooltipPopup side="top">Add provider</TooltipPopup>
979 </Tooltip>
980 ) : null
981 }
982 headerAction={
983 // The ghost button's padding would inset its label, so pull the text to the card edge.
984 <div className="-me-2 flex min-w-0 items-center gap-2">
985 <ProviderUpdatesAction />
986 <Tooltip>
987 <TooltipTrigger
988 render={
989 <Button
990 size="xs"
991 variant="ghost-muted"
992 disabled={isRefreshingProviders || !canRefreshProviders}
993 aria-busy={isRefreshingProviders}
994 onClick={() => void refreshProviders()}
995 >
996 <RefreshIcon refreshing={isRefreshingProviders} />
997 <span className="sr-only">Refresh provider status</span>
998 <span className="hidden min-w-0 truncate sm:inline">
999 {isRefreshingProviders ? (
1000 "Refreshing providers"
1001 ) : (
1002 <ProviderLastChecked environmentId={environmentId} />
1003 )}
1004 </span>
1005 </Button>
1006 }
1007 />
1008 <TooltipPopup side="top">Refresh provider status</TooltipPopup>
1009 </Tooltip>
1010 </div>
1011 }
1012 >
1013 {deviceTabs ? (
1014 <div className="flex min-h-11 min-w-0 items-center gap-2 px-3 sm:px-4">{deviceTabs}</div>
1015 ) : null}
1016 {readOnly ? (
1017 <SettingsGroup divided={false} className="overflow-hidden">
1018 <SettingsRow
1019 title="Limited permissions"
1020 description={`This session can view ${environmentLabel}'s providers but can't change their settings.`}
1021 />
1022 </SettingsGroup>
1023 ) : null}
1024 <SettingsGroup
1025 divided={false}
1026 className={cn(
1027 providerCardHeightClassName,
1028 "overflow-hidden @min-[48rem]/providers:grid @min-[48rem]/providers:grid-cols-[17rem_minmax(0,1fr)]",
1029 )}
1030 >
1031 <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">
1032 <ScrollArea
1033 scrollFade
1034 chainVerticalScroll
1035 className="@min-[48rem]/providers:min-h-0 @min-[48rem]/providers:flex-1"
1036 >
1037 <div className="divide-y divide-border/50">
1038 {rows.map((row) => renderProviderInstance(row, "list"))}
1039 {!readOnly ? (
1040 <button
1041 type="button"
1042 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"
1043 onClick={() => setIsAddInstanceDialogOpen(true)}
1044 >
1045 <PlusIcon className="size-4 shrink-0" />
1046 Add provider
1047 </button>
1048 ) : null}
1049 </div>
1050 </ScrollArea>
1051 </div>
1052
1053 <div data-provider-detail className="min-w-0 @min-[48rem]/providers:min-h-0">
1054 {selectedRow ? (
1055 <ScrollArea scrollFade chainVerticalScroll className="@min-[48rem]/providers:h-full">
1056 {/* Flat sections run dividers edge to edge and inset text like the list beside them. */}
1057 <div className="space-y-6 py-4">
1058 {renderProviderInstance(selectedRow, "editor")}
1059 </div>
1060 </ScrollArea>
1061 ) : (
1062 <div className="p-6 text-sm text-muted-foreground">
1063 {targetInstanceMissing
1064 ? "This provider instance is no longer available on this device."
1065 : "No providers configured."}
1066 </div>
1067 )}
1068 </div>
1069 </SettingsGroup>
1070 </SettingsSection>
1071
1072 <UsageProviderSettings
1073 key={environmentId}
1074 environmentId={environmentId}
1075 environmentLabel={environmentLabel}
1076 sources={settings.usageLimitSources}
1077 cursorKeychainUsageEnabled={settings.cursorKeychainUsageEnabled}
1078 readOnly={readOnly}
1079 />
1080
1081 <SettingsSection title="Advanced">
1082 <SettingsRow
1083 id={searchableSetting("provider-health-check-interval").id}
1084 title={
1085 <span className="inline-flex items-center gap-1.5">
1086 {searchableSetting("provider-health-check-interval").title}
1087 <PolicyTooltip>
1088 This interval is configured here, then the shared Background activity policy decides
1089 whether provider probes may run when the timer fires. Custom intervals appear as
1090 Advanced in Maintenance settings.
1091 </PolicyTooltip>
1092 </span>
1093 }
1094 description="Refresh provider status, versions, and models in the background. Set to 0 to disable."
1095 resetAction={
1096 providerHealthRefreshIntervalSeconds !== defaultProviderHealthRefreshIntervalSeconds ? (
1097 <span
1098 inert={!canWriteSettings}
1099 className={!canWriteSettings ? "opacity-50" : undefined}
1100 >
1101 <SettingResetButton
1102 label="provider health check interval"
1103 onClick={() =>
1104 updateSettings(
1105 backgroundActivityOverrideSettings(
1106 settings.backgroundActivity,
1107 resolvedBackgroundActivity,
1108 { providerHealthRefreshInterval: undefined },
1109 ),
1110 )
1111 }
1112 />
1113 </span>
1114 ) : null
1115 }
1116 control={
1117 <div
1118 inert={!canWriteSettings}
1119 aria-disabled={!canWriteSettings || undefined}
1120 className={cn(
1121 "flex shrink-0 items-center gap-2",
1122 !canWriteSettings && "opacity-50 select-none",
1123 )}
1124 >
1125 <NumberField
1126 value={providerHealthRefreshIntervalSeconds}
1127 min={0}
1128 step={PROVIDER_HEALTH_INTERVAL_STEP_SECONDS}
1129 size="sm"
1130 className="w-32"
1131 onValueChange={(value) =>
1132 updateSettings(
1133 backgroundActivityOverrideSettings(
1134 settings.backgroundActivity,
1135 resolvedBackgroundActivity,
1136 {
1137 providerHealthRefreshInterval: Duration.seconds(
1138 normalizeIntervalSeconds(value),
1139 ),
1140 },
1141 ),
1142 )
1143 }
1144 >
1145 <NumberFieldGroup>
1146 <NumberFieldDecrement aria-label="Decrease provider health check interval" />
1147 <NumberFieldInput aria-label="Provider health check interval in seconds" />
1148 <NumberFieldIncrement aria-label="Increase provider health check interval" />
1149 </NumberFieldGroup>
1150 </NumberField>
1151 <span className="text-xs text-muted-foreground">seconds</span>
1152 </div>
1153 }
1154 />
1155 <CompactIdleThreadsRow />
1156 </SettingsSection>
1157
1158 {isAddInstanceDialogOpen && !readOnly ? (
1159 <AddProviderInstanceDialog
1160 open
1161 environmentId={environmentId}
1162 environmentLabel={environmentLabel}
1163 onOpenChange={setIsAddInstanceDialogOpen}
1164 onCreated={setSelectedInstanceId}
1165 />
1166 ) : null}
1167 </>
1168 );
1169}
1170
1171interface ProviderInstanceRowActions {
1172 readonly acceptUrlAuthentication: (
1173 instanceId: ProviderInstanceId,
1174 action: AcpRegistryUrlAuthAction,
1175 ) => void;
1176 readonly runProviderUpdate: (
1177 candidate: Pick<ProviderSettingsUpdateCandidate, "driver" | "instanceId">,
1178 targetVersion?: string,
1179 ) => Promise<void>;
1180 readonly updateInstance: (
1181 instanceId: ProviderInstanceId,
1182 previous: ProviderInstanceConfig,
1183 next: ProviderInstanceConfig,
1184 ) => void;
1185 readonly enableInstance: (
1186 instanceId: ProviderInstanceId,
1187 next: ProviderInstanceConfig,
1188 ) => Promise<void>;
1189 readonly deleteInstance: (
1190 instanceId: ProviderInstanceId,
1191 instance: ProviderInstanceConfig,
1192 ) => Promise<void>;
1193 readonly resetDefaultInstance: (driverKind: ProviderDriverKind) => Promise<void>;
1194 readonly writeProjectOverride: (
1195 instanceId: ProviderInstanceId,
1196 next: boolean | undefined,
1197 ) => void;
1198 readonly updateModelPreferences: ReturnType<typeof useUpdateEnvironmentModelPreferences>;
1199 readonly toggleModelFavorite: ReturnType<typeof useToggleEnvironmentModelFavorite>;
1200 readonly selectInstance: (instanceId: ProviderInstanceId) => void;
1201}
1202
1203const NO_MODELS: ReadonlyArray<string> = [];
1204
1205/** Stable props let this boundary return cached cards even when settings rebuild parent row elements. */
1206function ProviderInstanceRow({
1207 environmentId,
1208 environmentLabel,
1209 instanceId,
1210 driver,
1211 explicitInstance,
1212 isDefault,
1213 isDirty,
1214 mode,
1215 selected,
1216 readOnly,
1217 canWriteSettings,
1218 liveProvider,
1219 isUpdateDispatching,
1220 showProjectOverride,
1221 projectOverrideValue,
1222 projectOverrideEffectiveEnabled,
1223 modelPreferences,
1224 favorites,
1225 actions,
1226}: {
1227 readonly environmentId: EnvironmentId;
1228 readonly environmentLabel: string;
1229 readonly instanceId: ProviderInstanceId;
1230 readonly driver: ProviderDriverKind;
1231 readonly explicitInstance: ProviderInstanceConfig | undefined;
1232 readonly isDefault: boolean;
1233 readonly isDirty: boolean;
1234 readonly mode: "list" | "editor";
1235 readonly selected: boolean;
1236 readonly readOnly: boolean;
1237 readonly canWriteSettings: boolean;
1238 readonly liveProvider: ServerProvider | undefined;
1239 readonly isUpdateDispatching: boolean;
1240 readonly showProjectOverride: boolean;
1241 readonly projectOverrideValue: boolean | undefined;
1242 readonly projectOverrideEffectiveEnabled: boolean;
1243 readonly modelPreferences:
1244 | { readonly hiddenModels: ReadonlyArray<string>; readonly modelOrder: ReadonlyArray<string> }
1245 | undefined;
1246 readonly favorites: UnifiedSettings["favorites"];
1247 readonly actions: ProviderInstanceRowActions;
1248}) {
1249 const allProjects = useProjects();
1250 const acpProjects =
1251 mode === "editor" && liveProvider?.driver === "acpRegistry"
1252 ? allProjects.filter((project) => project.environmentId === environmentId)
1253 : undefined;
1254 const instance = explicitInstance ?? { driver };
1255 const driverOption = providerClients.get(driver);
1256 const updateCandidate =
1257 liveProvider !== undefined && isProviderSettingsUpdateCandidate(liveProvider)
1258 ? liveProvider
1259 : undefined;
1260 const isInstanceUpdateRunning =
1261 isUpdateDispatching || (liveProvider !== undefined && isProviderUpdateActive(liveProvider));
1262 const hiddenModels = modelPreferences?.hiddenModels ?? NO_MODELS;
1263 const modelOrder = modelPreferences?.modelOrder ?? NO_MODELS;
1264 const favoriteModels = Arr.filterMap(favorites, (favorite) =>
1265 favorite.provider === instanceId ? Result.succeed(favorite.model) : Result.failVoid,
1266 );
1267 const resetLabel = driverOption?.label ?? String(driver);
1268 const projectOverride = showProjectOverride
1269 ? {
1270 value: projectOverrideValue,
1271 effectiveEnabled: projectOverrideEffectiveEnabled,
1272 onChange: (next: boolean) => actions.writeProjectOverride(instanceId, next),
1273 onReset: () => actions.writeProjectOverride(instanceId, undefined),
1274 }
1275 : undefined;
1276 const codexSetupMode = driver === "codex" ? readCodexSetupMode(instance.config) : null;
1277 const recommendedVersion = liveProvider?.compatibilityAdvisory?.recommendedVersion;
1278 const canInstallRecommended =
1279 !readOnly &&
1280 liveProvider !== undefined &&
1281 Boolean(liveProvider.compatibilityAdvisory?.message) &&
1282 Boolean(recommendedVersion) &&
1283 liveProvider.versionAdvisory?.canInstallVersion === true;
1284
1285 return (
1286 <ProviderInstanceCard
1287 environmentId={environmentId}
1288 acpProjects={acpProjects}
1289 projectOverride={projectOverride}
1290 onAcceptUrlAuth={
1291 readOnly ? undefined : (action) => actions.acceptUrlAuthentication(instanceId, action)
1292 }
1293 instanceId={instanceId}
1294 instance={instance}
1295 driverOption={driverOption}
1296 liveProvider={liveProvider}
1297 mode={mode}
1298 selected={selected}
1299 onSelect={mode === "list" ? () => actions.selectInstance(instanceId) : undefined}
1300 readOnly={readOnly}
1301 runtime={
1302 mode === "editor" && codexSetupMode === "managed" ? (
1303 <CodexManagedRuntimeFields
1304 environmentId={environmentId}
1305 instanceId={instanceId}
1306 provider={liveProvider}
1307 />
1308 ) : undefined
1309 }
1310 canWriteSettings={canWriteSettings}
1311 setup={
1312 mode === "editor" && driver === "antigravity" ? (
1313 <ProviderSetupSection
1314 environmentId={environmentId}
1315 environmentLabel={environmentLabel}
1316 instanceId={instanceId}
1317 provider={liveProvider}
1318 binaryPath={configuredBinaryPath(instance.config)}
1319 authMethod={readAntigravityAuthMethod(instance.config)}
1320 enabled={resolveProviderInstanceEnabled(instance)}
1321 readOnly={readOnly}
1322 onEnable={() => actions.enableInstance(instanceId, { ...instance, enabled: true })}
1323 />
1324 ) : mode === "editor" && codexSetupMode === "managed" ? (
1325 <CodexSetupSection
1326 environmentId={environmentId}
1327 instanceId={instanceId}
1328 provider={liveProvider}
1329 mode={codexSetupMode}
1330 enabled={resolveProviderInstanceEnabled(instance)}
1331 readOnly={readOnly}
1332 onModeChange={(setupMode) =>
1333 actions.enableInstance(instanceId, {
1334 ...instance,
1335 enabled: true,
1336 config: {
1337 ...(instance.config !== null && typeof instance.config === "object"
1338 ? instance.config
1339 : {}),
1340 enabled: true,
1341 setupMode,
1342 },
1343 })
1344 }
1345 />
1346 ) : mode === "editor" &&
1347 !readOnly &&
1348 liveProvider &&
1349 (liveProvider.setup?.canAuthenticate ||
1350 (liveProvider.driver === "acpRegistry" && liveProvider.installed)) ? (
1351 <ProviderAuthenticationSection
1352 key={`${environmentId}:${instanceId}`}
1353 environmentId={environmentId}
1354 environmentLabel={environmentLabel}
1355 instanceId={instanceId}
1356 provider={liveProvider}
1357 readOnly={readOnly}
1358 />
1359 ) : mode === "editor" &&
1360 !readOnly &&
1361 driver === "cursor" &&
1362 liveProvider?.setup?.canAuthenticate === false ? (
1363 <SettingsRow
1364 title="Cursor account"
1365 description="Using CURSOR_API_KEY. Remove it from this provider's environment to use browser sign-in."
1366 />
1367 ) : null
1368 }
1369 onUpdate={(next) => actions.updateInstance(instanceId, instance, next)}
1370 onDelete={
1371 mode === "editor" && !isDefault
1372 ? () => actions.deleteInstance(instanceId, instance)
1373 : undefined
1374 }
1375 headerAction={
1376 mode === "editor" && isDefault && isDirty ? (
1377 <SettingResetButton
1378 label={`${resetLabel} provider settings`}
1379 onClick={() => actions.resetDefaultInstance(driver)}
1380 />
1381 ) : null
1382 }
1383 hiddenModels={hiddenModels}
1384 favoriteModels={favoriteModels}
1385 modelOrder={modelOrder}
1386 onHiddenModelsChange={(next, affectedModels) => {
1387 const hidden = new Set(next);
1388 void actions.updateModelPreferences({
1389 setModelsHidden: affectedModels.map((model) => ({
1390 provider: instanceId,
1391 model,
1392 hidden: hidden.has(model),
1393 })),
1394 });
1395 }}
1396 onToggleFavorite={(model) => {
1397 void actions.toggleModelFavorite(instanceId, model);
1398 }}
1399 onFavoriteModelsChange={(next) => {
1400 void actions.updateModelPreferences({
1401 setModelFavorites: modelListChanges(favoriteModels, next).map(({ model, selected }) => ({
1402 provider: instanceId,
1403 model,
1404 favorite: selected,
1405 })),
1406 });
1407 }}
1408 onModelOrderChange={(nextOrder) => {
1409 void actions.updateModelPreferences({
1410 setProviderModelOrder: { provider: instanceId, modelOrder: nextOrder },
1411 });
1412 }}
1413 onInstallRecommended={
1414 canInstallRecommended
1415 ? () => {
1416 void actions.runProviderUpdate(liveProvider, recommendedVersion ?? undefined);
1417 }
1418 : undefined
1419 }
1420 onRunUpdate={
1421 !readOnly && updateCandidate
1422 ? () => {
1423 if (!isInstanceUpdateRunning) void actions.runProviderUpdate(updateCandidate);
1424 }
1425 : undefined
1426 }
1427 isUpdating={isInstanceUpdateRunning}
1428 />
1429 );
1430}