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

ProviderSettingsPanel.tsx

1,448 lines52.8 KB

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