Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { connectionStatusText } from "@t3tools/client-runtime/connection";
3import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
4import {
5 isAtomCommandInterrupted,
6 squashAtomCommandFailure,
7} from "@t3tools/client-runtime/state/runtime";
8import {
9 defaultInstanceIdForDriver,
10 type EnvironmentId,
11 PROVIDER_DISPLAY_NAMES,
12 ProviderDriverKind,
13 type ProviderInstanceConfig,
14 type ProviderInstanceId,
15} 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;
109}
110
111function withoutProviderInstanceFavorites(
112 favorites: ReadonlyArray<{ readonly provider: ProviderInstanceId; readonly model: string }>,
113 instanceId: ProviderInstanceId,
114) {
115 return favorites.filter((favorite) => favorite.provider !== instanceId);
116}
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 );
146}
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;
154}
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";
162}
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 );
189}
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 );
282}
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} />;
299}
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} />;
315}
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} />;
329}
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 );
353}
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-micro"
674 variant="ghost-muted"
675 onClick={() => setIsAddInstanceDialogOpen(true)}
676 aria-label="Add provider instance"
677 >
678 <PlusIcon className="size-3" />
679 </Button>
680 }
681 />
682 <TooltipPopup side="top">Add provider instance</TooltipPopup>
683 </Tooltip>
684 <Tooltip>
685 <TooltipTrigger
686 render={
687 <Button
688 size="icon-micro"
689 variant="ghost-muted"
690 disabled={isRefreshingProviders}
691 onClick={() => void refreshProviders()}
692 aria-label="Refresh provider status"
693 >
694 {isRefreshingProviders ? (
695 <LoaderIcon className="size-3 animate-spin" />
696 ) : (
697 <RefreshCwIcon className="size-3" />
698 )}
699 </Button>
700 }
701 />
702 <TooltipPopup side="top">Refresh provider status</TooltipPopup>
703 </Tooltip>
704 </>
705 ) : null}
706 </div>
707 }
708 >
709 {readOnly ? (
710 <SettingsRow
711 title="Limited permissions"
712 description={`This session can view ${environmentLabel}'s providers, but its credential does not allow changing their configuration.`}
713 />
714 ) : null}
715 <div
716 // `inert` blocks focus and interaction in one attribute, so the
717 // read-only view stays byte-for-byte the editable layout without
718 // threading a disabled flag through every control.
719 inert={readOnly}
720 aria-disabled={readOnly || undefined}
721 className={readOnly ? "space-y-1 opacity-50 select-none" : "space-y-1"}
722 >
723 <SettingsRow
724 title={
725 <span className="inline-flex items-center gap-1.5">
726 Health check interval
727 <PolicyTooltip>
728 This interval is configured here, then the shared Background activity policy
729 decides whether provider probes may run when the timer fires. Custom intervals
730 appear as Advanced in General settings.
731 </PolicyTooltip>
732 </span>
733 }
734 description="Refresh provider availability, versions, auth state, and model metadata in the background. Set this to 0 seconds to rely on manual refreshes."
735 resetAction={
736 providerHealthRefreshIntervalSeconds !==
737 defaultProviderHealthRefreshIntervalSeconds ? (
738 <SettingResetButton
739 label="provider health check interval"
740 onClick={() =>
741 updateSettings(
742 backgroundActivityOverrideSettings(
743 settings.backgroundActivity,
744 resolvedBackgroundActivity,
745 {
746 providerHealthRefreshInterval: undefined,
747 },
748 ),
749 )
750 }
751 />
752 ) : null
753 }
754 control={
755 <div className="flex shrink-0 items-center gap-2">
756 <NumberField
757 value={providerHealthRefreshIntervalSeconds}
758 min={0}
759 step={PROVIDER_HEALTH_INTERVAL_STEP_SECONDS}
760 size="sm"
761 className="w-32"
762 onValueChange={(value) =>
763 updateSettings(
764 backgroundActivityOverrideSettings(
765 settings.backgroundActivity,
766 resolvedBackgroundActivity,
767 {
768 providerHealthRefreshInterval: Duration.seconds(
769 normalizeIntervalSeconds(value),
770 ),
771 },
772 ),
773 )
774 }
775 >
776 <NumberFieldGroup>
777 <NumberFieldDecrement aria-label="Decrease provider health check interval" />
778 <NumberFieldInput aria-label="Provider health check interval in seconds" />
779 <NumberFieldIncrement aria-label="Increase provider health check interval" />
780 </NumberFieldGroup>
781 </NumberField>
782 <span className="text-xs text-muted-foreground">seconds</span>
783 </div>
784 }
785 />
786
787 {rows.map((row) => {
788 const driverOption = getDriverOption(row.driver);
789 const liveProvider = serverProviders.find(
790 (candidate) => candidate.instanceId === row.instanceId,
791 );
792 const updateCandidate = liveProvider
793 ? providerUpdateCandidateByInstanceId.get(liveProvider.instanceId)
794 : undefined;
795 const isDriverUpdateRunning =
796 updateCandidate !== undefined &&
797 (updatingProviderDrivers.has(updateCandidate.driver) ||
798 serverProviders.some(
799 (provider) =>
800 provider.driver === updateCandidate.driver && isProviderUpdateActive(provider),
801 ));
802 const showInlineUpdateButton =
803 updateCandidate !== undefined &&
804 hasOneClickUpdateProviderCandidate(updateCandidate, serverProviders);
805 const canRunInlineUpdate =
806 updateCandidate !== undefined &&
807 canOneClickUpdateProviderCandidate(updateCandidate, serverProviders) &&
808 !updatingProviderDrivers.has(updateCandidate.driver);
809 const modelPreferences = settings.providerModelPreferences?.[row.instanceId] ?? {
810 hiddenModels: [],
811 modelOrder: [],
812 };
813 const favoriteModels = Arr.filterMap(settings.favorites ?? [], (favorite) =>
814 favorite.provider === row.instanceId
815 ? Result.succeed(favorite.model)
816 : Result.failVoid,
817 );
818 const resetLabel = driverOption?.label ?? String(row.driver);
819 const headerAction =
820 row.isDefault && row.isDirty ? (
821 <SettingResetButton
822 label={`${resetLabel} provider settings`}
823 onClick={() => resetDefaultInstance(row.driver)}
824 />
825 ) : null;
826 return (
827 <ProviderInstanceCard
828 key={row.instanceId}
829 instanceId={row.instanceId}
830 instance={row.instance}
831 driverOption={driverOption}
832 liveProvider={liveProvider}
833 isExpanded={openInstanceDetails[row.instanceId] ?? false}
834 onExpandedChange={(open) =>
835 setOpenInstanceDetails((existing) => ({
836 ...existing,
837 [row.instanceId]: open,
838 }))
839 }
840 onUpdate={(next) => {
841 const wasEnabled = row.instance.enabled ?? true;
842 const isDisabling = next.enabled === false && wasEnabled;
843 const shouldClearTextGen = isDisabling && textGenInstanceId === row.instanceId;
844 if (shouldClearTextGen) {
845 updateProviderInstance(row, next, {
846 textGenerationModelSelection:
847 DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection,
848 });
849 } else {
850 updateProviderInstance(row, next);
851 }
852 }}
853 onDelete={row.isDefault ? undefined : () => deleteProviderInstance(row.instanceId)}
854 headerAction={headerAction}
855 hiddenModels={modelPreferences.hiddenModels}
856 favoriteModels={favoriteModels}
857 modelOrder={modelPreferences.modelOrder}
858 onHiddenModelsChange={(hiddenModels) =>
859 updateProviderModelPreferences(row.instanceId, {
860 ...modelPreferences,
861 hiddenModels,
862 })
863 }
864 onFavoriteModelsChange={(favoriteModels) =>
865 updateProviderFavoriteModels(row.instanceId, favoriteModels)
866 }
867 onModelOrderChange={(modelOrder) =>
868 updateProviderModelPreferences(row.instanceId, {
869 ...modelPreferences,
870 modelOrder,
871 })
872 }
873 onRunUpdate={
874 showInlineUpdateButton && updateCandidate
875 ? () => {
876 if (!canRunInlineUpdate) {
877 return;
878 }
879 void runProviderUpdate(updateCandidate);
880 }
881 : undefined
882 }
883 isUpdating={showInlineUpdateButton ? isDriverUpdateRunning : undefined}
884 />
885 );
886 })}
887 </div>
888 </SettingsSection>
889
890 {isAddInstanceDialogOpen ? (
891 <AddProviderInstanceDialog
892 open
893 environmentId={environmentId}
894 environmentLabel={environmentLabel}
895 onOpenChange={setIsAddInstanceDialogOpen}
896 />
897 ) : null}
898 </>
899 );
900}