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

ProviderSettingsPanel.tsx

1,449 lines52.9 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 return result._tag !== "Failure";
812 };
813​
814 const updateInstance = useStableCallback(
815 (
816 instanceId: ProviderInstanceId,
817 previous: ProviderInstanceConfig,
818 next: ProviderInstanceConfig,
819 ) => {
820 const isDisabling = next.enabled === false && resolveProviderInstanceEnabled(previous);
821 const shouldClearTextGen =
822 isDisabling &&
823 resolveAppModelSelectionState(settings, serverProviders).instanceId === instanceId &&
824 readEnvironmentScope(environmentId, AuthSettingsWriteScope);
825 return persistInstance(
826 instanceId,
827 next,
828 shouldClearTextGen ? DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection : undefined,
829 );
830 },
831 );
832​
833 const enableInstance = useStableCallback(
834 (instanceId: ProviderInstanceId, next: ProviderInstanceConfig) =>
835 persistInstance(instanceId, next),
836 );
837​
838 const deleteInstance = useStableCallback(
839 async (instanceId: ProviderInstanceId, instance: ProviderInstanceConfig) => {
840 const confirmed = await confirmProviderInstanceRemoval(
841 `Remove the ${providerInstanceName(instance)} provider instance?`,
842 );
843 if (!confirmed) return;
844 const updateResult = await persistProviderInstance({
845 operation: "remove",
846 instanceId,
847 });
848 if (updateResult._tag === "Failure") {
849 const error = squashAtomCommandFailure(updateResult);
850 toastManager.add({
851 type: "error",
852 title: "Could not delete provider instance",
853 description: error instanceof Error ? error.message : "The settings update failed.",
854 });
855 return;
856 }
857​
858 if (instance.driver !== ProviderDriverKind.make("acpRegistry")) return;
859 if (providerConfigString(instance.config, "source") === "local") return;
860 const agentId = providerConfigString(instance.config, "agentId");
861 if (agentId === null) return;
862​
863 // Concurrent removals race client snapshots; let the server decide whether the agent remains in use.
864 const uninstallResult = await uninstallAcpRegistryManagedBinary({
865 environmentId,
866 input: { agentId },
867 });
868 if (uninstallResult._tag === "Failure" && !isAtomCommandInterrupted(uninstallResult)) {
869 const error = squashAtomCommandFailure(uninstallResult);
870 toastManager.add({
871 type: "warning",
872 title: "Provider deleted, but managed files remain",
873 description: error instanceof Error ? error.message : "Managed binary cleanup failed.",
874 });
875 }
876 },
877 );
878​
879 const resetDefaultInstance = useStableCallback(async (driverKind: ProviderDriverKind) => {
880 const instanceId = defaultInstanceIdForDriver(driverKind);
881 const instance = settings.providerInstances?.[instanceId] ?? { driver: driverKind };
882 const turnsOff =
883 resolveProviderInstanceEnabled(instance) &&
884 !resolveProviderInstanceEnabled({ driver: driverKind });
885 const confirmed = await confirmProviderInstanceRemoval(
886 `Reset the ${providerInstanceName(instance)} provider to its defaults?`,
887 turnsOff ? " It will also be turned off." : "",
888 );
889 if (!confirmed) return;
890 const result = await persistProviderInstance({ operation: "remove", instanceId });
891 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
892 const error = squashAtomCommandFailure(result);
893 toastManager.add({
894 type: "error",
895 title: "Could not reset provider instance",
896 description: error instanceof Error ? error.message : "The settings update failed.",
897 });
898 }
899 });
900​
901 const writeProjectOverride = useStableCallback(
902 (instanceId: ProviderInstanceId, next: boolean | undefined) => {
903 updateSettings({
904 projectSettingsOverrides: buildProviderInstanceOverridePatch(
905 settings,
906 projectIds,
907 instanceId,
908 next,
909 ),
910 });
911 },
912 );
913​
914 const stableUpdateModelPreferences = useStableCallback(updateModelPreferences);
915 const stableToggleModelFavorite = useStableCallback(toggleModelFavorite);
916 const actions: ProviderInstanceRowActions = {
917 acceptUrlAuthentication,
918 runProviderUpdate,
919 updateInstance,
920 enableInstance,
921 deleteInstance,
922 resetDefaultInstance,
923 writeProjectOverride,
924 updateModelPreferences: stableUpdateModelPreferences,
925 toggleModelFavorite: stableToggleModelFavorite,
926 selectInstance: setSelectedInstanceId,
927 };
928 // resolveModelPreferences falls back to a fresh `[]`; keep it stable for the rows.
929 const favorites = settings.favorites.length > 0 ? settings.favorites : NO_FAVORITES;
930​
931 const representativeProjectId = projectIds[0];
932 const renderProviderInstance = (row: InstanceRow, mode: "list" | "editor") => {
933 const showProjectOverride =
934 representativeProjectId !== undefined && supportsProjectProviderOverrides;
935 return (
936 <ProviderInstanceRow
937 key={row.instanceId}
938 environmentId={environmentId}
939 environmentLabel={environmentLabel}
940 instanceId={row.instanceId}
941 driver={row.driver}
942 explicitInstance={row.explicitInstance}
943 isDefault={row.isDefault}
944 isDirty={row.isDirty === true}
945 mode={mode}
946 selected={mode === "list" && selectedRow?.instanceId === row.instanceId}
947 readOnly={readOnly}
948 canWriteSettings={canWriteSettings}
949 liveProvider={serverProviders.find((candidate) => candidate.instanceId === row.instanceId)}
950 isUpdateDispatching={updatingProviderInstanceIds.has(row.instanceId)}
951 showProjectOverride={showProjectOverride}
952 projectOverrideValue={
953 showProjectOverride
954 ? settings.projectSettingsOverrides[representativeProjectId]?.providerInstances?.[
955 row.instanceId
956 ]?.enabled
957 : undefined
958 }
959 projectOverrideEffectiveEnabled={
960 showProjectOverride
961 ? resolveProjectProviderInstanceEnabled(
962 settings,
963 representativeProjectId,
964 row.instanceId,
965 )
966 : false
967 }
968 modelPreferences={settings.providerModelPreferences?.[row.instanceId]}
969 favorites={favorites}
970 actions={actions}
971 />
972 );
973 };
974​
975 return (
976 <>
977 <SettingsSection
978 {...searchableSetting("providers")}
979 variant="plain"
980 titleAction={
981 canAddProvider ? (
982 <Tooltip>
983 <TooltipTrigger
984 render={
985 <Button
986 size="icon-xs"
987 variant="ghost-muted"
988 onClick={() => setIsAddInstanceDialogOpen(true)}
989 aria-label="Add provider"
990 >
991 <PlusIcon />
992 </Button>
993 }
994 />
995 <TooltipPopup side="top">Add provider</TooltipPopup>
996 </Tooltip>
997 ) : null
998 }
999 headerAction={
1000 // The ghost button's padding would inset its label, so pull the text to the card edge.
1001 <div className="-me-2 flex min-w-0 items-center gap-2">
1002 <ProviderUpdatesAction />
1003 <Tooltip>
1004 <TooltipTrigger
1005 render={
1006 <Button
1007 size="xs"
1008 variant="ghost-muted"
1009 disabled={isRefreshingProviders || !canRefreshProviders}
1010 aria-busy={isRefreshingProviders}
1011 onClick={() => void refreshProviders()}
1013 <RefreshIcon refreshing={isRefreshingProviders} />
1014 <span className="sr-only">Refresh provider status</span>
1015 <span className="hidden min-w-0 truncate sm:inline">
1016 {isRefreshingProviders ? (
1017 "Refreshing providers"
1018 ) : (
1019 <ProviderLastChecked environmentId={environmentId} />
1020 )}
1021 </span>
1022 </Button>
1024 />
1025 <TooltipPopup side="top">Refresh provider status</TooltipPopup>
1026 </Tooltip>
1027 </div>
1030 {deviceTabs ? (
1031 <div className="flex min-h-11 min-w-0 items-center gap-2 px-3 sm:px-4">{deviceTabs}</div>
1032 ) : null}
1033 {readOnly ? (
1034 <SettingsGroup divided={false} className="overflow-hidden">
1035 <SettingsRow
1036 title="Limited permissions"
1037 description={`This session can view ${environmentLabel}'s providers but can't change their settings.`}
1038 />
1039 </SettingsGroup>
1040 ) : null}
1041 <SettingsGroup
1042 divided={false}
1043 className={cn(
1044 providerCardHeightClassName,
1045 "overflow-hidden @min-[48rem]/providers:grid @min-[48rem]/providers:grid-cols-[17rem_minmax(0,1fr)]",
1046 )}
1048 <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">
1049 <ScrollArea
1050 scrollFade
1051 chainVerticalScroll
1052 className="@min-[48rem]/providers:min-h-0 @min-[48rem]/providers:flex-1"
1054 <div className="divide-y divide-border/50">
1055 {rows.map((row) => renderProviderInstance(row, "list"))}
1056 {canAddProvider ? (
1057 <button
1058 type="button"
1059 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"
1060 onClick={() => setIsAddInstanceDialogOpen(true)}
1062 <PlusIcon className="size-4 shrink-0" />
1063 Add provider
1064 </button>
1065 ) : null}
1066 </div>
1067 </ScrollArea>
1068 </div>
1069​
1070 <div data-provider-detail className="min-w-0 @min-[48rem]/providers:min-h-0">
1071 {selectedRow ? (
1072 <ScrollArea scrollFade chainVerticalScroll className="@min-[48rem]/providers:h-full">
1073 {/* Flat sections run dividers edge to edge and inset text like the list beside them. */}
1074 <div className="space-y-6 py-4">
1075 {renderProviderInstance(selectedRow, "editor")}
1076 </div>
1077 </ScrollArea>
1078 ) : (
1079 <div className="p-6 text-sm text-muted-foreground">
1080 {targetInstanceMissing
1081 ? "This provider instance is no longer available on this device."
1082 : "No providers configured."}
1083 </div>
1084 )}
1085 </div>
1086 </SettingsGroup>
1087 </SettingsSection>
1088​
1089 <UsageProviderSettings
1090 key={environmentId}
1091 environmentId={environmentId}
1092 environmentLabel={environmentLabel}
1093 sources={settings.usageLimitSources}
1094 readOnly={readOnly}
1095 />
1096​
1097 {/* The server drops text generators under a provider allow-list. */}
1098 {managedPolicy?.limits?.providers?.allowedDrivers === undefined ? (
1099 <TextGeneratorsSettings
1100 key={`text-generators:${environmentId}`}
1101 environmentId={environmentId}
1102 environmentLabel={environmentLabel}
1103 providers={serverProviders}
1104 readOnly={readOnly}
1105 />
1106 ) : null}
1107​
1108 <SettingsSection title="Advanced">
1109 <SettingsRow
1110 id={searchableSetting("provider-health-check-interval").id}
1111 title={
1112 <span className="inline-flex items-center gap-1.5">
1113 {searchableSetting("provider-health-check-interval").title}
1114 <PolicyTooltip>
1115 This interval is configured here, then the shared Background activity policy decides
1116 whether provider probes may run when the timer fires. Custom intervals appear as
1117 Advanced in Maintenance settings.
1118 </PolicyTooltip>
1119 </span>
1121 description="Refresh provider status, versions, and models in the background. Set to 0 to disable."
1122 resetAction={
1123 providerHealthRefreshIntervalSeconds !== defaultProviderHealthRefreshIntervalSeconds ? (
1124 <span
1125 inert={!canWriteSettings}
1126 className={!canWriteSettings ? "opacity-50" : undefined}
1128 <SettingResetButton
1129 label="provider health check interval"
1130 onClick={() =>
1131 updateSettings(
1132 backgroundActivityOverrideSettings(
1133 settings.backgroundActivity,
1134 resolvedBackgroundActivity,
1135 { providerHealthRefreshInterval: undefined },
1136 ),
1139 />
1140 </span>
1141 ) : null
1143 control={
1144 <div
1145 inert={!canWriteSettings}
1146 aria-disabled={!canWriteSettings || undefined}
1147 className={cn(
1148 "flex shrink-0 items-center gap-2",
1149 !canWriteSettings && "opacity-50 select-none",
1150 )}
1152 <IntervalSecondsField
1153 label="provider health check interval"
1154 value={providerHealthRefreshIntervalSeconds}
1155 min={0}
1156 step={PROVIDER_HEALTH_INTERVAL_STEP_SECONDS}
1157 onCommit={(seconds, options) =>
1158 updateSettings(
1159 backgroundActivityOverrideSettings(
1160 settings.backgroundActivity,
1161 resolvedBackgroundActivity,
1162 { providerHealthRefreshInterval: Duration.seconds(seconds) },
1163 ),
1164 options,
1167 />
1168 <span className="text-xs text-muted-foreground">seconds</span>
1169 </div>
1171 />
1172 <CompactIdleThreadsRow />
1173 </SettingsSection>
1174​
1175 {isAddInstanceDialogOpen && !readOnly ? (
1176 <AddProviderInstanceDialog
1177 open
1178 environmentId={environmentId}
1179 environmentLabel={environmentLabel}
1180 onOpenChange={setIsAddInstanceDialogOpen}
1181 onCreated={setSelectedInstanceId}
1182 />
1183 ) : null}
1184 </>
1185 );
1187​
1188interface ProviderInstanceRowActions {
1189 readonly acceptUrlAuthentication: (
1190 instanceId: ProviderInstanceId,
1191 action: AcpRegistryUrlAuthAction,
1192 ) => void;
1193 readonly runProviderUpdate: (
1194 candidate: Pick<ProviderSettingsUpdateCandidate, "driver" | "instanceId">,
1195 targetVersion?: string,
1196 ) => Promise<void>;
1197 readonly updateInstance: (
1198 instanceId: ProviderInstanceId,
1199 previous: ProviderInstanceConfig,
1200 next: ProviderInstanceConfig,
1201 ) => Promise<boolean>;
1202 readonly enableInstance: (
1203 instanceId: ProviderInstanceId,
1204 next: ProviderInstanceConfig,
1205 ) => Promise<boolean>;
1206 readonly deleteInstance: (
1207 instanceId: ProviderInstanceId,
1208 instance: ProviderInstanceConfig,
1209 ) => Promise<void>;
1210 readonly resetDefaultInstance: (driverKind: ProviderDriverKind) => Promise<void>;
1211 readonly writeProjectOverride: (
1212 instanceId: ProviderInstanceId,
1213 next: boolean | undefined,
1214 ) => void;
1215 readonly updateModelPreferences: ReturnType<typeof useUpdateEnvironmentModelPreferences>;
1216 readonly toggleModelFavorite: ReturnType<typeof useToggleEnvironmentModelFavorite>;
1217 readonly selectInstance: (instanceId: ProviderInstanceId) => void;
1219​
1220const NO_MODELS: ReadonlyArray<string> = [];
1221​
1222/** Stable props let this boundary return cached cards even when settings rebuild parent row elements. */
1223function ProviderInstanceRow({
1224 environmentId,
1225 environmentLabel,
1226 instanceId,
1227 driver,
1228 explicitInstance,
1229 isDefault,
1230 isDirty,
1231 mode,
1232 selected,
1233 readOnly,
1234 canWriteSettings,
1235 liveProvider,
1236 isUpdateDispatching,
1237 showProjectOverride,
1238 projectOverrideValue,
1239 projectOverrideEffectiveEnabled,
1240 modelPreferences,
1241 favorites,
1242 actions,
1243}: {
1244 readonly environmentId: EnvironmentId;
1245 readonly environmentLabel: string;
1246 readonly instanceId: ProviderInstanceId;
1247 readonly driver: ProviderDriverKind;
1248 readonly explicitInstance: ProviderInstanceConfig | undefined;
1249 readonly isDefault: boolean;
1250 readonly isDirty: boolean;
1251 readonly mode: "list" | "editor";
1252 readonly selected: boolean;
1253 readonly readOnly: boolean;
1254 readonly canWriteSettings: boolean;
1255 readonly liveProvider: ServerProvider | undefined;
1256 readonly isUpdateDispatching: boolean;
1257 readonly showProjectOverride: boolean;
1258 readonly projectOverrideValue: boolean | undefined;
1259 readonly projectOverrideEffectiveEnabled: boolean;
1260 readonly modelPreferences:
1261 | { readonly hiddenModels: ReadonlyArray<string>; readonly modelOrder: ReadonlyArray<string> }
1262 | undefined;
1263 readonly favorites: UnifiedSettings["favorites"];
1264 readonly actions: ProviderInstanceRowActions;
1265}) {
1266 const allProjects = useProjects();
1267 const secretSources = useSecretSources(environmentId);
1268 const acpProjects =
1269 mode === "editor" && liveProvider?.driver === "acpRegistry"
1270 ? allProjects.filter((project) => project.environmentId === environmentId)
1271 : undefined;
1272 const instance = explicitInstance ?? { driver };
1273 const driverOption = providerClients.get(driver);
1274 const updateCandidate =
1275 liveProvider !== undefined && isProviderSettingsUpdateCandidate(liveProvider)
1276 ? liveProvider
1277 : undefined;
1278 const isInstanceUpdateRunning =
1279 isUpdateDispatching || (liveProvider !== undefined && isProviderUpdateActive(liveProvider));
1280 const hiddenModels = modelPreferences?.hiddenModels ?? NO_MODELS;
1281 const modelOrder = modelPreferences?.modelOrder ?? NO_MODELS;
1282 const favoriteModels = Arr.filterMap(favorites, (favorite) =>
1283 favorite.provider === instanceId ? Result.succeed(favorite.model) : Result.failVoid,
1284 );
1285 const resetLabel = driverOption?.label ?? String(driver);
1286 const projectOverride = showProjectOverride
1287 ? {
1288 value: projectOverrideValue,
1289 effectiveEnabled: projectOverrideEffectiveEnabled,
1290 onChange: (next: boolean) => actions.writeProjectOverride(instanceId, next),
1291 onReset: () => actions.writeProjectOverride(instanceId, undefined),
1293 : undefined;
1294 const codexSetupMode = driver === "codex" ? readCodexSetupMode(instance.config) : null;
1295 const recommendedVersion = liveProvider?.compatibilityAdvisory?.recommendedVersion;
1296 const canInstallRecommended =
1297 !readOnly &&
1298 liveProvider !== undefined &&
1299 Boolean(liveProvider.compatibilityAdvisory?.message) &&
1300 Boolean(recommendedVersion) &&
1301 liveProvider.versionAdvisory?.canInstallVersion === true;
1302​
1303 return (
1304 <ProviderInstanceCard
1305 environmentId={environmentId}
1306 secretSources={secretSources}
1307 acpProjects={acpProjects}
1308 projectOverride={projectOverride}
1309 onAcceptUrlAuth={
1310 readOnly ? undefined : (action) => actions.acceptUrlAuthentication(instanceId, action)
1312 instanceId={instanceId}
1313 instance={instance}
1314 driverOption={driverOption}
1315 liveProvider={liveProvider}
1316 mode={mode}
1317 selected={selected}
1318 onSelect={mode === "list" ? () => actions.selectInstance(instanceId) : undefined}
1319 readOnly={readOnly}
1320 runtime={
1321 mode === "editor" && codexSetupMode === "managed" ? (
1322 <CodexManagedRuntimeFields
1323 environmentId={environmentId}
1324 instanceId={instanceId}
1325 provider={liveProvider}
1326 />
1327 ) : undefined
1329 canWriteSettings={canWriteSettings}
1330 setup={
1331 mode === "editor" && driver === "antigravity" ? (
1332 <ProviderSetupSection
1333 environmentId={environmentId}
1334 environmentLabel={environmentLabel}
1335 instanceId={instanceId}
1336 provider={liveProvider}
1337 binaryPath={configuredBinaryPath(instance.config)}
1338 authMethod={readAntigravityAuthMethod(instance.config)}
1339 enabled={resolveProviderInstanceEnabled(instance)}
1340 readOnly={readOnly}
1341 onEnable={() => actions.enableInstance(instanceId, { ...instance, enabled: true })}
1342 />
1343 ) : mode === "editor" && codexSetupMode === "managed" ? (
1344 <CodexSetupSection
1345 environmentId={environmentId}
1346 instanceId={instanceId}
1347 provider={liveProvider}
1348 mode={codexSetupMode}
1349 enabled={resolveProviderInstanceEnabled(instance)}
1350 readOnly={readOnly}
1351 onModeChange={(setupMode) =>
1352 actions.enableInstance(instanceId, {
1353 ...instance,
1354 enabled: true,
1355 config: {
1356 ...(instance.config !== null && typeof instance.config === "object"
1357 ? instance.config
1358 : {}),
1359 enabled: true,
1360 setupMode,
1361 },
1362 })
1364 />
1365 ) : mode === "editor" &&
1366 !readOnly &&
1367 liveProvider &&
1368 (liveProvider.setup?.canAuthenticate ||
1369 (liveProvider.driver === "acpRegistry" && liveProvider.installed)) ? (
1370 <ProviderAuthenticationSection
1371 key={`${environmentId}:${instanceId}`}
1372 environmentId={environmentId}
1373 environmentLabel={environmentLabel}
1374 instanceId={instanceId}
1375 provider={liveProvider}
1376 readOnly={readOnly}
1377 />
1378 ) : mode === "editor" &&
1379 !readOnly &&
1380 driver === "cursor" &&
1381 liveProvider?.setup?.canAuthenticate === false ? (
1382 <SettingsRow
1383 title="Cursor account"
1384 description="Using CURSOR_API_KEY. Remove it from this provider's environment to use browser sign-in."
1385 />
1386 ) : null
1388 onUpdate={(next) => actions.updateInstance(instanceId, instance, next)}
1389 onDelete={
1390 mode === "editor" && !isDefault
1391 ? () => actions.deleteInstance(instanceId, instance)
1392 : undefined
1394 headerAction={
1395 mode === "editor" && isDefault && isDirty ? (
1396 <SettingResetButton
1397 label={`${resetLabel} provider settings`}
1398 onClick={() => actions.resetDefaultInstance(driver)}
1399 />
1400 ) : null
1402 hiddenModels={hiddenModels}
1403 favoriteModels={favoriteModels}
1404 modelOrder={modelOrder}
1405 onHiddenModelsChange={(next, affectedModels) => {
1406 const hidden = new Set(next);
1407 void actions.updateModelPreferences({
1408 setModelsHidden: affectedModels.map((model) => ({
1409 provider: instanceId,
1410 model,
1411 hidden: hidden.has(model),
1412 })),
1413 });
1414 }}
1415 onToggleFavorite={(model) => {
1416 void actions.toggleModelFavorite(instanceId, model);
1417 }}
1418 onFavoriteModelsChange={(next) => {
1419 void actions.updateModelPreferences({
1420 setModelFavorites: modelListChanges(favoriteModels, next).map(({ model, selected }) => ({
1421 provider: instanceId,
1422 model,
1423 favorite: selected,
1424 })),
1425 });
1426 }}
1427 onModelOrderChange={(nextOrder) => {
1428 void actions.updateModelPreferences({
1429 setProviderModelOrder: { provider: instanceId, modelOrder: nextOrder },
1430 });
1431 }}
1432 onInstallRecommended={
1433 canInstallRecommended
1434 ? () => {
1435 void actions.runProviderUpdate(liveProvider, recommendedVersion ?? undefined);
1437 : undefined
1439 onRunUpdate={
1440 !readOnly && updateCandidate
1441 ? () => {
1442 if (!isInstanceUpdateRunning) void actions.runProviderUpdate(updateCandidate);
1444 : undefined
1446 isUpdating={isInstanceUpdateRunning}
1447 />
1448 );