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