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

ProviderSettingsPanel.tsx

994 lines36.6 KB

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