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

ProviderSettingsPanel.tsx

1,276 lines46.7 KB

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