refactor(webui): split settings frontend by domain

This commit is contained in:
chengyongru authored and chengyongru committed 2026-08-11 13:27:19 +08:00
1 parent 52e0a6a1e3
commit eab017766b
35 files changed
+16931 -15386

No files matched your search

File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,257 @@
import { useEffect, useRef, useState } from "react";
import { ChevronLeft, Loader2, Search } from "lucide-react";
import { useTranslation } from "react-i18next";
import {
channelIsRunning,
channelMatchesFilter,
channelSearchText,
localizedChannelDisplayName,
type ChannelFilter,
} from "@/components/settings/channels/ChannelIdentity";
import { ChannelCatalogRow, ChannelSetupPanel } from "@/components/settings/channels/ChannelSetupPanel";
import {
DismissibleStatusMessage,
RestartRequiredNotice,
SETTINGS_SEARCH_INPUT_CLASS,
} from "@/components/settings/shared/SettingsControls";
import { Input } from "@/components/ui/input";
import { useMediaQuery } from "@/hooks/useMediaQuery";
import type { NanobotFeaturesPayload } from "@/lib/types";
import { cn } from "@/lib/utils";
export function ChannelsSettings({
token,
nanobotFeatures,
loading,
query,
actionKey,
chatAppsDocsUrl,
showBrandLogos,
error,
requiresRestartPending,
onQueryChange,
onAction,
onFeaturesUpdate,
onDismissStatus,
onRestart,
isRestarting,
}: {
token: string;
nanobotFeatures: NanobotFeaturesPayload | null;
loading: boolean;
query: string;
actionKey: string | null;
chatAppsDocsUrl?: string;
showBrandLogos: boolean;
error: string | null;
requiresRestartPending: boolean;
onQueryChange: (value: string) => void;
onAction: (action: "enable" | "disable", name: string) => void;
onFeaturesUpdate: (payload: NanobotFeaturesPayload) => void;
onDismissStatus: () => void;
onRestart?: () => void;
isRestarting?: boolean;
}) {
const { t } = useTranslation();
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
const normalizedQuery = query.trim().toLowerCase();
const [filter, setFilter] = useState<ChannelFilter>("all");
const splitLayout = useMediaQuery("(min-width: 1280px)");
const containerRef = useRef<HTMLDivElement>(null);
const compactDetailTopRef = useRef<HTMLButtonElement>(null);
const [compactDetailOpen, setCompactDetailOpen] = useState(false);
const allChannels = (nanobotFeatures?.features ?? [])
.filter((feature) => feature.type === "channel")
.filter((feature) => feature.settings_visible !== false)
.filter((feature) => !normalizedQuery || channelSearchText(feature, t).includes(normalizedQuery))
.sort((left, right) => {
const rank = Number(!left.ready) - Number(!right.ready);
return rank || localizedChannelDisplayName(left, t).localeCompare(
localizedChannelDisplayName(right, t),
);
});
const channels = allChannels.filter((feature) => channelMatchesFilter(feature, filter));
const [selectedChannelName, setSelectedChannelName] = useState<string | null>(null);
const selectedChannel =
channels.find((feature) => feature.name === selectedChannelName) ?? channels[0] ?? null;
const enabledCount = allChannels.filter(channelIsRunning).length;
const offCount = Math.max(0, allChannels.length - enabledCount);
const filterOptions: Array<{ value: ChannelFilter; label: string; count: number }> = [
{ value: "all", label: tx("settings.channels.filterAll", "All"), count: allChannels.length },
{ value: "on", label: tx("settings.channels.filterOn", "On"), count: enabledCount },
{ value: "off", label: tx("settings.channels.filterOff", "Off"), count: offCount },
];
const statusMessage = error;
const statusIsError = true;
useEffect(() => {
if (!channels.length) {
if (selectedChannelName !== null) setSelectedChannelName(null);
setCompactDetailOpen(false);
return;
}
if (!selectedChannelName || !channels.some((feature) => feature.name === selectedChannelName)) {
setSelectedChannelName(channels[0].name);
setCompactDetailOpen(false);
}
}, [channels, selectedChannelName]);
useEffect(() => {
if (splitLayout) return;
const resetScroll = () => {
let node = containerRef.current?.parentElement ?? null;
while (node) {
node.scrollTop = 0;
node = node.parentElement;
}
if (compactDetailOpen) {
compactDetailTopRef.current?.scrollIntoView?.({ block: "start" });
}
};
resetScroll();
const frame = window.requestAnimationFrame(resetScroll);
return () => window.cancelAnimationFrame(frame);
}, [compactDetailOpen, selectedChannelName, splitLayout]);
const openChannel = (name: string) => {
setSelectedChannelName(name);
if (!splitLayout) setCompactDetailOpen(true);
};
const setupPanel = selectedChannel ? (
<ChannelSetupPanel
token={token}
feature={selectedChannel}
actionKey={actionKey}
chatAppsDocsUrl={chatAppsDocsUrl}
showBrandLogos={showBrandLogos}
onAction={onAction}
onFeaturesUpdate={onFeaturesUpdate}
/>
) : null;
const showingCompactDetail = !splitLayout && compactDetailOpen && selectedChannel !== null;
return (
<div
ref={containerRef}
className="flex min-h-full flex-1 flex-col xl:min-h-0 xl:overflow-hidden"
>
{!showingCompactDetail ? (
<section className="shrink-0 space-y-4">
<div className="flex flex-col gap-3 lg:flex-row lg:items-center">
<div className="relative min-w-0 flex-1">
<Search className="pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" aria-hidden />
<Input
value={query}
onChange={(event) => onQueryChange(event.target.value)}
placeholder={tx("settings.channels.searchPlaceholder", "Search channels")}
className={cn(
"h-12 rounded-[14px] pl-11 text-[15px]",
SETTINGS_SEARCH_INPUT_CLASS,
)}
/>
</div>
<div className="flex shrink-0 flex-wrap gap-1.5 rounded-[14px] bg-muted/55 p-1">
{filterOptions.map((option) => (
<button
key={option.value}
type="button"
onClick={() => setFilter(option.value)}
className={cn(
"rounded-[11px] px-3 py-1.5 text-[12px] font-medium transition-colors",
filter === option.value
? "bg-background text-foreground"
: "text-muted-foreground hover:text-foreground",
)}
>
{option.label}
<span className="ml-1 text-[11px] text-muted-foreground">{option.count}</span>
</button>
))}
</div>
</div>
</section>
) : null}
{statusMessage ? (
<div className="mt-3 shrink-0">
<DismissibleStatusMessage
message={statusMessage}
isError={statusIsError}
onDismiss={onDismissStatus}
/>
</div>
) : null}
{requiresRestartPending ? (
<div className="mt-3 shrink-0">
<RestartRequiredNotice
message={tx("settings.channels.restartRequired", "Restart nanobot to apply updated channel support.")}
onRestart={onRestart}
isRestarting={isRestarting}
/>
</div>
) : null}
<section
className={cn(
"flex flex-1 flex-col",
showingCompactDetail ? "mt-1" : "mt-5",
splitLayout && "min-h-0 overflow-hidden",
)}
>
{loading && !nanobotFeatures ? (
<div className="flex h-36 items-center justify-center text-sm text-muted-foreground">
<Loader2 className="mr-2 h-4 w-4 animate-spin" aria-hidden />
{tx("settings.channels.loading", "Loading Channels...")}
</div>
) : channels.length ? splitLayout ? (
<div className="grid min-h-0 flex-1 grid-cols-[minmax(0,1fr)_minmax(400px,460px)] gap-6 overflow-hidden">
<div className="min-h-0 space-y-1 overflow-y-auto overscroll-contain pr-1">
{channels.map((feature) => (
<ChannelCatalogRow
key={feature.name}
feature={feature}
selected={selectedChannel?.name === feature.name}
showBrandLogos={showBrandLogos}
onSelect={() => openChannel(feature.name)}
/>
))}
</div>
<div className="min-h-0 overflow-y-auto overscroll-contain pr-1">{setupPanel}</div>
</div>
) : showingCompactDetail ? (
<div className="pb-6">
<button
ref={compactDetailTopRef}
type="button"
onClick={() => setCompactDetailOpen(false)}
className="mb-4 inline-flex h-9 items-center gap-1.5 rounded-full px-2.5 text-[13px] font-medium text-muted-foreground transition-colors hover:bg-muted/70 hover:text-foreground"
>
<ChevronLeft className="h-4 w-4" aria-hidden />
{tx("settings.channels.backToChannels", "All channels")}
</button>
{setupPanel}
</div>
) : (
<div className="space-y-1 pb-6">
{channels.map((feature) => (
<ChannelCatalogRow
key={feature.name}
feature={feature}
selected={false}
showBrandLogos={showBrandLogos}
onSelect={() => openChannel(feature.name)}
/>
))}
</div>
) : (
<div className="min-h-0 flex-1 px-3 py-12 text-center text-sm text-muted-foreground">
{tx("settings.channels.empty", "No channels match this filter.")}
</div>
)}
</section>
</div>
);
}
@@ -0,0 +1,406 @@
import { useEffect, useState } from "react";
import { Eye, EyeOff, Loader2, PauseCircle, PlayCircle, RotateCcw } from "lucide-react";
import { useTranslation } from "react-i18next";
import type { AgentSettingsDraft } from "@/components/settings/models/ModelsSettings";
import {
NumberInput,
ReadOnlyRow,
SettingsGroup,
SettingsRow,
SettingsSectionTitle,
StatusPill,
} from "@/components/settings/shared/SettingsControls";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { SegmentedControl } from "@/components/ui/segmented-control";
import { isLoopbackHost } from "@/lib/network";
import { getRuntimeHost, isNativeRuntime } from "@/lib/runtime";
import type { ApiServicePayload, NanobotFeatureInfo, SettingsPayload } from "@/lib/types";
export function RuntimeSettings({
form,
settings,
onRestart,
isRestarting,
requiresRestartPending,
apiService,
apiServiceLoading,
apiServiceAction,
apiServiceError,
langfuseFeature,
capabilitiesLoading,
capabilityAction,
capabilityError,
onApiServiceAction,
onInstallCapability,
}: {
form: AgentSettingsDraft;
settings: SettingsPayload;
onRestart?: () => void;
isRestarting?: boolean;
requiresRestartPending: boolean;
apiService: ApiServicePayload | null;
apiServiceLoading: boolean;
apiServiceAction: "start" | "stop" | null;
apiServiceError: string | null;
langfuseFeature?: NanobotFeatureInfo;
capabilitiesLoading: boolean;
capabilityAction: string | null;
capabilityError: string | null;
onApiServiceAction: (
action: "start" | "stop",
values?: { host: string; port: number; timeout: number; apiKey?: string },
) => void;
onInstallCapability: (name: string) => void;
}) {
const { t } = useTranslation();
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
const runtimeSurface = settings.surface ?? settings.runtime_surface;
const runtimeHost = getRuntimeHost(runtimeSurface, settings.runtime_capabilities);
const openLogs = runtimeHost.openLogs;
const exportDiagnostics = runtimeHost.exportDiagnostics;
const isNativeHost = isNativeRuntime(runtimeSurface);
const restartActionLabel = isNativeHost
? tx("app.system.restartEngine", "Restart engine")
: t("app.system.restart");
const restartingActionLabel = isNativeHost
? tx("app.system.restartingEngine", "Restarting engine...")
: t("app.system.restarting");
const [diagnosticsPath, setDiagnosticsPath] = useState<string | null>(null);
const [hostActionMessage, setHostActionMessage] = useState<{
target: "logs" | "diagnostics";
message: string;
} | null>(null);
const [hostActionBusy, setHostActionBusy] =
useState<"logs" | "diagnostics" | null>(null);
const apiDefaults = apiService ?? {
installed: false,
running: false,
managed: false,
host: settings.api?.host ?? "127.0.0.1",
port: settings.api?.port ?? 8900,
timeout: settings.api?.timeout ?? 120,
api_key_hint: settings.api?.api_key_hint,
endpoint: `http://127.0.0.1:${settings.api?.port ?? 8900}/v1`,
command: "nanobot serve",
};
const [apiHost, setApiHost] = useState(apiDefaults.host);
const [apiPort, setApiPort] = useState(apiDefaults.port);
const [apiKey, setApiKey] = useState("");
const [apiKeyVisible, setApiKeyVisible] = useState(false);
useEffect(() => {
if (!apiService) return;
setApiHost(apiService.host);
setApiPort(apiService.port);
setApiKey("");
setApiKeyVisible(false);
}, [apiService]);
const apiNetworkAccess = !isLoopbackHost(apiHost);
const apiMissingNetworkKey = apiNetworkAccess && !apiKey.trim() && !apiDefaults.api_key_hint;
const engineState = isRestarting
? tx("settings.values.restartingEngine", "Restarting")
: settings.apply_state?.status === "pending"
? tx("settings.values.pending", "Pending")
: tx("settings.values.ready", "Ready");
const runHostAction = async (
target: "logs" | "diagnostics",
action: (() => Promise<string | void>) | undefined,
successMessage: (result: string | void) => string,
failureMessage: string,
) => {
if (!action) {
setHostActionMessage({
target,
message: tx(
"settings.status.hostApiUnavailable",
"Host actions are only available inside the native app.",
),
});
return;
}
setHostActionBusy(target);
setHostActionMessage(null);
try {
const result = await action();
setHostActionMessage({ target, message: successMessage(result) });
} catch {
setHostActionMessage({ target, message: failureMessage });
} finally {
setHostActionBusy(null);
}
};
return (
<div className="space-y-7">
{isNativeHost ? (
<section>
<SettingsSectionTitle>{tx("settings.sections.nativeHost", "Native host")}</SettingsSectionTitle>
<SettingsGroup>
<ReadOnlyRow title={tx("settings.rows.engine", "Engine")} value={engineState} />
{settings.runtime_capabilities?.can_open_logs ? (
<SettingsRow
title={tx("settings.rows.logs", "Logs")}
description={
hostActionMessage?.target === "logs" ? hostActionMessage.message : undefined
}
>
<Button
size="sm"
variant="outline"
onClick={() =>
void runHostAction(
"logs",
openLogs,
() => tx("settings.status.logsOpened", "Opened logs folder."),
tx("settings.status.logsOpenFailed", "Could not open logs folder."),
)
}
disabled={hostActionBusy !== null}
className="rounded-full"
>
{hostActionBusy === "logs"
? tx("settings.actions.opening", "Opening...")
: tx("settings.actions.open", "Open")}
</Button>
</SettingsRow>
) : null}
{settings.runtime_capabilities?.can_export_diagnostics ? (
<SettingsRow
title={tx("settings.rows.diagnostics", "Diagnostics")}
description={
hostActionMessage?.target === "diagnostics"
? hostActionMessage.message
: diagnosticsPath || undefined
}
>
<Button
size="sm"
variant="outline"
onClick={() =>
void runHostAction(
"diagnostics",
exportDiagnostics ? async () => {
const path = await exportDiagnostics();
setDiagnosticsPath(path);
return path;
} : undefined,
(path) =>
t("settings.status.diagnosticsExported", {
path: String(path ?? ""),
defaultValue: "Diagnostics exported to {{path}}.",
}),
tx("settings.status.diagnosticsExportFailed", "Could not export diagnostics."),
)
}
disabled={hostActionBusy !== null}
className="rounded-full"
>
{hostActionBusy === "diagnostics"
? tx("settings.actions.exporting", "Exporting...")
: tx("settings.actions.export", "Export")}
</Button>
</SettingsRow>
) : null}
</SettingsGroup>
</section>
) : null}
<section>
<SettingsSectionTitle>{tx("settings.api.title", "API server")}</SettingsSectionTitle>
<SettingsGroup>
<SettingsRow
title={tx("settings.api.openaiCompatible", "OpenAI-compatible API")}
description={
apiServiceError
? apiServiceError
: apiDefaults.running
? apiDefaults.endpoint
: undefined
}
>
<div className="flex items-center justify-end gap-2">
<StatusPill tone={apiDefaults.running ? "success" : "neutral"}>
{apiServiceLoading
? tx("settings.values.checking", "Checking")
: apiDefaults.running
? tx("settings.values.running", "Running")
: tx("settings.values.off", "Off")}
</StatusPill>
<Button
size="sm"
variant="outline"
disabled={apiServiceLoading || apiServiceAction !== null || apiMissingNetworkKey}
onClick={() =>
onApiServiceAction(
apiDefaults.running ? "stop" : "start",
apiDefaults.running
? undefined
: {
host: apiHost,
port: apiPort,
timeout: apiDefaults.timeout,
apiKey: apiKey.trim() || undefined,
},
)
}
className="rounded-full"
>
{apiServiceAction ? (
<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden />
) : apiDefaults.running ? (
<PauseCircle className="mr-1.5 h-3.5 w-3.5" aria-hidden />
) : (
<PlayCircle className="mr-1.5 h-3.5 w-3.5" aria-hidden />
)}
{apiServiceAction === "start"
? tx("settings.api.starting", "Starting...")
: apiServiceAction === "stop"
? tx("settings.api.stopping", "Stopping...")
: apiDefaults.running
? tx("settings.api.stop", "Stop")
: tx("settings.api.start", "Start API server")}
</Button>
</div>
</SettingsRow>
{!apiDefaults.running ? (
<>
<SettingsRow
title={tx("settings.api.access", "Access")}
description={
apiNetworkAccess
? tx("settings.api.networkHelp", "Other devices can connect; an API key is required.")
: tx("settings.api.localHelp", "Only this device can connect.")
}
>
<SegmentedControl
value={apiNetworkAccess ? "network" : "local"}
options={[
{ value: "local", label: tx("settings.api.thisDevice", "This device") },
{ value: "network", label: tx("settings.api.localNetwork", "Local network") },
]}
onChange={(value) => setApiHost(value === "network" ? "0.0.0.0" : "127.0.0.1")}
/>
</SettingsRow>
<SettingsRow title={tx("settings.api.port", "Port")}>
<NumberInput value={apiPort} min={1} max={65535} onChange={setApiPort} />
</SettingsRow>
{apiNetworkAccess ? (
<SettingsRow
title={tx("settings.api.apiKey", "API key")}
description={
apiMissingNetworkKey
? tx("settings.api.apiKeyRequired", "Required before exposing the API to your network.")
: tx("settings.api.apiKeyHelp", "Clients send this as a Bearer token.")
}
>
<div className="relative w-[280px] max-w-full">
<Input
type={apiKeyVisible ? "text" : "password"}
value={apiKey}
onChange={(event) => setApiKey(event.target.value)}
placeholder={apiDefaults.api_key_hint ?? tx("settings.api.apiKeyPlaceholder", "Enter an API key")}
className="h-9 rounded-full pr-10 text-[13px]"
/>
<Button
type="button"
variant="ghost"
size="icon"
onClick={() => setApiKeyVisible((visible) => !visible)}
aria-label={apiKeyVisible ? tx("settings.byok.hideApiKey", "Hide API key") : tx("settings.byok.showApiKey", "Show API key")}
className="absolute right-1 top-1/2 h-7 w-7 -translate-y-1/2 rounded-full"
>
{apiKeyVisible ? <EyeOff className="h-3.5 w-3.5" /> : <Eye className="h-3.5 w-3.5" />}
</Button>
</div>
</SettingsRow>
) : null}
</>
) : null}
</SettingsGroup>
</section>
<section>
<SettingsSectionTitle>{tx("settings.observability.title", "Observability")}</SettingsSectionTitle>
<SettingsGroup>
<SettingsRow
title="Langfuse"
description={
settings.observability?.configured
? undefined
: tx(
"settings.observability.environment",
"Set LANGFUSE_SECRET_KEY and LANGFUSE_PUBLIC_KEY, then restart nanobot.",
)
}
>
{capabilitiesLoading ? (
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" aria-hidden />
) : langfuseFeature?.installed ? (
<StatusPill tone={settings.observability?.configured ? "success" : "neutral"}>
{settings.observability?.configured
? tx("settings.values.ready", "Ready")
: tx("settings.values.needsSetup", "Needs setup")}
</StatusPill>
) : (
<Button
size="sm"
variant="outline"
disabled={capabilityAction === "enable:langfuse"}
onClick={() => onInstallCapability("langfuse")}
className="rounded-full"
>
{capabilityAction === "enable:langfuse" ? (
<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden />
) : null}
{capabilityAction === "enable:langfuse"
? tx("settings.capabilities.installing", "Installing support...")
: tx("settings.observability.enable", "Enable tracing support")}
</Button>
)}
</SettingsRow>
</SettingsGroup>
{capabilityError ? <p className="mt-2 text-[12px] text-destructive">{capabilityError}</p> : null}
</section>
<section>
<SettingsSectionTitle>{t("settings.sections.system")}</SettingsSectionTitle>
<SettingsGroup>
{!isNativeHost ? (
<ReadOnlyRow
title={tx("settings.rows.gateway", "Gateway")}
value={`${settings.runtime.gateway_host}:${settings.runtime.gateway_port}`}
/>
) : null}
<ReadOnlyRow title={t("settings.rows.configPath")} value={settings.runtime.config_path} />
<ReadOnlyRow title={tx("settings.rows.workspacePath", "Default workspace")} value={settings.runtime.workspace_path} />
<ReadOnlyRow title={tx("settings.rows.timezone", "Timezone")} value={form.timezone} />
{onRestart ? (
<SettingsRow
title={t("settings.rows.restart")}
description={
requiresRestartPending
? tx("settings.status.savedRestartApply", "Saved. Restart when ready.")
: undefined
}
>
<Button
size="sm"
variant="outline"
onClick={onRestart}
disabled={isRestarting}
className="rounded-full"
>
{isRestarting ? (
<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden />
) : (
<RotateCcw className="mr-1.5 h-3.5 w-3.5" aria-hidden />
)}
{isRestarting ? restartingActionLabel : restartActionLabel}
</Button>
</SettingsRow>
) : null}
</SettingsGroup>
</section>
</div>
);
}
@@ -0,0 +1,656 @@
import type { Dispatch, SetStateAction } from "react";
import type { TFunction } from "i18next";
import type {
ApplySettingsPayload,
MaybeRestartHostEngine,
PendingRestartSections,
} from "@/components/settings/contracts";
import type { AutomationAction } from "@/components/settings/system/AutomationsSettings";
import { DEFAULT_CUSTOM_MCP_FORM } from "@/components/settings/system/AppsSettings";
import type { SystemSettingsState } from "@/components/settings/system/useSystemSettingsState";
import {
cancelMcpOAuth,
completeMcpOAuth,
disableNanobotFeature,
enableNanobotFeature,
fetchNanobotFeatures,
fetchSettings,
fetchMcpOAuthStatus,
fetchMcpPresets,
importMcpConfig,
runAutomationAction,
runCliAppAction,
runMcpPresetAction,
saveCustomMcpServer,
startMcpOAuth,
startApiService,
stopApiService,
updateAutomation,
updateMcpServerTools,
} from "@/lib/api";
import { notifyCliAppsChanged } from "@/lib/cli-app-events";
import { notifyMcpPresetsChanged } from "@/lib/mcp-preset-events";
import type { NanobotClient } from "@/lib/nanobot-client";
import type {
AutomationUpdatePayload,
McpOAuthFlowPayload,
McpPresetsPayload,
NanobotFeatureInfo,
SessionAutomationJob,
} from "@/lib/types";
function isExpectedMcpOAuthPendingReloadFailure(
payload: McpPresetsPayload,
expectedName?: string,
): boolean {
if (
!expectedName
|| payload.last_action?.ok === false
|| payload.hot_reload?.ok !== false
) return false;
const normalizedName = expectedName.trim().toLowerCase();
const failed = payload.hot_reload.failed ?? [];
if (
!normalizedName
|| failed.length !== 1
|| failed[0].trim().toLowerCase() !== normalizedName
) return false;
return payload.presets.some((preset) => (
preset.name.trim().toLowerCase() === normalizedName
&& preset.auth === "oauth"
&& preset.status === "authorization_required"
));
}
interface SystemSettingsActionsOptions {
state: SystemSettingsState;
featureCatalog: NanobotFeatureInfo[];
client: NanobotClient;
token: string;
getToken: () => string;
t: TFunction;
applyPayload: ApplySettingsPayload;
maybeRestartHostEngine: MaybeRestartHostEngine;
setPendingRestartSections: Dispatch<SetStateAction<PendingRestartSections>>;
refreshAutomations: (showLoading?: boolean) => Promise<void>;
}
export function createSystemSettingsActions({
state,
featureCatalog,
client,
token,
getToken,
t,
applyPayload,
maybeRestartHostEngine,
setPendingRestartSections,
refreshAutomations,
}: SystemSettingsActionsOptions) {
const {
apiServiceAction,
customMcpForm,
mcpConfigImport,
mcpOAuthCallbackUrl,
mcpOAuthFlowRef,
mcpOAuthNavigatedUrlRef,
mcpOAuthPopupRef,
nanobotFeatures,
setApiService,
setApiServiceAction,
setApiServiceError,
setAutomationAction,
setAutomationPendingDelete,
setAutomationPendingEdit,
setAutomations,
setAutomationsError,
setCliApps,
setCliAppsAction,
setCliAppsError,
setCliAppsFocusName,
setCliAppsMessage,
setCustomMcpForm,
setMcpConfigImport,
setMcpError,
setMcpFieldValues,
setMcpMessage,
setMcpOAuthCallbackError,
setMcpOAuthCallbackUrl,
setMcpOAuthCompleting,
setMcpOAuthFlow,
setMcpOAuthPopupBlocked,
setMcpPresetAction,
setMcpPresets,
setNanobotFeatureAction,
setNanobotFeatureConfirm,
setNanobotFeatures,
setNanobotFeaturesError,
} = state;
const installCapabilities = async (names: string[]): Promise<boolean> => {
const missing = names.filter(
(name) => !featureCatalog.find((feature) => feature.name === name)?.installed,
);
if (!missing.length) return true;
setNanobotFeatureAction(`enable:${names.join("+")}`);
setNanobotFeaturesError(null);
try {
let latest = nanobotFeatures;
for (const name of missing) {
latest = await enableNanobotFeature(client, name);
if (latest.requires_restart) {
setPendingRestartSections((prev) => ({ ...prev, runtime: true }));
}
}
if (latest) setNanobotFeatures(latest);
return true;
} catch (err) {
setNanobotFeaturesError((err as Error).message);
return false;
} finally {
setNanobotFeatureAction(null);
}
};
const handleApiServiceAction = async (
action: "start" | "stop",
values?: { host: string; port: number; timeout: number; apiKey?: string },
) => {
if (apiServiceAction) return;
setApiServiceAction(action);
setApiServiceError(null);
try {
const payload = action === "start"
? await startApiService(client, values!)
: await stopApiService(client);
setApiService(payload);
const refreshed = await fetchNanobotFeatures(token);
setNanobotFeatures(refreshed);
const nextSettings = await fetchSettings(token);
applyPayload(nextSettings);
} catch (err) {
setApiServiceError((err as Error).message);
} finally {
setApiServiceAction(null);
}
};
const handleCliAppAction = async (
action: "install" | "update" | "uninstall" | "test",
name: string,
) => {
const key = `${action}:${name}`;
setCliAppsAction(key);
setCliAppsMessage(null);
setCliAppsError(null);
try {
const payload = await runCliAppAction(client, action, name);
setCliApps(payload);
if (action !== "test") {
notifyCliAppsChanged(payload);
}
setCliAppsMessage(payload.last_action?.message ?? null);
setCliAppsFocusName(action === "uninstall" ? null : name);
} catch (err) {
setCliAppsError((err as Error).message);
} finally {
setCliAppsAction(null);
}
};
const handleNanobotFeatureAction = async (
action: "enable" | "disable",
name: string,
confirmed = false,
) => {
const feature = featureCatalog.find((item) => item.name === name);
if (action === "enable" && !confirmed && feature && !feature.installed && feature.install_supported) {
setNanobotFeaturesError(null);
setNanobotFeatureConfirm(feature);
return;
}
const key = `${action}:${name}`;
setNanobotFeatureAction(key);
setNanobotFeatureConfirm(null);
setNanobotFeaturesError(null);
try {
const payload = action === "enable"
? await enableNanobotFeature(client, name)
: await disableNanobotFeature(client, name);
setNanobotFeatures(payload);
if (payload.requires_restart) {
setPendingRestartSections((prev) => ({ ...prev, runtime: true }));
}
} catch (err) {
setNanobotFeaturesError((err as Error).message);
} finally {
setNanobotFeatureAction(null);
}
};
const handleAutomationAction = async (
action: AutomationAction,
job: SessionAutomationJob,
) => {
const key = `${action}:${job.id}`;
setAutomationAction(key);
setAutomationsError(null);
try {
const payload = await runAutomationAction(client, action, job.id);
setAutomations(payload);
if (action === "delete") setAutomationPendingDelete(null);
if (action === "run") {
window.setTimeout(() => void refreshAutomations(false), 1200);
window.setTimeout(() => void refreshAutomations(false), 4000);
}
} catch (err) {
setAutomationsError((err as Error).message);
} finally {
setAutomationAction(null);
}
};
const handleAutomationEdit = async (
job: SessionAutomationJob,
values: AutomationUpdatePayload,
) => {
const key = `update:${job.id}`;
setAutomationAction(key);
setAutomationsError(null);
try {
const payload = await updateAutomation(client, job.id, values);
setAutomations(payload);
setAutomationPendingEdit(null);
} catch (err) {
setAutomationsError((err as Error).message);
} finally {
setAutomationAction(null);
}
};
const closeMcpOAuthPopup = () => {
const popup = mcpOAuthPopupRef.current;
mcpOAuthPopupRef.current = null;
mcpOAuthNavigatedUrlRef.current = null;
if (!popup) return;
try {
if (!popup.closed) popup.close();
} catch {
// The authorization page may have navigated cross-origin before it closed itself.
}
};
const openMcpOAuthPopup = (authorizationUrl?: string): Window | null => {
let popup: Window | null = null;
try {
popup = window.open(
authorizationUrl ?? "about:blank",
"nanobot-mcp-oauth",
"popup,width=560,height=720,resizable=yes,scrollbars=yes",
);
if (popup) {
mcpOAuthPopupRef.current = popup;
mcpOAuthNavigatedUrlRef.current = authorizationUrl ?? null;
if (!authorizationUrl) {
try {
popup.document.title = t("settings.oauth.signingIn", { defaultValue: "Preparing sign-in…" });
popup.document.body.textContent = t("settings.mcp.preparingSignIn", {
defaultValue: "Preparing secure sign-in…",
});
} catch {
// about:blank can become unavailable if the window is reused mid-navigation.
}
}
try {
popup.opener = null;
popup.focus();
} catch {
// A cross-origin authorization page can restrict window access.
}
}
} catch {
// Browsers can reject popup creation before returning a window handle.
}
setMcpOAuthPopupBlocked(!popup);
return popup;
};
const navigateMcpOAuthPopup = (flow: McpOAuthFlowPayload) => {
const authorizationUrl = flow.authorization_url;
if (!authorizationUrl) return;
const popup = mcpOAuthPopupRef.current;
// OAuth pages can use Cross-Origin-Opener-Policy, which severs the
// WindowProxy and makes an open tab appear closed. Once navigation was
// requested, do not mistake that browser isolation for a blocked popup.
if (popup && mcpOAuthNavigatedUrlRef.current === authorizationUrl) return;
try {
if (popup && !popup.closed) {
popup.location.replace(authorizationUrl);
mcpOAuthNavigatedUrlRef.current = authorizationUrl;
popup.focus();
setMcpOAuthPopupBlocked(false);
return;
}
if (popup) return;
} catch {
// Fall through to the explicit Continue in browser action.
}
setMcpOAuthPopupBlocked(true);
};
const finishMcpOAuthFlow = async (flow: McpOAuthFlowPayload) => {
if (mcpOAuthFlowRef.current?.flow_id !== flow.flow_id) return;
closeMcpOAuthPopup();
mcpOAuthFlowRef.current = null;
setMcpOAuthFlow(null);
setMcpPresetAction(null);
setMcpOAuthCallbackUrl("");
setMcpOAuthCompleting(false);
setMcpOAuthCallbackError(null);
if (flow.status === "connected") {
try {
const payload = await fetchMcpPresets(getToken());
setMcpPresets(payload);
notifyMcpPresetsChanged(payload);
setMcpMessage(null);
setMcpError(null);
} catch (err) {
setMcpError((err as Error).message);
}
return;
}
if (flow.status === "authorized" && flow.hot_reload) {
if (flow.hot_reload.requires_restart) {
setPendingRestartSections((prev) => ({ ...prev, runtime: true }));
}
setMcpError(
flow.hot_reload.message
|| t("settings.mcp.reloadFailed", {
defaultValue: "Signed in, but nanobot could not connect the tools. Try restarting nanobot.",
}),
);
return;
}
if (flow.status === "failed") {
setMcpError(
flow.error
|| t("settings.mcp.oauthFailed", {
defaultValue: "Unable to connect. Try signing in again.",
}),
);
}
};
const monitorMcpOAuthFlow = async (initial: McpOAuthFlowPayload) => {
let current = initial;
while (mcpOAuthFlowRef.current?.flow_id === current.flow_id) {
navigateMcpOAuthPopup(current);
const terminal =
current.status === "connected"
|| current.status === "failed"
|| current.status === "cancelled"
|| (current.status === "authorized" && Boolean(current.hot_reload));
if (terminal) {
await finishMcpOAuthFlow(current);
return;
}
await new Promise((resolve) => window.setTimeout(resolve, 800));
if (mcpOAuthFlowRef.current?.flow_id !== current.flow_id) return;
try {
current = await fetchMcpOAuthStatus(getToken(), current.flow_id);
if (mcpOAuthFlowRef.current?.flow_id !== current.flow_id) return;
mcpOAuthFlowRef.current = current;
setMcpOAuthFlow(current);
} catch (err) {
if (mcpOAuthFlowRef.current?.flow_id !== current.flow_id) return;
closeMcpOAuthPopup();
mcpOAuthFlowRef.current = null;
setMcpOAuthFlow(null);
setMcpPresetAction(null);
setMcpOAuthCallbackUrl("");
setMcpOAuthCompleting(false);
setMcpOAuthCallbackError(null);
setMcpError((err as Error).message);
return;
}
}
};
const handleMcpOAuthConnect = async (name: string) => {
openMcpOAuthPopup();
const key = `oauth:${name}`;
setMcpPresetAction(key);
setMcpMessage(null);
setMcpError(null);
setMcpOAuthCallbackUrl("");
setMcpOAuthCompleting(false);
setMcpOAuthCallbackError(null);
try {
const flow = await startMcpOAuth(client, name);
mcpOAuthFlowRef.current = flow;
setMcpOAuthFlow(flow);
navigateMcpOAuthPopup(flow);
void monitorMcpOAuthFlow(flow);
} catch (err) {
closeMcpOAuthPopup();
mcpOAuthFlowRef.current = null;
setMcpOAuthFlow(null);
setMcpPresetAction(null);
setMcpOAuthCallbackUrl("");
setMcpOAuthCompleting(false);
setMcpOAuthCallbackError(null);
setMcpError((err as Error).message);
}
};
const handleMcpOAuthCancel = async () => {
const flow = mcpOAuthFlowRef.current;
if (!flow) return;
mcpOAuthFlowRef.current = null;
setMcpOAuthFlow(null);
setMcpPresetAction(null);
setMcpOAuthCallbackUrl("");
setMcpOAuthCompleting(false);
setMcpOAuthCallbackError(null);
closeMcpOAuthPopup();
try {
await cancelMcpOAuth(client, flow.flow_id);
} catch (err) {
setMcpError((err as Error).message);
}
};
const handleMcpOAuthOpen = () => {
const authorizationUrl = mcpOAuthFlowRef.current?.authorization_url;
if (!authorizationUrl) return;
openMcpOAuthPopup(authorizationUrl);
};
const handleMcpOAuthComplete = async () => {
const flow = mcpOAuthFlowRef.current;
const callbackUrl = mcpOAuthCallbackUrl.trim();
if (!flow || flow.completion_input !== "callback_url") return;
if (!callbackUrl) {
setMcpOAuthCallbackError(t("settings.oauth.pasteCallbackToContinue"));
return;
}
setMcpOAuthCompleting(true);
setMcpOAuthCallbackError(null);
try {
const next = await completeMcpOAuth(client, flow.flow_id, callbackUrl);
if (mcpOAuthFlowRef.current?.flow_id !== flow.flow_id) return;
mcpOAuthFlowRef.current = next;
setMcpOAuthFlow(next);
} catch (err) {
if (mcpOAuthFlowRef.current?.flow_id !== flow.flow_id) return;
setMcpOAuthCallbackError((err as Error).message);
} finally {
if (mcpOAuthFlowRef.current?.flow_id === flow.flow_id) {
setMcpOAuthCompleting(false);
}
}
};
const applyMcpActionFeedback = (
payload: McpPresetsPayload,
announceSuccess = false,
expectedOAuthPendingName?: string,
) => {
const expectedOAuthPending = isExpectedMcpOAuthPendingReloadFailure(
payload,
expectedOAuthPendingName,
);
const actionError = payload.last_action?.ok === false
? payload.last_action.error || payload.last_action.message
: payload.hot_reload?.ok === false && !expectedOAuthPending
? payload.hot_reload.message
: null;
setMcpError(actionError || null);
setMcpMessage(
actionError || !announceSuccess
? null
: payload.last_action?.message ?? null,
);
};
const handleMcpPresetAction = async (
action: "enable" | "remove" | "test",
name: string,
values: Record<string, string> = {},
) => {
const key = `${action}:${name}`;
setMcpPresetAction(key);
setMcpMessage(null);
setMcpError(null);
try {
const payload = await runMcpPresetAction(client, action, name, values);
setMcpPresets(payload);
applyMcpActionFeedback(payload, action === "test");
if (action !== "test") {
notifyMcpPresetsChanged(payload);
}
if (payload.requires_restart) {
setPendingRestartSections((prev) => ({ ...prev, runtime: true }));
}
await maybeRestartHostEngine(payload);
if (action === "enable") {
setMcpFieldValues((prev) => ({ ...prev, [name]: {} }));
}
} catch (err) {
setMcpError((err as Error).message);
} finally {
setMcpPresetAction(null);
}
};
const handleSaveCustomMcp = async () => {
const name = customMcpForm.name.trim();
const expectsOAuthAuthorization = (
customMcpForm.transport !== "stdio" && customMcpForm.auth === "oauth"
);
const key = `custom:${name || "new"}`;
setMcpPresetAction(key);
setMcpMessage(null);
setMcpError(null);
try {
const payload = await saveCustomMcpServer(client, {
name,
transport: customMcpForm.transport,
auth:
customMcpForm.transport !== "stdio" && customMcpForm.auth === "oauth"
? "oauth"
: "",
command: customMcpForm.command,
args: customMcpForm.args,
url: customMcpForm.url,
env: customMcpForm.env,
headers:
customMcpForm.transport !== "stdio" && customMcpForm.auth === "headers"
? customMcpForm.headers
: "",
tool_timeout: customMcpForm.toolTimeout,
});
setMcpPresets(payload);
applyMcpActionFeedback(
payload,
false,
expectsOAuthAuthorization ? name : undefined,
);
notifyMcpPresetsChanged(payload);
if (payload.requires_restart) {
setPendingRestartSections((prev) => ({ ...prev, runtime: true }));
}
await maybeRestartHostEngine(payload);
setCustomMcpForm((prev) => ({ ...DEFAULT_CUSTOM_MCP_FORM, transport: prev.transport }));
} catch (err) {
setMcpError((err as Error).message);
} finally {
setMcpPresetAction(null);
}
};
const handleImportMcpConfig = async () => {
setMcpPresetAction("import");
setMcpMessage(null);
setMcpError(null);
try {
const payload = await importMcpConfig(client, mcpConfigImport);
setMcpPresets(payload);
applyMcpActionFeedback(payload);
notifyMcpPresetsChanged(payload);
if (payload.requires_restart) {
setPendingRestartSections((prev) => ({ ...prev, runtime: true }));
}
await maybeRestartHostEngine(payload);
setMcpConfigImport("");
} catch (err) {
setMcpError((err as Error).message);
} finally {
setMcpPresetAction(null);
}
};
const handleMcpToolsChange = async (name: string, enabledTools: string[]) => {
setMcpPresetAction(`tools:${name}`);
setMcpMessage(null);
setMcpError(null);
try {
const payload = await updateMcpServerTools(client, name, enabledTools);
setMcpPresets(payload);
applyMcpActionFeedback(payload);
notifyMcpPresetsChanged(payload);
if (payload.requires_restart) {
setPendingRestartSections((prev) => ({ ...prev, runtime: true }));
}
await maybeRestartHostEngine(payload);
} catch (err) {
setMcpError((err as Error).message);
} finally {
setMcpPresetAction(null);
}
};
return {
handleApiServiceAction,
handleAutomationAction,
handleAutomationEdit,
handleCliAppAction,
handleImportMcpConfig,
handleMcpOAuthCancel,
handleMcpOAuthComplete,
handleMcpOAuthConnect,
handleMcpOAuthOpen,
handleMcpPresetAction,
handleMcpToolsChange,
handleNanobotFeatureAction,
handleSaveCustomMcp,
installCapabilities,
};
}
@@ -0,0 +1,221 @@
import { useCallback, useEffect } from "react";
import type { SettingsSectionKey } from "@/components/settings/contracts";
import {
CLI_APPS_REFRESH_MAX_RETRIES,
CLI_APPS_REFRESH_RETRY_MS,
} from "@/components/settings/system/AppsSettings";
import type { SystemSettingsState } from "@/components/settings/system/useSystemSettingsState";
import {
fetchApiService,
fetchAutomations,
fetchCliApps,
fetchMcpPresets,
fetchNanobotFeatures,
} from "@/lib/api";
interface SystemSettingsEffectsOptions {
state: SystemSettingsState;
activeSection: SettingsSectionKey;
getToken: () => string;
pageVisible: boolean;
}
export function useSystemSettingsEffects({
state,
activeSection,
getToken,
pageVisible,
}: SystemSettingsEffectsOptions) {
const {
setApiService,
setApiServiceError,
setApiServiceLoading,
setAutomations,
setAutomationsError,
setAutomationsLoading,
setCliApps,
setCliAppsError,
setCliAppsLoading,
setMcpError,
setMcpPresets,
setMcpPresetsLoading,
setNanobotFeatures,
setNanobotFeaturesError,
setNanobotFeaturesLoading,
} = state;
useEffect(() => {
if (activeSection !== "apps") return;
let cancelled = false;
let retry: number | null = null;
let retryCount = 0;
const loadCliApps = (showLoading: boolean) => {
if (showLoading) setCliAppsLoading(true);
fetchCliApps(getToken())
.then((payload) => {
if (cancelled) return;
if (payload.catalog_refresh_pending && retryCount < CLI_APPS_REFRESH_MAX_RETRIES) {
retryCount += 1;
retry = window.setTimeout(() => {
retry = null;
loadCliApps(false);
}, CLI_APPS_REFRESH_RETRY_MS);
}
setCliApps(payload);
setCliAppsError(null);
setCliAppsLoading(false);
})
.catch((err) => {
if (!cancelled) {
setCliAppsError((err as Error).message);
setCliAppsLoading(false);
}
});
};
loadCliApps(true);
return () => {
cancelled = true;
if (retry !== null) window.clearTimeout(retry);
};
}, [activeSection, getToken]);
useEffect(() => {
if (
!pageVisible
|| !["channels", "models", "browser", "runtime"].includes(activeSection)
) {
return;
}
let cancelled = false;
let refreshing = false;
const refresh = async (showLoading = false): Promise<void> => {
if (refreshing) return;
refreshing = true;
if (showLoading) setNanobotFeaturesLoading(true);
try {
const payload = await fetchNanobotFeatures(getToken());
if (!cancelled) {
setNanobotFeatures(payload);
setNanobotFeaturesError(null);
}
} catch (err) {
const message = (err as Error).message;
if (!cancelled && message !== "HTTP 404") setNanobotFeaturesError(message);
} finally {
refreshing = false;
if (!cancelled && showLoading) setNanobotFeaturesLoading(false);
}
};
void refresh(true);
const interval = activeSection === "channels"
? window.setInterval(() => void refresh(false), 5000)
: null;
const refreshOnFocus = () => {
if (activeSection === "channels" && document.visibilityState !== "hidden") {
void refresh(false);
}
};
window.addEventListener("focus", refreshOnFocus);
document.addEventListener("visibilitychange", refreshOnFocus);
return () => {
cancelled = true;
if (interval !== null) window.clearInterval(interval);
window.removeEventListener("focus", refreshOnFocus);
document.removeEventListener("visibilitychange", refreshOnFocus);
};
}, [activeSection, getToken, pageVisible]);
useEffect(() => {
if (activeSection !== "runtime") return;
let cancelled = false;
setApiServiceLoading(true);
fetchApiService(getToken())
.then((payload) => {
if (!cancelled) {
setApiService(payload);
setApiServiceError(null);
}
})
.catch((err) => {
if (!cancelled) setApiServiceError((err as Error).message);
})
.finally(() => {
if (!cancelled) setApiServiceLoading(false);
});
return () => {
cancelled = true;
};
}, [activeSection, getToken]);
useEffect(() => {
if (activeSection !== "apps") return;
let cancelled = false;
setMcpPresetsLoading(true);
fetchMcpPresets(getToken())
.then((payload) => {
if (!cancelled) {
setMcpPresets(payload);
setMcpError(null);
}
})
.catch((err) => {
if (!cancelled) setMcpError((err as Error).message);
})
.finally(() => {
if (!cancelled) setMcpPresetsLoading(false);
});
return () => {
cancelled = true;
};
}, [activeSection, getToken]);
const refreshAutomations = useCallback(
async (showLoading = false) => {
if (showLoading) setAutomationsLoading(true);
try {
const payload = await fetchAutomations(getToken());
setAutomations(payload);
setAutomationsError(null);
} catch (err) {
setAutomationsError((err as Error).message);
} finally {
if (showLoading) setAutomationsLoading(false);
}
},
[getToken],
);
useEffect(() => {
if (activeSection !== "automations" || !pageVisible) return;
let cancelled = false;
let refreshing = false;
const refresh = async (showLoading = false) => {
if (cancelled || refreshing) return;
refreshing = true;
if (showLoading) setAutomationsLoading(true);
try {
const payload = await fetchAutomations(getToken());
if (cancelled) return;
setAutomations(payload);
setAutomationsError(null);
} catch (err) {
if (!cancelled) setAutomationsError((err as Error).message);
} finally {
refreshing = false;
if (!cancelled && showLoading) setAutomationsLoading(false);
}
};
void refresh(true);
const interval = window.setInterval(() => void refresh(false), 5000);
const refreshOnFocus = () => void refresh(false);
window.addEventListener("focus", refreshOnFocus);
return () => {
cancelled = true;
window.clearInterval(interval);
window.removeEventListener("focus", refreshOnFocus);
};
}, [activeSection, getToken, pageVisible]);
return { refreshAutomations };
}
@@ -0,0 +1,157 @@
import { useRef, useState } from "react";
import type {
AutomationFilter,
AutomationSort,
} from "@/components/settings/system/AutomationsSettings";
import {
DEFAULT_CUSTOM_MCP_FORM,
type AppsKindFilter,
type CustomMcpForm,
} from "@/components/settings/system/AppsSettings";
import type {
ApiServicePayload,
AutomationsPayload,
CliAppsPayload,
McpOAuthFlowPayload,
McpPresetsPayload,
NanobotFeatureInfo,
NanobotFeaturesPayload,
SessionAutomationJob,
} from "@/lib/types";
export function useSystemSettingsState() {
const [cliApps, setCliApps] = useState<CliAppsPayload | null>(null);
const [nanobotFeatures, setNanobotFeatures] = useState<NanobotFeaturesPayload | null>(null);
const [mcpPresets, setMcpPresets] = useState<McpPresetsPayload | null>(null);
const [automations, setAutomations] = useState<AutomationsPayload | null>(null);
const [cliAppsLoading, setCliAppsLoading] = useState(true);
const [nanobotFeaturesLoading, setNanobotFeaturesLoading] = useState(true);
const [mcpPresetsLoading, setMcpPresetsLoading] = useState(true);
const [automationsLoading, setAutomationsLoading] = useState(false);
const [cliAppsAction, setCliAppsAction] = useState<string | null>(null);
const [nanobotFeatureAction, setNanobotFeatureAction] = useState<string | null>(null);
const [nanobotFeatureConfirm, setNanobotFeatureConfirm] = useState<NanobotFeatureInfo | null>(null);
const [mcpPresetAction, setMcpPresetAction] = useState<string | null>(null);
const [mcpOAuthFlow, setMcpOAuthFlow] = useState<McpOAuthFlowPayload | null>(null);
const mcpOAuthFlowRef = useRef<McpOAuthFlowPayload | null>(null);
const mcpOAuthPopupRef = useRef<Window | null>(null);
const mcpOAuthNavigatedUrlRef = useRef<string | null>(null);
const [mcpOAuthPopupBlocked, setMcpOAuthPopupBlocked] = useState(false);
const [mcpOAuthCallbackUrl, setMcpOAuthCallbackUrl] = useState("");
const [mcpOAuthCompleting, setMcpOAuthCompleting] = useState(false);
const [mcpOAuthCallbackError, setMcpOAuthCallbackError] = useState<string | null>(null);
const [apiService, setApiService] = useState<ApiServicePayload | null>(null);
const [apiServiceLoading, setApiServiceLoading] = useState(false);
const [apiServiceAction, setApiServiceAction] = useState<"start" | "stop" | null>(null);
const [apiServiceError, setApiServiceError] = useState<string | null>(null);
const [appsQuery, setAppsQuery] = useState("");
const [channelsQuery, setChannelsQuery] = useState("");
const [automationsQuery, setAutomationsQuery] = useState("");
const [automationsFilter, setAutomationsFilter] = useState<AutomationFilter>("all");
const [automationsSort, setAutomationsSort] = useState<AutomationSort>("next");
const [cliAppsMessage, setCliAppsMessage] = useState<string | null>(null);
const [cliAppsError, setCliAppsError] = useState<string | null>(null);
const [nanobotFeaturesError, setNanobotFeaturesError] = useState<string | null>(null);
const [cliAppsFocusName, setCliAppsFocusName] = useState<string | null>(null);
const [appsKindFilter, setAppsKindFilter] = useState<AppsKindFilter>("cli");
const [mcpMessage, setMcpMessage] = useState<string | null>(null);
const [mcpError, setMcpError] = useState<string | null>(null);
const [automationsError, setAutomationsError] = useState<string | null>(null);
const [automationAction, setAutomationAction] = useState<string | null>(null);
const [automationPendingDelete, setAutomationPendingDelete] =
useState<SessionAutomationJob | null>(null);
const [automationPendingEdit, setAutomationPendingEdit] =
useState<SessionAutomationJob | null>(null);
const [mcpFieldValues, setMcpFieldValues] = useState<Record<string, Record<string, string>>>({});
const [customMcpForm, setCustomMcpForm] = useState<CustomMcpForm>(DEFAULT_CUSTOM_MCP_FORM);
const [mcpConfigImport, setMcpConfigImport] = useState("");
return {
apiService,
apiServiceAction,
apiServiceError,
apiServiceLoading,
appsKindFilter,
appsQuery,
automationAction,
automationPendingDelete,
automationPendingEdit,
automations,
automationsError,
automationsFilter,
automationsLoading,
automationsQuery,
automationsSort,
channelsQuery,
cliApps,
cliAppsAction,
cliAppsError,
cliAppsFocusName,
cliAppsLoading,
cliAppsMessage,
customMcpForm,
mcpConfigImport,
mcpError,
mcpFieldValues,
mcpMessage,
mcpOAuthCallbackError,
mcpOAuthCallbackUrl,
mcpOAuthCompleting,
mcpOAuthFlow,
mcpOAuthFlowRef,
mcpOAuthNavigatedUrlRef,
mcpOAuthPopupBlocked,
mcpOAuthPopupRef,
mcpPresetAction,
mcpPresets,
mcpPresetsLoading,
nanobotFeatureAction,
nanobotFeatureConfirm,
nanobotFeatures,
nanobotFeaturesError,
nanobotFeaturesLoading,
setApiService,
setApiServiceAction,
setApiServiceError,
setApiServiceLoading,
setAppsKindFilter,
setAppsQuery,
setAutomationAction,
setAutomationPendingDelete,
setAutomationPendingEdit,
setAutomations,
setAutomationsError,
setAutomationsFilter,
setAutomationsLoading,
setAutomationsQuery,
setAutomationsSort,
setChannelsQuery,
setCliApps,
setCliAppsAction,
setCliAppsError,
setCliAppsFocusName,
setCliAppsLoading,
setCliAppsMessage,
setCustomMcpForm,
setMcpConfigImport,
setMcpError,
setMcpFieldValues,
setMcpMessage,
setMcpOAuthCallbackError,
setMcpOAuthCallbackUrl,
setMcpOAuthCompleting,
setMcpOAuthFlow,
setMcpOAuthPopupBlocked,
setMcpPresetAction,
setMcpPresets,
setMcpPresetsLoading,
setNanobotFeatureAction,
setNanobotFeatureConfirm,
setNanobotFeatures,
setNanobotFeaturesError,
setNanobotFeaturesLoading,
};
}
export type SystemSettingsState = ReturnType<typeof useSystemSettingsState>;