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