Skip to content

The agent that grows with you

fix(dashboard): cache plugins hub payload and avoid auth probes

Hafiz Ahmad Ashfaq0de8c32f52f7
diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.py
index 5af536fdce1..8b8357e7079 100644
--- a/hermes_cli/web_server.py
+++ b/hermes_cli/web_server.py
@@ -5975,6 +5975,7 @@ async def setup_memory_provider(name: str, body: MemoryProviderSetupRequest):
except Exception:
_log.exception("Failed to persist memory provider setup values for %s", name)
raise HTTPException(status_code=500, detail="Internal server error")
+ _invalidate_plugins_hub_cache()
return _install_memory_provider_setup(name)
@@ -5992,6 +5993,7 @@ async def update_memory_provider_config(
if declared is None:
raise HTTPException(status_code=404, detail=f"Unknown memory provider: {name}")
_update_memory_provider_config(declared, _stringify_submitted_values(values))
+ _invalidate_plugins_hub_cache()
return {"ok": True}
provider = _load_memory_provider(name)
@@ -6006,6 +6008,7 @@ async def update_memory_provider_config(
config["memory"] = memory_config
memory_config["provider"] = name
save_config(config)
+ _invalidate_plugins_hub_cache()
return {"ok": True, "active": name}
try:
@@ -16630,8 +16633,37 @@ def _strip_dashboard_manifest(p: Dict[str, Any]) -> Dict[str, Any]:
return {k: v for k, v in p.items() if not k.startswith("_")}
-def _merged_plugins_hub() -> Dict[str, Any]:
- """Agent discovery + dashboard manifests + optional provider picker metadata."""
+_PLUGINS_HUB_CACHE_TTL_SECONDS = 5.0
+_plugins_hub_cache: Optional[Dict[str, Any]] = None
+_plugins_hub_cache_expires_at = 0.0
+_plugins_hub_cache_lock = threading.Lock()
+
+
+def _invalidate_plugins_hub_cache() -> None:
+ global _plugins_hub_cache, _plugins_hub_cache_expires_at
+ with _plugins_hub_cache_lock:
+ _plugins_hub_cache = None
+ _plugins_hub_cache_expires_at = 0.0
+
+
+def _merged_plugins_hub(force_refresh: bool = False) -> Dict[str, Any]:
+ """Agent discovery + dashboard manifests + optional provider picker metadata.
+
+ IMPORTANT: this powers a dashboard request path, so it must stay read-only
+ and cheap. In particular, do not execute tool ``check_fn`` probes here —
+ those can trigger imports, auth/network checks, and other synchronous work
+ that starves the root event loop. We only consume last-known cached tool
+ availability, and we memoize the assembled payload briefly to collapse the
+ dashboard's bursty duplicate fetches.
+ """
+ global _plugins_hub_cache, _plugins_hub_cache_expires_at
+ now = time.monotonic()
+ if not force_refresh:
+ with _plugins_hub_cache_lock:
+ if _plugins_hub_cache is not None and now < _plugins_hub_cache_expires_at:
+ return _plugins_hub_cache
+
+ started_at = time.monotonic()
from hermes_cli.plugins_cmd import (
_discover_all_plugins,
_get_current_context_engine,
@@ -16684,17 +16716,22 @@ def _merged_plugins_hub() -> Dict[str, Any]:
source in {"user", "git"} and under_user_tree and Path(dir_str).is_dir()
)
- # Check if this plugin provides tools that require auth
+ # Read-only auth hint: consult only last-known cached tool availability.
+ # A missing cache entry is treated as "unknown" rather than triggering a
+ # live probe inside this request path.
auth_required = False
auth_command = ""
manifest_data = _read_plugin_manifest_at(dir_path)
provides_tools = manifest_data.get("provides_tools") or []
if provides_tools:
try:
- from tools.registry import registry
+ from tools.registry import get_cached_check_fn_result, registry
for tname in provides_tools:
entry = registry.get_entry(tname)
- if entry and entry.check_fn and not entry.check_fn():
+ if not entry or not entry.check_fn:
+ continue
+ cached_result = get_cached_check_fn_result(entry.check_fn)
+ if cached_result is False:
auth_required = True
auth_command = f"hermes auth {name}"
break
@@ -16733,7 +16770,7 @@ def _merged_plugins_hub() -> Dict[str, Any]:
except Exception:
context_engines = []
- return {
+ payload = {
"plugins": rows,
"orphan_dashboard_plugins": orphan_dashboard,
"providers": {
@@ -16743,6 +16780,18 @@ def _merged_plugins_hub() -> Dict[str, Any]:
"context_options": context_engines,
},
}
+ duration = time.monotonic() - started_at
+ if duration >= 0.25:
+ _log.info(
+ "plugins/hub rebuilt in %.3fs (plugins=%d memory_options=%d)",
+ duration,
+ len(rows),
+ len(memory_providers),
+ )
+ with _plugins_hub_cache_lock:
+ _plugins_hub_cache = payload
+ _plugins_hub_cache_expires_at = time.monotonic() + _PLUGINS_HUB_CACHE_TTL_SECONDS
+ return payload
@app.get("/api/dashboard/plugins/hub")
@@ -16772,6 +16821,7 @@ async def post_agent_plugin_install(request: Request, body: _AgentPluginInstallB
detail=result.get("error") or "Install failed.",
)
_get_dashboard_plugins(force_rescan=True)
+ _invalidate_plugins_hub_cache()
# Strip internal paths from the response
result.pop("after_install_path", None)
return result
@@ -16794,6 +16844,7 @@ async def post_agent_plugin_enable(request: Request, name: str):
result = dashboard_set_agent_plugin_enabled(name, enabled=True)
if not result.get("ok"):
raise HTTPException(status_code=400, detail=result.get("error") or "Enable failed.")
+ _invalidate_plugins_hub_cache()
return result
@@ -16806,6 +16857,7 @@ async def post_agent_plugin_disable(request: Request, name: str):
result = dashboard_set_agent_plugin_enabled(name, enabled=False)
if not result.get("ok"):
raise HTTPException(status_code=400, detail=result.get("error") or "Disable failed.")
+ _invalidate_plugins_hub_cache()
return result
@@ -16819,6 +16871,7 @@ async def post_agent_plugin_update(request: Request, name: str):
if not result.get("ok"):
raise HTTPException(status_code=400, detail=result.get("error") or "Update failed.")
_get_dashboard_plugins(force_rescan=True)
+ _invalidate_plugins_hub_cache()
return result
@@ -16832,6 +16885,7 @@ async def delete_agent_plugin(request: Request, name: str):
if not result.get("ok"):
raise HTTPException(status_code=400, detail=result.get("error") or "Remove failed.")
_get_dashboard_plugins(force_rescan=True)
+ _invalidate_plugins_hub_cache()
return result
@@ -16850,6 +16904,7 @@ async def put_plugin_providers(request: Request, body: _PluginProvidersPutBody):
_save_memory_provider(memory_provider)
if body.context_engine is not None:
_save_context_engine(body.context_engine)
+ _invalidate_plugins_hub_cache()
return {"ok": True}
@@ -16873,6 +16928,7 @@ async def post_plugin_visibility(request: Request, name: str, body: _PluginVisib
config["dashboard"]["hidden_plugins"] = hidden_list
save_config(config)
+ _invalidate_plugins_hub_cache()
return {"ok": True, "name": name, "hidden": body.hidden}
diff --git a/tests/hermes_cli/test_plugins_hub_perf_guard.py b/tests/hermes_cli/test_plugins_hub_perf_guard.py
new file mode 100644
index 00000000000..dbd9d251bd2
--- /dev/null
+++ b/tests/hermes_cli/test_plugins_hub_perf_guard.py
@@ -0,0 +1,97 @@
+from __future__ import annotations
+
+from pathlib import Path
+from types import SimpleNamespace
+
+from hermes_cli import web_server
+from hermes_cli import plugins_cmd
+from tools import registry as tools_registry
+
+
+_PLUGIN_ROW = [("demo", "1.0.0", "demo plugin", "user", "/tmp/demo-plugin", "demo")]
+
+
+def _patch_minimal_hub_dependencies(monkeypatch, *, check_fn, discover_all_plugins=None):
+ monkeypatch.setattr(web_server, "_get_dashboard_plugins", lambda force_rescan=False: [])
+ monkeypatch.setattr(web_server, "_discover_memory_provider_statuses", lambda: [])
+ monkeypatch.setattr(web_server, "get_hermes_home", lambda: Path("/tmp/hermes-home"))
+ monkeypatch.setattr(web_server, "load_config", lambda: {"dashboard": {"hidden_plugins": []}})
+
+ monkeypatch.setattr(
+ plugins_cmd,
+ "_discover_all_plugins",
+ discover_all_plugins or (lambda: list(_PLUGIN_ROW)),
+ )
+ monkeypatch.setattr(plugins_cmd, "_get_current_context_engine", lambda: "compressor")
+ monkeypatch.setattr(plugins_cmd, "_get_current_memory_provider", lambda: "")
+ monkeypatch.setattr(plugins_cmd, "_discover_context_engines", lambda: [])
+ monkeypatch.setattr(plugins_cmd, "_get_disabled_set", lambda: set())
+ monkeypatch.setattr(plugins_cmd, "_get_enabled_set", lambda: {"demo"})
+ monkeypatch.setattr(plugins_cmd, "_read_manifest", lambda _path: {"provides_tools": ["demo_tool"]})
+
+ monkeypatch.setattr(
+ tools_registry.registry,
+ "get_entry",
+ lambda _name: SimpleNamespace(check_fn=check_fn),
+ )
+
+
+
+def test_plugins_hub_does_not_probe_cold_check_fns(monkeypatch):
+ tools_registry.invalidate_check_fn_cache()
+ web_server._invalidate_plugins_hub_cache()
+
+ calls = {"count": 0}
+
+ def check_fn():
+ calls["count"] += 1
+ return False
+
+ _patch_minimal_hub_dependencies(monkeypatch, check_fn=check_fn)
+
+ payload = web_server._merged_plugins_hub(force_refresh=True)
+
+ assert calls["count"] == 0
+ assert payload["plugins"][0]["auth_required"] is False
+ assert payload["plugins"][0]["auth_command"] == ""
+
+
+
+def test_plugins_hub_uses_cached_failed_check_fn_verdict(monkeypatch):
+ tools_registry.invalidate_check_fn_cache()
+ web_server._invalidate_plugins_hub_cache()
+
+ def check_fn():
+ return False
+
+ assert tools_registry._check_fn_cached(check_fn) is False
+ _patch_minimal_hub_dependencies(monkeypatch, check_fn=check_fn)
+
+ payload = web_server._merged_plugins_hub(force_refresh=True)
+
+ assert payload["plugins"][0]["auth_required"] is True
+ assert payload["plugins"][0]["auth_command"] == "hermes auth demo"
+
+
+
+def test_plugins_hub_short_ttl_cache_collapses_duplicate_fetches(monkeypatch):
+ tools_registry.invalidate_check_fn_cache()
+ web_server._invalidate_plugins_hub_cache()
+
+ calls = {"discover": 0}
+
+ def discover_all_plugins():
+ calls["discover"] += 1
+ return list(_PLUGIN_ROW)
+
+ _patch_minimal_hub_dependencies(
+ monkeypatch,
+ check_fn=lambda: True,
+ discover_all_plugins=discover_all_plugins,
+ )
+
+ first = web_server._merged_plugins_hub(force_refresh=True)
+ second = web_server._merged_plugins_hub()
+
+ assert calls["discover"] == 1
+ assert first is second
diff --git a/tools/registry.py b/tools/registry.py
index e66d4053cec..c92f8a0b9bc 100644
--- a/tools/registry.py
+++ b/tools/registry.py
@@ -346,6 +346,30 @@ def invalidate_check_fn_cache() -> None:
_check_fn_last_good.clear()
+def get_cached_check_fn_result(fn: Callable) -> Optional[bool]:
+ """Return the current cached verdict for *fn* if its TTL is still valid.
+
+ Unlike :func:`_check_fn_cached`, this NEVER executes the probe. It is for
+ read-only surfaces (e.g. dashboard status panels) that need the last-known
+ availability without triggering network / auth / SDK work inside a request
+ path. Returns ``None`` when there is no fresh cached verdict.
+ """
+ now = time.monotonic()
+ scope = check_fn_cache_scope()
+ if scope == CHECK_FN_CACHE_BYPASS:
+ # Unresolved profile identity bypasses the cache entirely; there is no
+ # trustworthy cached verdict to report.
+ return None
+ with _check_fn_cache_lock:
+ cached = _check_fn_cache.get((fn, scope))
+ if cached is None:
+ return None
+ ts, value = cached
+ if now - ts < _CHECK_FN_TTL_SECONDS:
+ return value
+ return None
+
+
class ToolRegistry:
"""Singleton registry that collects tool schemas + handlers from tool files."""