dashboard_ui.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. """Dashboard theme/font and dashboard-plugin (discovery, hub, install/enable, asset serving) routes.
  2. Extracted from ``hermes_cli.web_server``; helpers/state that tests monkeypatch on
  3. ``web_server`` stay there and are resolved late at call time (cycle-safe).
  4. """
  5. import asyncio
  6. import logging
  7. from pathlib import Path
  8. from typing import Callable, Optional
  9. from fastapi import APIRouter, HTTPException, Request
  10. from fastapi.responses import FileResponse
  11. from hermes_cli.web_deps import LateState, late
  12. from hermes_cli.config import cfg_get
  13. from hermes_cli.web_routers._common import config_scoped_to_thread
  14. from hermes_cli.web_server_dashboard import (
  15. _BUILTIN_DASHBOARD_THEMES, _discover_user_themes, _invalidate_plugins_hub_cache, _merged_plugins_hub,
  16. _plugin_consent_withheld,
  17. )
  18. from hermes_cli.web_server_memory import _normalize_memory_provider_name, _require_memory_provider_ready
  19. from hermes_cli.web_models import (
  20. FontSetBody, ThemeSetBody, _AgentPluginInstallBody, _PluginAutoUpdateBody, _PluginProvidersPutBody,
  21. _PluginVisibilityBody,
  22. )
  23. _log = logging.getLogger("hermes_cli.web_server")
  24. router = APIRouter()
  25. # Late-bound so a test's monkeypatch on the owning module wins at call time.
  26. _get_dashboard_plugins = late("_get_dashboard_plugins")
  27. _require_token = late("_require_token")
  28. load_config = late("load_config", "hermes_cli.config")
  29. save_config = late("save_config", "hermes_cli.config")
  30. # Home + secret scope for one request. NOT ``_profile_scope``: the bodies below clone/pull over the
  31. # network and hold the scope for their whole duration, and ``_profile_scope`` also holds the
  32. # process-global skills lock.
  33. _config_profile_scope = late("_config_profile_scope", "hermes_cli.web_server_profiles")
  34. _CONFIG_MUTATION_LOCK = LateState("_CONFIG_MUTATION_LOCK")
  35. def _set_dashboard_key(key: str, value, profile: Optional[str] = None) -> None:
  36. """Write ``dashboard.<key>`` to the profile's config.yaml under the config mutation lock."""
  37. with _config_profile_scope(profile), _CONFIG_MUTATION_LOCK:
  38. config = load_config()
  39. if "dashboard" not in config:
  40. config["dashboard"] = {}
  41. config["dashboard"][key] = value
  42. save_config(config)
  43. @router.get("/api/dashboard/themes")
  44. async def get_dashboard_themes(profile: Optional[str] = None):
  45. """Available themes + the active one. Built-ins ship name/label/description only
  46. (the frontend owns their definitions in `web/src/themes/presets.ts`); user themes
  47. from `~/.hermes/dashboard-themes/*.yaml` ship their normalised `definition`."""
  48. def _run():
  49. config = load_config()
  50. active = cfg_get(config, "dashboard", "theme", default="default")
  51. themes = list(_BUILTIN_DASHBOARD_THEMES)
  52. seen = {t["name"] for t in themes}
  53. for t in _discover_user_themes():
  54. if t["name"] in seen:
  55. continue
  56. themes.append({"name": t["name"], "label": t["label"], "description": t["description"], "definition": t})
  57. seen.add(t["name"])
  58. return {"themes": themes, "active": active}
  59. return await config_scoped_to_thread(profile, _run)
  60. @router.put("/api/dashboard/theme")
  61. async def set_dashboard_theme(body: ThemeSetBody, profile: Optional[str] = None):
  62. """Set the active dashboard theme (persists to config.yaml)."""
  63. await asyncio.to_thread(_set_dashboard_key, "theme", body.name, profile)
  64. return {"ok": True, "theme": body.name}
  65. # Curated font-override ids, kept in sync with FONT_CHOICES in web/src/themes/fonts.ts. The
  66. # frontend owns the stacks + webfont URLs; the backend only needs the id allow-list to reject
  67. # anything unvetted (the webfont URL is injected as a <link>, so never accept arbitrary ids/URLs).
  68. _FONT_DEFAULT_ID = "theme"
  69. _FONT_CHOICES = frozenset({
  70. "system-sans", "system-serif", "system-mono",
  71. "inter", "ibm-plex-sans", "work-sans", "atkinson-hyperlegible", "dm-sans",
  72. "spectral", "fraunces", "source-serif",
  73. "jetbrains-mono", "ibm-plex-mono", "space-mono",
  74. })
  75. @router.get("/api/dashboard/font")
  76. async def get_dashboard_font(profile: Optional[str] = None):
  77. """Return the active font override (``"theme"`` = use the theme's font)."""
  78. def _run():
  79. font = cfg_get(load_config(), "dashboard", "font", default=_FONT_DEFAULT_ID)
  80. return {"font": font if font in _FONT_CHOICES else _FONT_DEFAULT_ID}
  81. return await config_scoped_to_thread(profile, _run)
  82. @router.put("/api/dashboard/font")
  83. async def set_dashboard_font(body: FontSetBody, profile: Optional[str] = None):
  84. """Set the font override (config.yaml). Unknown ids coerce to ``"theme"`` rather than
  85. 400 so a stale client can't wedge the picker."""
  86. font = body.font if body.font in _FONT_CHOICES else _FONT_DEFAULT_ID
  87. await asyncio.to_thread(_set_dashboard_key, "font", font, profile)
  88. return {"ok": True, "font": font}
  89. @router.get("/api/dashboard/plugins")
  90. async def get_dashboard_plugins(profile: Optional[str] = None):
  91. """Return discovered dashboard plugins (excludes user-hidden and non-enabled ones)."""
  92. def _run():
  93. hidden: list = cfg_get(load_config(), "dashboard", "hidden_plugins", default=[]) or []
  94. # The consent the asset route and the API gates apply, so no listed tab fails to load.
  95. return [p for p in _get_dashboard_plugins()
  96. if p.get("name", "") not in hidden and not _plugin_consent_withheld(p)]
  97. # Strip internal fields before sending to frontend.
  98. return [{k: v for k, v in p.items() if not k.startswith("_")}
  99. for p in await config_scoped_to_thread(profile, _run)]
  100. @router.get("/api/dashboard/plugins/rescan")
  101. async def rescan_dashboard_plugins(profile: Optional[str] = None):
  102. """Force re-scan of the selected profile's dashboard plugins (its own cache, PLG-3)."""
  103. plugins = await config_scoped_to_thread(profile, lambda: _get_dashboard_plugins(force_rescan=True))
  104. return {"ok": True, "count": len(plugins)}
  105. @router.get("/api/dashboard/plugins/hub")
  106. async def get_plugins_hub(request: Request, profile: Optional[str] = None):
  107. """Unified agent plugins + dashboard extension metadata (session protected)."""
  108. _require_token(request)
  109. try:
  110. return await config_scoped_to_thread(profile, _merged_plugins_hub)
  111. except HTTPException:
  112. raise # an unknown ?profile= is the scope's 404, not a hub failure
  113. except Exception as exc:
  114. _log.warning("plugins/hub failed: %s", exc)
  115. raise HTTPException(status_code=500, detail="Failed to build plugins hub.") from exc
  116. def _plugin_action(result: dict, fallback_error: str, *, rescan: bool,
  117. client_decides: tuple[str, ...] = ("consent_required",)) -> dict:
  118. """Common tail of agent-plugin mutations: 400 on ``ok=False``, then invalidate caches
  119. (rescanning discovery when files changed on disk). An answer flagged by one of *client_decides*
  120. is not a failure: nothing changed, the client shows it (the capability delta, the scan findings)
  121. and retries with the user's decision."""
  122. if any(result.get(flag) for flag in client_decides):
  123. return result
  124. if not result.get("ok"):
  125. raise HTTPException(status_code=400, detail=result.get("error") or fallback_error)
  126. if rescan:
  127. _get_dashboard_plugins(force_rescan=True)
  128. _invalidate_plugins_hub_cache()
  129. return result
  130. @router.get("/api/dashboard/plugins/catalog")
  131. async def get_plugins_catalog(request: Request):
  132. """Curated plugin catalog merged with installed state (session protected)."""
  133. _require_token(request)
  134. def _run():
  135. from hermes_cli.plugins_cmd import _discover_all_plugins, _get_disabled_set, _get_enabled_set
  136. from hermes_cli.plugins_cmd_catalog import installed_catalog_state
  137. from hermes_cli.web_server_dashboard import _plugin_runtime_status
  138. enabled, disabled = _get_enabled_set(), _get_disabled_set()
  139. installed = {}
  140. for name, _v, _d, _s, dir_str, key in _discover_all_plugins():
  141. aliases = {name, key} - {""}
  142. info = {"dir": dir_str, "runtime_status": _plugin_runtime_status(aliases, enabled, disabled)}
  143. installed.update({alias: info for alias in aliases})
  144. return installed_catalog_state(installed)
  145. try:
  146. return await asyncio.to_thread(_run)
  147. except Exception as exc:
  148. _log.warning("plugins/catalog failed: %s", exc)
  149. raise HTTPException(status_code=500, detail="Failed to build plugins catalog.") from exc
  150. async def _plugin_mutation(fn: Callable[[], dict]) -> dict:
  151. """Run a dashboard plugin mutation inside the dashboard profile's home + secret scope, off the
  152. event loop.
  153. Scope: the git-credential path reaches ``get_secret("GITHUB_TOKEN")``, which fails closed once
  154. the process serves more than its launch profile — an unhandled ``UnscopedSecretError`` was the
  155. bare 500 on install/update (#115256). Off-loop: the bodies clone/pull and rescan the plugins
  156. directory. ``_config_profile_scope`` not ``_profile_scope``: the latter holds the process-wide
  157. skills lock for the whole (network-bound) body.
  158. """
  159. def _run():
  160. with _config_profile_scope(None):
  161. return fn()
  162. return await asyncio.to_thread(_run)
  163. @router.post("/api/dashboard/agent-plugins/install")
  164. async def post_agent_plugin_install(request: Request, body: _AgentPluginInstallBody):
  165. _require_token(request)
  166. from hermes_cli.plugins_cmd import dashboard_install_plugin
  167. catalog_name = (body.catalog_name or "").strip()
  168. identifier = body.identifier.strip()
  169. if not identifier and not catalog_name:
  170. raise HTTPException(status_code=400, detail="Provide an identifier or a catalog_name.")
  171. result = await _plugin_mutation(lambda: _plugin_action(
  172. dashboard_install_plugin(
  173. identifier, force=body.force, enable=body.enable, catalog_name=catalog_name or None,
  174. ref=body.ref),
  175. "Install failed.", rescan=True))
  176. # Strip internal paths from the response
  177. result.pop("after_install_path", None)
  178. return result
  179. def _validate_plugin_name(name: str) -> str:
  180. """Reject path-traversal attempts in plugin name URL parameters."""
  181. name = name.strip("/")
  182. if not name or ".." in name or "\\" in name:
  183. raise HTTPException(status_code=400, detail="Invalid plugin name.")
  184. return name
  185. async def _named_plugin_action(request: Request, name: str, action: Callable[[str], dict], fallback_error: str, *,
  186. rescan: bool, client_decides: tuple[str, ...] = ("consent_required",)) -> dict:
  187. _require_token(request)
  188. return await _plugin_mutation(lambda: _plugin_action(
  189. action(_validate_plugin_name(name)), fallback_error, rescan=rescan, client_decides=client_decides))
  190. @router.post("/api/dashboard/agent-plugins/update-all")
  191. async def post_agent_plugins_update_all(request: Request):
  192. """Update every plugin with an update, unattended: a widened pin or a git update's caution scan comes back
  193. ``needs_review`` (nothing changed) for the plugin's own Update action to walk."""
  194. _require_token(request)
  195. from hermes_cli.plugins_auto_update import update_all_unattended
  196. def _run() -> dict:
  197. outcome = update_all_unattended()
  198. if any(r["status"] == "updated" for r in outcome["results"]):
  199. _get_dashboard_plugins(force_rescan=True)
  200. _invalidate_plugins_hub_cache()
  201. return outcome
  202. return await _plugin_mutation(_run)
  203. @router.get("/api/dashboard/plugins/auto-update")
  204. async def get_plugins_auto_update(request: Request):
  205. _require_token(request)
  206. from hermes_cli.plugins_auto_update import auto_update_state
  207. return await _plugin_mutation(auto_update_state)
  208. @router.put("/api/dashboard/plugins/auto-update")
  209. async def put_plugins_auto_update(request: Request, body: _PluginAutoUpdateBody):
  210. _require_token(request)
  211. from hermes_cli.plugins_auto_update import set_auto_update
  212. from hermes_cli.plugins_cmd import PluginOperationError
  213. try:
  214. return await _plugin_mutation(lambda: set_auto_update(body.enabled))
  215. except PluginOperationError as exc:
  216. raise HTTPException(status_code=400, detail=str(exc)) from exc
  217. @router.post("/api/dashboard/agent-plugins/{name:path}/enable")
  218. async def post_agent_plugin_enable(request: Request, name: str):
  219. from hermes_cli.plugins_cmd import dashboard_set_agent_plugin_enabled
  220. return await _named_plugin_action(request, name, lambda n: dashboard_set_agent_plugin_enabled(n, enabled=True),
  221. "Enable failed.", rescan=False)
  222. @router.post("/api/dashboard/agent-plugins/{name:path}/disable")
  223. async def post_agent_plugin_disable(request: Request, name: str):
  224. from hermes_cli.plugins_cmd import dashboard_set_agent_plugin_enabled
  225. return await _named_plugin_action(request, name, lambda n: dashboard_set_agent_plugin_enabled(n, enabled=False),
  226. "Disable failed.", rescan=False)
  227. @router.post("/api/dashboard/agent-plugins/{name:path}/update")
  228. async def post_agent_plugin_update(request: Request, name: str):
  229. from hermes_cli.plugins_cmd import dashboard_update_user_plugin
  230. # Body is optional: ``{"accept_capabilities": true}`` applies a re-pin the user confirmed after a
  231. # ``consent_required`` answer; ``{"force": true}`` applies an update whose scan returned caution
  232. # after the user saw the ``scan_findings``.
  233. try:
  234. body = await request.json()
  235. except Exception:
  236. body = {}
  237. body = body if isinstance(body, dict) else {}
  238. accept, force = body.get("accept_capabilities") is True, body.get("force") is True
  239. return await _named_plugin_action(
  240. request, name, lambda n: dashboard_update_user_plugin(n, accept_capabilities=accept, force=force),
  241. "Update failed.", rescan=True, client_decides=("consent_required", "scan_blocked"))
  242. @router.delete("/api/dashboard/agent-plugins/{name:path}")
  243. async def delete_agent_plugin(request: Request, name: str):
  244. from hermes_cli.plugins_cmd import dashboard_remove_user_plugin
  245. return await _named_plugin_action(request, name, dashboard_remove_user_plugin, "Remove failed.", rescan=True)
  246. @router.post("/api/dashboard/agent-plugins/activate")
  247. async def post_agent_plugin_activate(request: Request):
  248. """``hermes plugins install`` / ``enable`` in another process asks this backend to load the plugin
  249. for ``home`` and hand its MCP servers and skills to that profile's open chats
  250. (``hermes_cli.plugins_activation.load_and_go_live``). ``home`` must be a profile this host serves."""
  251. _require_token(request)
  252. try:
  253. body = await request.json()
  254. except Exception:
  255. body = {}
  256. name = _validate_plugin_name(str((body or {}).get("name") or ""))
  257. from hermes_constants import get_hermes_home, hermes_home_key, profile_name_for_home
  258. home = Path(str((body or {}).get("home") or "")).expanduser()
  259. profile = profile_name_for_home(home) if str(home) not in ("", ".") else None
  260. if profile is None:
  261. raise HTTPException(status_code=400, detail="Not a Hermes profile home.")
  262. from hermes_cli.plugins_activation import load_and_go_live
  263. def _run():
  264. with _config_profile_scope(None if profile == "default" else profile):
  265. if hermes_home_key(get_hermes_home()) != hermes_home_key(home):
  266. raise HTTPException(status_code=400, detail="Home is not served by this backend.")
  267. return {"ok": True, "activation": load_and_go_live(name)}
  268. return await asyncio.to_thread(_run)
  269. @router.put("/api/dashboard/plugin-providers")
  270. async def put_plugin_providers(request: Request, body: _PluginProvidersPutBody,
  271. profile: Optional[str] = None):
  272. """Persist memory provider / context engine selection (writes config.yaml)."""
  273. _require_token(request)
  274. from hermes_cli.plugins_cmd import _save_context_engine, _save_memory_provider
  275. def _run():
  276. # ``_save_memory_provider``/``_save_context_engine`` are functools.partial over
  277. # ``_write_config_value`` -> save_config: the write is one hop away and lands in
  278. # whatever home the scope names. Unlike plugin INSTALLATION (host venv, pinned to the
  279. # serving profile), these two keys are per-profile settings — `memory.provider` is the
  280. # same key PUT /api/memory/provider scopes — so they follow ``?profile=``.
  281. with _config_profile_scope(profile), _CONFIG_MUTATION_LOCK:
  282. if body.memory_provider is not None:
  283. memory_provider = _normalize_memory_provider_name(body.memory_provider)
  284. # Readiness resolves through load_config(); inside the scope so the answer is
  285. # about the profile being written, not the launch profile.
  286. _require_memory_provider_ready(memory_provider)
  287. _save_memory_provider(memory_provider)
  288. if body.context_engine is not None:
  289. _save_context_engine(body.context_engine)
  290. _invalidate_plugins_hub_cache()
  291. return {"ok": True}
  292. return await asyncio.to_thread(_run)
  293. @router.post("/api/dashboard/plugins/{name:path}/visibility")
  294. async def post_plugin_visibility(request: Request, name: str, body: _PluginVisibilityBody,
  295. profile: Optional[str] = None):
  296. """Toggle a plugin's sidebar visibility (persists to config.yaml dashboard.hidden_plugins)."""
  297. _require_token(request)
  298. name = _validate_plugin_name(name)
  299. def _run():
  300. with _config_profile_scope(profile), _CONFIG_MUTATION_LOCK:
  301. config = load_config()
  302. if "dashboard" not in config or not isinstance(config.get("dashboard"), dict):
  303. config["dashboard"] = {}
  304. hidden_list: list = config["dashboard"].get("hidden_plugins") or []
  305. if not isinstance(hidden_list, list):
  306. hidden_list = []
  307. if body.hidden and name not in hidden_list:
  308. hidden_list.append(name)
  309. elif not body.hidden and name in hidden_list:
  310. hidden_list.remove(name)
  311. config["dashboard"]["hidden_plugins"] = hidden_list
  312. save_config(config)
  313. _invalidate_plugins_hub_cache()
  314. return {"ok": True, "name": name, "hidden": body.hidden}
  315. return await asyncio.to_thread(_run)
  316. # Browser-asset suffix allowlist. Everything else is 404'd so we never leak ``.py`` backend
  317. # sources, READMEs, ``.env.example`` etc. Extend deliberately; do NOT add a fallback.
  318. _PLUGIN_ASSET_CONTENT_TYPES = {
  319. ".js": "application/javascript", ".mjs": "application/javascript", ".css": "text/css",
  320. ".json": "application/json", ".html": "text/html", ".svg": "image/svg+xml",
  321. ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif",
  322. ".webp": "image/webp", ".ico": "image/x-icon", ".woff2": "font/woff2", ".woff": "font/woff",
  323. ".ttf": "font/ttf", ".otf": "font/otf", ".map": "application/json",
  324. }
  325. @router.get("/dashboard-plugins/@{profile}/{plugin_name}/{file_path:path}") # before the unscoped route
  326. async def serve_profile_plugin_asset(profile: str, plugin_name: str, file_path: str):
  327. """``serve_plugin_asset`` with the profile as a path segment (PLG-3): URLs relative to a stylesheet
  328. or bundle (``url("./icon.svg")``, chunk imports) drop a query string but keep this prefix."""
  329. return await serve_plugin_asset(plugin_name, file_path, profile)
  330. @router.get("/dashboard-plugins/{plugin_name}/{file_path:path}")
  331. async def serve_plugin_asset(plugin_name: str, file_path: str, profile: Optional[str] = None):
  332. """Serve static assets from a dashboard plugin's ``dashboard/`` directory.
  333. Unauthenticated on purpose: the SPA loads plugin JS via ``<script src>`` and CSS
  334. via ``<link href>``, which cannot attach an auth header. Hence the suffix
  335. allowlist — user plugins ship a ``plugin_api.py`` backend the browser never
  336. fetches, and without it anyone on the loopback port could curl a private
  337. plugin's source. Path traversal is blocked via ``resolve().is_relative_to()``;
  338. user plugins must be enabled (bundled ones not disabled) (GHSA-mcfc-hp25-cjv7) in the profile
  339. whose copy these files are: a native ticket's, the ``?profile=`` the browser's plugin list used
  340. (PLG-3), else the launch profile. An unknown profile answers as an unknown plugin.
  341. See #46435.
  342. """
  343. def _consented() -> Optional[dict]:
  344. plugin = next((p for p in _get_dashboard_plugins() if p["name"] == plugin_name), None)
  345. return None if not plugin or _plugin_consent_withheld(plugin) else plugin
  346. try:
  347. plugin = await config_scoped_to_thread(profile, _consented)
  348. except HTTPException:
  349. plugin = None
  350. if plugin is None:
  351. raise HTTPException(status_code=404, detail="Plugin not found")
  352. base = Path(plugin["_dir"])
  353. target = (base / file_path).resolve()
  354. if not target.is_relative_to(base.resolve()):
  355. raise HTTPException(status_code=403, detail="Path traversal blocked")
  356. if not target.exists() or not target.is_file():
  357. raise HTTPException(status_code=404, detail="File not found")
  358. media_type = _PLUGIN_ASSET_CONTENT_TYPES.get(target.suffix.lower())
  359. if media_type is None:
  360. raise HTTPException(status_code=404, detail="File not found")
  361. return FileResponse(target, media_type=media_type, headers={"Cache-Control": "no-store, no-cache, must-revalidate"})