Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { connectionStatusTitle } from "@t3tools/client-runtime/connection";
3import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
4import {
5 isAtomCommandInterrupted,
6 squashAtomCommandFailure,
7} from "@t3tools/client-runtime/state/runtime";
8import {
9 defaultInstanceIdForDriver,
10 type EnvironmentId,
11 PROVIDER_DISPLAY_NAMES,
12 ProviderDriverKind,
13 type ProviderInstanceConfig,
14 type ProviderInstanceId,
15 resolveEnvironmentMachineKind,
16 resolveProviderInstanceEnabled,
17} from "@t3tools/contracts";
18import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
19import {
20 getBackgroundActivityPresetSettings,
21 resolveServerBackgroundActivitySettings,
22} from "@t3tools/shared/backgroundActivitySettings";
23import * as Arr from "effect/Array";
24import * as Duration from "effect/Duration";
25import * as Equal from "effect/Equal";
26import * as Result from "effect/Result";
27import { PlusIcon, RefreshCwIcon } from "lucide-react";
28import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
29
30import { isDesktopLocalConnectionTarget } from "../../connection/desktopLocal";
31import { isElectron } from "../../env";
32import { usePrimarySessionState } from "../../environments/primary";
33import { useEnvironmentSettings, useUpdateEnvironmentSettings } from "../../hooks/useSettings";
34import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
35import { cn } from "../../lib/utils";
36import { resolveAppModelSelectionState } from "../../modelSelection";
37import {
38 useEnvironments,
39 usePrimaryEnvironmentId,
40 type EnvironmentPresentation,
41} from "../../state/environments";
42import { EMPTY_SERVER_PROVIDERS, serverEnvironment } from "../../state/server";
43import { useEnvironmentSessionState } from "../../state/session";
44import { useAtomCommand } from "../../state/use-atom-command";
45import { getRelativeTimeState } from "../../timestampFormat";
46import {
47 ConnectionStatusDot,
48 connectionPhaseDotClassName,
49 connectionPhasePingClassName,
50} from "../ConnectionStatusDot";
51import {
52 canOneClickUpdateProviderCandidate,
53 collectProviderUpdateCandidates,
54 hasOneClickUpdateProviderCandidate,
55 isProviderUpdateActive,
56 type ProviderUpdateCandidate,
57} from "../ProviderUpdateLaunchNotification.logic";
58import { Button } from "../ui/button";
59import {
60 Empty,
61 EmptyContent,
62 EmptyDescription,
63 EmptyHeader,
64 EmptyMedia,
65 EmptyTitle,
66} from "../ui/empty";
67import {
68 NumberField,
69 NumberFieldDecrement,
70 NumberFieldGroup,
71 NumberFieldIncrement,
72 NumberFieldInput,
73} from "../ui/number-field";
74import { ScrollArea } from "../ui/scroll-area";
75import { Toggle, ToggleGroup } from "../ui/toggle-group";
76import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
77import { stackedThreadToast, toastManager } from "../ui/toast";
78import { AddProviderInstanceDialog } from "./AddProviderInstanceDialog";
79import { ExpandableText } from "./ExpandableText";
80import { ProviderInstanceCard } from "./ProviderInstanceCard";
81import { UsageProviderSettings } from "./UsageProviderSettings";
82import { ProviderSetupSection, readAntigravityAuthMethod } from "./ProviderSetupSection";
83import { DRIVER_OPTIONS, getDriverOption } from "./providerDriverMeta";
84import { searchableSetting } from "./settingsSearch";
85import {
86 backgroundActivityOverrideSettings,
87 buildProviderInstanceUpdatePatch,
88 durationToSeconds,
89 normalizeIntervalSeconds,
90 PROVIDER_HEALTH_INTERVAL_STEP_SECONDS,
91} from "./SettingsPanels.logic";
92import {
93 PolicyTooltip,
94 SettingResetButton,
95 SettingsPageContainer,
96 SettingsRow,
97 SettingsSection,
98 useRelativeTimeTick,
99 useSettingsSearchTargetId,
100} from "./settingsLayout";
101import {
102 buildProviderEnvironmentOptions,
103 classifyProviderEnvironmentAccess,
104 isProviderSettingsEnvironmentAvailable,
105 type ProviderEnvironmentAccess,
106 type ProviderOperateAccess,
107 resolvePrimaryOperateAccess,
108 resolveRemoteOperateAccess,
109 resolveSelectedProviderEnvironmentId,
110} from "./ProviderSettingsPanel.logic";
111
112function withoutProviderInstanceKey<V>(
113 record: Readonly<Record<ProviderInstanceId, V>> | undefined,
114 key: ProviderInstanceId,
115): Record<ProviderInstanceId, V> {
116 const next = { ...record } as Record<ProviderInstanceId, V>;
117 delete next[key];
118 return next;
119}
120
121function withoutProviderInstanceFavorites(
122 favorites: ReadonlyArray<{ readonly provider: ProviderInstanceId; readonly model: string }>,
123 instanceId: ProviderInstanceId,
124) {
125 return favorites.filter((favorite) => favorite.provider !== instanceId);
126}
127
128const PROVIDER_SETTINGS = DRIVER_OPTIONS.map((definition) => ({
129 provider: definition.value,
130}));
131
132function configuredBinaryPath(config: unknown): string {
133 if (config === null || typeof config !== "object" || !("binaryPath" in config)) return "";
134 return typeof config.binaryPath === "string" ? config.binaryPath.trim() : "";
135}
136
137function ProviderLastChecked({ lastCheckedAt }: { lastCheckedAt: string | null }) {
138 useRelativeTimeTick();
139 const lastCheckedRelative = getRelativeTimeState(lastCheckedAt);
140
141 if (lastCheckedRelative.status === "missing") {
142 return null;
143 }
144
145 if (lastCheckedRelative.status === "invalid") {
146 return <span>Checked unavailable</span>;
147 }
148
149 return (
150 <span>
151 {lastCheckedRelative.suffix ? (
152 <>
153 Checked <span className="font-mono tabular-nums">{lastCheckedRelative.value}</span>{" "}
154 {lastCheckedRelative.suffix}
155 </>
156 ) : (
157 <>Checked {lastCheckedRelative.value}</>
158 )}
159 </span>
160 );
161}
162
163function providerEnvironmentDetail(environment: EnvironmentPresentation): string {
164 if (environment.entry.target._tag === "PrimaryConnectionTarget") return "Primary device";
165 if (environment.relayManaged) return "T3 Connect";
166 if (environment.entry.target._tag === "SshConnectionTarget") return "SSH";
167 if (isDesktopLocalConnectionTarget(environment.entry.target)) return "Local device";
168 return environment.displayUrl ?? "Remote device";
169}
170
171const providerCardClassName = "rounded-xl border border-border/60 bg-card/40 shadow-xs/5";
172// Shared by the editor grid and the placeholder states so switching devices
173// never changes the card's footprint.
174const providerCardHeightClassName = "lg:h-[min(44rem,calc(100dvh-11rem))] lg:min-h-[32rem]";
175
176/**
177 * Same chrome as the provider editor (section heading, floating device tabs,
178 * tall card) for states that cannot render provider settings yet.
179 */
180function ProviderSettingsPlaceholder({
181 deviceTabs,
182 icon,
183 title,
184 description,
185 children,
186}: {
187 readonly deviceTabs?: ReactNode;
188 readonly icon: ReactNode;
189 readonly title: string;
190 readonly description: string;
191 readonly children?: ReactNode;
192}) {
193 return (
194 <SettingsSection {...searchableSetting("providers")} hideTitle variant="plain">
195 {deviceTabs ? (
196 <div className="flex min-h-11 min-w-0 items-center px-3 sm:px-4">{deviceTabs}</div>
197 ) : null}
198 <div
199 className={cn(
200 providerCardClassName,
201 providerCardHeightClassName,
202 "flex overflow-x-hidden overflow-y-auto",
203 )}
204 >
205 <Empty className="min-h-88">
206 <EmptyMedia variant="icon">{icon}</EmptyMedia>
207 <EmptyHeader>
208 <EmptyTitle>{title}</EmptyTitle>
209 <EmptyDescription>{description}</EmptyDescription>
210 </EmptyHeader>
211 {children ? <EmptyContent className="max-w-xl">{children}</EmptyContent> : null}
212 </Empty>
213 </div>
214 </SettingsSection>
215 );
216}
217
218function EnvironmentUnavailablePlaceholder({
219 environment,
220 access,
221 deviceTabs,
222}: {
223 readonly environment: EnvironmentPresentation;
224 readonly access: Exclude<ProviderEnvironmentAccess, { kind: "editable" | "read-only" }>;
225 readonly deviceTabs?: ReactNode;
226}) {
227 const isLoading = access.kind === "loading";
228 const title = isLoading
229 ? "Loading provider settings"
230 : access.kind === "error"
231 ? "Could not connect to this device"
232 : "Provider settings are unavailable";
233 // Keep the description to a short status; the raw failure can be a
234 // multi-paragraph CLI dump, so it goes below, clamped and expandable.
235 const description = isLoading
236 ? access.reason === "permissions"
237 ? "Checking what this session is allowed to change."
238 : `Waiting for ${environment.label}'s configuration.`
239 : connectionStatusTitle(environment.connection);
240 const error = isLoading ? null : environment.connection.error;
241 // No spinner: this state can persist indefinitely for a wedged device, and a
242 // continuously repainting animation would run the whole time.
243 return (
244 <ProviderSettingsPlaceholder
245 deviceTabs={deviceTabs}
246 icon={
247 <EnvironmentMachineIcon kind={resolveEnvironmentMachineKind(environment.serverConfig)} />
248 }
249 title={title}
250 description={description}
251 >
252 {error ? (
253 <ExpandableText
254 key={environment.environmentId}
255 text={error}
256 className="w-full text-left font-mono text-xs leading-relaxed text-muted-foreground"
257 />
258 ) : null}
259 </ProviderSettingsPlaceholder>
260 );
261}
262
263interface ProviderSettingsTarget {
264 readonly environmentId?: EnvironmentId;
265 readonly instanceId?: ProviderInstanceId;
266}
267
268export function ProviderSettingsPanel(target: ProviderSettingsTarget) {
269 return (
270 <SettingsPageContainer width="wide" className="gap-8">
271 <ProviderSettingsPanelContent
272 key={`${target.environmentId ?? ""}:${target.instanceId ?? ""}`}
273 {...target}
274 />
275 </SettingsPageContainer>
276 );
277}
278
279function ProviderSettingsPanelContent(target: ProviderSettingsTarget) {
280 const { environments, isReady } = useEnvironments();
281 const primaryEnvironmentId = usePrimaryEnvironmentId();
282 const searchTargetId = useSettingsSearchTargetId();
283 const options = useMemo(
284 () => buildProviderEnvironmentOptions(environments, primaryEnvironmentId),
285 [environments, primaryEnvironmentId],
286 );
287 // Raw user intent; the effective selection is re-derived every render so a
288 // device that drops out of the catalog falls back without erasing the pick —
289 // if it reappears (e.g. after a reconnect) the selection is restored.
290 const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<EnvironmentId | null>(
291 target.environmentId ?? primaryEnvironmentId,
292 );
293 const targetEnvironmentMissing =
294 target.environmentId !== undefined &&
295 selectedEnvironmentId === target.environmentId &&
296 !options.some((environment) => environment.environmentId === target.environmentId);
297 const effectiveEnvironmentId = targetEnvironmentMissing
298 ? target.environmentId
299 : resolveSelectedProviderEnvironmentId(options, selectedEnvironmentId, primaryEnvironmentId);
300 const selectedEnvironment =
301 options.find((environment) => environment.environmentId === effectiveEnvironmentId) ?? null;
302 const selectedEnvironmentCanRenderSettings =
303 selectedEnvironment !== null &&
304 isProviderSettingsEnvironmentAvailable({
305 connectionPhase: selectedEnvironment.connection.phase,
306 hasServerConfig: selectedEnvironment.serverConfig !== null,
307 });
308 const searchableEnvironmentId = options.find((environment) =>
309 isProviderSettingsEnvironmentAvailable({
310 connectionPhase: environment.connection.phase,
311 hasServerConfig: environment.serverConfig !== null,
312 }),
313 )?.environmentId;
314 useEffect(() => {
315 if (
316 (searchTargetId === searchableSetting("provider-health-check-interval").id ||
317 searchTargetId === searchableSetting("usage-providers").id) &&
318 !selectedEnvironmentCanRenderSettings &&
319 searchableEnvironmentId !== undefined
320 ) {
321 setSelectedEnvironmentId(searchableEnvironmentId);
322 }
323 }, [searchTargetId, searchableEnvironmentId, selectedEnvironmentCanRenderSettings]);
324 const onlyPrimaryDevice =
325 options.length === 1 && options[0]?.entry.target._tag === "PrimaryConnectionTarget";
326 const deviceTabs =
327 !onlyPrimaryDevice && options.length > 0 ? (
328 <ScrollArea hideScrollbars scrollFade className="h-11 min-w-0 flex-1 rounded-none">
329 <ToggleGroup
330 aria-label="Devices"
331 variant="segmented"
332 className="my-2"
333 value={effectiveEnvironmentId ? [effectiveEnvironmentId] : []}
334 onValueChange={(next) => {
335 const environment = options.find((option) => option.environmentId === next[0]);
336 if (environment) setSelectedEnvironmentId(environment.environmentId);
337 }}
338 >
339 {options.map((environment) => {
340 const machine = resolveEnvironmentMachineKind(environment.serverConfig);
341 const detail = providerEnvironmentDetail(environment);
342 const statusText = connectionStatusTitle(environment.connection);
343 return (
344 <Tooltip key={environment.environmentId}>
345 <TooltipTrigger
346 render={
347 <Toggle value={environment.environmentId} className="gap-2 text-left">
348 <EnvironmentMachineIcon
349 kind={machine}
350 className="size-3.5 shrink-0"
351 aria-hidden
352 />
353 <span className="max-w-40 truncate">{environment.label}</span>
354 {environment.connection.phase !== "connected" ? (
355 <ConnectionStatusDot
356 dotClassName={connectionPhaseDotClassName(environment.connection.phase)}
357 pingClassName={connectionPhasePingClassName(environment.connection.phase)}
358 />
359 ) : null}
360 <span className="sr-only">
361 {detail}, {statusText}
362 </span>
363 </Toggle>
364 }
365 />
366 <TooltipPopup side="top">
367 {detail} · {statusText}
368 </TooltipPopup>
369 </Tooltip>
370 );
371 })}
372 </ToggleGroup>
373 </ScrollArea>
374 ) : null;
375
376 return (
377 <>
378 {targetEnvironmentMissing ? (
379 <ProviderSettingsPlaceholder
380 deviceTabs={deviceTabs}
381 icon={<EnvironmentMachineIcon kind={resolveEnvironmentMachineKind(null)} />}
382 title="Device unavailable"
383 description="Reconnect this device to set up its provider, or select another device."
384 />
385 ) : null}
386 {options.length === 0 && !targetEnvironmentMissing ? (
387 <ProviderSettingsPlaceholder
388 icon={<EnvironmentMachineIcon kind={resolveEnvironmentMachineKind(null)} />}
389 title={isReady ? "No connected devices" : "Loading devices"}
390 description={
391 isReady
392 ? "Connect an execution environment before configuring providers."
393 : "Reading connected execution environments."
394 }
395 />
396 ) : null}
397
398 {selectedEnvironment ? (
399 <SelectedEnvironmentProviderSettings
400 key={selectedEnvironment.environmentId}
401 environment={selectedEnvironment}
402 deviceTabs={deviceTabs}
403 targetInstanceId={
404 target.environmentId === undefined ||
405 selectedEnvironment.environmentId === target.environmentId
406 ? target.instanceId
407 : undefined
408 }
409 />
410 ) : null}
411 </>
412 );
413}
414
415function SelectedEnvironmentProviderSettings({
416 environment,
417 deviceTabs,
418 targetInstanceId,
419}: {
420 readonly environment: EnvironmentPresentation;
421 readonly deviceTabs?: ReactNode;
422 readonly targetInstanceId?: ProviderInstanceId | undefined;
423}) {
424 const isPrimary = environment.entry.target._tag === "PrimaryConnectionTarget";
425 if (isPrimary) {
426 // The desktop app owns its primary server outright; a browser session
427 // checks the scopes its cookie session was granted.
428 if (isElectron) {
429 return (
430 <AccessGatedProviderSettings
431 environment={environment}
432 operateAccess="granted"
433 deviceTabs={deviceTabs}
434 targetInstanceId={targetInstanceId}
435 />
436 );
437 }
438 return (
439 <PrimarySessionGatedProviderSettings
440 environment={environment}
441 deviceTabs={deviceTabs}
442 targetInstanceId={targetInstanceId}
443 />
444 );
445 }
446 return (
447 <RemoteSessionGatedProviderSettings
448 environment={environment}
449 deviceTabs={deviceTabs}
450 targetInstanceId={targetInstanceId}
451 />
452 );
453}
454
455function PrimarySessionGatedProviderSettings({
456 environment,
457 deviceTabs,
458 targetInstanceId,
459}: {
460 readonly environment: EnvironmentPresentation;
461 readonly deviceTabs?: ReactNode;
462 readonly targetInstanceId?: ProviderInstanceId | undefined;
463}) {
464 const primarySessionState = usePrimarySessionState();
465 const operateAccess = resolvePrimaryOperateAccess({
466 isPrimary: true,
467 hasDesktopBridge: false,
468 session: primarySessionState.data,
469 isPending: primarySessionState.isPending,
470 hasError: primarySessionState.error !== null,
471 });
472 return (
473 <AccessGatedProviderSettings
474 environment={environment}
475 operateAccess={operateAccess}
476 deviceTabs={deviceTabs}
477 targetInstanceId={targetInstanceId}
478 />
479 );
480}
481
482function RemoteSessionGatedProviderSettings({
483 environment,
484 deviceTabs,
485 targetInstanceId,
486}: {
487 readonly environment: EnvironmentPresentation;
488 readonly deviceTabs?: ReactNode;
489 readonly targetInstanceId?: ProviderInstanceId | undefined;
490}) {
491 const sessionState = useEnvironmentSessionState(environment.environmentId);
492 const operateAccess = resolveRemoteOperateAccess({
493 session: sessionState.data,
494 isPending: sessionState.isPending,
495 hasError: sessionState.hasError,
496 });
497 return (
498 <AccessGatedProviderSettings
499 environment={environment}
500 operateAccess={operateAccess}
501 deviceTabs={deviceTabs}
502 targetInstanceId={targetInstanceId}
503 />
504 );
505}
506
507function AccessGatedProviderSettings({
508 environment,
509 operateAccess,
510 deviceTabs,
511 targetInstanceId,
512}: {
513 readonly environment: EnvironmentPresentation;
514 readonly operateAccess: ProviderOperateAccess;
515 readonly deviceTabs?: ReactNode;
516 readonly targetInstanceId?: ProviderInstanceId | undefined;
517}) {
518 const access = classifyProviderEnvironmentAccess({
519 connectionPhase: environment.connection.phase,
520 hasServerConfig: environment.serverConfig !== null,
521 operateAccess,
522 });
523 if (access.kind !== "editable" && access.kind !== "read-only") {
524 return (
525 <EnvironmentUnavailablePlaceholder
526 environment={environment}
527 access={access}
528 deviceTabs={deviceTabs}
529 />
530 );
531 }
532 return (
533 <EnvironmentProviderSettings
534 environmentId={environment.environmentId}
535 environmentLabel={environment.label}
536 readOnly={access.kind === "read-only"}
537 deviceTabs={deviceTabs}
538 targetInstanceId={targetInstanceId}
539 />
540 );
541}
542
543export function EnvironmentProviderSettings({
544 environmentId,
545 environmentLabel,
546 readOnly = false,
547 deviceTabs,
548 targetInstanceId,
549}: {
550 readonly environmentId: EnvironmentId;
551 readonly environmentLabel: string;
552 readonly deviceTabs?: ReactNode;
553 readonly targetInstanceId?: ProviderInstanceId | undefined;
554 /**
555 * Grey out and freeze every write control when this session's credential
556 * lacks `orchestration:operate` on the environment. Selecting providers
557 * still works so the real configuration stays readable; switches, forms,
558 * and the health interval are inert so no write is offered and then rejected.
559 */
560 readonly readOnly?: boolean;
561}) {
562 const settings = useEnvironmentSettings(environmentId);
563 const updateSettings = useUpdateEnvironmentSettings(environmentId);
564 const serverProviders =
565 useAtomValue(serverEnvironment.providersValueAtom(environmentId)) ?? EMPTY_SERVER_PROVIDERS;
566 const refreshServerProviders = useAtomCommand(serverEnvironment.refreshProviders, {
567 reportFailure: false,
568 });
569 const updateProvider = useAtomCommand(serverEnvironment.updateProvider, {
570 reportFailure: false,
571 });
572 const [isRefreshingProviders, setIsRefreshingProviders] = useState(false);
573 const [isAddInstanceDialogOpen, setIsAddInstanceDialogOpen] = useState(false);
574 const [selectedInstanceId, setSelectedInstanceId] = useState<ProviderInstanceId | null>(
575 targetInstanceId ?? null,
576 );
577 const [updatingProviderDrivers, setUpdatingProviderDrivers] = useState<
578 ReadonlySet<ProviderDriverKind>
579 >(() => new Set());
580 const refreshingRef = useRef(false);
581 const updatingDriversRef = useRef<Set<ProviderDriverKind>>(new Set());
582
583 const providerUpdateCandidates = useMemo(
584 () => collectProviderUpdateCandidates(serverProviders),
585 [serverProviders],
586 );
587 const providerUpdateCandidateByInstanceId = useMemo(
588 () => new Map(providerUpdateCandidates.map((candidate) => [candidate.instanceId, candidate])),
589 [providerUpdateCandidates],
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: ProviderUpdateCandidate) => {
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 (updatingDriversRef.current.has(candidate.driver)) {
643 return;
644 }
645 updatingDriversRef.current.add(candidate.driver);
646 setUpdatingProviderDrivers((previous) => new Set(previous).add(candidate.driver));
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 updatingDriversRef.current.delete(candidate.driver);
669 setUpdatingProviderDrivers((previous) => {
670 if (!previous.has(candidate.driver)) {
671 return previous;
672 }
673 const next = new Set(previous);
674 next.delete(candidate.driver);
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 = liveProvider
876 ? providerUpdateCandidateByInstanceId.get(liveProvider.instanceId)
877 : undefined;
878 const isDriverUpdateRunning =
879 updateCandidate !== undefined &&
880 (updatingProviderDrivers.has(updateCandidate.driver) ||
881 serverProviders.some(
882 (provider) =>
883 provider.driver === updateCandidate.driver && isProviderUpdateActive(provider),
884 ));
885 const showInlineUpdateButton =
886 updateCandidate !== undefined &&
887 hasOneClickUpdateProviderCandidate(updateCandidate, serverProviders);
888 const canRunInlineUpdate =
889 updateCandidate !== undefined &&
890 canOneClickUpdateProviderCandidate(updateCandidate, serverProviders) &&
891 !updatingProviderDrivers.has(updateCandidate.driver);
892 const modelPreferences = settings.providerModelPreferences?.[row.instanceId] ?? {
893 hiddenModels: [],
894 modelOrder: [],
895 };
896 const favoriteModels = Arr.filterMap(settings.favorites ?? [], (favorite) =>
897 favorite.provider === row.instanceId ? Result.succeed(favorite.model) : Result.failVoid,
898 );
899 const resetLabel = driverOption?.label ?? String(row.driver);
900
901 return (
902 <ProviderInstanceCard
903 key={row.instanceId}
904 instanceId={row.instanceId}
905 instance={row.instance}
906 driverOption={driverOption}
907 liveProvider={liveProvider}
908 mode={mode}
909 selected={mode === "list" && selectedRow?.instanceId === row.instanceId}
910 onSelect={mode === "list" ? () => setSelectedInstanceId(row.instanceId) : undefined}
911 readOnly={readOnly}
912 setup={
913 mode === "editor" && row.driver === "antigravity" ? (
914 <ProviderSetupSection
915 environmentId={environmentId}
916 environmentLabel={environmentLabel}
917 instanceId={row.instanceId}
918 provider={liveProvider}
919 binaryPath={configuredBinaryPath(row.instance.config)}
920 authMethod={readAntigravityAuthMethod(row.instance.config)}
921 enabled={resolveProviderInstanceEnabled(row.instance)}
922 readOnly={readOnly}
923 onEnable={() => updateProviderInstance(row, { ...row.instance, enabled: true })}
924 />
925 ) : null
926 }
927 onUpdate={(next) => {
928 const wasEnabled = resolveProviderInstanceEnabled(row.instance);
929 const isDisabling = next.enabled === false && wasEnabled;
930 const shouldClearTextGen = isDisabling && textGenInstanceId === row.instanceId;
931 updateProviderInstance(
932 row,
933 next,
934 shouldClearTextGen
935 ? {
936 textGenerationModelSelection:
937 DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection,
938 }
939 : undefined,
940 );
941 }}
942 onDelete={
943 mode === "editor" && !row.isDefault
944 ? () => deleteProviderInstance(row.instanceId)
945 : undefined
946 }
947 headerAction={
948 mode === "editor" && row.isDefault && row.isDirty ? (
949 <SettingResetButton
950 label={`${resetLabel} provider settings`}
951 onClick={() => resetDefaultInstance(row.driver)}
952 />
953 ) : null
954 }
955 hiddenModels={modelPreferences.hiddenModels}
956 favoriteModels={favoriteModels}
957 modelOrder={modelPreferences.modelOrder}
958 onHiddenModelsChange={(hiddenModels) =>
959 updateProviderModelPreferences(row.instanceId, {
960 ...modelPreferences,
961 hiddenModels,
962 })
963 }
964 onFavoriteModelsChange={(next) => updateProviderFavoriteModels(row.instanceId, next)}
965 onModelOrderChange={(modelOrder) =>
966 updateProviderModelPreferences(row.instanceId, {
967 ...modelPreferences,
968 modelOrder,
969 })
970 }
971 onRunUpdate={
972 mode === "editor" && showInlineUpdateButton && updateCandidate
973 ? () => {
974 if (canRunInlineUpdate) void runProviderUpdate(updateCandidate);
975 }
976 : undefined
977 }
978 isUpdating={mode === "editor" && showInlineUpdateButton ? isDriverUpdateRunning : undefined}
979 />
980 );
981 };
982
983 return (
984 <>
985 <SettingsSection {...searchableSetting("providers")} hideTitle variant="plain">
986 <div className="flex min-h-11 min-w-0 items-center gap-2 px-3 sm:px-4">
987 {deviceTabs}
988 <div className="ml-auto flex min-w-0 shrink-0 items-center gap-2">
989 {readOnly ? (
990 <span className="min-w-0 truncate text-xs text-muted-foreground">
991 <ProviderLastChecked lastCheckedAt={lastCheckedAt} />
992 </span>
993 ) : (
994 <>
995 <Tooltip>
996 <TooltipTrigger
997 render={
998 <Button
999 size="xs"
1000 variant="ghost-muted"
1001 disabled={isRefreshingProviders}
1002 aria-busy={isRefreshingProviders}
1003 onClick={() => void refreshProviders()}
1004 >
1005 <RefreshCwIcon />
1006 <span className="sr-only">Refresh provider status</span>
1007 <span className="hidden min-w-0 truncate sm:inline">
1008 {isRefreshingProviders ? (
1009 "Refreshing providers"
1010 ) : (
1011 <ProviderLastChecked lastCheckedAt={lastCheckedAt} />
1012 )}
1013 </span>
1014 </Button>
1015 }
1016 />
1017 <TooltipPopup side="top">Refresh provider status</TooltipPopup>
1018 </Tooltip>
1019 <Tooltip>
1020 <TooltipTrigger
1021 render={
1022 <Button
1023 size="icon-xs"
1024 variant="ghost-muted"
1025 onClick={() => setIsAddInstanceDialogOpen(true)}
1026 aria-label="Add provider"
1027 >
1028 <PlusIcon />
1029 </Button>
1030 }
1031 />
1032 <TooltipPopup side="top">Add provider</TooltipPopup>
1033 </Tooltip>
1034 </>
1035 )}
1036 </div>
1037 </div>
1038 {readOnly ? (
1039 <div className={cn(providerCardClassName, "overflow-hidden")}>
1040 <SettingsRow
1041 title="Limited permissions"
1042 description={`This session can view ${environmentLabel}'s providers but can't change their settings.`}
1043 />
1044 </div>
1045 ) : null}
1046 <div
1047 className={cn(
1048 providerCardClassName,
1049 providerCardHeightClassName,
1050 "overflow-hidden lg:grid lg:grid-cols-[17rem_minmax(0,1fr)]",
1051 )}
1052 >
1053 <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">
1054 <ScrollArea scrollFade chainVerticalScroll className="lg:min-h-0 lg:flex-1">
1055 <div className="divide-y divide-border/50">
1056 {rows.map((row) => renderProviderInstance(row, "list"))}
1057 </div>
1058 </ScrollArea>
1059 </div>
1060
1061 <div className="min-w-0 lg:min-h-0">
1062 {selectedRow ? (
1063 <ScrollArea scrollFade chainVerticalScroll className="lg:h-full">
1064 <div className="space-y-6 p-4">{renderProviderInstance(selectedRow, "editor")}</div>
1065 </ScrollArea>
1066 ) : (
1067 <div className="p-6 text-sm text-muted-foreground">
1068 {targetInstanceMissing
1069 ? "This provider instance is no longer available on this device."
1070 : "No providers configured."}
1071 </div>
1072 )}
1073 </div>
1074 </div>
1075 </SettingsSection>
1076
1077 <UsageProviderSettings
1078 key={environmentId}
1079 environmentId={environmentId}
1080 environmentLabel={environmentLabel}
1081 sources={settings.usageLimitSources}
1082 readOnly={readOnly}
1083 />
1084
1085 <SettingsSection title="Advanced">
1086 <SettingsRow
1087 id={searchableSetting("provider-health-check-interval").id}
1088 title={
1089 <span className="inline-flex items-center gap-1.5">
1090 {searchableSetting("provider-health-check-interval").title}
1091 <PolicyTooltip>
1092 This interval is configured here, then the shared Background activity policy decides
1093 whether provider probes may run when the timer fires. Custom intervals appear as
1094 Advanced in General settings.
1095 </PolicyTooltip>
1096 </span>
1097 }
1098 description="Refresh provider status, versions, and models in the background. Set to 0 to disable."
1099 resetAction={
1100 providerHealthRefreshIntervalSeconds !== defaultProviderHealthRefreshIntervalSeconds ? (
1101 <span inert={readOnly} className={readOnly ? "opacity-50" : undefined}>
1102 <SettingResetButton
1103 label="provider health check interval"
1104 onClick={() =>
1105 updateSettings(
1106 backgroundActivityOverrideSettings(
1107 settings.backgroundActivity,
1108 resolvedBackgroundActivity,
1109 { providerHealthRefreshInterval: undefined },
1110 ),
1111 )
1112 }
1113 />
1114 </span>
1115 ) : null
1116 }
1117 control={
1118 <div
1119 inert={readOnly}
1120 aria-disabled={readOnly || undefined}
1121 className={cn(
1122 "flex shrink-0 items-center gap-2",
1123 readOnly && "opacity-50 select-none",
1124 )}
1125 >
1126 <NumberField
1127 value={providerHealthRefreshIntervalSeconds}
1128 min={0}
1129 step={PROVIDER_HEALTH_INTERVAL_STEP_SECONDS}
1130 size="sm"
1131 className="w-32"
1132 onValueChange={(value) =>
1133 updateSettings(
1134 backgroundActivityOverrideSettings(
1135 settings.backgroundActivity,
1136 resolvedBackgroundActivity,
1137 {
1138 providerHealthRefreshInterval: Duration.seconds(
1139 normalizeIntervalSeconds(value),
1140 ),
1141 },
1142 ),
1143 )
1144 }
1145 >
1146 <NumberFieldGroup>
1147 <NumberFieldDecrement aria-label="Decrease provider health check interval" />
1148 <NumberFieldInput aria-label="Provider health check interval in seconds" />
1149 <NumberFieldIncrement aria-label="Increase provider health check interval" />
1150 </NumberFieldGroup>
1151 </NumberField>
1152 <span className="text-xs text-muted-foreground">seconds</span>
1153 </div>
1154 }
1155 />
1156 </SettingsSection>
1157
1158 {isAddInstanceDialogOpen ? (
1159 <AddProviderInstanceDialog
1160 open
1161 environmentId={environmentId}
1162 environmentLabel={environmentLabel}
1163 onOpenChange={setIsAddInstanceDialogOpen}
1164 />
1165 ) : null}
1166 </>
1167 );
1168}