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>
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 radius="none" hideScrollbars scrollFade className="h-11 min-w-0 flex-1">
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 (
653 candidate: Pick<ProviderSettingsUpdateCandidate, "driver" | "instanceId">,
654 targetVersion?: string,
655 ) => {
656 // Ref-based re-entry guard, mirroring refreshProviders: a state updater
657 // may run after this function returns, so it cannot gate the dispatch.
658 if (updatingInstanceIdsRef.current.has(candidate.instanceId)) {
659 return;
660 }
661 updatingInstanceIdsRef.current.add(candidate.instanceId);
662 setUpdatingProviderInstanceIds((previous) => new Set(previous).add(candidate.instanceId));
663
664 const result = await updateProvider({
665 environmentId,
666 input: {
667 provider: candidate.driver,
668 instanceId: candidate.instanceId,
669 ...(targetVersion ? { targetVersion } : {}),
670 },
671 });
672 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
673 const error = squashAtomCommandFailure(result);
674 toastManager.add(
675 stackedThreadToast({
676 type: "error",
677 title: `Could not update ${PROVIDER_DISPLAY_NAMES[candidate.driver] ?? candidate.driver}`,
678 description:
679 error instanceof Error
680 ? error.message
681 : "The provider update command could not be started.",
682 }),
683 );
684 }
685 updatingInstanceIdsRef.current.delete(candidate.instanceId);
686 setUpdatingProviderInstanceIds((previous) => {
687 if (!previous.has(candidate.instanceId)) {
688 return previous;
689 }
690 const next = new Set(previous);
691 next.delete(candidate.instanceId);
692 return next;
693 });
694 },
695 [environmentId, updateProvider],
696 );
697
698 interface InstanceRow {
699 readonly instanceId: ProviderInstanceId;
700 readonly instance: ProviderInstanceConfig;
701 readonly driver: ProviderDriverKind;
702 readonly isDefault: boolean;
703 readonly isDirty?: boolean;
704 }
705
706 const instancesByDriver = new Map<
707 ProviderDriverKind,
708 Array<[ProviderInstanceId, ProviderInstanceConfig]>
709 >();
710 for (const [rawId, instance] of Object.entries(settings.providerInstances ?? {})) {
711 const driver = instance.driver;
712 const list = instancesByDriver.get(driver) ?? [];
713 list.push([rawId as ProviderInstanceId, instance]);
714 instancesByDriver.set(driver, list);
715 }
716
717 const defaultSlotIdsBySource = new Set<string>(
718 visibleProviderSettings.map((providerSettings) =>
719 String(defaultInstanceIdForDriver(providerSettings.provider)),
720 ),
721 );
722
723 const rows: InstanceRow[] = [];
724 const visibleDriverKinds = new Set<ProviderDriverKind>(
725 visibleProviderSettings.map((providerSettings) => providerSettings.provider),
726 );
727
728 for (const providerSettings of visibleProviderSettings) {
729 type LegacyProviderSettings = (typeof settings.providers)[keyof typeof settings.providers];
730 const legacyProviders = settings.providers as Record<string, LegacyProviderSettings>;
731 const defaultLegacyProviders = DEFAULT_UNIFIED_SETTINGS.providers as Record<
732 string,
733 LegacyProviderSettings
734 >;
735 const driver = providerSettings.provider;
736 const defaultInstanceId = defaultInstanceIdForDriver(driver);
737 const explicitInstance = settings.providerInstances?.[defaultInstanceId];
738 // A remote device may run a server version whose settings predate this
739 // driver, so the legacy mirror can be absent. Without either an explicit
740 // instance or a legacy blob there is nothing to render for the slot.
741 const legacyConfig = legacyProviders[providerSettings.provider];
742 const defaultLegacyConfig = defaultLegacyProviders[providerSettings.provider];
743 // The envelope is the single enabled flag: keep the legacy in-config
744 // flag out of the synthesized blob, or an explicit `enabled: false`
745 // would keep winning over the envelope and the Switch could never
746 // turn a default-off provider on.
747 const synthesizedInstance = (): ProviderInstanceConfig | undefined => {
748 if (legacyConfig === undefined) {
749 return undefined;
750 }
751 const { enabled: legacyEnabled, ...legacyConfigRest } = legacyConfig;
752 return {
753 driver,
754 enabled: legacyEnabled,
755 config: legacyConfigRest,
756 } satisfies ProviderInstanceConfig;
757 };
758 const effectiveInstance: ProviderInstanceConfig | undefined =
759 explicitInstance ?? synthesizedInstance();
760 // Only the default slot depends on the legacy blob; custom instances for
761 // the driver must still render even when the slot has nothing to show.
762 if (effectiveInstance !== undefined) {
763 const isDirty =
764 explicitInstance !== undefined || !Equal.equals(legacyConfig, defaultLegacyConfig);
765 rows.push({
766 instanceId: defaultInstanceId,
767 instance: effectiveInstance,
768 driver,
769 isDefault: true,
770 isDirty,
771 });
772 }
773 for (const [id, instance] of instancesByDriver.get(providerSettings.provider) ?? []) {
774 if (id === defaultInstanceId) continue;
775 rows.push({ instanceId: id, instance, driver: instance.driver, isDefault: false });
776 }
777 }
778 for (const [driver, list] of instancesByDriver) {
779 if (visibleDriverKinds.has(driver)) continue;
780 for (const [id, instance] of list) {
781 rows.push({
782 instanceId: id,
783 instance,
784 driver: instance.driver,
785 isDefault: defaultSlotIdsBySource.has(String(id)),
786 });
787 }
788 }
789
790 const targetInstanceMissing =
791 targetInstanceId !== undefined &&
792 selectedInstanceId === targetInstanceId &&
793 !rows.some((row) => row.instanceId === targetInstanceId);
794 const selectedRow =
795 rows.find((row) => row.instanceId === selectedInstanceId) ??
796 (targetInstanceMissing ? null : (rows[0] ?? null));
797
798 const updateProviderInstance = (
799 row: InstanceRow,
800 next: ProviderInstanceConfig,
801 options?: {
802 readonly textGenerationModelSelection?: Parameters<
803 typeof buildProviderInstanceUpdatePatch
804 >[0]["textGenerationModelSelection"];
805 },
806 ) => {
807 updateSettings(
808 buildProviderInstanceUpdatePatch({
809 settings,
810 instanceId: row.instanceId,
811 instance: next,
812 driver: row.driver,
813 isDefault: row.isDefault,
814 textGenerationModelSelection: options?.textGenerationModelSelection,
815 }),
816 );
817 };
818
819 const deleteProviderInstance = (id: ProviderInstanceId) => {
820 updateSettings({
821 providerInstances: withoutProviderInstanceKey(settings.providerInstances, id),
822 });
823 };
824
825 const updateProviderModelPreferences = (
826 instanceId: ProviderInstanceId,
827 next: {
828 readonly hiddenModels: ReadonlyArray<string>;
829 readonly modelOrder: ReadonlyArray<string>;
830 },
831 ) => {
832 const hiddenModels = [...new Set(next.hiddenModels.filter((slug) => slug.trim().length > 0))];
833 const modelOrder = [...new Set(next.modelOrder.filter((slug) => slug.trim().length > 0))];
834 const rest = withoutProviderInstanceKey(settings.providerModelPreferences, instanceId);
835 updateClientSettings({
836 providerModelPreferences:
837 hiddenModels.length === 0 && modelOrder.length === 0
838 ? rest
839 : {
840 ...rest,
841 [instanceId]: {
842 hiddenModels,
843 modelOrder,
844 },
845 },
846 });
847 };
848
849 const updateProviderFavoriteModels = (
850 instanceId: ProviderInstanceId,
851 nextFavoriteModels: ReadonlyArray<string>,
852 ) => {
853 const favoriteModels = [
854 ...new Set(
855 Arr.filterMap(nextFavoriteModels, (slug) => {
856 const trimmedSlug = slug.trim();
857 return trimmedSlug.length > 0 ? Result.succeed(trimmedSlug) : Result.failVoid;
858 }),
859 ),
860 ];
861 updateClientSettings({
862 favorites: [
863 ...withoutProviderInstanceFavorites(settings.favorites ?? [], instanceId),
864 ...favoriteModels.map((model) => ({ provider: instanceId, model })),
865 ],
866 });
867 };
868
869 const resetDefaultInstance = (driverKind: ProviderDriverKind) => {
870 type LegacyProviderSettings = (typeof settings.providers)[keyof typeof settings.providers];
871 const defaultLegacyProviders = DEFAULT_UNIFIED_SETTINGS.providers as Record<
872 string,
873 LegacyProviderSettings | undefined
874 >;
875 const defaultInstanceId = defaultInstanceIdForDriver(driverKind);
876 const defaultLegacyProvider = defaultLegacyProviders[driverKind];
877 if (defaultLegacyProvider === undefined) return;
878 updateSettings({
879 providers: {
880 ...settings.providers,
881 [driverKind]: defaultLegacyProvider,
882 } as typeof settings.providers,
883 providerInstances: withoutProviderInstanceKey(settings.providerInstances, defaultInstanceId),
884 });
885 };
886
887 const renderProviderInstance = (row: InstanceRow, mode: "list" | "editor") => {
888 const driverOption = getDriverOption(row.driver);
889 const liveProvider = serverProviders.find(
890 (candidate) => candidate.instanceId === row.instanceId,
891 );
892 const updateCandidate = providerUpdateCandidateByInstanceId.get(row.instanceId);
893 const isInstanceUpdateRunning =
894 updatingProviderInstanceIds.has(row.instanceId) ||
895 (liveProvider !== undefined && isProviderUpdateActive(liveProvider));
896 const showInlineUpdateButton = updateCandidate !== undefined;
897 const canRunInlineUpdate = updateCandidate !== undefined && !isInstanceUpdateRunning;
898 const modelPreferences = settings.providerModelPreferences?.[row.instanceId] ?? {
899 hiddenModels: [],
900 modelOrder: [],
901 };
902 const favoriteModels = Arr.filterMap(settings.favorites ?? [], (favorite) =>
903 favorite.provider === row.instanceId ? Result.succeed(favorite.model) : Result.failVoid,
904 );
905 const resetLabel = driverOption?.label ?? String(row.driver);
906
907 return (
908 <ProviderInstanceCard
909 key={row.instanceId}
910 instanceId={row.instanceId}
911 instance={row.instance}
912 driverOption={driverOption}
913 liveProvider={liveProvider}
914 mode={mode}
915 selected={mode === "list" && selectedRow?.instanceId === row.instanceId}
916 onSelect={mode === "list" ? () => setSelectedInstanceId(row.instanceId) : undefined}
917 readOnly={readOnly}
918 setup={
919 mode === "editor" && row.driver === "antigravity" ? (
920 <ProviderSetupSection
921 environmentId={environmentId}
922 environmentLabel={environmentLabel}
923 instanceId={row.instanceId}
924 provider={liveProvider}
925 binaryPath={configuredBinaryPath(row.instance.config)}
926 authMethod={readAntigravityAuthMethod(row.instance.config)}
927 enabled={resolveProviderInstanceEnabled(row.instance)}
928 readOnly={readOnly}
929 onEnable={() => updateProviderInstance(row, { ...row.instance, enabled: true })}
930 />
931 ) : null
932 }
933 onUpdate={(next) => {
934 const wasEnabled = resolveProviderInstanceEnabled(row.instance);
935 const isDisabling = next.enabled === false && wasEnabled;
936 const shouldClearTextGen = isDisabling && textGenInstanceId === row.instanceId;
937 updateProviderInstance(
938 row,
939 next,
940 shouldClearTextGen
941 ? {
942 textGenerationModelSelection:
943 DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection,
944 }
945 : undefined,
946 );
947 }}
948 onDelete={
949 mode === "editor" && !row.isDefault
950 ? () => deleteProviderInstance(row.instanceId)
951 : undefined
952 }
953 headerAction={
954 mode === "editor" && row.isDefault && row.isDirty ? (
955 <SettingResetButton
956 label={`${resetLabel} provider settings`}
957 onClick={() => resetDefaultInstance(row.driver)}
958 />
959 ) : null
960 }
961 hiddenModels={modelPreferences.hiddenModels}
962 favoriteModels={favoriteModels}
963 modelOrder={modelPreferences.modelOrder}
964 onHiddenModelsChange={(hiddenModels) =>
965 updateProviderModelPreferences(row.instanceId, {
966 ...modelPreferences,
967 hiddenModels,
968 })
969 }
970 onFavoriteModelsChange={(next) => updateProviderFavoriteModels(row.instanceId, next)}
971 onModelOrderChange={(modelOrder) =>
972 updateProviderModelPreferences(row.instanceId, {
973 ...modelPreferences,
974 modelOrder,
975 })
976 }
977 onInstallRecommended={
978 mode === "editor" &&
979 liveProvider?.compatibilityAdvisory?.message &&
980 liveProvider.compatibilityAdvisory.recommendedVersion &&
981 liveProvider.versionAdvisory?.canInstallVersion
982 ? () => {
983 void runProviderUpdate(
984 liveProvider,
985 liveProvider.compatibilityAdvisory?.recommendedVersion ?? undefined,
986 );
987 }
988 : undefined
989 }
990 onRunUpdate={
991 mode === "editor" && showInlineUpdateButton && updateCandidate
992 ? () => {
993 if (canRunInlineUpdate) void runProviderUpdate(updateCandidate);
994 }
995 : undefined
996 }
997 isUpdating={mode === "editor" ? isInstanceUpdateRunning : undefined}
998 />
999 );
1000 };
1001
1002 return (
1003 <>
1004 <SettingsSection {...searchableSetting("providers")} variant="plain">
1005 <div className="flex min-h-11 min-w-0 items-center gap-2 px-3 sm:px-4">
1006 {deviceTabs}
1007 <div className="ml-auto flex min-w-0 shrink-0 items-center gap-2">
1008 {readOnly ? (
1009 <span className="min-w-0 truncate text-xs text-muted-foreground">
1010 <ProviderLastChecked lastCheckedAt={lastCheckedAt} />
1011 </span>
1012 ) : (
1013 <>
1014 <Tooltip>
1015 <TooltipTrigger
1016 render={
1017 <Button
1018 size="xs"
1019 variant="ghost-muted"
1020 disabled={isRefreshingProviders}
1021 aria-busy={isRefreshingProviders}
1022 onClick={() => void refreshProviders()}
1023 >
1024 <RefreshIcon refreshing={isRefreshingProviders} />
1025 <span className="sr-only">Refresh provider status</span>
1026 <span className="hidden min-w-0 truncate sm:inline">
1027 {isRefreshingProviders ? (
1028 "Refreshing providers"
1029 ) : (
1030 <ProviderLastChecked lastCheckedAt={lastCheckedAt} />
1031 )}
1032 </span>
1033 </Button>
1034 }
1035 />
1036 <TooltipPopup side="top">Refresh provider status</TooltipPopup>
1037 </Tooltip>
1038 <Tooltip>
1039 <TooltipTrigger
1040 render={
1041 <Button
1042 size="icon-xs"
1043 variant="ghost-muted"
1044 onClick={() => setIsAddInstanceDialogOpen(true)}
1045 aria-label="Add provider"
1046 >
1047 <PlusIcon />
1048 </Button>
1049 }
1050 />
1051 <TooltipPopup side="top">Add provider</TooltipPopup>
1052 </Tooltip>
1053 </>
1054 )}
1055 </div>
1056 </div>
1057 {readOnly ? (
1058 <SettingsGroup divided={false} className="overflow-hidden">
1059 <SettingsRow
1060 title="Limited permissions"
1061 description={`This session can view ${environmentLabel}'s providers but can't change their settings.`}
1062 />
1063 </SettingsGroup>
1064 ) : null}
1065 <SettingsGroup
1066 divided={false}
1067 className={cn(
1068 providerCardHeightClassName,
1069 "overflow-hidden @min-[48rem]/providers:grid @min-[48rem]/providers:grid-cols-[17rem_minmax(0,1fr)]",
1070 )}
1071 >
1072 <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">
1073 <ScrollArea
1074 scrollFade
1075 chainVerticalScroll
1076 className="@min-[48rem]/providers:min-h-0 @min-[48rem]/providers:flex-1"
1077 >
1078 <div className="divide-y divide-border/50">
1079 {rows.map((row) => renderProviderInstance(row, "list"))}
1080 </div>
1081 </ScrollArea>
1082 </div>
1083
1084 <div className="min-w-0 @min-[48rem]/providers:min-h-0">
1085 {selectedRow ? (
1086 <ScrollArea scrollFade chainVerticalScroll className="@min-[48rem]/providers:h-full">
1087 <div className="space-y-6 p-4">{renderProviderInstance(selectedRow, "editor")}</div>
1088 </ScrollArea>
1089 ) : (
1090 <div className="p-6 text-sm text-muted-foreground">
1091 {targetInstanceMissing
1092 ? "This provider instance is no longer available on this device."
1093 : "No providers configured."}
1094 </div>
1095 )}
1096 </div>
1097 </SettingsGroup>
1098 </SettingsSection>
1099
1100 <UsageProviderSettings
1101 key={environmentId}
1102 environmentId={environmentId}
1103 environmentLabel={environmentLabel}
1104 sources={settings.usageLimitSources}
1105 readOnly={readOnly}
1106 />
1107
1108 <SettingsSection title="Advanced">
1109 <SettingsRow
1110 id={searchableSetting("provider-health-check-interval").id}
1111 title={
1112 <span className="inline-flex items-center gap-1.5">
1113 {searchableSetting("provider-health-check-interval").title}
1114 <PolicyTooltip>
1115 This interval is configured here, then the shared Background activity policy decides
1116 whether provider probes may run when the timer fires. Custom intervals appear as
1117 Advanced in General settings.
1118 </PolicyTooltip>
1119 </span>
1120 }
1121 description="Refresh provider status, versions, and models in the background. Set to 0 to disable."
1122 resetAction={
1123 providerHealthRefreshIntervalSeconds !== defaultProviderHealthRefreshIntervalSeconds ? (
1124 <span inert={readOnly} className={readOnly ? "opacity-50" : undefined}>
1125 <SettingResetButton
1126 label="provider health check interval"
1127 onClick={() =>
1128 updateSettings(
1129 backgroundActivityOverrideSettings(
1130 settings.backgroundActivity,
1131 resolvedBackgroundActivity,
1132 { providerHealthRefreshInterval: undefined },
1133 ),
1134 )
1135 }
1136 />
1137 </span>
1138 ) : null
1139 }
1140 control={
1141 <div
1142 inert={readOnly}
1143 aria-disabled={readOnly || undefined}
1144 className={cn(
1145 "flex shrink-0 items-center gap-2",
1146 readOnly && "opacity-50 select-none",
1147 )}
1148 >
1149 <NumberField
1150 value={providerHealthRefreshIntervalSeconds}
1151 min={0}
1152 step={PROVIDER_HEALTH_INTERVAL_STEP_SECONDS}
1153 size="sm"
1154 className="w-32"
1155 onValueChange={(value) =>
1156 updateSettings(
1157 backgroundActivityOverrideSettings(
1158 settings.backgroundActivity,
1159 resolvedBackgroundActivity,
1160 {
1161 providerHealthRefreshInterval: Duration.seconds(
1162 normalizeIntervalSeconds(value),
1163 ),
1164 },
1165 ),
1166 )
1167 }
1168 >
1169 <NumberFieldGroup>
1170 <NumberFieldDecrement aria-label="Decrease provider health check interval" />
1171 <NumberFieldInput aria-label="Provider health check interval in seconds" />
1172 <NumberFieldIncrement aria-label="Increase provider health check interval" />
1173 </NumberFieldGroup>
1174 </NumberField>
1175 <span className="text-xs text-muted-foreground">seconds</span>
1176 </div>
1177 }
1178 />
1179 </SettingsSection>
1180
1181 {isAddInstanceDialogOpen ? (
1182 <AddProviderInstanceDialog
1183 open
1184 environmentId={environmentId}
1185 environmentLabel={environmentLabel}
1186 onOpenChange={setIsAddInstanceDialogOpen}
1187 />
1188 ) : null}
1189 </>
1190 );
1191}