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

ProviderSettingsPanel.tsx

902 lines34.1 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} from "@t3tools/contracts";
16import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
17import {
18 getBackgroundActivityPresetSettings,
19 resolveServerBackgroundActivitySettings,
20} from "@t3tools/shared/backgroundActivitySettings";
21import * as Arr from "effect/Array";
22import * as Duration from "effect/Duration";
23import * as Equal from "effect/Equal";
24import * as Result from "effect/Result";
25import {
26 CloudIcon,
27 LaptopIcon,
28 LoaderIcon,
29 MonitorIcon,
30 PlusIcon,
31 RefreshCwIcon,
32 TerminalIcon,
33} from "lucide-react";
34import { useCallback, useMemo, useRef, useState } from "react";
35​
36import { isDesktopLocalConnectionTarget } from "../../connection/desktopLocal";
37import { isElectron } from "../../env";
38import { usePrimarySessionState } from "../../environments/primary";
39import { useEnvironmentSettings, useUpdateEnvironmentSettings } from "../../hooks/useSettings";
40import { cn } from "../../lib/utils";
41import { resolveAppModelSelectionState } from "../../modelSelection";
42import {
43 useEnvironments,
44 usePrimaryEnvironmentId,
45 type EnvironmentPresentation,
46} from "../../state/environments";
47import { EMPTY_SERVER_PROVIDERS, serverEnvironment } from "../../state/server";
48import { useEnvironmentSessionState } from "../../state/session";
49import { useAtomCommand } from "../../state/use-atom-command";
50import { getRelativeTimeState } from "../../timestampFormat";
51import {
52 ConnectionStatusDot,
53 connectionPhaseDotClassName,
54 connectionPhasePingClassName,
55} from "../ConnectionStatusDot";
56import {
57 canOneClickUpdateProviderCandidate,
58 collectProviderUpdateCandidates,
59 hasOneClickUpdateProviderCandidate,
60 isProviderUpdateActive,
61 type ProviderUpdateCandidate,
62} from "../ProviderUpdateLaunchNotification.logic";
63import { Button } from "../ui/button";
64import {
65 NumberField,
66 NumberFieldDecrement,
67 NumberFieldGroup,
68 NumberFieldIncrement,
69 NumberFieldInput,
70} from "../ui/number-field";
71import { stackedThreadToast, toastManager } from "../ui/toast";
72import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
73import { AddProviderInstanceDialog } from "./AddProviderInstanceDialog";
74import { ProviderInstanceCard } from "./ProviderInstanceCard";
75import { DRIVER_OPTIONS, getDriverOption } from "./providerDriverMeta";
76import { searchableSetting } from "./settingsSearch";
77import {
78 backgroundActivityOverrideSettings,
79 buildProviderInstanceUpdatePatch,
80 durationToSeconds,
81 normalizeIntervalSeconds,
82 PROVIDER_HEALTH_INTERVAL_STEP_SECONDS,
83} from "./SettingsPanels.logic";
84import {
85 PolicyTooltip,
86 SettingResetButton,
87 SettingsPageContainer,
88 SettingsRow,
89 SettingsSection,
90 useRelativeTimeTick,
91} from "./settingsLayout";
92import {
93 buildProviderEnvironmentOptions,
94 classifyProviderEnvironmentAccess,
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 ProviderLastChecked({ lastCheckedAt }: { lastCheckedAt: string | null }) {
123 useRelativeTimeTick();
124 const lastCheckedRelative = getRelativeTimeState(lastCheckedAt);
125​
126 if (lastCheckedRelative.status === "missing") {
127 return null;
128 }
129​
130 if (lastCheckedRelative.status === "invalid") {
131 return <span className="text-[11px] text-muted-foreground/50">Checked unavailable</span>;
132 }
133​
134 return (
135 <span className="text-[11px] text-muted-foreground/60">
136 {lastCheckedRelative.suffix ? (
137 <>
138 Checked <span className="font-mono tabular-nums">{lastCheckedRelative.value}</span>{" "}
139 {lastCheckedRelative.suffix}
140 </>
141 ) : (
142 <>Checked {lastCheckedRelative.value}</>
143 )}
144 </span>
145 );
147​
148function providerEnvironmentIcon(environment: EnvironmentPresentation) {
149 if (environment.entry.target._tag === "PrimaryConnectionTarget") return MonitorIcon;
150 if (environment.entry.target._tag === "RelayConnectionTarget") return CloudIcon;
151 if (environment.entry.target._tag === "SshConnectionTarget") return TerminalIcon;
152 if (isDesktopLocalConnectionTarget(environment.entry.target)) return LaptopIcon;
153 return CloudIcon;
155​
156function providerEnvironmentDetail(environment: EnvironmentPresentation): string {
157 if (environment.entry.target._tag === "PrimaryConnectionTarget") return "Primary device";
158 if (environment.relayManaged) return "T3 Connect";
159 if (environment.entry.target._tag === "SshConnectionTarget") return "SSH";
160 if (isDesktopLocalConnectionTarget(environment.entry.target)) return "Local device";
161 return environment.displayUrl ?? "Remote device";
163​
164function EnvironmentUnavailableRow({
165 environment,
166 access,
167}: {
168 readonly environment: EnvironmentPresentation;
169 readonly access: Exclude<ProviderEnvironmentAccess, { kind: "editable" | "read-only" }>;
170}) {
171 const isLoading = access.kind === "loading";
172 const title = isLoading
173 ? "Loading provider settings"
174 : access.kind === "error"
175 ? "Could not connect to this device"
176 : "Provider settings are unavailable";
177 const description = isLoading
178 ? access.reason === "permissions"
179 ? "Checking what this session is allowed to change."
180 : `Waiting for ${environment.label}'s configuration.`
181 : connectionStatusText(environment.connection);
182 // No spinner: this state can persist indefinitely for a wedged device, and a
183 // continuously repainting animation would run the whole time.
184 return (
185 <SettingsSection title="Providers">
186 <SettingsRow title={title} description={description} />
187 </SettingsSection>
188 );
190​
191export function ProviderSettingsPanel() {
192 const { environments, isReady } = useEnvironments();
193 const primaryEnvironmentId = usePrimaryEnvironmentId();
194 const options = useMemo(
195 () => buildProviderEnvironmentOptions(environments, primaryEnvironmentId),
196 [environments, primaryEnvironmentId],
197 );
198 // Raw user intent; the effective selection is re-derived every render so a
199 // device that drops out of the catalog falls back without erasing the pick —
200 // if it reappears (e.g. after a reconnect) the selection is restored.
201 const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<EnvironmentId | null>(
202 primaryEnvironmentId,
203 );
204 const effectiveEnvironmentId = resolveSelectedProviderEnvironmentId(
205 options,
206 selectedEnvironmentId,
207 primaryEnvironmentId,
208 );
209 const selectedEnvironment =
210 options.find((environment) => environment.environmentId === effectiveEnvironmentId) ?? null;
211 const onlyPrimaryDevice =
212 options.length === 1 && options[0]?.entry.target._tag === "PrimaryConnectionTarget";
213​
214 return (
215 <SettingsPageContainer>
216 {!onlyPrimaryDevice ? (
217 <SettingsSection title="Devices">
218 {options.length === 0 ? (
219 // The catalog hydrates asynchronously, so an empty list before it is
220 // ready means "not loaded yet", not "nothing is connected".
221 <SettingsRow
222 title={isReady ? "No connected devices" : "Loading devices"}
223 description={
224 isReady
225 ? "Connect an execution environment before configuring providers."
226 : "Reading connected execution environments."
227 }
228 />
229 ) : (
230 <div className="grid gap-1 sm:grid-cols-2">
231 {options.map((environment) => {
232 const Icon = providerEnvironmentIcon(environment);
233 const selected = environment.environmentId === effectiveEnvironmentId;
234 const statusText = connectionStatusText(environment.connection);
235 return (
236 <button
237 key={environment.environmentId}
238 type="button"
239 aria-pressed={selected}
240 className={cn(
241 "flex min-w-0 items-center gap-3 rounded-xl px-3 py-2.5 text-left transition-colors sm:px-4",
242 selected
243 ? "bg-primary/8 ring-1 ring-primary/25 dark:bg-primary/12"
244 : "hover:bg-muted/40",
245 )}
246 onClick={() => setSelectedEnvironmentId(environment.environmentId)}
247 >
248 <span className="flex size-8 shrink-0 items-center justify-center rounded-lg border border-border/60 bg-background text-muted-foreground">
249 <Icon className="size-4" aria-hidden />
250 </span>
251 <span className="min-w-0 flex-1">
252 <span className="flex items-center gap-1.5">
253 <ConnectionStatusDot
254 tooltipText={statusText}
255 dotClassName={connectionPhaseDotClassName(environment.connection.phase)}
256 pingClassName={connectionPhasePingClassName(environment.connection.phase)}
257 />
258 <span className="truncate text-sm font-medium text-foreground">
259 {environment.label}
260 </span>
261 </span>
262 <span className="block truncate pl-[18px] text-xs text-muted-foreground">
263 {providerEnvironmentDetail(environment)} · {statusText}
264 </span>
265 </span>
266 </button>
267 );
268 })}
269 </div>
270 )}
271 </SettingsSection>
272 ) : null}
273​
274 {selectedEnvironment ? (
275 <SelectedEnvironmentProviderSettings
276 key={selectedEnvironment.environmentId}
277 environment={selectedEnvironment}
278 />
279 ) : null}
280 </SettingsPageContainer>
281 );
283​
284function SelectedEnvironmentProviderSettings({
285 environment,
286}: {
287 readonly environment: EnvironmentPresentation;
288}) {
289 const isPrimary = environment.entry.target._tag === "PrimaryConnectionTarget";
290 if (isPrimary) {
291 // The desktop app owns its primary server outright; a browser session
292 // checks the scopes its cookie session was granted.
293 if (isElectron) {
294 return <AccessGatedProviderSettings environment={environment} operateAccess="granted" />;
295 }
296 return <PrimarySessionGatedProviderSettings environment={environment} />;
297 }
298 return <RemoteSessionGatedProviderSettings environment={environment} />;
300​
301function PrimarySessionGatedProviderSettings({
302 environment,
303}: {
304 readonly environment: EnvironmentPresentation;
305}) {
306 const primarySessionState = usePrimarySessionState();
307 const operateAccess = resolvePrimaryOperateAccess({
308 isPrimary: true,
309 hasDesktopBridge: false,
310 session: primarySessionState.data,
311 isPending: primarySessionState.isPending,
312 hasError: primarySessionState.error !== null,
313 });
314 return <AccessGatedProviderSettings environment={environment} operateAccess={operateAccess} />;
316​
317function RemoteSessionGatedProviderSettings({
318 environment,
319}: {
320 readonly environment: EnvironmentPresentation;
321}) {
322 const sessionState = useEnvironmentSessionState(environment.environmentId);
323 const operateAccess = resolveRemoteOperateAccess({
324 session: sessionState.data,
325 isPending: sessionState.isPending,
326 hasError: sessionState.hasError,
327 });
328 return <AccessGatedProviderSettings environment={environment} operateAccess={operateAccess} />;
330​
331function AccessGatedProviderSettings({
332 environment,
333 operateAccess,
334}: {
335 readonly environment: EnvironmentPresentation;
336 readonly operateAccess: ProviderOperateAccess;
337}) {
338 const access = classifyProviderEnvironmentAccess({
339 connectionPhase: environment.connection.phase,
340 hasServerConfig: environment.serverConfig !== null,
341 operateAccess,
342 });
343 if (access.kind !== "editable" && access.kind !== "read-only") {
344 return <EnvironmentUnavailableRow environment={environment} access={access} />;
345 }
346 return (
347 <EnvironmentProviderSettings
348 environmentId={environment.environmentId}
349 environmentLabel={environment.label}
350 readOnly={access.kind === "read-only"}
351 />
352 );
354​
355export function EnvironmentProviderSettings({
356 environmentId,
357 environmentLabel,
358 readOnly = false,
359}: {
360 readonly environmentId: EnvironmentId;
361 readonly environmentLabel: string;
362 /**
363 * Render the full provider layout, greyed out and inert, when this session's
364 * credential lacks `orchestration:operate` on the environment. Showing the
365 * real configuration keeps the view honest; disabling interaction keeps
366 * every one of its writes from being offered and then rejected.
367 */
368 readonly readOnly?: boolean;
369}) {
370 const settings = useEnvironmentSettings(environmentId);
371 const updateSettings = useUpdateEnvironmentSettings(environmentId);
372 const serverProviders =
373 useAtomValue(serverEnvironment.providersValueAtom(environmentId)) ?? EMPTY_SERVER_PROVIDERS;
374 const refreshServerProviders = useAtomCommand(serverEnvironment.refreshProviders, {
375 reportFailure: false,
376 });
377 const updateProvider = useAtomCommand(serverEnvironment.updateProvider, {
378 reportFailure: false,
379 });
380 const [isRefreshingProviders, setIsRefreshingProviders] = useState(false);
381 const [isAddInstanceDialogOpen, setIsAddInstanceDialogOpen] = useState(false);
382 const [updatingProviderDrivers, setUpdatingProviderDrivers] = useState<
383 ReadonlySet<ProviderDriverKind>
384 >(() => new Set());
385 const [openInstanceDetails, setOpenInstanceDetails] = useState<Record<string, boolean>>({});
386 const refreshingRef = useRef(false);
387 const updatingDriversRef = useRef<Set<ProviderDriverKind>>(new Set());
388​
389 const providerUpdateCandidates = useMemo(
390 () => collectProviderUpdateCandidates(serverProviders),
391 [serverProviders],
392 );
393 const providerUpdateCandidateByInstanceId = useMemo(
394 () => new Map(providerUpdateCandidates.map((candidate) => [candidate.instanceId, candidate])),
395 [providerUpdateCandidates],
396 );
397 const visibleProviderSettings = PROVIDER_SETTINGS.filter(
398 (providerSettings) =>
399 providerSettings.provider !== "cursor" ||
400 serverProviders.some(
401 (provider) =>
402 provider.instanceId === defaultInstanceIdForDriver(ProviderDriverKind.make("cursor")),
403 ),
404 );
405 const textGenerationModelSelection = resolveAppModelSelectionState(settings, serverProviders);
406 const textGenInstanceId = textGenerationModelSelection.instanceId;
407 const resolvedBackgroundActivity = resolveServerBackgroundActivitySettings(settings);
408 const providerHealthPreset = getBackgroundActivityPresetSettings(
409 resolvedBackgroundActivity.profile,
410 ).providerHealthRefreshInterval;
411 const providerHealthRefreshIntervalSeconds = durationToSeconds(
412 resolvedBackgroundActivity.providerHealthRefreshInterval,
413 );
414 const defaultProviderHealthRefreshIntervalSeconds = durationToSeconds(providerHealthPreset);
415 const lastCheckedAt =
416 serverProviders.length > 0
417 ? serverProviders.reduce(
418 (latest, provider) => (provider.checkedAt > latest ? provider.checkedAt : latest),
419 serverProviders[0]!.checkedAt,
420 )
421 : null;
422​
423 const refreshProviders = useCallback(() => {
424 if (refreshingRef.current) return;
425 refreshingRef.current = true;
426 setIsRefreshingProviders(true);
427 void (async () => {
428 const result = await refreshServerProviders({
429 environmentId,
430 input: {},
431 });
432 refreshingRef.current = false;
433 setIsRefreshingProviders(false);
434 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
435 console.warn("Failed to refresh providers", {
436 operation: "refresh-providers",
437 environmentId,
438 ...safeErrorLogAttributes(squashAtomCommandFailure(result)),
439 });
440 }
441 })();
442 }, [environmentId, refreshServerProviders]);
443​
444 const runProviderUpdate = useCallback(
445 async (candidate: ProviderUpdateCandidate) => {
446 // Ref-based re-entry guard, mirroring refreshProviders: a state updater
447 // may run after this function returns, so it cannot gate the dispatch.
448 if (updatingDriversRef.current.has(candidate.driver)) {
449 return;
450 }
451 updatingDriversRef.current.add(candidate.driver);
452 setUpdatingProviderDrivers((previous) => new Set(previous).add(candidate.driver));
453​
454 const result = await updateProvider({
455 environmentId,
456 input: {
457 provider: candidate.driver,
458 instanceId: candidate.instanceId,
459 },
460 });
461 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
462 const error = squashAtomCommandFailure(result);
463 toastManager.add(
464 stackedThreadToast({
465 type: "error",
466 title: `Could not update ${PROVIDER_DISPLAY_NAMES[candidate.driver] ?? candidate.driver}`,
467 description:
468 error instanceof Error
469 ? error.message
470 : "The provider update command could not be started.",
471 }),
472 );
473 }
474 updatingDriversRef.current.delete(candidate.driver);
475 setUpdatingProviderDrivers((previous) => {
476 if (!previous.has(candidate.driver)) {
477 return previous;
478 }
479 const next = new Set(previous);
480 next.delete(candidate.driver);
481 return next;
482 });
483 },
484 [environmentId, updateProvider],
485 );
486​
487 interface InstanceRow {
488 readonly instanceId: ProviderInstanceId;
489 readonly instance: ProviderInstanceConfig;
490 readonly driver: ProviderDriverKind;
491 readonly isDefault: boolean;
492 readonly isDirty?: boolean;
493 }
494​
495 const instancesByDriver = new Map<
496 ProviderDriverKind,
497 Array<[ProviderInstanceId, ProviderInstanceConfig]>
498 >();
499 for (const [rawId, instance] of Object.entries(settings.providerInstances ?? {})) {
500 const driver = instance.driver;
501 const list = instancesByDriver.get(driver) ?? [];
502 list.push([rawId as ProviderInstanceId, instance]);
503 instancesByDriver.set(driver, list);
504 }
505​
506 const defaultSlotIdsBySource = new Set<string>(
507 visibleProviderSettings.map((providerSettings) =>
508 String(defaultInstanceIdForDriver(providerSettings.provider)),
509 ),
510 );
511​
512 const rows: InstanceRow[] = [];
513 const visibleDriverKinds = new Set<ProviderDriverKind>(
514 visibleProviderSettings.map((providerSettings) => providerSettings.provider),
515 );
516​
517 for (const providerSettings of visibleProviderSettings) {
518 type LegacyProviderSettings = (typeof settings.providers)[keyof typeof settings.providers];
519 const legacyProviders = settings.providers as Record<string, LegacyProviderSettings>;
520 const defaultLegacyProviders = DEFAULT_UNIFIED_SETTINGS.providers as Record<
521 string,
522 LegacyProviderSettings
523 >;
524 const driver = providerSettings.provider;
525 const defaultInstanceId = defaultInstanceIdForDriver(driver);
526 const explicitInstance = settings.providerInstances?.[defaultInstanceId];
527 // A remote device may run a server version whose settings predate this
528 // driver, so the legacy mirror can be absent. Without either an explicit
529 // instance or a legacy blob there is nothing to render for the slot.
530 const legacyConfig = legacyProviders[providerSettings.provider];
531 const defaultLegacyConfig = defaultLegacyProviders[providerSettings.provider];
532 const effectiveInstance: ProviderInstanceConfig | undefined =
533 explicitInstance ??
534 (legacyConfig !== undefined
535 ? ({
536 driver,
537 enabled: legacyConfig.enabled,
538 config: legacyConfig,
539 } satisfies ProviderInstanceConfig)
540 : undefined);
541 // Only the default slot depends on the legacy blob; custom instances for
542 // the driver must still render even when the slot has nothing to show.
543 if (effectiveInstance !== undefined) {
544 const isDirty =
545 explicitInstance !== undefined || !Equal.equals(legacyConfig, defaultLegacyConfig);
546 rows.push({
547 instanceId: defaultInstanceId,
548 instance: effectiveInstance,
549 driver,
550 isDefault: true,
551 isDirty,
552 });
553 }
554 for (const [id, instance] of instancesByDriver.get(providerSettings.provider) ?? []) {
555 if (id === defaultInstanceId) continue;
556 rows.push({ instanceId: id, instance, driver: instance.driver, isDefault: false });
557 }
558 }
559 for (const [driver, list] of instancesByDriver) {
560 if (visibleDriverKinds.has(driver)) continue;
561 for (const [id, instance] of list) {
562 rows.push({
563 instanceId: id,
564 instance,
565 driver: instance.driver,
566 isDefault: defaultSlotIdsBySource.has(String(id)),
567 });
568 }
569 }
570​
571 const updateProviderInstance = (
572 row: InstanceRow,
573 next: ProviderInstanceConfig,
574 options?: {
575 readonly textGenerationModelSelection?: Parameters<
576 typeof buildProviderInstanceUpdatePatch
577 >[0]["textGenerationModelSelection"];
578 },
579 ) => {
580 updateSettings(
581 buildProviderInstanceUpdatePatch({
582 settings,
583 instanceId: row.instanceId,
584 instance: next,
585 driver: row.driver,
586 isDefault: row.isDefault,
587 textGenerationModelSelection: options?.textGenerationModelSelection,
588 }),
589 );
590 };
591​
592 const deleteProviderInstance = (id: ProviderInstanceId) => {
593 updateSettings({
594 providerInstances: withoutProviderInstanceKey(settings.providerInstances, id),
595 });
596 };
597​
598 const updateProviderModelPreferences = (
599 instanceId: ProviderInstanceId,
600 next: {
601 readonly hiddenModels: ReadonlyArray<string>;
602 readonly modelOrder: ReadonlyArray<string>;
603 },
604 ) => {
605 const hiddenModels = [...new Set(next.hiddenModels.filter((slug) => slug.trim().length > 0))];
606 const modelOrder = [...new Set(next.modelOrder.filter((slug) => slug.trim().length > 0))];
607 const rest = withoutProviderInstanceKey(settings.providerModelPreferences, instanceId);
608 updateSettings({
609 providerModelPreferences:
610 hiddenModels.length === 0 && modelOrder.length === 0
611 ? rest
612 : {
613 ...rest,
614 [instanceId]: {
615 hiddenModels,
616 modelOrder,
617 },
618 },
619 });
620 };
621​
622 const updateProviderFavoriteModels = (
623 instanceId: ProviderInstanceId,
624 nextFavoriteModels: ReadonlyArray<string>,
625 ) => {
626 const favoriteModels = [
627 ...new Set(
628 Arr.filterMap(nextFavoriteModels, (slug) => {
629 const trimmedSlug = slug.trim();
630 return trimmedSlug.length > 0 ? Result.succeed(trimmedSlug) : Result.failVoid;
631 }),
632 ),
633 ];
634 updateSettings({
635 favorites: [
636 ...withoutProviderInstanceFavorites(settings.favorites ?? [], instanceId),
637 ...favoriteModels.map((model) => ({ provider: instanceId, model })),
638 ],
639 });
640 };
641​
642 const resetDefaultInstance = (driverKind: ProviderDriverKind) => {
643 type LegacyProviderSettings = (typeof settings.providers)[keyof typeof settings.providers];
644 const defaultLegacyProviders = DEFAULT_UNIFIED_SETTINGS.providers as Record<
645 string,
646 LegacyProviderSettings | undefined
647 >;
648 const defaultInstanceId = defaultInstanceIdForDriver(driverKind);
649 const defaultLegacyProvider = defaultLegacyProviders[driverKind];
650 if (defaultLegacyProvider === undefined) return;
651 updateSettings({
652 providers: {
653 ...settings.providers,
654 [driverKind]: defaultLegacyProvider,
655 } as typeof settings.providers,
656 providerInstances: withoutProviderInstanceKey(settings.providerInstances, defaultInstanceId),
657 });
658 };
659​
660 return (
661 <>
662 <SettingsSection
663 {...searchableSetting("providers")}
664 headerAction={
665 <div className="flex items-center gap-1.5">
666 <ProviderLastChecked lastCheckedAt={lastCheckedAt} />
667 {!readOnly ? (
668 <>
669 <Tooltip>
670 <TooltipTrigger
671 render={
672 <Button
673 size="icon-xs"
674 variant="ghost"
675 className="size-5 rounded-sm p-0 text-muted-foreground hover:text-foreground"
676 onClick={() => setIsAddInstanceDialogOpen(true)}
677 aria-label="Add provider instance"
678 >
679 <PlusIcon className="size-3" />
680 </Button>
681 }
682 />
683 <TooltipPopup side="top">Add provider instance</TooltipPopup>
684 </Tooltip>
685 <Tooltip>
686 <TooltipTrigger
687 render={
688 <Button
689 size="icon-xs"
690 variant="ghost"
691 className="size-5 rounded-sm p-0 text-muted-foreground hover:text-foreground"
692 disabled={isRefreshingProviders}
693 onClick={() => void refreshProviders()}
694 aria-label="Refresh provider status"
695 >
696 {isRefreshingProviders ? (
697 <LoaderIcon className="size-3 animate-spin" />
698 ) : (
699 <RefreshCwIcon className="size-3" />
700 )}
701 </Button>
702 }
703 />
704 <TooltipPopup side="top">Refresh provider status</TooltipPopup>
705 </Tooltip>
706 </>
707 ) : null}
708 </div>
709 }
710 >
711 {readOnly ? (
712 <SettingsRow
713 title="Limited permissions"
714 description={`This session can view ${environmentLabel}'s providers, but its credential does not allow changing their configuration.`}
715 />
716 ) : null}
717 <div
718 // `inert` blocks focus and interaction in one attribute, so the
719 // read-only view stays byte-for-byte the editable layout without
720 // threading a disabled flag through every control.
721 inert={readOnly}
722 aria-disabled={readOnly || undefined}
723 className={readOnly ? "space-y-1 opacity-50 select-none" : "space-y-1"}
724 >
725 <SettingsRow
726 title={
727 <span className="inline-flex items-center gap-1.5">
728 Health check interval
729 <PolicyTooltip>
730 This interval is configured here, then the shared Background activity policy
731 decides whether provider probes may run when the timer fires. Custom intervals
732 appear as Advanced in General settings.
733 </PolicyTooltip>
734 </span>
735 }
736 description="Refresh provider availability, versions, auth state, and model metadata in the background. Set this to 0 seconds to rely on manual refreshes."
737 resetAction={
738 providerHealthRefreshIntervalSeconds !==
739 defaultProviderHealthRefreshIntervalSeconds ? (
740 <SettingResetButton
741 label="provider health check interval"
742 onClick={() =>
743 updateSettings(
744 backgroundActivityOverrideSettings(
745 settings.backgroundActivity,
746 resolvedBackgroundActivity,
747 {
748 providerHealthRefreshInterval: undefined,
749 },
750 ),
751 )
752 }
753 />
754 ) : null
755 }
756 control={
757 <div className="flex shrink-0 items-center gap-2">
758 <NumberField
759 value={providerHealthRefreshIntervalSeconds}
760 min={0}
761 step={PROVIDER_HEALTH_INTERVAL_STEP_SECONDS}
762 size="sm"
763 className="w-32"
764 onValueChange={(value) =>
765 updateSettings(
766 backgroundActivityOverrideSettings(
767 settings.backgroundActivity,
768 resolvedBackgroundActivity,
769 {
770 providerHealthRefreshInterval: Duration.seconds(
771 normalizeIntervalSeconds(value),
772 ),
773 },
774 ),
775 )
776 }
777 >
778 <NumberFieldGroup>
779 <NumberFieldDecrement aria-label="Decrease provider health check interval" />
780 <NumberFieldInput aria-label="Provider health check interval in seconds" />
781 <NumberFieldIncrement aria-label="Increase provider health check interval" />
782 </NumberFieldGroup>
783 </NumberField>
784 <span className="text-xs text-muted-foreground">seconds</span>
785 </div>
786 }
787 />
788​
789 {rows.map((row) => {
790 const driverOption = getDriverOption(row.driver);
791 const liveProvider = serverProviders.find(
792 (candidate) => candidate.instanceId === row.instanceId,
793 );
794 const updateCandidate = liveProvider
795 ? providerUpdateCandidateByInstanceId.get(liveProvider.instanceId)
796 : undefined;
797 const isDriverUpdateRunning =
798 updateCandidate !== undefined &&
799 (updatingProviderDrivers.has(updateCandidate.driver) ||
800 serverProviders.some(
801 (provider) =>
802 provider.driver === updateCandidate.driver && isProviderUpdateActive(provider),
803 ));
804 const showInlineUpdateButton =
805 updateCandidate !== undefined &&
806 hasOneClickUpdateProviderCandidate(updateCandidate, serverProviders);
807 const canRunInlineUpdate =
808 updateCandidate !== undefined &&
809 canOneClickUpdateProviderCandidate(updateCandidate, serverProviders) &&
810 !updatingProviderDrivers.has(updateCandidate.driver);
811 const modelPreferences = settings.providerModelPreferences?.[row.instanceId] ?? {
812 hiddenModels: [],
813 modelOrder: [],
814 };
815 const favoriteModels = Arr.filterMap(settings.favorites ?? [], (favorite) =>
816 favorite.provider === row.instanceId
817 ? Result.succeed(favorite.model)
818 : Result.failVoid,
819 );
820 const resetLabel = driverOption?.label ?? String(row.driver);
821 const headerAction =
822 row.isDefault && row.isDirty ? (
823 <SettingResetButton
824 label={`${resetLabel} provider settings`}
825 onClick={() => resetDefaultInstance(row.driver)}
826 />
827 ) : null;
828 return (
829 <ProviderInstanceCard
830 key={row.instanceId}
831 instanceId={row.instanceId}
832 instance={row.instance}
833 driverOption={driverOption}
834 liveProvider={liveProvider}
835 isExpanded={openInstanceDetails[row.instanceId] ?? false}
836 onExpandedChange={(open) =>
837 setOpenInstanceDetails((existing) => ({
838 ...existing,
839 [row.instanceId]: open,
840 }))
841 }
842 onUpdate={(next) => {
843 const wasEnabled = row.instance.enabled ?? true;
844 const isDisabling = next.enabled === false && wasEnabled;
845 const shouldClearTextGen = isDisabling && textGenInstanceId === row.instanceId;
846 if (shouldClearTextGen) {
847 updateProviderInstance(row, next, {
848 textGenerationModelSelection:
849 DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection,
850 });
851 } else {
852 updateProviderInstance(row, next);
853 }
854 }}
855 onDelete={row.isDefault ? undefined : () => deleteProviderInstance(row.instanceId)}
856 headerAction={headerAction}
857 hiddenModels={modelPreferences.hiddenModels}
858 favoriteModels={favoriteModels}
859 modelOrder={modelPreferences.modelOrder}
860 onHiddenModelsChange={(hiddenModels) =>
861 updateProviderModelPreferences(row.instanceId, {
862 ...modelPreferences,
863 hiddenModels,
864 })
865 }
866 onFavoriteModelsChange={(favoriteModels) =>
867 updateProviderFavoriteModels(row.instanceId, favoriteModels)
868 }
869 onModelOrderChange={(modelOrder) =>
870 updateProviderModelPreferences(row.instanceId, {
871 ...modelPreferences,
872 modelOrder,
873 })
874 }
875 onRunUpdate={
876 showInlineUpdateButton && updateCandidate
877 ? () => {
878 if (!canRunInlineUpdate) {
879 return;
880 }
881 void runProviderUpdate(updateCandidate);
882 }
883 : undefined
884 }
885 isUpdating={showInlineUpdateButton ? isDriverUpdateRunning : undefined}
886 />
887 );
888 })}
889 </div>
890 </SettingsSection>
891​
892 {isAddInstanceDialogOpen ? (
893 <AddProviderInstanceDialog
894 open
895 environmentId={environmentId}
896 environmentLabel={environmentLabel}
897 onOpenChange={setIsAddInstanceDialogOpen}
898 />
899 ) : null}
900 </>
901 );