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 { 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 {
60 NumberField,
61 NumberFieldDecrement,
62 NumberFieldGroup,
63 NumberFieldIncrement,
64 NumberFieldInput,
65} from "../ui/number-field";
66import { ScrollArea } from "../ui/scroll-area";
67import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
68import { stackedThreadToast, toastManager } from "../ui/toast";
69import { AddProviderInstanceDialog } from "./AddProviderInstanceDialog";
70import { ProviderInstanceCard } from "./ProviderInstanceCard";
71import { UsageProviderSettings } from "./UsageProviderSettings";
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 width="wide" 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 searchTargetId === searchableSetting("usage-providers").id) &&
247 !selectedEnvironmentCanRenderSettings &&
248 searchableEnvironmentId !== undefined
249 ) {
250 setSelectedEnvironmentId(searchableEnvironmentId);
251 }
252 }, [searchTargetId, searchableEnvironmentId, selectedEnvironmentCanRenderSettings]);
253 const onlyPrimaryDevice =
254 options.length === 1 && options[0]?.entry.target._tag === "PrimaryConnectionTarget";
255 const deviceTabs =
256 !onlyPrimaryDevice && options.length > 0 ? (
257 <ScrollArea hideScrollbars scrollFade className="mx-3 h-11 min-w-0 rounded-none sm:mx-4">
258 <div role="group" aria-label="Devices" className="flex h-full w-max min-w-full px-1">
259 {options.map((environment) => {
260 const machine = resolveEnvironmentMachineKind(environment.serverConfig);
261 const selected = environment.environmentId === effectiveEnvironmentId;
262 const detail = providerEnvironmentDetail(environment);
263 const statusText = connectionStatusText(environment.connection);
264 return (
265 <Tooltip key={environment.environmentId}>
266 <TooltipTrigger
267 render={
268 <button
269 type="button"
270 aria-pressed={selected}
271 className={cn(providerSettingsTabClassName(selected), "gap-2 text-left")}
272 onClick={() => setSelectedEnvironmentId(environment.environmentId)}
273 >
274 <EnvironmentMachineIcon
275 kind={machine}
276 className="size-3.5 shrink-0"
277 aria-hidden
278 />
279 <span className="max-w-40 truncate">{environment.label}</span>
280 {environment.connection.phase !== "connected" ? (
281 <ConnectionStatusDot
282 dotClassName={connectionPhaseDotClassName(environment.connection.phase)}
283 pingClassName={connectionPhasePingClassName(environment.connection.phase)}
284 />
285 ) : null}
286 <span className="sr-only">
287 {detail}, {statusText}
288 </span>
289 </button>
290 }
291 />
292 <TooltipPopup side="top">
293 {detail} · {statusText}
294 </TooltipPopup>
295 </Tooltip>
296 );
297 })}
298 </div>
299 </ScrollArea>
300 ) : null;
301
302 return (
303 <>
304 {targetEnvironmentMissing ? (
305 <SettingsSection {...searchableSetting("providers")}>
306 {deviceTabs}
307 <SettingsRow
308 title="Device unavailable"
309 description="Reconnect this device to set up its provider, or select another device."
310 />
311 </SettingsSection>
312 ) : null}
313 {options.length === 0 && !targetEnvironmentMissing ? (
314 <SettingsSection {...searchableSetting("providers")}>
315 <SettingsRow
316 title={isReady ? "No connected devices" : "Loading devices"}
317 description={
318 isReady
319 ? "Connect an execution environment before configuring providers."
320 : "Reading connected execution environments."
321 }
322 />
323 </SettingsSection>
324 ) : null}
325
326 {selectedEnvironment ? (
327 <SelectedEnvironmentProviderSettings
328 key={selectedEnvironment.environmentId}
329 environment={selectedEnvironment}
330 deviceTabs={deviceTabs}
331 targetInstanceId={
332 target.environmentId === undefined ||
333 selectedEnvironment.environmentId === target.environmentId
334 ? target.instanceId
335 : undefined
336 }
337 />
338 ) : null}
339 </>
340 );
341}
342
343function SelectedEnvironmentProviderSettings({
344 environment,
345 deviceTabs,
346 targetInstanceId,
347}: {
348 readonly environment: EnvironmentPresentation;
349 readonly deviceTabs?: ReactNode;
350 readonly targetInstanceId?: ProviderInstanceId | undefined;
351}) {
352 const isPrimary = environment.entry.target._tag === "PrimaryConnectionTarget";
353 if (isPrimary) {
354 // The desktop app owns its primary server outright; a browser session
355 // checks the scopes its cookie session was granted.
356 if (isElectron) {
357 return (
358 <AccessGatedProviderSettings
359 environment={environment}
360 operateAccess="granted"
361 deviceTabs={deviceTabs}
362 targetInstanceId={targetInstanceId}
363 />
364 );
365 }
366 return (
367 <PrimarySessionGatedProviderSettings
368 environment={environment}
369 deviceTabs={deviceTabs}
370 targetInstanceId={targetInstanceId}
371 />
372 );
373 }
374 return (
375 <RemoteSessionGatedProviderSettings
376 environment={environment}
377 deviceTabs={deviceTabs}
378 targetInstanceId={targetInstanceId}
379 />
380 );
381}
382
383function PrimarySessionGatedProviderSettings({
384 environment,
385 deviceTabs,
386 targetInstanceId,
387}: {
388 readonly environment: EnvironmentPresentation;
389 readonly deviceTabs?: ReactNode;
390 readonly targetInstanceId?: ProviderInstanceId | undefined;
391}) {
392 const primarySessionState = usePrimarySessionState();
393 const operateAccess = resolvePrimaryOperateAccess({
394 isPrimary: true,
395 hasDesktopBridge: false,
396 session: primarySessionState.data,
397 isPending: primarySessionState.isPending,
398 hasError: primarySessionState.error !== null,
399 });
400 return (
401 <AccessGatedProviderSettings
402 environment={environment}
403 operateAccess={operateAccess}
404 deviceTabs={deviceTabs}
405 targetInstanceId={targetInstanceId}
406 />
407 );
408}
409
410function RemoteSessionGatedProviderSettings({
411 environment,
412 deviceTabs,
413 targetInstanceId,
414}: {
415 readonly environment: EnvironmentPresentation;
416 readonly deviceTabs?: ReactNode;
417 readonly targetInstanceId?: ProviderInstanceId | undefined;
418}) {
419 const sessionState = useEnvironmentSessionState(environment.environmentId);
420 const operateAccess = resolveRemoteOperateAccess({
421 session: sessionState.data,
422 isPending: sessionState.isPending,
423 hasError: sessionState.hasError,
424 });
425 return (
426 <AccessGatedProviderSettings
427 environment={environment}
428 operateAccess={operateAccess}
429 deviceTabs={deviceTabs}
430 targetInstanceId={targetInstanceId}
431 />
432 );
433}
434
435function AccessGatedProviderSettings({
436 environment,
437 operateAccess,
438 deviceTabs,
439 targetInstanceId,
440}: {
441 readonly environment: EnvironmentPresentation;
442 readonly operateAccess: ProviderOperateAccess;
443 readonly deviceTabs?: ReactNode;
444 readonly targetInstanceId?: ProviderInstanceId | undefined;
445}) {
446 const access = classifyProviderEnvironmentAccess({
447 connectionPhase: environment.connection.phase,
448 hasServerConfig: environment.serverConfig !== null,
449 operateAccess,
450 });
451 if (access.kind !== "editable" && access.kind !== "read-only") {
452 return (
453 <EnvironmentUnavailableRow
454 environment={environment}
455 access={access}
456 deviceTabs={deviceTabs}
457 />
458 );
459 }
460 return (
461 <EnvironmentProviderSettings
462 environmentId={environment.environmentId}
463 environmentLabel={environment.label}
464 readOnly={access.kind === "read-only"}
465 deviceTabs={deviceTabs}
466 targetInstanceId={targetInstanceId}
467 />
468 );
469}
470
471export function EnvironmentProviderSettings({
472 environmentId,
473 environmentLabel,
474 readOnly = false,
475 deviceTabs,
476 targetInstanceId,
477}: {
478 readonly environmentId: EnvironmentId;
479 readonly environmentLabel: string;
480 readonly deviceTabs?: ReactNode;
481 readonly targetInstanceId?: ProviderInstanceId | undefined;
482 /**
483 * Grey out and freeze every write control when this session's credential
484 * lacks `orchestration:operate` on the environment. Selecting providers
485 * still works so the real configuration stays readable; switches, forms,
486 * and the health interval are inert so no write is offered and then rejected.
487 */
488 readonly readOnly?: boolean;
489}) {
490 const settings = useEnvironmentSettings(environmentId);
491 const updateSettings = useUpdateEnvironmentSettings(environmentId);
492 const serverProviders =
493 useAtomValue(serverEnvironment.providersValueAtom(environmentId)) ?? EMPTY_SERVER_PROVIDERS;
494 const refreshServerProviders = useAtomCommand(serverEnvironment.refreshProviders, {
495 reportFailure: false,
496 });
497 const updateProvider = useAtomCommand(serverEnvironment.updateProvider, {
498 reportFailure: false,
499 });
500 const [isRefreshingProviders, setIsRefreshingProviders] = useState(false);
501 const [isAddInstanceDialogOpen, setIsAddInstanceDialogOpen] = useState(false);
502 const [selectedInstanceId, setSelectedInstanceId] = useState<ProviderInstanceId | null>(
503 targetInstanceId ?? null,
504 );
505 const [updatingProviderDrivers, setUpdatingProviderDrivers] = useState<
506 ReadonlySet<ProviderDriverKind>
507 >(() => new Set());
508 const refreshingRef = useRef(false);
509 const updatingDriversRef = useRef<Set<ProviderDriverKind>>(new Set());
510
511 const providerUpdateCandidates = useMemo(
512 () => collectProviderUpdateCandidates(serverProviders),
513 [serverProviders],
514 );
515 const providerUpdateCandidateByInstanceId = useMemo(
516 () => new Map(providerUpdateCandidates.map((candidate) => [candidate.instanceId, candidate])),
517 [providerUpdateCandidates],
518 );
519 const visibleProviderSettings = PROVIDER_SETTINGS.filter(
520 (providerSettings) =>
521 providerSettings.provider !== "cursor" ||
522 serverProviders.some(
523 (provider) =>
524 provider.instanceId === defaultInstanceIdForDriver(ProviderDriverKind.make("cursor")),
525 ),
526 );
527 const textGenerationModelSelection = resolveAppModelSelectionState(settings, serverProviders);
528 const textGenInstanceId = textGenerationModelSelection.instanceId;
529 const resolvedBackgroundActivity = resolveServerBackgroundActivitySettings(settings);
530 const providerHealthPreset = getBackgroundActivityPresetSettings(
531 resolvedBackgroundActivity.profile,
532 ).providerHealthRefreshInterval;
533 const providerHealthRefreshIntervalSeconds = durationToSeconds(
534 resolvedBackgroundActivity.providerHealthRefreshInterval,
535 );
536 const defaultProviderHealthRefreshIntervalSeconds = durationToSeconds(providerHealthPreset);
537 const lastCheckedAt =
538 serverProviders.length > 0
539 ? serverProviders.reduce(
540 (latest, provider) => (provider.checkedAt > latest ? provider.checkedAt : latest),
541 serverProviders[0]!.checkedAt,
542 )
543 : null;
544
545 const refreshProviders = useCallback(() => {
546 if (refreshingRef.current) return;
547 refreshingRef.current = true;
548 setIsRefreshingProviders(true);
549 void (async () => {
550 const result = await refreshServerProviders({
551 environmentId,
552 input: { refreshModels: true },
553 });
554 refreshingRef.current = false;
555 setIsRefreshingProviders(false);
556 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
557 console.warn("Failed to refresh providers", {
558 operation: "refresh-providers",
559 environmentId,
560 ...safeErrorLogAttributes(squashAtomCommandFailure(result)),
561 });
562 }
563 })();
564 }, [environmentId, refreshServerProviders]);
565
566 const runProviderUpdate = useCallback(
567 async (candidate: ProviderUpdateCandidate) => {
568 // Ref-based re-entry guard, mirroring refreshProviders: a state updater
569 // may run after this function returns, so it cannot gate the dispatch.
570 if (updatingDriversRef.current.has(candidate.driver)) {
571 return;
572 }
573 updatingDriversRef.current.add(candidate.driver);
574 setUpdatingProviderDrivers((previous) => new Set(previous).add(candidate.driver));
575
576 const result = await updateProvider({
577 environmentId,
578 input: {
579 provider: candidate.driver,
580 instanceId: candidate.instanceId,
581 },
582 });
583 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
584 const error = squashAtomCommandFailure(result);
585 toastManager.add(
586 stackedThreadToast({
587 type: "error",
588 title: `Could not update ${PROVIDER_DISPLAY_NAMES[candidate.driver] ?? candidate.driver}`,
589 description:
590 error instanceof Error
591 ? error.message
592 : "The provider update command could not be started.",
593 }),
594 );
595 }
596 updatingDriversRef.current.delete(candidate.driver);
597 setUpdatingProviderDrivers((previous) => {
598 if (!previous.has(candidate.driver)) {
599 return previous;
600 }
601 const next = new Set(previous);
602 next.delete(candidate.driver);
603 return next;
604 });
605 },
606 [environmentId, updateProvider],
607 );
608
609 interface InstanceRow {
610 readonly instanceId: ProviderInstanceId;
611 readonly instance: ProviderInstanceConfig;
612 readonly driver: ProviderDriverKind;
613 readonly isDefault: boolean;
614 readonly isDirty?: boolean;
615 }
616
617 const instancesByDriver = new Map<
618 ProviderDriverKind,
619 Array<[ProviderInstanceId, ProviderInstanceConfig]>
620 >();
621 for (const [rawId, instance] of Object.entries(settings.providerInstances ?? {})) {
622 const driver = instance.driver;
623 const list = instancesByDriver.get(driver) ?? [];
624 list.push([rawId as ProviderInstanceId, instance]);
625 instancesByDriver.set(driver, list);
626 }
627
628 const defaultSlotIdsBySource = new Set<string>(
629 visibleProviderSettings.map((providerSettings) =>
630 String(defaultInstanceIdForDriver(providerSettings.provider)),
631 ),
632 );
633
634 const rows: InstanceRow[] = [];
635 const visibleDriverKinds = new Set<ProviderDriverKind>(
636 visibleProviderSettings.map((providerSettings) => providerSettings.provider),
637 );
638
639 for (const providerSettings of visibleProviderSettings) {
640 type LegacyProviderSettings = (typeof settings.providers)[keyof typeof settings.providers];
641 const legacyProviders = settings.providers as Record<string, LegacyProviderSettings>;
642 const defaultLegacyProviders = DEFAULT_UNIFIED_SETTINGS.providers as Record<
643 string,
644 LegacyProviderSettings
645 >;
646 const driver = providerSettings.provider;
647 const defaultInstanceId = defaultInstanceIdForDriver(driver);
648 const explicitInstance = settings.providerInstances?.[defaultInstanceId];
649 // A remote device may run a server version whose settings predate this
650 // driver, so the legacy mirror can be absent. Without either an explicit
651 // instance or a legacy blob there is nothing to render for the slot.
652 const legacyConfig = legacyProviders[providerSettings.provider];
653 const defaultLegacyConfig = defaultLegacyProviders[providerSettings.provider];
654 // The envelope is the single enabled flag: keep the legacy in-config
655 // flag out of the synthesized blob, or an explicit `enabled: false`
656 // would keep winning over the envelope and the Switch could never
657 // turn a default-off provider on.
658 const synthesizedInstance = (): ProviderInstanceConfig | undefined => {
659 if (legacyConfig === undefined) {
660 return undefined;
661 }
662 const { enabled: legacyEnabled, ...legacyConfigRest } = legacyConfig;
663 return {
664 driver,
665 enabled: legacyEnabled,
666 config: legacyConfigRest,
667 } satisfies ProviderInstanceConfig;
668 };
669 const effectiveInstance: ProviderInstanceConfig | undefined =
670 explicitInstance ?? synthesizedInstance();
671 // Only the default slot depends on the legacy blob; custom instances for
672 // the driver must still render even when the slot has nothing to show.
673 if (effectiveInstance !== undefined) {
674 const isDirty =
675 explicitInstance !== undefined || !Equal.equals(legacyConfig, defaultLegacyConfig);
676 rows.push({
677 instanceId: defaultInstanceId,
678 instance: effectiveInstance,
679 driver,
680 isDefault: true,
681 isDirty,
682 });
683 }
684 for (const [id, instance] of instancesByDriver.get(providerSettings.provider) ?? []) {
685 if (id === defaultInstanceId) continue;
686 rows.push({ instanceId: id, instance, driver: instance.driver, isDefault: false });
687 }
688 }
689 for (const [driver, list] of instancesByDriver) {
690 if (visibleDriverKinds.has(driver)) continue;
691 for (const [id, instance] of list) {
692 rows.push({
693 instanceId: id,
694 instance,
695 driver: instance.driver,
696 isDefault: defaultSlotIdsBySource.has(String(id)),
697 });
698 }
699 }
700
701 const targetInstanceMissing =
702 targetInstanceId !== undefined &&
703 selectedInstanceId === targetInstanceId &&
704 !rows.some((row) => row.instanceId === targetInstanceId);
705 const selectedRow =
706 rows.find((row) => row.instanceId === selectedInstanceId) ??
707 (targetInstanceMissing ? null : (rows[0] ?? null));
708
709 const updateProviderInstance = (
710 row: InstanceRow,
711 next: ProviderInstanceConfig,
712 options?: {
713 readonly textGenerationModelSelection?: Parameters<
714 typeof buildProviderInstanceUpdatePatch
715 >[0]["textGenerationModelSelection"];
716 },
717 ) => {
718 updateSettings(
719 buildProviderInstanceUpdatePatch({
720 settings,
721 instanceId: row.instanceId,
722 instance: next,
723 driver: row.driver,
724 isDefault: row.isDefault,
725 textGenerationModelSelection: options?.textGenerationModelSelection,
726 }),
727 );
728 };
729
730 const deleteProviderInstance = (id: ProviderInstanceId) => {
731 updateSettings({
732 providerInstances: withoutProviderInstanceKey(settings.providerInstances, id),
733 });
734 };
735
736 const updateProviderModelPreferences = (
737 instanceId: ProviderInstanceId,
738 next: {
739 readonly hiddenModels: ReadonlyArray<string>;
740 readonly modelOrder: ReadonlyArray<string>;
741 },
742 ) => {
743 const hiddenModels = [...new Set(next.hiddenModels.filter((slug) => slug.trim().length > 0))];
744 const modelOrder = [...new Set(next.modelOrder.filter((slug) => slug.trim().length > 0))];
745 const rest = withoutProviderInstanceKey(settings.providerModelPreferences, instanceId);
746 updateSettings({
747 providerModelPreferences:
748 hiddenModels.length === 0 && modelOrder.length === 0
749 ? rest
750 : {
751 ...rest,
752 [instanceId]: {
753 hiddenModels,
754 modelOrder,
755 },
756 },
757 });
758 };
759
760 const updateProviderFavoriteModels = (
761 instanceId: ProviderInstanceId,
762 nextFavoriteModels: ReadonlyArray<string>,
763 ) => {
764 const favoriteModels = [
765 ...new Set(
766 Arr.filterMap(nextFavoriteModels, (slug) => {
767 const trimmedSlug = slug.trim();
768 return trimmedSlug.length > 0 ? Result.succeed(trimmedSlug) : Result.failVoid;
769 }),
770 ),
771 ];
772 updateSettings({
773 favorites: [
774 ...withoutProviderInstanceFavorites(settings.favorites ?? [], instanceId),
775 ...favoriteModels.map((model) => ({ provider: instanceId, model })),
776 ],
777 });
778 };
779
780 const resetDefaultInstance = (driverKind: ProviderDriverKind) => {
781 type LegacyProviderSettings = (typeof settings.providers)[keyof typeof settings.providers];
782 const defaultLegacyProviders = DEFAULT_UNIFIED_SETTINGS.providers as Record<
783 string,
784 LegacyProviderSettings | undefined
785 >;
786 const defaultInstanceId = defaultInstanceIdForDriver(driverKind);
787 const defaultLegacyProvider = defaultLegacyProviders[driverKind];
788 if (defaultLegacyProvider === undefined) return;
789 updateSettings({
790 providers: {
791 ...settings.providers,
792 [driverKind]: defaultLegacyProvider,
793 } as typeof settings.providers,
794 providerInstances: withoutProviderInstanceKey(settings.providerInstances, defaultInstanceId),
795 });
796 };
797
798 const renderProviderInstance = (row: InstanceRow, mode: "list" | "editor") => {
799 const driverOption = getDriverOption(row.driver);
800 const liveProvider = serverProviders.find(
801 (candidate) => candidate.instanceId === row.instanceId,
802 );
803 const updateCandidate = liveProvider
804 ? providerUpdateCandidateByInstanceId.get(liveProvider.instanceId)
805 : undefined;
806 const isDriverUpdateRunning =
807 updateCandidate !== undefined &&
808 (updatingProviderDrivers.has(updateCandidate.driver) ||
809 serverProviders.some(
810 (provider) =>
811 provider.driver === updateCandidate.driver && isProviderUpdateActive(provider),
812 ));
813 const showInlineUpdateButton =
814 updateCandidate !== undefined &&
815 hasOneClickUpdateProviderCandidate(updateCandidate, serverProviders);
816 const canRunInlineUpdate =
817 updateCandidate !== undefined &&
818 canOneClickUpdateProviderCandidate(updateCandidate, serverProviders) &&
819 !updatingProviderDrivers.has(updateCandidate.driver);
820 const modelPreferences = settings.providerModelPreferences?.[row.instanceId] ?? {
821 hiddenModels: [],
822 modelOrder: [],
823 };
824 const favoriteModels = Arr.filterMap(settings.favorites ?? [], (favorite) =>
825 favorite.provider === row.instanceId ? Result.succeed(favorite.model) : Result.failVoid,
826 );
827 const resetLabel = driverOption?.label ?? String(row.driver);
828
829 return (
830 <ProviderInstanceCard
831 key={row.instanceId}
832 instanceId={row.instanceId}
833 instance={row.instance}
834 driverOption={driverOption}
835 liveProvider={liveProvider}
836 mode={mode}
837 selected={mode === "list" && selectedRow?.instanceId === row.instanceId}
838 onSelect={mode === "list" ? () => setSelectedInstanceId(row.instanceId) : undefined}
839 readOnly={readOnly}
840 setup={
841 mode === "editor" && row.driver === "antigravity" ? (
842 <ProviderSetupSection
843 environmentId={environmentId}
844 environmentLabel={environmentLabel}
845 instanceId={row.instanceId}
846 provider={liveProvider}
847 binaryPath={configuredBinaryPath(row.instance.config)}
848 authMethod={readAntigravityAuthMethod(row.instance.config)}
849 enabled={resolveProviderInstanceEnabled(row.instance)}
850 readOnly={readOnly}
851 onEnable={() => updateProviderInstance(row, { ...row.instance, enabled: true })}
852 />
853 ) : null
854 }
855 onUpdate={(next) => {
856 const wasEnabled = resolveProviderInstanceEnabled(row.instance);
857 const isDisabling = next.enabled === false && wasEnabled;
858 const shouldClearTextGen = isDisabling && textGenInstanceId === row.instanceId;
859 updateProviderInstance(
860 row,
861 next,
862 shouldClearTextGen
863 ? {
864 textGenerationModelSelection:
865 DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection,
866 }
867 : undefined,
868 );
869 }}
870 onDelete={
871 mode === "editor" && !row.isDefault
872 ? () => deleteProviderInstance(row.instanceId)
873 : undefined
874 }
875 headerAction={
876 mode === "editor" && row.isDefault && row.isDirty ? (
877 <SettingResetButton
878 label={`${resetLabel} provider settings`}
879 onClick={() => resetDefaultInstance(row.driver)}
880 />
881 ) : null
882 }
883 hiddenModels={modelPreferences.hiddenModels}
884 favoriteModels={favoriteModels}
885 modelOrder={modelPreferences.modelOrder}
886 onHiddenModelsChange={(hiddenModels) =>
887 updateProviderModelPreferences(row.instanceId, {
888 ...modelPreferences,
889 hiddenModels,
890 })
891 }
892 onFavoriteModelsChange={(next) => updateProviderFavoriteModels(row.instanceId, next)}
893 onModelOrderChange={(modelOrder) =>
894 updateProviderModelPreferences(row.instanceId, {
895 ...modelPreferences,
896 modelOrder,
897 })
898 }
899 onRunUpdate={
900 mode === "editor" && showInlineUpdateButton && updateCandidate
901 ? () => {
902 if (canRunInlineUpdate) void runProviderUpdate(updateCandidate);
903 }
904 : undefined
905 }
906 isUpdating={mode === "editor" && showInlineUpdateButton ? isDriverUpdateRunning : undefined}
907 />
908 );
909 };
910
911 return (
912 <>
913 <SettingsSection
914 {...searchableSetting("providers")}
915 variant="plain"
916 headerAction={
917 <div className="flex min-w-0 items-center gap-2">
918 {readOnly ? (
919 <span className="min-w-0 truncate text-xs text-muted-foreground">
920 <ProviderLastChecked lastCheckedAt={lastCheckedAt} />
921 </span>
922 ) : (
923 <>
924 <Tooltip>
925 <TooltipTrigger
926 render={
927 <Button
928 size="xs"
929 variant="ghost-muted"
930 disabled={isRefreshingProviders}
931 aria-busy={isRefreshingProviders}
932 onClick={() => void refreshProviders()}
933 >
934 <RefreshCwIcon />
935 <span className="sr-only">Refresh provider status</span>
936 <span className="hidden min-w-0 truncate sm:inline">
937 {isRefreshingProviders ? (
938 "Refreshing providers"
939 ) : (
940 <ProviderLastChecked lastCheckedAt={lastCheckedAt} />
941 )}
942 </span>
943 </Button>
944 }
945 />
946 <TooltipPopup side="top">Refresh provider status</TooltipPopup>
947 </Tooltip>
948 <Tooltip>
949 <TooltipTrigger
950 render={
951 <Button
952 size="icon-xs"
953 variant="ghost-muted"
954 onClick={() => setIsAddInstanceDialogOpen(true)}
955 aria-label="Add provider"
956 >
957 <PlusIcon />
958 </Button>
959 }
960 />
961 <TooltipPopup side="top">Add provider</TooltipPopup>
962 </Tooltip>
963 </>
964 )}
965 </div>
966 }
967 >
968 {deviceTabs}
969 {readOnly ? (
970 <div className="overflow-hidden rounded-xl border border-border/60 bg-card/40 shadow-xs/5">
971 <SettingsRow
972 title="Limited permissions"
973 description={`This session can view ${environmentLabel}'s providers but can't change their settings.`}
974 />
975 </div>
976 ) : null}
977 <div className="overflow-hidden rounded-xl border border-border/60 bg-card/40 shadow-xs/5 lg:grid lg:h-[min(44rem,calc(100dvh-11rem))] lg:min-h-[32rem] lg:grid-cols-[17rem_minmax(0,1fr)]">
978 <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">
979 <ScrollArea scrollFade chainVerticalScroll className="lg:min-h-0 lg:flex-1">
980 <div className="divide-y divide-border/50">
981 {rows.map((row) => renderProviderInstance(row, "list"))}
982 </div>
983 </ScrollArea>
984 </div>
985
986 <div className="min-w-0 lg:min-h-0">
987 {selectedRow ? (
988 <ScrollArea scrollFade chainVerticalScroll className="lg:h-full">
989 <div className="space-y-6 p-4">{renderProviderInstance(selectedRow, "editor")}</div>
990 </ScrollArea>
991 ) : (
992 <div className="p-6 text-sm text-muted-foreground">
993 {targetInstanceMissing
994 ? "This provider instance is no longer available on this device."
995 : "No providers configured."}
996 </div>
997 )}
998 </div>
999 </div>
1000 </SettingsSection>
1001
1002 <UsageProviderSettings
1003 key={environmentId}
1004 environmentId={environmentId}
1005 environmentLabel={environmentLabel}
1006 sources={settings.usageLimitSources}
1007 readOnly={readOnly}
1008 />
1009
1010 <SettingsSection title="Advanced">
1011 <SettingsRow
1012 id={searchableSetting("provider-health-check-interval").id}
1013 title={
1014 <span className="inline-flex items-center gap-1.5">
1015 {searchableSetting("provider-health-check-interval").title}
1016 <PolicyTooltip>
1017 This interval is configured here, then the shared Background activity policy decides
1018 whether provider probes may run when the timer fires. Custom intervals appear as
1019 Advanced in General settings.
1020 </PolicyTooltip>
1021 </span>
1022 }
1023 description="Refresh provider status, versions, and models in the background. Set to 0 to disable."
1024 resetAction={
1025 providerHealthRefreshIntervalSeconds !== defaultProviderHealthRefreshIntervalSeconds ? (
1026 <span inert={readOnly} className={readOnly ? "opacity-50" : undefined}>
1027 <SettingResetButton
1028 label="provider health check interval"
1029 onClick={() =>
1030 updateSettings(
1031 backgroundActivityOverrideSettings(
1032 settings.backgroundActivity,
1033 resolvedBackgroundActivity,
1034 { providerHealthRefreshInterval: undefined },
1035 ),
1036 )
1037 }
1038 />
1039 </span>
1040 ) : null
1041 }
1042 control={
1043 <div
1044 inert={readOnly}
1045 aria-disabled={readOnly || undefined}
1046 className={cn(
1047 "flex shrink-0 items-center gap-2",
1048 readOnly && "opacity-50 select-none",
1049 )}
1050 >
1051 <NumberField
1052 value={providerHealthRefreshIntervalSeconds}
1053 min={0}
1054 step={PROVIDER_HEALTH_INTERVAL_STEP_SECONDS}
1055 size="sm"
1056 className="w-32"
1057 onValueChange={(value) =>
1058 updateSettings(
1059 backgroundActivityOverrideSettings(
1060 settings.backgroundActivity,
1061 resolvedBackgroundActivity,
1062 {
1063 providerHealthRefreshInterval: Duration.seconds(
1064 normalizeIntervalSeconds(value),
1065 ),
1066 },
1067 ),
1068 )
1069 }
1070 >
1071 <NumberFieldGroup>
1072 <NumberFieldDecrement aria-label="Decrease provider health check interval" />
1073 <NumberFieldInput aria-label="Provider health check interval in seconds" />
1074 <NumberFieldIncrement aria-label="Increase provider health check interval" />
1075 </NumberFieldGroup>
1076 </NumberField>
1077 <span className="text-xs text-muted-foreground">seconds</span>
1078 </div>
1079 }
1080 />
1081 </SettingsSection>
1082
1083 {isAddInstanceDialogOpen ? (
1084 <AddProviderInstanceDialog
1085 open
1086 environmentId={environmentId}
1087 environmentLabel={environmentLabel}
1088 onOpenChange={setIsAddInstanceDialogOpen}
1089 />
1090 ) : null}
1091 </>
1092 );
1093}