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

ProviderSettingsPanel.tsx

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