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

ProviderSettingsPanel.tsx

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