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