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