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