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