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

ProviderSettingsPanel.tsx

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