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