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

ProviderSettingsPanel.tsx

1,462 lines53.0 KB

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