Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ProviderSettingsPanel.tsx

1,083 lines39.6 KB

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