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