Skip to content

Your lightweight open-source personal agent.

fix(webui): cache tool catalogs across settings navigation (#6552)

chengyongru8632940a996b
diff --git a/webui/browser/fixture.tsx b/webui/browser/fixture.tsx
index d8ab521da..52ff08947 100644
--- a/webui/browser/fixture.tsx
+++ b/webui/browser/fixture.tsx
@@ -19,6 +19,7 @@ import { initializeI18n, setAppLanguage } from "@/i18n";
import { normalizeLocale } from "@/i18n/config";
import type { McpPresetInfo, UIMessage } from "@/lib/types";
import { SkeletonFixture } from "./skeleton-fixture";
+import { installToolsCatalogPreviewApi, ToolsCatalogFixture } from "./tools-catalog-fixture";
import { installSkeletonPreviewApi, SkeletonAdditionsFixture } from "./skeleton-additions-fixture";
import { NewChatSkeletonFixture } from "./new-chat-skeleton-fixture";
import "../src/globals.css";
@@ -215,6 +216,7 @@ function AppsFixture() {
/>{managing && <output data-testid="mcp-actions">{JSON.stringify(actions)}</output>}</main>;
}
if (parameters.get("case") === "skeleton-additions") installSkeletonPreviewApi();
+if (parameters.get("case") === "tools-catalog") installToolsCatalogPreviewApi();
if (parameters.get("case") === "idle-compaction") installIdleCompactionApi();
if (parameters.get("case") === "subagent-dock") installSubagentDockApi();
await initializeI18n();
@@ -274,6 +276,8 @@ createRoot(document.getElementById("root")!).render(<TooltipProvider>
? <ClientProvider client={railClient} token="fixture"><SkeletonAdditionsFixture /></ClientProvider>
: parameters.get("case") === "skeleton"
? <ClientProvider client={railClient} token="fixture"><SkeletonFixture surface={parameters.get("surface") ?? "skills"} loading={parameters.has("loading")} /></ClientProvider>
+ : parameters.get("case") === "tools-catalog"
+ ? <ClientProvider client={railClient} token="fixture"><ToolsCatalogFixture /></ClientProvider>
: parameters.get("case") === "apps"
? <ClientProvider client={railClient} token="fixture"><AppsFixture /></ClientProvider>
: parameters.get("case") === "rail"
diff --git a/webui/browser/tools-catalog-fixture.tsx b/webui/browser/tools-catalog-fixture.tsx
new file mode 100644
index 000000000..8dc4d25e0
--- /dev/null
+++ b/webui/browser/tools-catalog-fixture.tsx
@@ -0,0 +1,26 @@
+import { useState } from "react";
+
+import { SettingsView } from "@/components/settings/SettingsView";
+import { settings } from "@/dev/gallery/settings";
+
+export function installToolsCatalogPreviewApi() {
+ const fetch = window.fetch.bind(window);
+ window.fetch = (input, init) => String(input) === "/api/settings"
+ ? Promise.resolve(Response.json(settings))
+ : fetch(input, init);
+}
+
+export function ToolsCatalogFixture() {
+ const [open, setOpen] = useState(true);
+ return <main>
+ <button onClick={() => setOpen(value => !value)}>{open ? "Leave settings" : "Open settings"}</button>
+ {open && <SettingsView
+ initialSection="apps"
+ initialSettings={settings}
+ themePreference="light"
+ onChangeTheme={() => {}}
+ onModelNameChange={() => {}}
+ onBackToChat={() => setOpen(false)}
+ />}
+ </main>;
+}
diff --git a/webui/browser/tools-catalog.spec.ts b/webui/browser/tools-catalog.spec.ts
new file mode 100644
index 000000000..d4f40eeca
--- /dev/null
+++ b/webui/browser/tools-catalog.spec.ts
@@ -0,0 +1,46 @@
+import { expect, test } from "@playwright/test";
+
+test("settings reentry reuses tools immediately and refreshes expired catalogs without hiding rows", async ({ page }) => {
+ const counts = { cli: 0, mcp: 0 };
+ let refresh = false;
+ let release!: () => void;
+ const gate = new Promise<void>(resolve => { release = resolve; });
+ await page.route("**/api/settings/cli-apps", async route => {
+ counts.cli++;
+ if (refresh) await gate;
+ await route.fulfill({ json: { apps: [{
+ name: "fixture-cli", display_name: refresh ? "Updated CLI" : "Fixture CLI", category: "tools",
+ description: "Fixture app", requires: "", source: "catalog", entry_point: "fixture-cli",
+ install_supported: true, installed: true, available: true, status: "installed", skill_installed: false,
+ }], installed_count: 1 } });
+ });
+ await page.route("**/api/settings/mcp-presets", async route => {
+ counts.mcp++;
+ if (refresh) await gate;
+ await route.fulfill({ json: { presets: [{
+ name: "fixture-plugin", display_name: refresh ? "Updated plugin" : "Fixture plugin", category: "Plugin",
+ description: "Fixture plugin", requires: "", transport: "stdio", source: "agent-plugin",
+ install_supported: false, installed: true, configured: true, enabled: false, available: false,
+ status: "disabled", required_fields: [], docs_url: "", note: "", connection_summary: "",
+ }], installed_count: 1 } });
+ });
+ await page.goto("/browser/fixture.html?case=tools-catalog");
+ await expect(page.getByRole("heading", { name: "Fixture CLI", exact: true })).toBeVisible();
+ await expect(page.getByRole("heading", { name: "Fixture plugin", exact: true })).toBeVisible();
+ await page.getByRole("button", { name: "Leave settings", exact: true }).click();
+ await page.getByRole("button", { name: "Open settings", exact: true }).click();
+ await expect(page.getByRole("heading", { name: "Fixture CLI", exact: true })).toBeVisible();
+ await expect(page.getByRole("heading", { name: "Fixture plugin", exact: true })).toBeVisible();
+ expect(counts).toEqual({ cli: 1, mcp: 1 });
+ await page.getByRole("button", { name: "Leave settings", exact: true }).click();
+ refresh = true;
+ await page.clock.setFixedTime(new Date(Date.now() + 31_000));
+ await page.getByRole("button", { name: "Open settings", exact: true }).click();
+ await expect.poll(() => counts).toEqual({ cli: 2, mcp: 2 });
+ await expect(page.getByRole("heading", { name: "Fixture CLI", exact: true })).toBeVisible();
+ await expect(page.getByRole("heading", { name: "Fixture plugin", exact: true })).toBeVisible();
+ await expect(page.getByRole("status", { name: "Loading apps…", exact: true })).toHaveCount(0);
+ release();
+ await expect(page.getByRole("heading", { name: "Updated CLI", exact: true })).toBeVisible();
+ await expect(page.getByRole("heading", { name: "Updated plugin", exact: true })).toBeVisible();
+});
diff --git a/webui/src/App.tsx b/webui/src/App.tsx
index d23c79f40..e8d4c1018 100644
--- a/webui/src/App.tsx
+++ b/webui/src/App.tsx
@@ -20,6 +20,7 @@ import { LazyRemoteConnectionsPage } from "@/components/remote/LazyRemoteConnect
import { LanguageSwitcher } from "@/components/LanguageSwitcher";
import { SidebarResizeHandle, SIDEBAR_MIN_WIDTH, SIDEBAR_MAX_WIDTH } from "@/components/SidebarResizeHandle";
import { matchSidebarShortcut } from "@/lib/sidebar-shortcuts";
+import { invalidateToolsCatalog } from "@/lib/tools-catalog-cache";
import type { SidebarDeleteDecision, SidebarDeleteItem } from "@/components/ChatList";
import type { SettingsSectionKey } from "@/components/settings/SettingsView";
import { StartupShell } from "@/components/StartupShell";
@@ -1519,6 +1520,8 @@ function Shell({
return request;
}, [getToken]);
+ useEffect(() => client.onReady(() => invalidateToolsCatalog(client)), [client]);
+
useEffect(() => {
if (!pageVisible) return undefined;
diff --git a/webui/src/components/settings/system/RuntimeConfigSettings.tsx b/webui/src/components/settings/system/RuntimeConfigSettings.tsx
index 8a0b82610..bc9302d3d 100644
--- a/webui/src/components/settings/system/RuntimeConfigSettings.tsx
+++ b/webui/src/components/settings/system/RuntimeConfigSettings.tsx
@@ -13,6 +13,7 @@ import { IdleCompactionControl } from "@/components/settings/system/IdleCompacti
import { Input } from "@/components/ui/input";
import { RUNTIME_CONFIG_FIELDS, RUNTIME_CONFIG_GROUPS, type RuntimeConfigField, type RuntimeConfigPage } from "@/components/settings/system/runtime-config-fields";
import { updateRuntimeConfigSettings } from "@/lib/api";
+import { invalidateToolsCatalog } from "@/lib/tools-catalog-cache";
import type { NanobotClient } from "@/lib/nanobot-client";
import type { RuntimeConfigValue, SettingsPayload } from "@/lib/types";
import type { ApplySettingsPayload } from "@/components/settings/contracts";
@@ -111,6 +112,9 @@ export function useRuntimeConfigSettings(
setErrors((prev) => ({ ...prev, [group]: "" }));
try {
const payload = await updateRuntimeConfigSettings(client, values);
+ if (Object.keys(values).some(path => path.startsWith("tools.cli_apps.") || path === "network.proxy")) {
+ invalidateToolsCatalog(client);
+ }
applyPayload(payload, { preserveAgentForm: true, preserveCapabilityForms: true });
discard(group);
setSaved((prev) => ({ ...prev, [group]: true }));
@@ -151,6 +155,7 @@ export function useRuntimeConfigSettings(
setSaving("proxy");
try {
const payload = await updateRuntimeConfigSettings(client, { "network.proxy": next.trim() || null });
+ invalidateToolsCatalog(client);
applyPayload(payload, { preserveAgentForm: true, preserveCapabilityForms: true });
discard("proxy");
setSaved((prev) => ({ ...prev, proxy: true }));
diff --git a/webui/src/components/settings/system/createSystemSettingsActions.ts b/webui/src/components/settings/system/createSystemSettingsActions.ts
index e733e923d..86ba95e30 100644
--- a/webui/src/components/settings/system/createSystemSettingsActions.ts
+++ b/webui/src/components/settings/system/createSystemSettingsActions.ts
@@ -414,6 +414,7 @@ export function createSystemSettingsActions({
return;
}
+ state.toolsCatalog.invalidate();
if (flow.status === "authorized" && flow.hot_reload) {
if (flow.hot_reload.requires_restart) {
setPendingRestartSections((prev) => ({ ...prev, runtime: true }));
@@ -487,7 +488,8 @@ export function createSystemSettingsActions({
setMcpOAuthCompleting(false);
setMcpOAuthCallbackError(null);
try {
- const flow = await startMcpOAuth(client, name, reset, values);
+ const flow = await startMcpOAuth(client, name, reset, values)
+ .finally(() => state.toolsCatalog.invalidate());
mcpOAuthFlowRef.current = flow;
setMcpOAuthFlow(flow);
navigateMcpOAuthPopup(flow);
diff --git a/webui/src/components/settings/system/useSystemSettingsEffects.ts b/webui/src/components/settings/system/useSystemSettingsEffects.ts
index 4f8764eca..69481ade0 100644
--- a/webui/src/components/settings/system/useSystemSettingsEffects.ts
+++ b/webui/src/components/settings/system/useSystemSettingsEffects.ts
@@ -9,8 +9,6 @@ import type { SystemSettingsState } from "@/components/settings/system/useSystem
import {
fetchApiService,
fetchAutomations,
- fetchCliApps,
- fetchMcpPresets,
fetchNanobotFeatures,
} from "@/lib/api";
@@ -36,17 +34,25 @@ export function useSystemSettingsEffects({
setAutomations,
setAutomationsError,
setAutomationsLoading,
- setCliApps,
+ toolsCatalog,
+ toolsCatalogInvalidation,
setCliAppsError,
setCliAppsLoading,
setMcpError,
- setMcpPresets,
setMcpPresetsLoading,
setNanobotFeatures,
setNanobotFeaturesError,
setNanobotFeaturesLoading,
} = state;
+ useEffect(() => {
+ setCliAppsError(null);
+ setMcpError(null);
+ }, [toolsCatalog]);
+
+ const cliPending = Boolean(state.cliApps?.catalog_refresh_pending);
+ const mcpConnecting = Boolean(state.mcpPresets?.presets.some(preset => preset.runtime_status === "connecting"));
+
useEffect(() => {
if (activeSection !== "apps") return;
let cancelled = false;
@@ -54,17 +60,16 @@ export function useSystemSettingsEffects({
let retryCount = 0;
const loadCliApps = (showLoading: boolean) => {
if (showLoading) setCliAppsLoading(true);
- fetchCliApps(getToken())
- .then((payload) => {
+ toolsCatalog.loadCliApps()
+ .then(() => {
if (cancelled) return;
- if (payload.catalog_refresh_pending && retryCount < CLI_APPS_REFRESH_MAX_RETRIES) {
+ if (toolsCatalog.getSnapshot().cliApps?.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);
})
@@ -75,12 +80,15 @@ export function useSystemSettingsEffects({
}
});
};
- loadCliApps(true);
+ const cached = toolsCatalog.getSnapshot().cliApps;
+ setCliAppsLoading(!cached);
+ if (!toolsCatalog.cliFresh()) loadCliApps(!cached);
+ else if (cliPending) retry = window.setTimeout(() => loadCliApps(false), CLI_APPS_REFRESH_RETRY_MS);
return () => {
cancelled = true;
if (retry !== null) window.clearTimeout(retry);
};
- }, [activeSection, getToken]);
+ }, [activeSection, toolsCatalog, toolsCatalogInvalidation, cliPending]);
useEffect(() => {
if (
@@ -156,12 +164,11 @@ export function useSystemSettingsEffects({
let retry: number | null = null;
const loadMcpPresets = (showLoading: boolean) => {
if (showLoading) setMcpPresetsLoading(true);
- fetchMcpPresets(getToken())
- .then((payload) => {
+ toolsCatalog.loadMcpPresets()
+ .then(() => {
if (cancelled) return;
- setMcpPresets(payload);
setMcpError(null);
- if (payload.presets.some((preset) => preset.runtime_status === "connecting")) {
+ if (toolsCatalog.getSnapshot().mcpPresets?.presets.some((preset) => preset.runtime_status === "connecting")) {
retry = window.setTimeout(() => {
retry = null;
loadMcpPresets(false);
@@ -175,12 +182,15 @@ export function useSystemSettingsEffects({
if (!cancelled && showLoading) setMcpPresetsLoading(false);
});
};
- loadMcpPresets(true);
+ const cached = toolsCatalog.getSnapshot().mcpPresets;
+ setMcpPresetsLoading(!cached);
+ if (!toolsCatalog.mcpFresh()) loadMcpPresets(!cached);
+ else if (mcpConnecting) retry = window.setTimeout(() => loadMcpPresets(false), MCP_RUNTIME_STATUS_REFRESH_MS);
return () => {
cancelled = true;
if (retry !== null) window.clearTimeout(retry);
};
- }, [activeSection, getToken, pageVisible]);
+ }, [activeSection, toolsCatalog, toolsCatalogInvalidation, pageVisible, mcpConnecting]);
const refreshAutomations = useCallback(
async (showLoading = false) => {
diff --git a/webui/src/components/settings/system/useSystemSettingsState.ts b/webui/src/components/settings/system/useSystemSettingsState.ts
index d9152ef76..5e2900d63 100644
--- a/webui/src/components/settings/system/useSystemSettingsState.ts
+++ b/webui/src/components/settings/system/useSystemSettingsState.ts
@@ -1,4 +1,6 @@
-import { useRef, useState } from "react";
+import { useRef, useState, useSyncExternalStore } from "react";
+
+import type { ToolsCatalog } from "@/lib/tools-catalog-cache";
import type { AutomationFilter } from "@/components/settings/system/AutomationsSettings";
import {
@@ -9,9 +11,7 @@ import {
import type {
ApiServicePayload,
AutomationsPayload,
- CliAppsPayload,
McpOAuthFlowPayload,
- McpPresetsPayload,
NanobotFeatureInfo,
NanobotFeaturesPayload,
SessionAutomationJob,
@@ -22,10 +22,10 @@ export type NanobotFeatureInstallRequest = {
installOnly: boolean;
};
-export function useSystemSettingsState() {
- const [cliApps, setCliApps] = useState<CliAppsPayload | null>(null);
+export function useSystemSettingsState(toolsCatalog: ToolsCatalog) {
+ const { cliApps, mcpPresets, invalidation: toolsCatalogInvalidation } = useSyncExternalStore(toolsCatalog.subscribe, toolsCatalog.getSnapshot);
+ const { setCliApps, setMcpPresets } = toolsCatalog;
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);
@@ -69,6 +69,8 @@ export function useSystemSettingsState() {
const [mcpConfigImport, setMcpConfigImport] = useState("");
return {
+ toolsCatalog,
+ toolsCatalogInvalidation,
apiService,
apiServiceAction,
apiServiceError,
diff --git a/webui/src/components/settings/useSettingsController.ts b/webui/src/components/settings/useSettingsController.ts
index b70eee357..0b1e2e9bf 100644
--- a/webui/src/components/settings/useSettingsController.ts
+++ b/webui/src/components/settings/useSettingsController.ts
@@ -33,6 +33,7 @@ import { useRuntimeConfigSettings } from "@/components/settings/system/RuntimeCo
import { createSystemSettingsActions } from "@/components/settings/system/createSystemSettingsActions";
import { useSystemSettingsEffects } from "@/components/settings/system/useSystemSettingsEffects";
import { useSystemSettingsState } from "@/components/settings/system/useSystemSettingsState";
+import { getToolsCatalog } from "@/lib/tools-catalog-cache";
import { usePageVisibility } from "@/hooks/usePageVisibility";
import { useEditCompletion } from "@/components/settings/shared/useEditCompletion";
import { cancelProviderOAuth, fetchSettings, fetchSettingsUsage } from "@/lib/api";
@@ -113,7 +114,7 @@ export function useSettingsController({
} = capabilityState;
const draftsRef = useRef({ form, imageGenerationForm, networkSafetyForm, transcriptionForm, webSearchForm });
draftsRef.current = { form, imageGenerationForm, networkSafetyForm, transcriptionForm, webSearchForm };
- const systemState = useSystemSettingsState();
+ const systemState = useSystemSettingsState(getToolsCatalog(client, token));
const featureCatalog = systemState.nanobotFeatures?.features ?? [];
useEffect(() => {
diff --git a/webui/src/lib/tools-catalog-cache.ts b/webui/src/lib/tools-catalog-cache.ts
new file mode 100644
index 000000000..25f4a4cba
--- /dev/null
+++ b/webui/src/lib/tools-catalog-cache.ts
@@ -0,0 +1,89 @@
+import { fetchCliApps, fetchMcpPresets } from "./api";
+import type { CliAppsPayload, McpPresetsPayload } from "./types";
+
+export const TOOLS_CATALOG_TTL_MS = 30_000;
+
+function createToolsCatalog(token: string) {
+ let snapshot: { cliApps: CliAppsPayload | null; mcpPresets: McpPresetsPayload | null; invalidation: number } = {
+ cliApps: null, mcpPresets: null, invalidation: 0,
+ };
+ let cliUpdated = 0;
+ let mcpUpdated = 0;
+ let cliRevision = 0;
+ let mcpRevision = 0;
+ let cliRequest: Promise<void> | null = null;
+ let mcpRequest: Promise<void> | null = null;
+ const listeners = new Set<() => void>();
+ const publish = () => listeners.forEach(listener => listener());
+ const setCliApps = (cliApps: CliAppsPayload) => {
+ cliRevision++;
+ cliUpdated = Date.now();
+ snapshot = { ...snapshot, cliApps };
+ publish();
+ };
+ const setMcpPresets = (mcpPresets: McpPresetsPayload) => {
+ mcpRevision++;
+ mcpUpdated = Date.now();
+ snapshot = { ...snapshot, mcpPresets };
+ publish();
+ };
+ return {
+ getSnapshot: () => snapshot,
+ subscribe(listener: () => void) {
+ listeners.add(listener);
+ return () => { listeners.delete(listener); };
+ },
+ setCliApps,
+ setMcpPresets,
+ invalidate() {
+ cliUpdated = mcpUpdated = -Infinity;
+ cliRevision++;
+ mcpRevision++;
+ cliRequest = mcpRequest = null;
+ snapshot = { ...snapshot, invalidation: snapshot.invalidation + 1 };
+ publish();
+ },
+ cliFresh: () => snapshot.cliApps !== null && Date.now() - cliUpdated < TOOLS_CATALOG_TTL_MS,
+ mcpFresh: () => snapshot.mcpPresets !== null && Date.now() - mcpUpdated < TOOLS_CATALOG_TTL_MS,
+ loadCliApps(): Promise<void> {
+ if (cliRequest) return cliRequest;
+ const revision = cliRevision;
+ const request = fetchCliApps(token).then(payload => {
+ // A mutation response supersedes an earlier catalog read.
+ if (revision === cliRevision) setCliApps(payload);
+ }, error => {
+ if (revision === cliRevision) throw error;
+ }).finally(() => { if (cliRequest === request) cliRequest = null; });
+ cliRequest = request;
+ return request;
+ },
+ loadMcpPresets(): Promise<void> {
+ if (mcpRequest) return mcpRequest;
+ const revision = mcpRevision;
+ const request = fetchMcpPresets(token).then(payload => {
+ if (revision === mcpRevision) setMcpPresets(payload);
+ }, error => {
+ if (revision === mcpRevision) throw error;
+ }).finally(() => { if (mcpRequest === request) mcpRequest = null; });
+ mcpRequest = request;
+ return request;
+ },
+ };
+}
+
+// App creates a client per host connection. Keep only its current auth scope;
+// superseded clients and credentials never persist in browser storage.
+const catalogs = new WeakMap<object, { token: string; catalog: ToolsCatalog }>();
+export type ToolsCatalog = ReturnType<typeof createToolsCatalog>;
+
+export function getToolsCatalog(client: object, token: string): ToolsCatalog {
+ const existing = catalogs.get(client);
+ if (existing?.token === token) return existing.catalog;
+ const catalog = createToolsCatalog(token);
+ catalogs.set(client, { token, catalog });
+ return catalog;
+}
+
+export function invalidateToolsCatalog(client: object): void {
+ catalogs.get(client)?.catalog.invalidate();
+}
diff --git a/webui/src/tests/catalog-loading.test.tsx b/webui/src/tests/catalog-loading.test.tsx
index 17ddecb13..aea01111e 100644
--- a/webui/src/tests/catalog-loading.test.tsx
+++ b/webui/src/tests/catalog-loading.test.tsx
@@ -1,7 +1,10 @@
-import { act, fireEvent, screen } from "@testing-library/react";
+import { act, cleanup, fireEvent, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import type { CliAppInfo, McpPresetInfo, NanobotFeatureInfo } from "@/lib/types";
+import type { NanobotClient } from "@/lib/nanobot-client";
+import { invalidateToolsCatalog, TOOLS_CATALOG_TTL_MS } from "@/lib/tools-catalog-cache";
+import { CLI_APPS_REFRESH_RETRY_MS } from "@/components/settings/system/AppsSettings";
import {
installSettingsViewTestHooks,
jsonResponse,
@@ -37,6 +40,90 @@ const channel: NanobotFeatureInfo = {
describe("catalog loading", () => {
installSettingsViewTestHooks();
+ it("reuses both catalogs after leaving settings and keeps expired rows visible during refresh", async () => {
+ const client = { status: "open", onStatus: () => () => {} } as unknown as NanobotClient;
+ const cli = deferred<Response>();
+ const mcp = deferred<Response>();
+ let refresh = false;
+ const fetch = vi.fn((input: RequestInfo | URL) => {
+ const url = String(input);
+ if (url === "/api/settings/cli-apps") return refresh ? cli.promise : Promise.resolve(jsonResponse({ apps: [app], installed_count: 1 }));
+ if (url === "/api/settings/mcp-presets") return refresh ? mcp.promise : Promise.resolve(jsonResponse({ presets: [plugin], installed_count: 1 }));
+ return Promise.resolve(jsonResponse(settingsPayload()));
+ });
+ vi.stubGlobal("fetch", fetch);
+ renderSettingsView({ client, initialSettings: settingsPayload() });
+ await act(async () => {});
+ cleanup();
+ fetch.mockClear();
+ renderSettingsView({ client, initialSettings: settingsPayload() });
+ expect(screen.getByRole("heading", { name: "AnyGen" })).toBeInTheDocument();
+ expect(screen.getByRole("heading", { name: "Computer Use" })).toBeInTheDocument();
+ expect(screen.queryByRole("status", { name: "Loading apps…" })).not.toBeInTheDocument();
+ expect(fetch.mock.calls.filter(([url]) => String(url).match(/cli-apps|mcp-presets/))).toHaveLength(0);
+ cleanup();
+ refresh = true;
+ const now = vi.spyOn(Date, "now").mockReturnValue(Date.now() + TOOLS_CATALOG_TTL_MS + 1);
+ try {
+ renderSettingsView({ client, initialSettings: settingsPayload() });
+ expect(screen.getByRole("heading", { name: "AnyGen" })).toBeInTheDocument();
+ expect(screen.getByRole("heading", { name: "Computer Use" })).toBeInTheDocument();
+ expect(screen.queryByRole("status", { name: "Loading apps…" })).not.toBeInTheDocument();
+ expect(fetch.mock.calls.filter(([url]) => String(url).match(/cli-apps|mcp-presets/))).toHaveLength(2);
+ await act(async () => {
+ cli.resolve(jsonResponse({ apps: [{ ...app, display_name: "Updated app" }], installed_count: 1 }));
+ mcp.resolve(jsonResponse({ presets: [{ ...plugin, display_name: "Updated plugin" }], installed_count: 1 }));
+ });
+ expect(screen.getByRole("heading", { name: "Updated app" })).toBeInTheDocument();
+ expect(screen.getByRole("heading", { name: "Updated plugin" })).toBeInTheDocument();
+ } finally {
+ now.mockRestore();
+ }
+ });
+
+ it("refreshes an invalidated initial read immediately and ignores its superseded response", async () => {
+ const client = { status: "open", onStatus: () => () => {} } as unknown as NanobotClient;
+ const old = deferred<Response>();
+ let reads = 0;
+ vi.stubGlobal("fetch", vi.fn((input: RequestInfo | URL) => {
+ if (String(input) === "/api/settings") return Promise.resolve(jsonResponse(settingsPayload()));
+ if (String(input) === "/api/settings/cli-apps") {
+ reads++;
+ return reads === 1 ? old.promise : Promise.resolve(jsonResponse({ apps: [app], installed_count: 1 }));
+ }
+ return Promise.resolve(jsonResponse({ presets: [], installed_count: 0 }));
+ }));
+ renderSettingsView({ client, initialSettings: settingsPayload() });
+ await act(async () => { invalidateToolsCatalog(client); });
+ expect(reads).toBe(2);
+ expect(screen.getByRole("heading", { name: "AnyGen" })).toBeInTheDocument();
+ await act(async () => { old.resolve(jsonResponse({ apps: [], installed_count: 0 })); });
+ expect(screen.getByRole("heading", { name: "AnyGen" })).toBeInTheDocument();
+ });
+
+ it("resumes a pending CLI catalog refresh after remount", async () => {
+ vi.useFakeTimers();
+ const client = { status: "open", onStatus: () => () => {} } as unknown as NanobotClient;
+ let reads = 0;
+ vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {
+ if (String(input) === "/api/settings") return jsonResponse(settingsPayload());
+ if (String(input) === "/api/settings/cli-apps") {
+ reads++;
+ return jsonResponse({ apps: [{ ...app, display_name: reads === 1 ? "AnyGen" : "Refreshed app" }], installed_count: 1, catalog_refresh_pending: reads === 1 });
+ }
+ return jsonResponse({ presets: [], installed_count: 0 });
+ }));
+ renderSettingsView({ client, initialSettings: settingsPayload() });
+ await act(async () => {});
+ cleanup();
+ renderSettingsView({ client, initialSettings: settingsPayload() });
+ expect(screen.getByRole("heading", { name: "AnyGen" })).toBeInTheDocument();
+ expect(reads).toBe(1);
+ await act(async () => { await vi.advanceTimersByTimeAsync(CLI_APPS_REFRESH_RETRY_MS); });
+ expect(reads).toBe(2);
+ expect(screen.getByRole("heading", { name: "Refreshed app" })).toBeInTheDocument();
+ });
+
it("keeps loaded Apps rows visible while waiting for Agent Plugins", async () => {
const cli = deferred<Response>();
const mcp = deferred<Response>();
diff --git a/webui/src/tests/mcp-management-dialog.test.tsx b/webui/src/tests/mcp-management-dialog.test.tsx
index f0af5bdb6..047637fde 100644
--- a/webui/src/tests/mcp-management-dialog.test.tsx
+++ b/webui/src/tests/mcp-management-dialog.test.tsx
@@ -10,6 +10,7 @@ import { createSystemSettingsActions } from "@/components/settings/system/create
import { useSystemSettingsState } from "@/components/settings/system/useSystemSettingsState";
import i18n from "@/i18n";
import { NanobotClient } from "@/lib/nanobot-client";
+import { getToolsCatalog } from "@/lib/tools-catalog-cache";
import type { McpPresetInfo, McpPresetsPayload } from "@/lib/types";
import {
installSettingsViewTestHooks,
@@ -490,7 +491,7 @@ function renderMcpActions() {
const client = new NanobotClient({ url: "ws://example.test" });
client.requestMutation = requestMutationMock;
return renderHook(() => {
- const state = useSystemSettingsState();
+ const state = useSystemSettingsState(getToolsCatalog(client, "tok"));
const actions = createSystemSettingsActions({
state,
featureCatalog: [],
diff --git a/webui/src/tests/settings-apps-oauth.test.tsx b/webui/src/tests/settings-apps-oauth.test.tsx
index 2ff14dd2d..4e701a115 100644
--- a/webui/src/tests/settings-apps-oauth.test.tsx
+++ b/webui/src/tests/settings-apps-oauth.test.tsx
@@ -1,4 +1,4 @@
-import { act, fireEvent, screen, waitFor, within } from "@testing-library/react";
+import { act, cleanup, fireEvent, screen, waitFor, within } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import i18n from "@/i18n";
@@ -423,11 +423,17 @@ describe("SettingsView Apps catalog", () => {
});
vi.stubGlobal("fetch", fetchMock);
- renderSettingsView({ initialSection: "apps" });
+ const client = { requestMutation: requestMutationMock, status: "open", onStatus: () => () => {} } as never;
+ renderSettingsView({ client, initialSection: "apps" });
fireEvent.click(await screen.findByRole("button", { name: "MCP" }));
expect(await screen.findByRole("button", { name: "Xmind" }))
.toHaveAccessibleDescription("Connecting…");
+ cleanup();
+ renderSettingsView({ client, initialSection: "apps", initialSettings: settingsPayload() });
+ fireEvent.click(screen.getByRole("button", { name: "MCP" }));
+ expect(screen.getByRole("button", { name: "Xmind" })).toHaveAccessibleDescription("Connecting…");
+ expect(mcpPresetRequests).toBe(1);
expect(await screen.findByRole(
"button",
{ name: "Manage Xmind" },
diff --git a/webui/src/tests/settings-system.test.tsx b/webui/src/tests/settings-system.test.tsx
index 540a2d52a..1edac2120 100644
--- a/webui/src/tests/settings-system.test.tsx
+++ b/webui/src/tests/settings-system.test.tsx
@@ -1,4 +1,4 @@
-import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
+import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { expect, it, vi } from "vitest";
import { installedMcpPresetsFromPayload } from "@/lib/mcp-preset-events";
import { SkillsCatalogSettings } from "@/components/settings/SkillsCatalogSettings";
@@ -562,7 +562,8 @@ describe("Settings system domains", () => {
},
});
- renderSettingsView();
+ const client = { requestMutation: requestMutationMock, status: "open", onStatus: () => () => {} } as never;
+ renderSettingsView({ client });
expect(await screen.findByText("AnyGen")).toBeInTheDocument();
const uninstall = screen.getByRole("button", { name: "Uninstall app" });
@@ -579,7 +580,12 @@ describe("Settings system domains", () => {
expect(await screen.findByText("Uninstalled CLI for AnyGen.")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Dismiss" }));
-
+ cleanup();
+ fetchMock.mockClear();
+ renderSettingsView({ client, initialSettings: settingsPayload() });
+ expect(screen.getByText("AnyGen")).toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "Uninstall app" })).not.toBeInTheDocument();
+ expect(fetchMock.mock.calls.filter(([url]) => String(url).includes("cli-apps"))).toHaveLength(0);
});
it("keeps runtime dependencies out of Apps and explains chat mentions", async () => {
diff --git a/webui/src/tests/tools-catalog-cache.test.ts b/webui/src/tests/tools-catalog-cache.test.ts
new file mode 100644
index 000000000..dbc7023e9
--- /dev/null
+++ b/webui/src/tests/tools-catalog-cache.test.ts
@@ -0,0 +1,105 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { getToolsCatalog, invalidateToolsCatalog, TOOLS_CATALOG_TTL_MS } from "@/lib/tools-catalog-cache";
+import type { CliAppsPayload, McpPresetsPayload } from "@/lib/types";
+
+const cli: CliAppsPayload = { apps: [], installed_count: 0 };
+const mcp: McpPresetsPayload = { presets: [], installed_count: 0 };
+const response = (payload: unknown) => new Response(JSON.stringify(payload), { headers: { "content-type": "application/json" } });
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>(res => { resolve = res; });
+ return { promise, resolve };
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+describe("tools catalog cache", () => {
+ it("isolates host clients and changed credentials, including late responses", async () => {
+ const client = {};
+ const old = getToolsCatalog(client, "old-token");
+ const pending = deferred<Response>();
+ vi.stubGlobal("fetch", vi.fn(() => pending.promise));
+ const loading = old.loadCliApps();
+ const next = getToolsCatalog(client, "new-token");
+ const otherHost = getToolsCatalog({}, "old-token");
+ pending.resolve(response(cli));
+ await loading;
+ expect(old.getSnapshot().cliApps).toEqual(cli);
+ expect(next.getSnapshot().cliApps).toBeNull();
+ expect(otherHost.getSnapshot().cliApps).toBeNull();
+ expect(getToolsCatalog(client, "old-token").getSnapshot().cliApps).toBeNull();
+ expect(vi.mocked(fetch).mock.calls[0][1]?.headers).toEqual({ Authorization: "Bearer old-token" });
+ });
+
+ it("deduplicates in-flight reads and does not overwrite mutation payloads with older GETs", async () => {
+ const client = {};
+ const cache = getToolsCatalog(client, "token");
+ const cliRead = deferred<Response>();
+ const mcpRead = deferred<Response>();
+ const fetch = vi.fn((url: string) => url.endsWith("cli-apps") ? cliRead.promise : mcpRead.promise);
+ vi.stubGlobal("fetch", fetch);
+ const first = cache.loadCliApps();
+ expect(cache.loadCliApps()).toBe(first);
+ const second = cache.loadMcpPresets();
+ const changedCli = { ...cli, installed_count: 1 };
+ const changedMcp = { ...mcp, installed_count: 1 };
+ cache.setCliApps(changedCli);
+ cache.setMcpPresets(changedMcp);
+ cliRead.resolve(response(cli));
+ mcpRead.resolve(response(mcp));
+ await Promise.all([first, second]);
+ expect(fetch).toHaveBeenCalledTimes(2);
+ expect(getToolsCatalog(client, "token").getSnapshot()).toMatchObject({ cliApps: changedCli, mcpPresets: changedMcp });
+ });
+
+ it("retains expired and invalidated data, but refreshes it rather than treating it as fresh", async () => {
+ const client = {};
+ const cache = getToolsCatalog(client, "token");
+ cache.setCliApps(cli);
+ cache.setMcpPresets(mcp);
+ expect(cache.cliFresh()).toBe(true);
+ expect(cache.mcpFresh()).toBe(true);
+ vi.spyOn(Date, "now").mockReturnValue(Date.now() + TOOLS_CATALOG_TTL_MS);
+ expect(cache.cliFresh()).toBe(false);
+ expect(cache.mcpFresh()).toBe(false);
+ cache.setCliApps(cli);
+ cache.setMcpPresets(mcp);
+ invalidateToolsCatalog(client);
+ expect(cache.cliFresh()).toBe(false);
+ expect(cache.mcpFresh()).toBe(false);
+ expect(cache.getSnapshot()).toMatchObject({ cliApps: cli, mcpPresets: mcp });
+ vi.stubGlobal("fetch", vi.fn(async (url: string) => response(url.endsWith("cli-apps") ? cli : mcp)));
+ await Promise.all([cache.loadCliApps(), cache.loadMcpPresets()]);
+ expect(cache.cliFresh()).toBe(true);
+ expect(cache.mcpFresh()).toBe(true);
+ });
+
+ it("does not surface an older GET failure after a mutation has succeeded", async () => {
+ const cache = getToolsCatalog({}, "token");
+ let reject!: (reason: Error) => void;
+ vi.stubGlobal("fetch", vi.fn(() => new Promise<Response>((_, fail) => { reject = fail; })));
+ const loading = cache.loadMcpPresets();
+ cache.setMcpPresets(mcp);
+ reject(new Error("old read failed"));
+ await expect(loading).resolves.toBeUndefined();
+ expect(cache.getSnapshot().mcpPresets).toEqual(mcp);
+ });
+
+ it("leaves failures retryable and preserves stale payloads on a refresh failure", async () => {
+ const cache = getToolsCatalog({}, "token");
+ vi.stubGlobal("fetch", vi.fn().mockRejectedValueOnce(new Error("offline")).mockResolvedValueOnce(response(cli)).mockRejectedValueOnce(new Error("offline")));
+ await expect(cache.loadCliApps()).rejects.toThrow("offline");
+ expect(cache.getSnapshot().cliApps).toBeNull();
+ expect(cache.cliFresh()).toBe(false);
+ await cache.loadCliApps();
+ cache.invalidate();
+ await expect(cache.loadCliApps()).rejects.toThrow("offline");
+ expect(cache.getSnapshot().cliApps).toEqual(cli);
+ expect(cache.cliFresh()).toBe(false);
+ });
+});