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