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

ProviderSettingsPanel.tsx

1,284 lines47.6 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 ProviderInstanceConfig,
23 type ProviderInstanceId,
24 resolveEnvironmentMachineKind,
25 resolveProviderInstanceEnabled,
26} from "@t3tools/contracts";
27import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
28import {
29 getBackgroundActivityPresetSettings,
30 resolveServerBackgroundActivitySettings,
31} from "@t3tools/shared/backgroundActivitySettings";
32import * as Arr from "effect/Array";
33import * as Duration from "effect/Duration";
34import * as Equal from "effect/Equal";
35import * as Result from "effect/Result";
36import { PlusIcon } from "lucide-react";
37import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
38​
39import { isDesktopLocalConnectionTarget } from "../../connection/desktopLocal";
40import {
41 useEnvironmentSettings,
42 usePersistEnvironmentProviderInstanceMutation,
43 useUpdateEnvironmentSettings,
44 useUpdateEnvironmentModelPreferences,
45 useToggleEnvironmentModelFavorite,
46} from "../../hooks/useSettings";
47import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
48import { cn } from "../../lib/utils";
49import { resolveAppModelSelectionState } from "../../modelSelection";
50import {
51 useEnvironments,
52 usePrimaryEnvironmentId,
53 type EnvironmentPresentation,
54} from "../../state/environments";
55import { EMPTY_SERVER_PROVIDERS, serverEnvironment } from "../../state/server";
56import { useEnvironmentSessionState } from "../../state/session";
57import { useProjects } from "../../state/entities";
58import { useAtomCommand } from "../../state/use-atom-command";
59import { getRelativeTimeState } from "../../timestampFormat";
60import {
61 ConnectionStatusDot,
62 connectionPhaseDotClassName,
63 connectionPhasePingClassName,
64} from "../ConnectionStatusDot";
65import {
66 isProviderSettingsUpdateCandidate,
67 isProviderUpdateActive,
68 type ProviderSettingsUpdateCandidate,
69} from "../ProviderUpdateLaunchNotification.logic";
70import { ProviderUpdatesAction } from "../ProviderUpdatesAction";
71import { Button } from "../ui/button";
72import {
73 Empty,
74 EmptyContent,
75 EmptyDescription,
76 EmptyHeader,
77 EmptyMedia,
78 EmptyTitle,
79} from "../ui/empty";
80import {
81 NumberField,
82 NumberFieldDecrement,
83 NumberFieldGroup,
84 NumberFieldIncrement,
85 NumberFieldInput,
86} from "../ui/number-field";
87import { ScrollArea } from "../ui/scroll-area";
88import { Toggle, ToggleGroup } from "../ui/toggle-group";
89import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
90import { stackedThreadToast, toastManager } from "../ui/toast";
91import { AddProviderInstanceDialog } from "./AddProviderInstanceDialog";
92import { ExpandableText } from "./ExpandableText";
93import { ProviderInstanceCard } from "./ProviderInstanceCard";
94import { UsageProviderSettings } from "./UsageProviderSettings";
95import { ProviderSetupSection, readAntigravityAuthMethod } from "./ProviderSetupSection";
96import { ProviderAuthenticationSection } from "./ProviderAuthenticationSection";
97import { CodexSetupSection, CodexManagedRuntimeFields } from "./CodexSetupSection";
98import { readCodexSetupMode } from "./CodexSetupSection.logic";
99import { providerClients } from "./providerDriverMeta";
100import { searchableSetting } from "./settingsSearch";
101import {
102 backgroundActivityOverrideSettings,
103 buildProviderInstanceUpdatePatch,
104 durationToSeconds,
105 normalizeIntervalSeconds,
106 PROVIDER_HEALTH_INTERVAL_STEP_SECONDS,
107} from "./SettingsPanels.logic";
108import {
109 PolicyTooltip,
110 SettingResetButton,
111 SettingsPageContainer,
112 SettingsRow,
113 SettingsSection,
114 useRelativeTimeTick,
115 useSettingsSearchTargetId,
116} from "./settingsLayout";
117import {
118 buildProviderEnvironmentOptions,
119 classifyProviderEnvironmentAccess,
120 isProviderSettingsEnvironmentAvailable,
121 type ProviderEnvironmentAccess,
122 type ProviderOperateAccess,
123 resolveRemoteOperateAccess,
124 resolveSelectedProviderEnvironmentId,
125} from "./ProviderSettingsPanel.logic";
126​
127function modelListChanges(current: ReadonlyArray<string>, next: ReadonlyArray<string>) {
128 const currentSet = new Set(current);
129 const nextSet = new Set(next.map((model) => model.trim()).filter(Boolean));
130 return [...new Set([...currentSet, ...nextSet])]
131 .filter((model) => currentSet.has(model) !== nextSet.has(model))
132 .map((model) => ({ model, selected: nextSet.has(model) }));
134​
135function providerConfigString(config: unknown, key: string): string | null {
136 if (config === null || typeof config !== "object") return null;
137 const value = (config as Record<string, unknown>)[key];
138 return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
140​
141const PROVIDER_SETTINGS = providerClients.definitions.map((definition) => ({
142 provider: definition.driverKind,
143 hasDefaultInstance: definition.hasDefaultInstance !== false,
144}));
145​
146function configuredBinaryPath(config: unknown): string {
147 if (config === null || typeof config !== "object" || !("binaryPath" in config)) return "";
148 return typeof config.binaryPath === "string" ? config.binaryPath.trim() : "";
150​
151function ProviderLastChecked({ lastCheckedAt }: { lastCheckedAt: string | null }) {
152 useRelativeTimeTick();
153 const lastCheckedRelative = getRelativeTimeState(lastCheckedAt);
154​
155 if (lastCheckedRelative.status === "missing") {
156 return null;
157 }
158​
159 if (lastCheckedRelative.status === "invalid") {
160 return <span>Checked unavailable</span>;
161 }
162​
163 return (
164 <span>
165 {lastCheckedRelative.suffix ? (
166 <>
167 Checked <span className="font-mono tabular-nums">{lastCheckedRelative.value}</span>{" "}
168 {lastCheckedRelative.suffix}
169 </>
170 ) : (
171 <>Checked {lastCheckedRelative.value}</>
172 )}
173 </span>
174 );
176​
177function providerEnvironmentDetail(environment: EnvironmentPresentation): string {
178 if (environment.entry.target._tag === "PrimaryConnectionTarget") return "Primary device";
179 if (environment.relayManaged) return "T3 Connect";
180 if (environment.entry.target._tag === "SshConnectionTarget") return "SSH";
181 if (isDesktopLocalConnectionTarget(environment.entry.target)) return "Local device";
182 return environment.displayUrl ?? "Remote device";
184​
185// Shared by the editor grid and the placeholder states so switching devices
186// never changes the card's footprint.
187const providerCardHeightClassName =
188 "@min-[48rem]/providers:h-[min(44rem,calc(100dvh-11rem))] @min-[48rem]/providers:min-h-[32rem]";
189​
190/**
191 * Same chrome as the provider editor (section heading, floating device tabs,
192 * tall card) for states that cannot render provider settings yet.
193 */
194function ProviderSettingsPlaceholder({
195 deviceTabs,
196 icon,
197 title,
198 description,
199 children,
200}: {
201 readonly deviceTabs?: ReactNode;
202 readonly icon: ReactNode;
203 readonly title: string;
204 readonly description: string;
205 readonly children?: ReactNode;
206}) {
207 return (
208 <SettingsSection {...searchableSetting("providers")} variant="plain">
209 {deviceTabs ? (
210 <div className="flex min-h-11 min-w-0 items-center px-3 sm:px-4">{deviceTabs}</div>
211 ) : null}
212 <SettingsGroup
213 divided={false}
214 className={cn(
215 providerCardHeightClassName,
216 "scrollbar-gutter-both flex overflow-x-hidden overflow-y-auto",
217 )}
218 >
219 <Empty>
220 <EmptyMedia variant="icon">{icon}</EmptyMedia>
221 <EmptyHeader>
222 <EmptyTitle>{title}</EmptyTitle>
223 <EmptyDescription>{description}</EmptyDescription>
224 </EmptyHeader>
225 {children ? <EmptyContent className="max-w-xl">{children}</EmptyContent> : null}
226 </Empty>
227 </SettingsGroup>
228 </SettingsSection>
229 );
231​
232function EnvironmentUnavailablePlaceholder({
233 environment,
234 access,
235 deviceTabs,
236}: {
237 readonly environment: EnvironmentPresentation;
238 readonly access: Exclude<ProviderEnvironmentAccess, { kind: "editable" | "read-only" }>;
239 readonly deviceTabs?: ReactNode;
240}) {
241 const isLoading = access.kind === "loading";
242 const title = isLoading
243 ? "Loading provider settings"
244 : access.kind === "error"
245 ? "Could not connect to this device"
246 : "Provider settings are unavailable";
247 // Keep the description to a short status; the raw failure can be a
248 // multi-paragraph CLI dump, so it goes below, clamped and expandable.
249 const description = isLoading
250 ? access.reason === "permissions"
251 ? "Checking what this session is allowed to change."
252 : `Waiting for ${environment.label}'s configuration.`
253 : connectionStatusTitle(environment.connection);
254 const error = isLoading ? null : environment.connection.error;
255 // No spinner: this state can persist indefinitely for a wedged device, and a
256 // continuously repainting animation would run the whole time.
257 return (
258 <ProviderSettingsPlaceholder
259 deviceTabs={deviceTabs}
260 icon={
261 <EnvironmentMachineIcon kind={resolveEnvironmentMachineKind(environment.serverConfig)} />
262 }
263 title={title}
264 description={description}
265 >
266 {error ? (
267 <ExpandableText
268 key={environment.environmentId}
269 text={error}
270 className="w-full text-left font-mono text-xs leading-relaxed text-muted-foreground"
271 />
272 ) : null}
273 </ProviderSettingsPlaceholder>
274 );
276​
277interface ProviderSettingsTarget {
278 readonly environmentId?: EnvironmentId;
279 readonly instanceId?: ProviderInstanceId;
280 readonly scoped?: boolean;
281 readonly environmentIds?: readonly EnvironmentId[];
283​
284export function ProviderSettingsPanel(target: ProviderSettingsTarget) {
285 return (
286 <SettingsPageContainer className="@container/providers gap-8">
287 <ProviderSettingsPanelContent
288 key={`${target.environmentId ?? ""}:${target.instanceId ?? ""}`}
289 {...target}
290 />
291 </SettingsPageContainer>
292 );
294​
295function ProviderSettingsPanelContent(target: ProviderSettingsTarget) {
296 const { environments, isReady } = useEnvironments();
297 const primaryEnvironmentId = usePrimaryEnvironmentId();
298 const searchTargetId = useSettingsSearchTargetId();
299 const options = useMemo(
300 () =>
301 buildProviderEnvironmentOptions(environments, primaryEnvironmentId, target.environmentIds),
302 [environments, primaryEnvironmentId, target.environmentIds],
303 );
304 // Raw user intent; the effective selection is re-derived every render so a
305 // device that drops out of the catalog falls back without erasing the pick —
306 // if it reappears (e.g. after a reconnect) the selection is restored.
307 const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<EnvironmentId | null>(
308 target.environmentId ?? primaryEnvironmentId,
309 );
310 const targetEnvironmentMissing =
311 target.environmentId !== undefined &&
312 selectedEnvironmentId === target.environmentId &&
313 !options.some((environment) => environment.environmentId === target.environmentId);
314 const effectiveEnvironmentId =
315 target.scoped || targetEnvironmentMissing
316 ? target.environmentId
317 : resolveSelectedProviderEnvironmentId(options, selectedEnvironmentId, primaryEnvironmentId);
318 const selectedEnvironment =
319 options.find((environment) => environment.environmentId === effectiveEnvironmentId) ?? null;
320 const selectedEnvironmentCanRenderSettings =
321 selectedEnvironment !== null &&
322 isProviderSettingsEnvironmentAvailable({
323 connectionPhase: selectedEnvironment.connection.phase,
324 hasServerConfig: selectedEnvironment.serverConfig !== null,
325 });
326 const searchableEnvironmentId = options.find((environment) =>
327 isProviderSettingsEnvironmentAvailable({
328 connectionPhase: environment.connection.phase,
329 hasServerConfig: environment.serverConfig !== null,
330 }),
331 )?.environmentId;
332 const searchableCursorEnvironmentId = options.find(
333 (environment) =>
334 environment.serverConfig?.environment.platform.os === "darwin" &&
335 isProviderSettingsEnvironmentAvailable({
336 connectionPhase: environment.connection.phase,
337 hasServerConfig: true,
338 }),
339 )?.environmentId;
340 useEffect(() => {
341 if (
342 !target.scoped &&
343 searchTargetId === searchableSetting("cursor-keychain-usage").id &&
344 (!selectedEnvironmentCanRenderSettings ||
345 selectedEnvironment?.serverConfig?.environment.platform.os !== "darwin") &&
346 searchableCursorEnvironmentId !== undefined
347 ) {
348 setSelectedEnvironmentId(searchableCursorEnvironmentId);
349 return;
350 }
351 if (
352 !target.scoped &&
353 (searchTargetId === searchableSetting("provider-health-check-interval").id ||
354 searchTargetId === searchableSetting("usage-providers").id) &&
355 !selectedEnvironmentCanRenderSettings &&
356 searchableEnvironmentId !== undefined
357 ) {
358 setSelectedEnvironmentId(searchableEnvironmentId);
359 }
360 }, [
361 searchTargetId,
362 searchableCursorEnvironmentId,
363 searchableEnvironmentId,
364 selectedEnvironment,
365 selectedEnvironmentCanRenderSettings,
366 target.scoped,
367 ]);
368 const onlyPrimaryDevice =
369 options.length === 1 && options[0]?.entry.target._tag === "PrimaryConnectionTarget";
370 const deviceTabs =
371 !target.scoped && !onlyPrimaryDevice && options.length > 0 ? (
372 <ScrollArea radius="none" hideScrollbars scrollFade className="h-11 min-w-0 flex-1">
373 <ToggleGroup
374 aria-label="Devices"
375 variant="segmented"
376 className="my-2"
377 value={effectiveEnvironmentId ? [effectiveEnvironmentId] : []}
378 onValueChange={(next) => {
379 const environment = options.find((option) => option.environmentId === next[0]);
380 if (environment) setSelectedEnvironmentId(environment.environmentId);
381 }}
382 >
383 {options.map((environment) => {
384 const machine = resolveEnvironmentMachineKind(environment.serverConfig);
385 const detail = providerEnvironmentDetail(environment);
386 const statusText = connectionStatusTitle(environment.connection);
387 return (
388 <Tooltip key={environment.environmentId}>
389 <TooltipTrigger
390 render={
391 <Toggle value={environment.environmentId}>
392 <EnvironmentMachineIcon
393 kind={machine}
394 className="size-3.5 shrink-0"
395 aria-hidden
396 />
397 <span className="max-w-40 truncate">{environment.label}</span>
398 {environment.connection.phase !== "connected" ? (
399 <ConnectionStatusDot
400 dotClassName={connectionPhaseDotClassName(environment.connection.phase)}
401 pingClassName={connectionPhasePingClassName(environment.connection.phase)}
402 />
403 ) : null}
404 <span className="sr-only">
405 {detail}, {statusText}
406 </span>
407 </Toggle>
408 }
409 />
410 <TooltipPopup side="top">
411 {detail} · {statusText}
412 </TooltipPopup>
413 </Tooltip>
414 );
415 })}
416 </ToggleGroup>
417 </ScrollArea>
418 ) : null;
419​
420 return (
421 <>
422 {targetEnvironmentMissing ? (
423 <ProviderSettingsPlaceholder
424 deviceTabs={deviceTabs}
425 icon={<EnvironmentMachineIcon kind={resolveEnvironmentMachineKind(null)} />}
426 title="Device unavailable"
427 description="Reconnect this device to set up its provider, or select another device."
428 />
429 ) : null}
430 {options.length === 0 && !targetEnvironmentMissing ? (
431 <ProviderSettingsPlaceholder
432 icon={<EnvironmentMachineIcon kind={resolveEnvironmentMachineKind(null)} />}
433 title={isReady ? "No connected devices" : "Loading devices"}
434 description={
435 isReady
436 ? "Connect an execution environment before configuring providers."
437 : "Reading connected execution environments."
438 }
439 />
440 ) : null}
441​
442 {selectedEnvironment ? (
443 <SelectedEnvironmentProviderSettings
444 key={selectedEnvironment.environmentId}
445 environment={selectedEnvironment}
446 deviceTabs={deviceTabs}
447 targetInstanceId={
448 target.environmentId === undefined ||
449 selectedEnvironment.environmentId === target.environmentId
450 ? target.instanceId
451 : undefined
452 }
453 />
454 ) : null}
455 </>
456 );
458​
459function SelectedEnvironmentProviderSettings({
460 environment,
461 deviceTabs,
462 targetInstanceId,
463}: {
464 readonly environment: EnvironmentPresentation;
465 readonly deviceTabs?: ReactNode;
466 readonly targetInstanceId?: ProviderInstanceId | undefined;
467}) {
468 return (
469 <RemoteSessionGatedProviderSettings
470 environment={environment}
471 deviceTabs={deviceTabs}
472 targetInstanceId={targetInstanceId}
473 />
474 );
476​
477function RemoteSessionGatedProviderSettings({
478 environment,
479 deviceTabs,
480 targetInstanceId,
481}: {
482 readonly environment: EnvironmentPresentation;
483 readonly deviceTabs?: ReactNode;
484 readonly targetInstanceId?: ProviderInstanceId | undefined;
485}) {
486 const sessionState = useEnvironmentSessionState(environment.environmentId);
487 const operateAccess = resolveRemoteOperateAccess({
488 session: sessionState.data,
489 isPending: sessionState.isPending,
490 hasError: sessionState.hasError,
491 });
492 return (
493 <AccessGatedProviderSettings
494 environment={environment}
495 operateAccess={operateAccess}
496 deviceTabs={deviceTabs}
497 targetInstanceId={targetInstanceId}
498 />
499 );
501​
502function AccessGatedProviderSettings({
503 environment,
504 operateAccess,
505 deviceTabs,
506 targetInstanceId,
507}: {
508 readonly environment: EnvironmentPresentation;
509 readonly operateAccess: ProviderOperateAccess;
510 readonly deviceTabs?: ReactNode;
511 readonly targetInstanceId?: ProviderInstanceId | undefined;
512}) {
513 const access = classifyProviderEnvironmentAccess({
514 connectionPhase: environment.connection.phase,
515 hasServerConfig: environment.serverConfig !== null,
516 operateAccess,
517 });
518 if (access.kind !== "editable" && access.kind !== "read-only") {
519 return (
520 <EnvironmentUnavailablePlaceholder
521 environment={environment}
522 access={access}
523 deviceTabs={deviceTabs}
524 />
525 );
526 }
527 return (
528 <EnvironmentProviderSettings
529 environmentId={environment.environmentId}
530 environmentLabel={environment.label}
531 readOnly={access.kind === "read-only"}
532 deviceTabs={deviceTabs}
533 targetInstanceId={targetInstanceId}
534 />
535 );
537​
538export function EnvironmentProviderSettings({
539 environmentId,
540 environmentLabel,
541 readOnly = false,
542 deviceTabs,
543 targetInstanceId,
544}: {
545 readonly environmentId: EnvironmentId;
546 readonly environmentLabel: string;
547 readonly deviceTabs?: ReactNode;
548 readonly targetInstanceId?: ProviderInstanceId | undefined;
549 /**
550 * Grey out and freeze every write control when this session's credential
551 * lacks `providers:manage` on the environment. Selecting providers
552 * still works so the real configuration stays readable; switches, forms,
553 * are inert so no write is offered and then rejected.
554 */
555 readonly readOnly?: boolean;
556}) {
557 const settings = useEnvironmentSettings(environmentId);
558 const canWriteSettings = useEnvironmentScope(environmentId, AuthSettingsWriteScope);
559 const canRefreshProviders = useEnvironmentScope(environmentId, AuthOrchestrationReadScope);
560 const updateSettings = useUpdateEnvironmentSettings(environmentId);
561 const updateModelPreferences = useUpdateEnvironmentModelPreferences(environmentId);
562 const toggleModelFavorite = useToggleEnvironmentModelFavorite(environmentId);
563 const persistProviderInstance = usePersistEnvironmentProviderInstanceMutation(environmentId);
564 const serverProviders =
565 useAtomValue(serverEnvironment.providersValueAtom(environmentId)) ?? EMPTY_SERVER_PROVIDERS;
566 const projects = useProjects().filter((project) => project.environmentId === environmentId);
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 = useCallback(
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 [acceptAcpRegistryUrlAuth, environmentId],
617 );
618​
619 const providerUpdateCandidateByInstanceId = useMemo(
620 () =>
621 new Map(
622 serverProviders
623 .filter(isProviderSettingsUpdateCandidate)
624 .map((candidate) => [candidate.instanceId, candidate]),
625 ),
626 [serverProviders],
627 );
628 const visibleProviderSettings = PROVIDER_SETTINGS.filter(
629 (providerSettings) =>
630 providerSettings.provider !== "cursor" ||
631 serverProviders.some(
632 (provider) =>
633 provider.instanceId === defaultInstanceIdForDriver(ProviderDriverKind.make("cursor")),
634 ),
635 );
636 const textGenerationModelSelection = resolveAppModelSelectionState(settings, serverProviders);
637 const textGenInstanceId = textGenerationModelSelection.instanceId;
638 const resolvedBackgroundActivity = resolveServerBackgroundActivitySettings(settings);
639 const providerHealthPreset = getBackgroundActivityPresetSettings(
640 resolvedBackgroundActivity.profile,
641 ).providerHealthRefreshInterval;
642 const providerHealthRefreshIntervalSeconds = durationToSeconds(
643 resolvedBackgroundActivity.providerHealthRefreshInterval,
644 );
645 const defaultProviderHealthRefreshIntervalSeconds = durationToSeconds(providerHealthPreset);
646 const lastCheckedAt =
647 serverProviders.length > 0
648 ? serverProviders.reduce(
649 (latest, provider) => (provider.checkedAt > latest ? provider.checkedAt : latest),
650 serverProviders[0]!.checkedAt,
651 )
652 : null;
653​
654 const refreshProviders = useCallback(() => {
655 if (refreshingRef.current || !readEnvironmentScope(environmentId, AuthOrchestrationReadScope))
656 return;
657 refreshingRef.current = true;
658 setIsRefreshingProviders(true);
659 void (async () => {
660 const result = await refreshServerProviders({
661 environmentId,
662 input: { refreshModels: true },
663 });
664 refreshingRef.current = false;
665 setIsRefreshingProviders(false);
666 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
667 console.warn("Failed to refresh providers", {
668 operation: "refresh-providers",
669 environmentId,
670 ...safeErrorLogAttributes(squashAtomCommandFailure(result)),
671 });
672 }
673 })();
674 }, [environmentId, refreshServerProviders]);
675​
676 const runProviderUpdate = useCallback(
677 async (
678 candidate: Pick<ProviderSettingsUpdateCandidate, "driver" | "instanceId">,
679 targetVersion?: string,
680 ) => {
681 if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
682 // Ref-based re-entry guard, mirroring refreshProviders: a state updater
683 // may run after this function returns, so it cannot gate the dispatch.
684 if (updatingInstanceIdsRef.current.has(candidate.instanceId)) {
685 return;
686 }
687 updatingInstanceIdsRef.current.add(candidate.instanceId);
688 setUpdatingProviderInstanceIds((previous) => new Set(previous).add(candidate.instanceId));
689​
690 const result = await updateProvider({
691 environmentId,
692 input: {
693 provider: candidate.driver,
694 instanceId: candidate.instanceId,
695 ...(targetVersion ? { targetVersion } : {}),
696 },
697 });
698 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
699 const error = squashAtomCommandFailure(result);
700 toastManager.add(
701 stackedThreadToast({
702 type: "error",
703 title: `Could not update ${PROVIDER_DISPLAY_NAMES[candidate.driver] ?? candidate.driver}`,
704 description:
705 error instanceof Error
706 ? error.message
707 : "The provider update command could not be started.",
708 }),
709 );
710 }
711 updatingInstanceIdsRef.current.delete(candidate.instanceId);
712 setUpdatingProviderInstanceIds((previous) => {
713 if (!previous.has(candidate.instanceId)) {
714 return previous;
715 }
716 const next = new Set(previous);
717 next.delete(candidate.instanceId);
718 return next;
719 });
720 },
721 [environmentId, updateProvider],
722 );
723​
724 interface InstanceRow {
725 readonly instanceId: ProviderInstanceId;
726 readonly instance: ProviderInstanceConfig;
727 readonly driver: ProviderDriverKind;
728 readonly isDefault: boolean;
729 readonly isDirty?: boolean;
730 }
731​
732 const instancesByDriver = new Map<
733 ProviderDriverKind,
734 Array<[ProviderInstanceId, ProviderInstanceConfig]>
735 >();
736 for (const [rawId, instance] of Object.entries(settings.providerInstances ?? {})) {
737 const driver = instance.driver;
738 const list = instancesByDriver.get(driver) ?? [];
739 list.push([rawId as ProviderInstanceId, instance]);
740 instancesByDriver.set(driver, list);
741 }
742​
743 const defaultSlotIdsBySource = new Set<string>(
744 visibleProviderSettings.map((providerSettings) =>
745 String(defaultInstanceIdForDriver(providerSettings.provider)),
746 ),
747 );
748​
749 const rows: InstanceRow[] = [];
750 const visibleDriverKinds = new Set<ProviderDriverKind>(
751 visibleProviderSettings.map((providerSettings) => providerSettings.provider),
752 );
753​
754 for (const providerSettings of visibleProviderSettings) {
755 const driver = providerSettings.provider;
756 const defaultInstanceId = defaultInstanceIdForDriver(driver);
757 const explicitInstance = settings.providerInstances?.[defaultInstanceId];
758 // An unconfigured default slot runs with the driver's default config.
759 const effectiveInstance: ProviderInstanceConfig = explicitInstance ?? { driver };
760 const isDirty = explicitInstance !== undefined;
761 // Drivers without a default instance list only their configured instances.
762 const hasDefaultSlot = providerSettings.hasDefaultInstance || explicitInstance !== undefined;
763 if (
764 hasDefaultSlot &&
765 (driver === "codex" ||
766 driver === "claudeAgent" ||
767 isDirty ||
768 resolveProviderInstanceEnabled(effectiveInstance) ||
769 defaultInstanceId === targetInstanceId)
770 ) {
771 rows.push({
772 instanceId: defaultInstanceId,
773 instance: effectiveInstance,
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({ instanceId: id, instance, driver: instance.driver, isDefault: false });
782 }
783 }
784 for (const [driver, list] of instancesByDriver) {
785 if (visibleDriverKinds.has(driver)) continue;
786 for (const [id, instance] of list) {
787 rows.push({
788 instanceId: id,
789 instance,
790 driver: instance.driver,
791 isDefault: defaultSlotIdsBySource.has(String(id)),
792 });
793 }
794 }
795​
796 const targetInstanceMissing =
797 targetInstanceId !== undefined &&
798 selectedInstanceId === targetInstanceId &&
799 !rows.some((row) => row.instanceId === targetInstanceId);
800 const selectedRow =
801 rows.find((row) => row.instanceId === selectedInstanceId) ??
802 (targetInstanceMissing ? null : (rows[0] ?? null));
803​
804 const updateProviderInstance = async (
805 row: InstanceRow,
806 next: ProviderInstanceConfig,
807 options?: {
808 readonly textGenerationModelSelection?: Parameters<
809 typeof buildProviderInstanceUpdatePatch
810 >[0]["textGenerationModelSelection"];
811 },
812 ) => {
813 const { providerInstances: _providerInstances, ...patch } = buildProviderInstanceUpdatePatch({
814 settings,
815 instanceId: row.instanceId,
816 instance: next,
817 textGenerationModelSelection: options?.textGenerationModelSelection,
818 });
819 const result = await persistProviderInstance(
820 { operation: "upsert", instanceId: row.instanceId, instance: next },
821 patch,
822 );
823 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
824 const error = squashAtomCommandFailure(result);
825 toastManager.add({
826 type: "error",
827 title: "Could not update provider instance",
828 description: error instanceof Error ? error.message : "The settings update failed.",
829 });
830 }
831 };
832​
833 const deleteProviderInstance = async (row: InstanceRow) => {
834 const updateResult = await persistProviderInstance({
835 operation: "remove",
836 instanceId: row.instanceId,
837 });
838 if (updateResult._tag === "Failure") {
839 const error = squashAtomCommandFailure(updateResult);
840 toastManager.add({
841 type: "error",
842 title: "Could not delete provider instance",
843 description: error instanceof Error ? error.message : "The settings update failed.",
844 });
845 return;
846 }
847​
848 if (row.driver !== ProviderDriverKind.make("acpRegistry")) return;
849 if (providerConfigString(row.instance.config, "source") === "local") return;
850 const agentId = providerConfigString(row.instance.config, "agentId");
851 if (agentId === null) return;
852​
853 // The server decides from its latest settings whether this was the last
854 // instance using the managed agent. A client-side snapshot check can race
855 // two removals and make both callers skip cleanup.
856 const uninstallResult = await uninstallAcpRegistryManagedBinary({
857 environmentId,
858 input: { agentId },
859 });
860 if (uninstallResult._tag === "Failure" && !isAtomCommandInterrupted(uninstallResult)) {
861 const error = squashAtomCommandFailure(uninstallResult);
862 toastManager.add({
863 type: "warning",
864 title: "Provider deleted, but managed files remain",
865 description: error instanceof Error ? error.message : "Managed binary cleanup failed.",
866 });
867 }
868 };
869​
870 const resetDefaultInstance = async (driverKind: ProviderDriverKind) => {
871 const result = await persistProviderInstance({
872 operation: "remove",
873 instanceId: defaultInstanceIdForDriver(driverKind),
874 });
875 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
876 const error = squashAtomCommandFailure(result);
877 toastManager.add({
878 type: "error",
879 title: "Could not reset provider instance",
880 description: error instanceof Error ? error.message : "The settings update failed.",
881 });
882 }
883 };
884​
885 const renderProviderInstance = (row: InstanceRow, mode: "list" | "editor") => {
886 const driverOption = providerClients.get(row.driver);
887 const liveProvider = serverProviders.find(
888 (candidate) => candidate.instanceId === row.instanceId,
889 );
890 const updateCandidate = providerUpdateCandidateByInstanceId.get(row.instanceId);
891 const isInstanceUpdateRunning =
892 updatingProviderInstanceIds.has(row.instanceId) ||
893 (liveProvider !== undefined && isProviderUpdateActive(liveProvider));
894 const showInlineUpdateButton = updateCandidate !== undefined;
895 const canRunInlineUpdate = updateCandidate !== undefined && !isInstanceUpdateRunning;
896 const modelPreferences = settings.providerModelPreferences?.[row.instanceId] ?? {
897 hiddenModels: [],
898 modelOrder: [],
899 };
900 const favoriteModels = Arr.filterMap(settings.favorites ?? [], (favorite) =>
901 favorite.provider === row.instanceId ? Result.succeed(favorite.model) : Result.failVoid,
902 );
903 const resetLabel = driverOption?.label ?? String(row.driver);
904​
905 return (
906 <ProviderInstanceCard
907 key={row.instanceId}
908 environmentId={environmentId}
909 acpProjects={projects}
910 onAcceptUrlAuth={
911 readOnly ? undefined : (action) => acceptUrlAuthentication(row.instanceId, action)
912 }
913 instanceId={row.instanceId}
914 instance={row.instance}
915 driverOption={driverOption}
916 liveProvider={liveProvider}
917 mode={mode}
918 selected={mode === "list" && selectedRow?.instanceId === row.instanceId}
919 onSelect={mode === "list" ? () => setSelectedInstanceId(row.instanceId) : undefined}
920 readOnly={readOnly}
921 runtime={
922 mode === "editor" &&
923 row.driver === "codex" &&
924 readCodexSetupMode(row.instance.config) === "managed" ? (
925 <CodexManagedRuntimeFields
926 environmentId={environmentId}
927 instanceId={row.instanceId}
928 provider={liveProvider}
929 />
930 ) : undefined
931 }
932 canWriteSettings={canWriteSettings}
933 setup={
934 mode === "editor" && row.driver === "antigravity" ? (
935 <ProviderSetupSection
936 environmentId={environmentId}
937 environmentLabel={environmentLabel}
938 instanceId={row.instanceId}
939 provider={liveProvider}
940 binaryPath={configuredBinaryPath(row.instance.config)}
941 authMethod={readAntigravityAuthMethod(row.instance.config)}
942 enabled={resolveProviderInstanceEnabled(row.instance)}
943 readOnly={readOnly}
944 onEnable={() => updateProviderInstance(row, { ...row.instance, enabled: true })}
945 />
946 ) : mode === "editor" &&
947 row.driver === "codex" &&
948 readCodexSetupMode(row.instance.config) === "managed" ? (
949 <CodexSetupSection
950 environmentId={environmentId}
951 instanceId={row.instanceId}
952 provider={liveProvider}
953 mode={readCodexSetupMode(row.instance.config)}
954 enabled={resolveProviderInstanceEnabled(row.instance)}
955 readOnly={readOnly}
956 onModeChange={(setupMode) =>
957 updateProviderInstance(row, {
958 ...row.instance,
959 enabled: true,
960 config: {
961 ...(row.instance.config !== null && typeof row.instance.config === "object"
962 ? row.instance.config
963 : {}),
964 enabled: true,
965 setupMode,
966 },
967 })
968 }
969 />
970 ) : mode === "editor" &&
971 !readOnly &&
972 liveProvider &&
973 (liveProvider.setup?.canAuthenticate ||
974 (liveProvider.driver === "acpRegistry" && liveProvider.installed)) ? (
975 <ProviderAuthenticationSection
976 key={`${environmentId}:${row.instanceId}`}
977 environmentId={environmentId}
978 environmentLabel={environmentLabel}
979 instanceId={row.instanceId}
980 provider={liveProvider}
981 readOnly={readOnly}
982 />
983 ) : mode === "editor" &&
984 !readOnly &&
985 row.driver === "cursor" &&
986 liveProvider?.setup?.canAuthenticate === false ? (
987 <SettingsRow
988 title="Cursor account"
989 description="Using CURSOR_API_KEY. Remove it from this provider's environment to use browser sign-in."
990 />
991 ) : null
992 }
993 onUpdate={(next) => {
994 const wasEnabled = resolveProviderInstanceEnabled(row.instance);
995 const isDisabling = next.enabled === false && wasEnabled;
996 const shouldClearTextGen =
997 isDisabling &&
998 textGenInstanceId === row.instanceId &&
999 readEnvironmentScope(environmentId, AuthSettingsWriteScope);
1000 updateProviderInstance(
1001 row,
1002 next,
1003 shouldClearTextGen
1004 ? {
1005 textGenerationModelSelection:
1006 DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection,
1008 : undefined,
1009 );
1010 }}
1011 onDelete={
1012 mode === "editor" && !row.isDefault ? () => deleteProviderInstance(row) : undefined
1014 headerAction={
1015 mode === "editor" && row.isDefault && row.isDirty ? (
1016 <SettingResetButton
1017 label={`${resetLabel} provider settings`}
1018 onClick={() => resetDefaultInstance(row.driver)}
1019 />
1020 ) : null
1022 hiddenModels={modelPreferences.hiddenModels}
1023 favoriteModels={favoriteModels}
1024 modelOrder={modelPreferences.modelOrder}
1025 onHiddenModelsChange={(next, affectedModels) => {
1026 const hidden = new Set(next);
1027 const models =
1028 affectedModels ??
1029 modelListChanges(modelPreferences.hiddenModels, next).map((change) => change.model);
1030 void updateModelPreferences({
1031 setModelsHidden: models.map((model) => ({
1032 provider: row.instanceId,
1033 model,
1034 hidden: hidden.has(model),
1035 })),
1036 });
1037 }}
1038 onToggleFavorite={(model) => {
1039 void toggleModelFavorite(row.instanceId, model);
1040 }}
1041 onFavoriteModelsChange={(next) => {
1042 void updateModelPreferences({
1043 setModelFavorites: modelListChanges(favoriteModels, next).map(
1044 ({ model, selected }) => ({ provider: row.instanceId, model, favorite: selected }),
1045 ),
1046 });
1047 }}
1048 onModelOrderChange={(modelOrder) => {
1049 void updateModelPreferences({
1050 setProviderModelOrder: { provider: row.instanceId, modelOrder },
1051 });
1052 }}
1053 onInstallRecommended={
1054 !readOnly &&
1055 liveProvider?.compatibilityAdvisory?.message &&
1056 liveProvider.compatibilityAdvisory.recommendedVersion &&
1057 liveProvider.versionAdvisory?.canInstallVersion
1058 ? () => {
1059 void runProviderUpdate(
1060 liveProvider,
1061 liveProvider.compatibilityAdvisory?.recommendedVersion ?? undefined,
1062 );
1064 : undefined
1066 onRunUpdate={
1067 !readOnly && showInlineUpdateButton && updateCandidate
1068 ? () => {
1069 if (canRunInlineUpdate) void runProviderUpdate(updateCandidate);
1071 : undefined
1073 isUpdating={isInstanceUpdateRunning}
1074 />
1075 );
1076 };
1077​
1078 return (
1079 <>
1080 <SettingsSection
1081 {...searchableSetting("providers")}
1082 variant="plain"
1083 titleAction={
1084 !readOnly ? (
1085 <Tooltip>
1086 <TooltipTrigger
1087 render={
1088 <Button
1089 size="icon-xs"
1090 variant="ghost-muted"
1091 onClick={() => setIsAddInstanceDialogOpen(true)}
1092 aria-label="Add provider"
1094 <PlusIcon />
1095 </Button>
1097 />
1098 <TooltipPopup side="top">Add provider</TooltipPopup>
1099 </Tooltip>
1100 ) : null
1102 headerAction={
1103 <div className="flex min-w-0 items-center gap-2">
1104 <ProviderUpdatesAction />
1105 <Tooltip>
1106 <TooltipTrigger
1107 render={
1108 <Button
1109 size="xs"
1110 variant="ghost-muted"
1111 disabled={isRefreshingProviders || !canRefreshProviders}
1112 aria-busy={isRefreshingProviders}
1113 onClick={() => void refreshProviders()}
1115 <RefreshIcon refreshing={isRefreshingProviders} />
1116 <span className="sr-only">Refresh provider status</span>
1117 <span className="hidden min-w-0 truncate sm:inline">
1118 {isRefreshingProviders ? (
1119 "Refreshing providers"
1120 ) : (
1121 <ProviderLastChecked lastCheckedAt={lastCheckedAt} />
1122 )}
1123 </span>
1124 </Button>
1126 />
1127 <TooltipPopup side="top">Refresh provider status</TooltipPopup>
1128 </Tooltip>
1129 </div>
1132 {deviceTabs ? (
1133 <div className="flex min-h-11 min-w-0 items-center gap-2 px-3 sm:px-4">{deviceTabs}</div>
1134 ) : null}
1135 {readOnly ? (
1136 <SettingsGroup divided={false} className="overflow-hidden">
1137 <SettingsRow
1138 title="Limited permissions"
1139 description={`This session can view ${environmentLabel}'s providers but can't change their settings.`}
1140 />
1141 </SettingsGroup>
1142 ) : null}
1143 <SettingsGroup
1144 divided={false}
1145 className={cn(
1146 providerCardHeightClassName,
1147 "overflow-hidden @min-[48rem]/providers:grid @min-[48rem]/providers:grid-cols-[17rem_minmax(0,1fr)]",
1148 )}
1150 <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">
1151 <ScrollArea
1152 scrollFade
1153 chainVerticalScroll
1154 className="@min-[48rem]/providers:min-h-0 @min-[48rem]/providers:flex-1"
1156 <div className="divide-y divide-border/50">
1157 {rows.map((row) => renderProviderInstance(row, "list"))}
1158 {!readOnly ? (
1159 <button
1160 type="button"
1161 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"
1162 onClick={() => setIsAddInstanceDialogOpen(true)}
1164 <PlusIcon className="size-4 shrink-0" />
1165 Add provider
1166 </button>
1167 ) : null}
1168 </div>
1169 </ScrollArea>
1170 </div>
1171​
1172 <div className="min-w-0 @min-[48rem]/providers:min-h-0">
1173 {selectedRow ? (
1174 <ScrollArea scrollFade chainVerticalScroll className="@min-[48rem]/providers:h-full">
1175 <div className="space-y-6 p-4">{renderProviderInstance(selectedRow, "editor")}</div>
1176 </ScrollArea>
1177 ) : (
1178 <div className="p-6 text-sm text-muted-foreground">
1179 {targetInstanceMissing
1180 ? "This provider instance is no longer available on this device."
1181 : "No providers configured."}
1182 </div>
1183 )}
1184 </div>
1185 </SettingsGroup>
1186 </SettingsSection>
1187​
1188 <UsageProviderSettings
1189 key={environmentId}
1190 environmentId={environmentId}
1191 environmentLabel={environmentLabel}
1192 sources={settings.usageLimitSources}
1193 cursorKeychainUsageEnabled={settings.cursorKeychainUsageEnabled}
1194 readOnly={readOnly}
1195 />
1196​
1197 <SettingsSection title="Advanced">
1198 <SettingsRow
1199 id={searchableSetting("provider-health-check-interval").id}
1200 title={
1201 <span className="inline-flex items-center gap-1.5">
1202 {searchableSetting("provider-health-check-interval").title}
1203 <PolicyTooltip>
1204 This interval is configured here, then the shared Background activity policy decides
1205 whether provider probes may run when the timer fires. Custom intervals appear as
1206 Advanced in General settings.
1207 </PolicyTooltip>
1208 </span>
1210 description="Refresh provider status, versions, and models in the background. Set to 0 to disable."
1211 resetAction={
1212 providerHealthRefreshIntervalSeconds !== defaultProviderHealthRefreshIntervalSeconds ? (
1213 <span
1214 inert={!canWriteSettings}
1215 className={!canWriteSettings ? "opacity-50" : undefined}
1217 <SettingResetButton
1218 label="provider health check interval"
1219 onClick={() =>
1220 updateSettings(
1221 backgroundActivityOverrideSettings(
1222 settings.backgroundActivity,
1223 resolvedBackgroundActivity,
1224 { providerHealthRefreshInterval: undefined },
1225 ),
1228 />
1229 </span>
1230 ) : null
1232 control={
1233 <div
1234 inert={!canWriteSettings}
1235 aria-disabled={!canWriteSettings || undefined}
1236 className={cn(
1237 "flex shrink-0 items-center gap-2",
1238 !canWriteSettings && "opacity-50 select-none",
1239 )}
1241 <NumberField
1242 value={providerHealthRefreshIntervalSeconds}
1243 min={0}
1244 step={PROVIDER_HEALTH_INTERVAL_STEP_SECONDS}
1245 size="sm"
1246 className="w-32"
1247 onValueChange={(value) =>
1248 updateSettings(
1249 backgroundActivityOverrideSettings(
1250 settings.backgroundActivity,
1251 resolvedBackgroundActivity,
1253 providerHealthRefreshInterval: Duration.seconds(
1254 normalizeIntervalSeconds(value),
1255 ),
1256 },
1257 ),
1261 <NumberFieldGroup>
1262 <NumberFieldDecrement aria-label="Decrease provider health check interval" />
1263 <NumberFieldInput aria-label="Provider health check interval in seconds" />
1264 <NumberFieldIncrement aria-label="Increase provider health check interval" />
1265 </NumberFieldGroup>
1266 </NumberField>
1267 <span className="text-xs text-muted-foreground">seconds</span>
1268 </div>
1270 />
1271 </SettingsSection>
1272​
1273 {isAddInstanceDialogOpen && !readOnly ? (
1274 <AddProviderInstanceDialog
1275 open
1276 environmentId={environmentId}
1277 environmentLabel={environmentLabel}
1278 onOpenChange={setIsAddInstanceDialogOpen}
1279 onCreated={setSelectedInstanceId}
1280 />
1281 ) : null}
1282 </>
1283 );