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

ProviderSettingsPanel.tsx

1,274 lines46.4 KB

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