Skip to content

The agent that grows with you

fix(plugins): run a served profile's dashboard plugins in its own plugin host

unsupportedpastelsda01ee9c3c38
diff --git a/hermes_cli/web_routers/dashboard_ui.py b/hermes_cli/web_routers/dashboard_ui.py
index 545bd2a001b..f01c11eba53 100644
--- a/hermes_cli/web_routers/dashboard_ui.py
+++ b/hermes_cli/web_routers/dashboard_ui.py
@@ -122,9 +122,9 @@ async def get_dashboard_plugins(profile: Optional[str] = None):
@router.get("/api/dashboard/plugins/rescan")
-async def rescan_dashboard_plugins():
- """Force re-scan of dashboard plugins."""
- plugins = _get_dashboard_plugins(force_rescan=True)
+async def rescan_dashboard_plugins(profile: Optional[str] = None):
+ """Force re-scan of the selected profile's dashboard plugins (its own cache, PLG-3)."""
+ plugins = await config_scoped_to_thread(profile, lambda: _get_dashboard_plugins(force_rescan=True))
return {"ok": True, "count": len(plugins)}
@@ -357,8 +357,15 @@ _PLUGIN_ASSET_CONTENT_TYPES = {
}
[email protected]("/dashboard-plugins/@{profile}/{plugin_name}/{file_path:path}") # before the unscoped route
+async def serve_profile_plugin_asset(profile: str, plugin_name: str, file_path: str):
+ """``serve_plugin_asset`` with the profile as a path segment (PLG-3): URLs relative to a stylesheet
+ or bundle (``url("./icon.svg")``, chunk imports) drop a query string but keep this prefix."""
+ return await serve_plugin_asset(plugin_name, file_path, profile)
+
+
@router.get("/dashboard-plugins/{plugin_name}/{file_path:path}")
-async def serve_plugin_asset(plugin_name: str, file_path: str):
+async def serve_plugin_asset(plugin_name: str, file_path: str, profile: Optional[str] = None):
"""Serve static assets from a dashboard plugin's ``dashboard/`` directory.
Unauthenticated on purpose: the SPA loads plugin JS via ``<script src>`` and CSS
@@ -366,14 +373,21 @@ async def serve_plugin_asset(plugin_name: str, file_path: str):
allowlist — user plugins ship a ``plugin_api.py`` backend the browser never
fetches, and without it anyone on the loopback port could curl a private
plugin's source. Path traversal is blocked via ``resolve().is_relative_to()``;
- user plugins must be enabled (bundled ones not disabled) (GHSA-mcfc-hp25-cjv7), in the
- launch profile whose copy these files are as well as in a native ticket's profile.
+ user plugins must be enabled (bundled ones not disabled) (GHSA-mcfc-hp25-cjv7) in the profile
+ whose copy these files are: a native ticket's, the ``?profile=`` the browser's plugin list used
+ (PLG-3), else the launch profile. An unknown profile answers as an unknown plugin.
See #46435.
"""
- plugins = _get_dashboard_plugins()
- plugin = next((p for p in plugins if p["name"] == plugin_name), None)
- if not plugin or _plugin_consent_withheld(plugin):
+ def _consented() -> Optional[dict]:
+ plugin = next((p for p in _get_dashboard_plugins() if p["name"] == plugin_name), None)
+ return None if not plugin or _plugin_consent_withheld(plugin) else plugin
+
+ try:
+ plugin = await config_scoped_to_thread(profile, _consented)
+ except HTTPException:
+ plugin = None
+ if plugin is None:
raise HTTPException(status_code=404, detail="Plugin not found")
base = Path(plugin["_dir"])
diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.py
index c332feef5e5..50eb4d543bd 100644
--- a/hermes_cli/web_server.py
+++ b/hermes_cli/web_server.py
@@ -402,6 +402,7 @@ async def host_header_middleware(request: Request, call_next):
from hermes_cli.web_server_dashboard import (
PluginApiWebSocketGate, _plugin_api_name, _plugin_api_request_refused,
)
+from hermes_cli.web_server_plugin_profiles import forward_secondary_plugin_request, plugin_request_scope
@app.middleware("http")
@@ -424,8 +425,13 @@ async def _plugin_api_runtime_gate(request: Request, call_next):
or getattr(request.app.state, "auth_required", False)
or _has_valid_session_token(request)
or _has_valid_query_token(request, path)
- ) and _plugin_api_request_refused(plugin_name):
- return JSONResponse(status_code=404, content={"detail": "Plugin not found"})
+ ):
+ with plugin_request_scope(request.scope): # a secondary profile's plugins run in its host
+ if _plugin_api_request_refused(plugin_name):
+ return JSONResponse(status_code=404, content={"detail": "Plugin not found"})
+ hosted = await forward_secondary_plugin_request(request, plugin_name)
+ if hosted is not None:
+ return hosted
return await call_next(request)
@@ -741,7 +747,12 @@ _dashboard_plugins_cache: Optional[list] = None
def _get_dashboard_plugins(force_rescan: bool = False) -> list:
+ """The active scope's dashboard plugins: a secondary profile's are its own (PLG-3)."""
global _dashboard_plugins_cache
+ from hermes_cli.web_server_plugin_profiles import profile_dashboard_plugins, secondary_profile_home
+ home = secondary_profile_home()
+ if home is not None:
+ return profile_dashboard_plugins(home, force_rescan)
stale = _dashboard_plugins_cache is None or force_rescan or any(
not Path(p["_dir"]).is_dir() for p in _dashboard_plugins_cache
)
diff --git a/hermes_cli/web_server_dashboard.py b/hermes_cli/web_server_dashboard.py
index b6ed033fb79..f8963cf19b9 100644
--- a/hermes_cli/web_server_dashboard.py
+++ b/hermes_cli/web_server_dashboard.py
@@ -562,12 +562,12 @@ def _dashboard_plugin_entry(data: dict[str, Any], name: str, dashboard_dir: Path
}
-def _discover_dashboard_plugins() -> list:
+def _discover_dashboard_plugins(search_dirs: Optional[list] = None) -> list:
"""Scan ``<plugins root>/*/dashboard/manifest.json`` across user, bundled and (opt-in)
- project plugin sources — same three sources as ``hermes_cli.plugins``."""
+ project plugin sources — same three sources as ``hermes_cli.plugins`` — or ``search_dirs``."""
plugins = []
seen_names: set = set()
- for plugins_root, source in _dashboard_plugin_search_dirs():
+ for plugins_root, source in (_dashboard_plugin_search_dirs() if search_dirs is None else search_dirs):
try:
if not plugins_root.is_dir():
continue
@@ -842,19 +842,12 @@ def _plugin_enable_sets_here() -> tuple[set, set]:
def _plugin_consent_withheld(plugin: dict[str, Any]) -> bool:
"""Whether a request must not reach ``plugin``'s backend or assets (#46435, GHSA-mcfc-hp25-cjv7).
- Discovery scans only the launch home and the root, so every copy this process imports, hands to
- a plugin host or serves files from is the launch profile's: the launch profile must have it
- enabled. So must the profile the request acts for, the active scope: a native ticket's profile,
- a ``?profile=`` selection once :func:`_plugin_route_secret_scope` binds it, else the launch
- profile (#134889).
+ ``plugin`` is the active scope's own copy (a secondary profile's plugins are discovered under
+ its home and run in its plugin host, :mod:`hermes_cli.web_server_plugin_profiles`), so the
+ profile the request acts for decides alone: a native ticket's profile, a ``?profile=``
+ selection, else the launch profile (#134889, PLG-3).
"""
- from hermes_constants import get_hermes_home, hermes_home_key
- if _plugin_api_mount_skip_reason(plugin, *_plugin_enable_sets_here()):
- return True
- if hermes_home_key(get_hermes_home()) == hermes_home_key(get_process_hermes_home()):
- return False
- with _launch_profile_scope():
- return _plugin_api_mount_skip_reason(plugin, *_plugin_enable_sets_here()) is not None
+ return _plugin_api_mount_skip_reason(plugin, *_plugin_enable_sets_here()) is not None
def _plugin_api_name(scope) -> str:
@@ -872,8 +865,11 @@ def _plugin_api_request_refused(name: str) -> bool:
counts as a user plugin (safe default: refused).
"""
from hermes_cli.web_server import _get_dashboard_plugins
- plugin = next((p for p in _get_dashboard_plugins() if p.get("name") == name), {"name": name, "source": "user"})
- return _plugin_consent_withheld(plugin)
+ from hermes_cli.web_server_plugin_profiles import secondary_profile_home
+ plugin = next((p for p in _get_dashboard_plugins() if p.get("name") == name), None)
+ if plugin is None and secondary_profile_home() is not None: # installed since the last scan
+ plugin = next((p for p in _get_dashboard_plugins(force_rescan=True) if p.get("name") == name), None)
+ return _plugin_consent_withheld(plugin or {"name": name, "source": "user"})
class PluginApiWebSocketGate:
@@ -887,20 +883,23 @@ class PluginApiWebSocketGate:
answer whether the plugin is disabled, unknown, or the credential was refused.
A Desktop's native grant is the exception: it names the profile the socket acts for, so it is
- redeemed here, once (:func:`_native_ws_scope`), and consent is checked in that profile.
+ redeemed here, once (:func:`_native_ws_scope`), and consent is checked in that profile. A
+ secondary profile's socket to a plugin its own host serves is answered here too (PLG-3).
"""
def __init__(self, app) -> None:
self.app = app
async def __call__(self, scope, receive, send) -> None:
+ from hermes_cli.web_server_plugin_profiles import plugin_request_scope, refuse_secondary_plugin_socket
name = _plugin_api_name(scope) if scope["type"] == "websocket" else ""
if not name:
await self.app(scope, receive, send)
return
- with _native_ws_scope(scope) as admitted:
+ with _native_ws_scope(scope) as admitted, plugin_request_scope(scope):
if admitted and not _plugin_api_request_refused(name):
- await self.app(scope, receive, send)
+ if not await refuse_secondary_plugin_socket(scope, receive, send, name):
+ await self.app(scope, receive, send)
return
await send({"type": "websocket.close", "code": status.WS_1008_POLICY_VIOLATION})
@@ -943,11 +942,13 @@ async def _plugin_route_secret_scope(conn: HTTPConnection, profile: Optional[str
a sync yield-dependency's setup and teardown run on different threadpool threads, so the
scope token would be reset in a foreign context; sync handlers still see the scope because
``run_in_threadpool`` copies the request context into the worker."""
+ from hermes_cli.web_server_plugin_profiles import in_process_router_refused
from hermes_cli.web_server_profiles import _config_profile_scope, _is_current_profile
+ name = _plugin_api_name(conn.scope)
with _config_profile_scope(profile):
- # The gates checked the request's own scope; a ``?profile=`` selection binds another one
- # only here, and the plugin must not run on a profile that disabled it (#134889).
- if not _is_current_profile(profile) and _plugin_api_request_refused(_plugin_api_name(conn.scope)):
+ # The plugin must not run on a profile that disabled it (#134889), and this router is the
+ # launch profile's copy: a secondary profile reaches it only for bundled plugins (PLG-3).
+ if (not _is_current_profile(profile) and _plugin_api_request_refused(name)) or in_process_router_refused(name):
if conn.scope["type"] == "websocket":
raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION)
raise HTTPException(status_code=404, detail="Plugin not found")
@@ -968,15 +969,11 @@ def _mount_hosted_plugin_api(app, plugin: dict, api_file_name: str) -> None:
if target is None:
return JSONResponse({"detail": f"plugin {name!r} is not enabled in this profile"}, status_code=404)
host, dashboard_dir, api_file = target
- result = await asyncio.to_thread(
+ from hermes_cli.web_server_plugin_profiles import hosted_response
+ return hosted_response(await asyncio.to_thread(
host.asgi_request, name, dashboard_dir, api_file, request.method, "/" + path,
request.url.query, [(k, v) for k, v in request.headers.items() if k.lower() != "host"],
- await request.body())
- response = Response(content=result["body"], status_code=int(result["status"]))
- for key, value in result["headers"]: # a list, so repeated headers (Set-Cookie) all survive
- if key.lower() not in {"content-length", "transfer-encoding", "connection"}:
- response.headers.append(key, value)
- return response
+ await request.body()))
app.add_api_route(f"/api/plugins/{name}/{{path:path}}", forward, include_in_schema=False,
methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"],
@@ -1033,22 +1030,31 @@ def _try_hot_mount_plugin_api(name: str) -> bool:
A plugin installed or enabled after server start had no route until restart: the startup
sweep is the only other caller of ``_mount_one_plugin_api``. Discovery is re-run (the plugin
- dir may not have existed at startup) and the whole decision is the launch profile's, exactly
- as at startup (its enable sets and its ``plugins.isolation``), whichever profile's request
- triggered it, so a plugin the launch profile did not enable is never imported or forwarded
- (#134889). New routes are spliced in just ahead of the hot-mount fallback, which sits before
- the SPA catch-all: appended at the end they would land behind ``/{full_path:path}`` and every
- GET would keep missing them.
+ dir may not have existed at startup) and the decision is the launch profile's, exactly as at
+ startup (its enable sets and its ``plugins.isolation``), so a plugin the launch profile did not
+ enable is never imported or forwarded (#134889); a secondary profile's request (its grant or a
+ ``?profile=`` selection) may mount only its own bundled copy, by its own lists (PLG-3). New
+ routes are spliced in just ahead of the hot-mount fallback, which sits before the SPA
+ catch-all: appended at the end they would land behind ``/{full_path:path}`` and every GET
+ would keep missing them.
"""
if not name or any(c in name for c in "/\\{}") or name == "..":
return False
from hermes_cli.plugins_cmd import _get_disabled_set, _get_enabled_set
from hermes_cli.web_server import _get_dashboard_plugins, app
+ from hermes_cli.web_server_plugin_profiles import plugin_api_path, secondary_plugin, secondary_profile_home
+ # A secondary profile reaches this router only for its own bundled copy (Hermes code), and its
+ # own lists decide that one (PLG-3).
+ secondary, own, requester_sets = secondary_profile_home() is not None, secondary_plugin(name), _plugin_enable_sets_here()
with _launch_profile_scope(), _plugin_api_mount_lock:
enabled_set, disabled_set = _get_enabled_set(), _get_disabled_set()
if _plugin_api_mounted(app, name): # a mounted plugin's unknown subpath: no disk rescan
return False
plugin = next((p for p in _get_dashboard_plugins(force_rescan=True) if p.get("name") == name), None)
+ if secondary:
+ if own is None or own.get("source") != "bundled" or plugin_api_path(plugin) != plugin_api_path(own):
+ return False
+ enabled_set, disabled_set = requester_sets
routes = app.router.routes
before = len(routes)
if plugin is None or not _mount_one_plugin_api(app, plugin, enabled_set, disabled_set):
@@ -1086,8 +1092,11 @@ class _PluginApiHotMount:
async def __call__(self, scope, receive, send) -> None:
from hermes_cli.web_server import app
+ from hermes_cli.web_server_plugin_profiles import plugin_request_scope
name = str(scope.get("path_params", {}).get("name", ""))
- if await asyncio.to_thread(_try_hot_mount_plugin_api, name):
+ with plugin_request_scope(scope): # a ``?profile=`` selection decides its own cold mount (PLG-3)
+ mounted = await asyncio.to_thread(_try_hot_mount_plugin_api, name)
+ if mounted:
_log.info("Hot-mounted plugin API routes on first request: /api/plugins/%s/", name)
await app.router(dict(scope, path_params={}), receive, send)
return
diff --git a/hermes_cli/web_server_plugin_profiles.py b/hermes_cli/web_server_plugin_profiles.py
new file mode 100644
index 00000000000..e8650a45d45
--- /dev/null
+++ b/hermes_cli/web_server_plugin_profiles.py
@@ -0,0 +1,194 @@
+"""Dashboard plugins of a secondary served profile (PLG-3, #134889).
+
+A gateway serving several profiles imports dashboard plugin code for its launch profile only. A
+request scoped to another served profile (its native grant, a ``?profile=`` selection) gets that
+profile's own plugins: discovered under its own home and the root, gated by its own ``plugins.enabled`` /
+``plugins.disabled``, and run in its own plugin host (bound to its home and secret scope) whatever
+its ``plugins.isolation`` says, so another profile's plugin code never enters this process. Bundled
+plugins are Hermes code and stay in-process. The host protocol is request/response, so a secondary
+profile's plugin websockets are refused by name until it carries them.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import threading
+from contextlib import ExitStack, contextmanager
+from pathlib import Path
+from typing import Any, Iterator, Optional
+from urllib.parse import parse_qsl, urlencode
+
+from fastapi.responses import JSONResponse, Response
+from starlette import status
+from starlette._utils import get_route_path
+from starlette.websockets import WebSocket
+
+from hermes_cli.config import get_process_hermes_home
+
+_log = logging.getLogger("hermes_cli.web_server")
+
+# Valid for every served profile, so a profile's plugin code must never receive them.
+_GATEWAY_CREDENTIAL_HEADERS = frozenset({
+ "authorization", "cookie", "host", "x-hermes-gateway-ticket", "x-hermes-session-token"})
+# Every query credential the gateway accepts (``web_server_chat._ws_auth_ok``, ``_has_valid_query_token``,
+# the display bridge, the PTY reattach key) and the profile selector; compared after URL-decoding.
+_GATEWAY_QUERY_KEYS = frozenset({"token", "ticket", "internal", "display_ticket", "attach", "profile"})
+
+_profile_plugins: dict[str, list] = {}
+_profile_plugins_lock = threading.Lock()
+
+
+def secondary_profile_home() -> Optional[Path]:
+ """The active scope's home when it is a profile other than the launch profile, else None."""
+ from hermes_constants import get_hermes_home, hermes_home_key
+ home = get_hermes_home()
+ return None if hermes_home_key(home) == hermes_home_key(get_process_hermes_home()) else Path(home)
+
+
+def profile_dashboard_plugins(home: Path, force_rescan: bool = False) -> list:
+ """Dashboard plugins of the profile at ``home``, cached per home like the launch profile's list:
+ its own ``plugins/``, then the root's (as a standalone ``hermes --profile <name> serve`` scanned
+ them; the profile's own copy wins a same-name conflict), then the bundled ones."""
+ from hermes_cli.plugins import get_bundled_plugins_dir
+ from hermes_cli.profiles import _get_default_hermes_home
+ from hermes_cli.web_server_dashboard import _discover_dashboard_plugins
+ from hermes_constants import hermes_home_key
+ key = hermes_home_key(home)
+ with _profile_plugins_lock:
+ cached = _profile_plugins.get(key)
+ if cached is None or force_rescan or any(not Path(p["_dir"]).is_dir() for p in cached):
+ bundled, own = get_bundled_plugins_dir(), Path(home) / "plugins"
+ dirs = [own] + [r for r in [_get_default_hermes_home() / "plugins"]
+ if r.resolve(strict=False) != own.resolve(strict=False)]
+ cached = _profile_plugins[key] = _discover_dashboard_plugins(
+ [(d, "user") for d in dirs] + [(bundled / "memory", "bundled"), (bundled, "bundled")])
+ return cached
+
+
+def _named(plugins: list, name: str) -> Optional[dict]:
+ return next((p for p in plugins if p.get("name") == name), None)
+
+
+def plugin_api_path(plugin: Optional[dict]) -> Optional[Path]:
+ """The resolved backend file of a discovered plugin entry, or None."""
+ if not plugin or not plugin.get("_api_file"):
+ return None
+ return (Path(plugin["_dir"]) / plugin["_api_file"]).resolve()
+
+
+def _in_process_api_file(name: str) -> Optional[Path]:
+ """The file this process's ``/api/plugins/<name>/`` router runs: the imported module's when one is
+ mounted (a hosted forward route has none here), else the copy the first request would mount,
+ the launch profile's discovery entry."""
+ import sys
+ from hermes_cli.web_server import _get_dashboard_plugins, app
+ from hermes_cli.web_server_dashboard import _launch_profile_scope, _plugin_api_mounted
+ if _plugin_api_mounted(app, name):
+ file = getattr(sys.modules.get(f"hermes_dashboard_plugin_{name}"), "__file__", None)
+ return Path(file).resolve() if file else None
+ with _launch_profile_scope():
+ return plugin_api_path(_named(_get_dashboard_plugins(), name))
+
+
+def _runs_in_process(plugin: Optional[dict]) -> bool:
+ """Whether a secondary profile's entry may use this process's router: only its bundled copy,
+ and only when that router runs that very file (a launch-profile user plugin can shadow the
+ bundled name, or a disabled one hide it)."""
+ return (plugin is not None and plugin.get("source") == "bundled"
+ and _in_process_api_file(plugin["name"]) == plugin_api_path(plugin))
+
+
+def secondary_plugin(name: str) -> Optional[dict]:
+ """The active secondary profile's own entry for ``name``, or None (also in the launch scope)."""
+ home = secondary_profile_home()
+ return None if home is None else _named(profile_dashboard_plugins(home), name)
+
+
+def _secondary_hosted_plugin(name: str) -> Optional[dict]:
+ """The active secondary profile's own entry for ``name`` when its plugin host serves it, or None:
+ the launch profile's scope, an unknown name, or the bundled copy this process runs."""
+ plugin = secondary_plugin(name)
+ return None if plugin is None or _runs_in_process(plugin) else plugin
+
+
+def in_process_router_refused(name: str) -> bool:
+ """Whether this process's ``/api/plugins/<name>/`` router (the launch profile's copy) must not
+ serve the active scope: a secondary profile runs only its own bundled copy here."""
+ return secondary_profile_home() is not None and not _runs_in_process(secondary_plugin(name))
+
+
+@contextmanager
+def plugin_request_scope(scope) -> Iterator[None]:
+ """Bind a plugin request's ``?profile=`` selection for its routing decision (the route
+ dependency binds it again for the handler). An unknown profile binds nothing: the route
+ dependency answers it as for any other route."""
+ from fastapi import HTTPException
+ from hermes_cli.web_server_profiles import _config_profile_scope, _is_current_profile
+ profile = dict(parse_qsl(scope.get("query_string", b"").decode("latin-1"))).get("profile")
+ with ExitStack() as stack:
+ if not _is_current_profile(profile):
+ try:
+ stack.enter_context(_config_profile_scope(profile))
+ except HTTPException as exc:
+ _log.debug("Plugin request for profile %r left unscoped: %s", profile, exc.detail)
+ yield
+
+
+def hosted_response(result: dict[str, Any]) -> Response:
+ """A plugin host's buffered ``asgi`` answer as a response."""
+ response = Response(content=result["body"], status_code=int(result["status"]))
+ for key, value in result["headers"]: # a list, so repeated headers (Set-Cookie) all survive
+ if key.lower() not in {"content-length", "transfer-encoding", "connection"}:
+ response.headers.append(key, value)
+ return response
+
+
+async def forward_secondary_plugin_request(request, name: str) -> Optional[Response]:
+ """Serve ``/api/plugins/<name>/`` for a secondary profile through its own plugin host, or None
+ when the in-process router answers (the launch profile, or a bundled plugin). Consent has been
+ checked in the request's scope already."""
+ plugin = _secondary_hosted_plugin(name)
+ if plugin is None:
+ return None
+ if not plugin.get("_api_file"):
+ return JSONResponse({"detail": "Not Found"}, status_code=404)
+ rest = get_route_path(request.scope).split("/", 4)
+ path = "/" + (rest[4] if len(rest) > 4 else "")
+ query = urlencode([(k, v) for k, v in parse_qsl(request.url.query, keep_blank_values=True)
+ if k not in _GATEWAY_QUERY_KEYS])
+ headers = [(k, v) for k, v in request.headers.items() if k.lower() not in _GATEWAY_CREDENTIAL_HEADERS]
+ body = await request.body()
+
+ def call() -> dict[str, Any]:
+ from hermes_cli.plugins import get_plugin_manager
+ host = get_plugin_manager()._plugin_host() # the active (secondary) profile's own host
+ return host.asgi_request(name, str(plugin["_dir"]), str(plugin["_api_file"]), request.method, path,
+ query, headers, body)
+
+ try:
+ return hosted_response(await asyncio.to_thread(call))
+ except Exception as exc: # health: allow BLE001 -- the host runs third-party code; any failure is this request's 502
+ _log.warning("Plugin %s: its profile's plugin host could not serve %s: %s", name, path, exc)
+ return JSONResponse({"detail": f"plugin {name!r} could not run in this profile's plugin host"},
+ status_code=502)
+
+
+async def refuse_secondary_plugin_socket(scope, receive, send, name: str) -> bool:
+ """Answer a secondary profile's socket to a plugin its host serves, and return True; False when
+ the in-process router takes it. An authenticated dial is refused by name (HTTP 501 before
+ accept, so Desktop's reconnect budget counts it); any other gets the plain policy close."""
+ if _secondary_hosted_plugin(name) is None:
+ return False
+ from hermes_cli.web_server_chat import _ws_auth_ok
+ socket = WebSocket(scope, receive, send)
+ if not ((scope.get("state") or {}).get("native_http_principal") or _ws_auth_ok(socket)):
+ await send({"type": "websocket.close", "code": status.WS_1008_POLICY_VIOLATION})
+ return True
+ detail = f"plugin {name!r} runs in this profile's plugin host, which does not carry websockets yet"
+ _log.info("Plugin %s: refused a websocket for %s: %s", name, secondary_profile_home(), detail)
+ if "websocket.http.response" in (scope.get("extensions") or {}):
+ await socket.send_denial_response(JSONResponse({"detail": detail}, status_code=501))
+ else:
+ await send({"type": "websocket.close", "code": status.WS_1008_POLICY_VIOLATION, "reason": detail[:120]})
+ return True
diff --git a/tests/hermes_cli/test_plugin_api_consent_gate.py b/tests/hermes_cli/test_plugin_api_consent_gate.py
index 0133e08f085..0f225af30cd 100644
--- a/tests/hermes_cli/test_plugin_api_consent_gate.py
+++ b/tests/hermes_cli/test_plugin_api_consent_gate.py
@@ -98,10 +98,12 @@ def daemon(_isolate_hermes_home, monkeypatch):
monkeypatch.setattr(launch_policy, "_snapshot", None)
monkeypatch.setattr(profiles, "_get_default_hermes_home", lambda: launch)
monkeypatch.setattr(profiles, "_get_profiles_root", lambda: launch / "profiles")
- hosted = []
+ hosted, calls = [], []
- def asgi_request(host, plugin, dashboard_dir, *_request):
+ def asgi_request(host, plugin, dashboard_dir, api_file, method, path, query, headers, body):
hosted.append(plugin)
+ calls.append(SimpleNamespace(home=host._home, dir=dashboard_dir, path=path, query=query,
+ headers={str(k).lower() for k, _ in headers}))
return {"status": 200, "headers": [], "body": b'{"hosted": true}'}
monkeypatch.setattr(PluginHost, "asgi_request", asgi_request)
@@ -116,7 +118,7 @@ def daemon(_isolate_hermes_home, monkeypatch):
client = TestClient(loopback_peer)
try:
yield SimpleNamespace(
- client=client, launch=launch, beta=beta, hosted=hosted,
+ client=client, launch=launch, beta=beta, hosted=hosted, calls=calls,
owner={web_server._SESSION_HEADER_NAME: web_server._SESSION_TOKEN},
beta_ticket=lambda: {"X-Hermes-Gateway-Ticket": store.mint(
profile_id=str(beta), subject="desktop", purpose="native-http")})
@@ -151,70 +153,91 @@ def test_disabled_plugin_refuses_new_websocket_connections(daemon):
assert refused.value.code == anonymous.value.code == no_credential.value.code
-def test_secondary_ticket_cannot_reach_a_plugin_the_launch_profile_disabled(daemon):
- """PLG-9: the in-process router and the served files are the launch profile's copy; when the
- launch profile disables the plugin at runtime a secondary profile's ticket loses both too,
- whatever that profile's own lists say, and the plugin list stops offering a tab that cannot load."""
+def test_launch_profile_runtime_disable_closes_its_router_assets_and_tab(daemon):
+ """PLG-9 for the launch profile's own copy: disabling it at runtime closes the in-process
+ router and the served files, and the plugin list stops offering a tab that cannot load. A
+ secondary profile never reaches this router: it runs the root copy in its own host (PLG-3,
+ ``test_plugin_secondary_profile_host``)."""
_install(daemon.launch, "consent-probe")
_plugins(daemon.launch, enabled=["consent-probe"])
_plugins(daemon.beta, enabled=["consent-probe"])
ping, asset = "/api/plugins/consent-probe/ping", "/dashboard-plugins/consent-probe/index.js"
+ owner_list = lambda: {p["name"] for p in daemon.client.get("/api/dashboard/plugins", headers=daemon.owner).json()}
assert daemon.client.get(ping, headers=daemon.owner).status_code == 200
- assert daemon.client.get(ping, headers=daemon.beta_ticket()).status_code == 200
- assert daemon.client.get(asset, headers=daemon.beta_ticket()).status_code == 200
- assert "consent-probe" in listed(daemon)
+ assert daemon.client.get(asset).status_code == 200
+ assert "consent-probe" in owner_list()
+ assert daemon.client.get(ping, headers=daemon.beta_ticket()).json() == {"hosted": True}
+ assert [c.home for c in daemon.calls] == [daemon.beta]
_plugins(daemon.launch, enabled=["consent-probe"], disabled=["consent-probe"])
assert daemon.client.get(ping, headers=daemon.owner).status_code == 404
- assert daemon.client.get(ping, headers=daemon.beta_ticket()).status_code == 404
- assert daemon.client.get(asset, headers=daemon.beta_ticket()).status_code == 404
- assert "consent-probe" not in listed(daemon)
+ assert daemon.client.get(asset).status_code == 404
+ assert "consent-probe" not in owner_list()
@pytest.mark.parametrize("isolation", ["in_process", "host"])
-def test_secondary_ticket_never_runs_a_plugin_only_it_enabled(daemon, isolation):
- """PLG-9 "loses one it enabled": the only copy this server can find is the launch profile's,
- which the launch profile never enabled, so a secondary profile's consent must neither import it
- here nor hand it to that profile's plugin host."""
+def test_secondary_ticket_runs_a_root_plugin_only_it_enabled_in_its_own_host(daemon, isolation):
+ """PLG-9 "loses one it enabled", PLG-3: a root plugin (the launch home is the root here) that only
+ the secondary profile enabled runs in that profile's plugin host whatever its isolation says;
+ it is never imported here."""
imported = _install(daemon.launch, "beta-only")
_plugins(daemon.launch)
_plugins(daemon.beta, enabled=["beta-only"], isolation=isolation)
- assert daemon.client.get("/api/plugins/beta-only/ping", headers=daemon.beta_ticket()).status_code == 404
- assert not imported.exists() and daemon.hosted == []
+ assert daemon.client.get("/api/plugins/beta-only/ping", headers=daemon.beta_ticket()).json() == {"hosted": True}
+ assert [c.home for c in daemon.calls] == [daemon.beta]
+ assert not imported.exists()
def test_hot_mount_keeps_the_launch_profiles_isolation(daemon):
- """The launch profile runs its plugins in a plugin host; a secondary profile's first request
- must not import the launch copy into this process because that profile's own config says
- in-process."""
+ """The launch profile runs its plugins in a plugin host; a secondary profile's first request for
+ a same-named plugin goes to its own host and neither imports nor mounts the launch copy here
+ because that profile's own config says in-process."""
imported = _install(daemon.launch, "iso-probe")
+ beta_imported = _install(daemon.beta, "iso-probe")
_plugins(daemon.launch, enabled=["iso-probe"], isolation="host")
_plugins(daemon.beta, enabled=["iso-probe"])
+ ping = "/api/plugins/iso-probe/ping"
- assert daemon.client.get("/api/plugins/iso-probe/ping", headers=daemon.beta_ticket()).json() == {"hosted": True}
- assert not imported.exists() and daemon.hosted == ["iso-probe"]
+ assert daemon.client.get(ping, headers=daemon.beta_ticket()).json() == {"hosted": True}
+ assert daemon.client.get(ping, headers=daemon.owner).json() == {"hosted": True}
+ assert [c.home for c in daemon.calls] == [daemon.beta, daemon.launch]
+ assert not imported.exists() and not beta_imported.exists()
-def test_launch_consent_read_under_a_secondary_grant_keeps_the_launch_secrets(daemon, monkeypatch):
- """A secondary profile's plugin socket binds that profile's secrets before the gate reads the
- launch profile's lists. That read must expand the launch config's ``${VAR}`` refs with the
- launch profile's secrets: otherwise the launch home's last-good config holds the secondary's
- values, and the launch profile is served them once its config.yaml stops parsing."""
+def test_launch_consent_read_under_a_secondary_grant_keeps_the_launch_secrets(daemon, tmp_path, monkeypatch):
+ """A secondary profile's first request for its bundled plugin (a ``?profile=`` selection) binds
+ that profile's secrets before the cold mount reads the launch profile's lists. That read must
+ expand the launch config's ``${VAR}`` refs with the launch profile's secrets: otherwise the
+ launch home's last-good config holds the secondary's values, and the launch profile is served
+ them once its config.yaml stops parsing. A root plugin's socket for that profile is refused by
+ name (PLG-3): its host serves it."""
+ from starlette.testclient import WebSocketDenialResponse
+
+ from hermes_cli import plugins as plugins_mod
from hermes_cli.config import load_config
from hermes_cli.web_server_profiles import _config_profile_scope
monkeypatch.delenv("PLG_SCOPE_PROBE", raising=False)
+ _install(tmp_path / "bundled-home", "scope-bundled")
+ monkeypatch.setattr(plugins_mod, "get_bundled_plugins_dir", lambda: tmp_path / "bundled-home" / "plugins")
_install(daemon.launch, "scope-probe")
config = {"plugins": {"enabled": ["scope-probe"], "disabled": []}, "scope_probe": "${PLG_SCOPE_PROBE}"}
(daemon.launch / "config.yaml").write_text(json.dumps(config))
(daemon.launch / ".env").write_text("PLG_SCOPE_PROBE=launch-value\n")
_plugins(daemon.beta, enabled=["scope-probe"])
(daemon.beta / ".env").write_text("PLG_SCOPE_PROBE=beta-value\n")
- assert daemon.client.get("/api/plugins/scope-probe/ping", headers=daemon.owner).status_code == 200
- with daemon.client.websocket_connect("/api/plugins/scope-probe/events", headers=daemon.beta_ticket()) as ws:
+
+ cold = daemon.client.get("/api/plugins/scope-bundled/ping", params={"profile": "beta"}, headers=daemon.owner)
+ assert cold.json() == {"pong": True}
+ with daemon.client.websocket_connect("/api/plugins/scope-bundled/events", headers=daemon.beta_ticket()) as ws:
assert ws.receive_text() == "hello"
+ with pytest.raises(WebSocketDenialResponse) as denied, \
+ daemon.client.websocket_connect("/api/plugins/scope-probe/events", headers=daemon.beta_ticket()):
+ pass
+ assert denied.value.status_code == 501 and "plugin host" in denied.value.json()["detail"]
+ assert daemon.calls == []
(daemon.launch / "config.yaml").write_text("plugins: [unclosed\n")
@@ -237,3 +260,9 @@ def test_profile_selector_cannot_run_a_plugin_on_a_profile_that_disabled_it(daem
assert ws.receive_text() == "hello"
with pytest.raises(WebSocketDisconnect), daemon.client.websocket_connect(f"{events}&profile=beta"):
pass
+ assert daemon.calls == []
+ # The secondary profile does see this root copy (PLG-3): its own opt-out alone refused it, and
+ # once it enables the plugin the copy runs in its own host, not in the launch profile's router.
+ _plugins(daemon.beta, enabled=["q-probe"])
+ assert daemon.client.get(ping, params={"profile": "beta"}, headers=daemon.owner).json() == {"hosted": True}
+ assert [c.home for c in daemon.calls] == [daemon.beta]
diff --git a/tests/hermes_cli/test_plugin_native_ws_scope.py b/tests/hermes_cli/test_plugin_native_ws_scope.py
index 849643c8dc1..26b41c46cca 100644
--- a/tests/hermes_cli/test_plugin_native_ws_scope.py
+++ b/tests/hermes_cli/test_plugin_native_ws_scope.py
@@ -4,10 +4,13 @@ The one-use ``native-http`` grant names the profile the socket acts for. The han
redeem it, after the runtime gate had checked consent in the launch profile's ambient scope and
the route dependency had bound the launch profile's secrets: a secondary profile's socket ran a
plugin that profile never enabled (or had disabled), with its home but the launch profile's
-secrets. The grant is now redeemed once, ahead of routing; both profiles' consent holds before
+secrets. The grant is now redeemed once, ahead of routing; the grant profile's consent holds before
accept, and the handler resolves home and secrets in the grant's profile.
-Driven through the real app on the multiplexed daemon stand-in of the consent-gate tests.
+The probe is a bundled plugin: since PLG-3 a secondary profile reaches user plugins only through its
+own plugin host (``test_plugin_secondary_profile_host``), so bundled plugins (kanban's socket) are
+the in-process sockets a secondary grant still opens. Driven through the real app on the
+multiplexed daemon stand-in of the consent-gate tests.
"""
from __future__ import annotations
@@ -20,6 +23,7 @@ from starlette.status import WS_1008_POLICY_VIOLATION
from starlette.testclient import TestClient
from starlette.websockets import WebSocketDisconnect
+from hermes_cli import plugins as plugins_mod
from hermes_cli import web_server
from hermes_cli.web_server_dashboard import PluginApiWebSocketGate
from hermes_cli.web_server_profiles import _config_profile_scope
@@ -63,22 +67,29 @@ NAME = "scope-probe"
EVENTS = f"/api/plugins/{NAME}/events"
-def _setup(daemon, *, beta_enabled=True, beta_disabled=False):
- dashboard = daemon.launch / "plugins" / NAME / "dashboard"
[email protected](autouse=True)
+def _bundled_root(tmp_path, monkeypatch):
+ root = tmp_path / "bundled"
+ root.mkdir()
+ monkeypatch.setattr(plugins_mod, "get_bundled_plugins_dir", lambda: root)
+
+
+def _setup(daemon, *, beta_disabled=False):
+ dashboard = plugins_mod.get_bundled_plugins_dir() / NAME / "dashboard"
dashboard.mkdir(parents=True)
(dashboard / "manifest.json").write_text(json.dumps({"name": NAME, "api": "plugin_api.py"}))
(dashboard / "plugin_api.py").write_text(_PROBE_API)
(dashboard / "index.js").write_text("export {}\n")
(daemon.launch / ".env").write_text("PLG_WS_SENTINEL=launch-sentinel\n")
(daemon.beta / ".env").write_text("PLG_WS_SENTINEL=beta-sentinel\n")
- _plugins(daemon.launch, enabled=[NAME])
- _beta(daemon, enabled=beta_enabled, disabled=beta_disabled)
+ _plugins(daemon.launch)
+ _beta(daemon, disabled=beta_disabled)
assert daemon.client.get(f"/api/plugins/{NAME}/ping", headers=daemon.owner).status_code == 200 # mounts it
return dashboard / "ENTERED"
-def _beta(daemon, *, enabled=True, disabled=False):
- _plugins(daemon.beta, enabled=[NAME] if enabled else [], disabled=[NAME] if disabled else [])
+def _beta(daemon, *, disabled=False):
+ _plugins(daemon.beta, disabled=[NAME] if disabled else [])
def _store():
@@ -112,18 +123,17 @@ SELECTORS = ["", "?profile=current", "?profile=beta"]
@pytest.mark.parametrize("selector", SELECTORS)
[email protected]("beta_consent", ["absent", "disabled"])
-def test_secondary_grant_needs_its_own_profiles_consent(daemon, selector, beta_consent):
- """Enabled in the launch profile only: the secondary profile's grant is refused before any
- plugin code runs, with the profile selector omitted (the Desktop's shape), current or explicit."""
- entered = _setup(daemon, beta_enabled=beta_consent == "disabled", beta_disabled=beta_consent == "disabled")
+def test_secondary_grant_needs_its_own_profiles_consent(daemon, selector):
+ """Disabled in the secondary profile only: its grant is refused before any plugin code runs,
+ with the profile selector omitted (the Desktop's shape), current or explicit."""
+ entered = _setup(daemon, beta_disabled=True)
assert _refused(daemon.client, EVENTS + selector, _grant(daemon.beta))
assert not entered.exists()
assert not _refused(daemon.client, EVENTS, _grant(daemon.launch)) # the launch profile's own socket opens
-def test_runtime_disable_in_either_profile_refuses_new_grant_sockets(daemon):
+def test_runtime_disable_refuses_new_grant_sockets_in_that_profile_only(daemon):
_setup(daemon)
assert not _refused(daemon.client, EVENTS, _grant(daemon.beta))
@@ -132,8 +142,8 @@ def test_runtime_disable_in_either_profile_refuses_new_grant_sockets(daemon):
assert not _refused(daemon.client, EVENTS, _grant(daemon.launch))
_beta(daemon)
- _plugins(daemon.launch, enabled=[NAME], disabled=[NAME])
- assert _refused(daemon.client, EVENTS, _grant(daemon.beta))
+ _plugins(daemon.launch, disabled=[NAME]) # PLG-3: the launch profile's lists no longer gate beta
+ assert not _refused(daemon.client, EVENTS, _grant(daemon.beta))
assert _refused(daemon.client, EVENTS, _grant(daemon.launch))
diff --git a/tests/hermes_cli/test_plugin_secondary_profile_host.py b/tests/hermes_cli/test_plugin_secondary_profile_host.py
new file mode 100644
index 00000000000..4e982fede1c
--- /dev/null
+++ b/tests/hermes_cli/test_plugin_secondary_profile_host.py
@@ -0,0 +1,424 @@
+"""PLG-3: a secondary served profile's dashboard plugins run in that profile's own plugin host.
+
+On a gateway serving several profiles, dashboard plugins were discovered from the launch home only
+and mounted once in the gateway process: a plugin installed only in a secondary profile answered 404
+from that profile's Desktop window, and its ``plugins.isolation`` was ignored. Now a request scoped to
+a secondary profile (native grant, ``?profile=``) reaches that profile's own copy through its own
+plugin host, whatever its isolation setting says; its assets and plugin list are its own; the launch
+profile's consent no longer gates them; and its plugin code is never imported here.
+
+Driven through the real app on the multiplexed daemon stand-in of the consent-gate tests. The host is
+a recorder there; the last test runs a real one.
+"""
+from __future__ import annotations
+
+import json
+import os
+import sys
+from pathlib import Path
+from urllib.parse import parse_qsl, urljoin
+
+import pytest
+from starlette.testclient import WebSocketDenialResponse
+from starlette.websockets import WebSocketDisconnect
+
+from hermes_cli import plugins as plugins_mod
+from hermes_cli import web_server
+from hermes_cli.plugin_host import PluginHost
+from tests.hermes_cli import test_plugin_api_consent_gate as consent_gate
+
+daemon = consent_gate.daemon # the multiplexed daemon stand-in fixture
+_install, _plugins, listed = consent_gate._install, consent_gate._plugins, consent_gate.listed
+
+_REAL_ASGI_REQUEST = PluginHost.asgi_request
+NAME = "beta-only"
+PING, EVENTS, ASSET = (f"/api/plugins/{NAME}/ping", f"/api/plugins/{NAME}/events",
+ f"/dashboard-plugins/{NAME}/index.js")
+
+
+def _beta_plugin(daemon, *, isolation="in_process"):
+ imported = _install(daemon.beta, NAME)
+ _plugins(daemon.beta, enabled=[NAME], isolation=isolation)
+ _plugins(daemon.launch)
+ return imported
+
+
+def _never_imported(imported) -> bool:
+ return not imported.exists() and f"hermes_dashboard_plugin_{NAME}" not in sys.modules
+
+
[email protected]("isolation", ["in_process", "host"])
+def test_secondary_profiles_own_plugin_answers_through_its_own_host(daemon, isolation):
+ imported = _beta_plugin(daemon, isolation=isolation)
+
+ response = daemon.client.get(PING, headers=daemon.beta_ticket())
+
+ assert (response.status_code, response.json()) == (200, {"hosted": True})
+ (call,) = daemon.calls
+ assert call.home == daemon.beta
+ assert Path(call.dir) == daemon.beta / "plugins" / NAME / "dashboard"
+ assert call.path == "/ping"
+ assert _never_imported(imported)
+
+
+def test_profile_selector_reaches_the_selected_profiles_host(daemon):
+ imported = _beta_plugin(daemon)
+
+ response = daemon.client.get(PING, params={"profile": "beta"}, headers=daemon.owner)
+
+ assert response.json() == {"hosted": True}
+ assert [c.home for c in daemon.calls] == [daemon.beta]
+ assert _never_imported(imported)
+
+
+def test_launch_profile_cannot_reach_a_secondary_profiles_plugin(daemon):
+ imported = _beta_plugin(daemon)
+
+ assert daemon.client.get(PING, headers=daemon.owner).status_code == 404
+ assert daemon.client.get(ASSET).status_code == 404
+ assert NAME not in {p["name"] for p in daemon.client.get("/api/dashboard/plugins", headers=daemon.owner).json()}
+ assert daemon.calls == [] and _never_imported(imported)
+
+
+def test_assets_and_plugin_list_are_the_secondary_profiles_own(daemon):
+ _beta_plugin(daemon)
+
+ asset = daemon.client.get(ASSET, headers=daemon.beta_ticket())
+ assert (asset.status_code, asset.text) == (200, "export {}\n")
+ assert NAME in listed(daemon)
+
+
+def test_browser_assets_follow_the_selected_profile(daemon):
+ """The browser loads assets with the ``?profile=`` its plugin list used: same-named plugins
+ answer with that profile's own files, a secondary-only plugin loads, and that profile's consent,
+ the traversal check and the suffix allowlist hold."""
+ for home in (daemon.launch, daemon.beta):
+ _install(home, "same")
+ (home / "plugins" / "same" / "dashboard" / "index.js").write_text(home.name)
+ _install(daemon.beta, NAME)
+ _plugins(daemon.launch, enabled=["same"])
+ _plugins(daemon.beta, enabled=["same", NAME])
+
+ def asset(name, file="index.js", **params):
+ return daemon.client.get(f"/dashboard-plugins/{name}/{file}", params=params)
+
+ assert asset("same").text == daemon.launch.name
+ assert asset("same", profile="beta").text == "beta"
+ assert asset(NAME, profile="beta").status_code == 200
+ assert asset(NAME).status_code == 404
+ assert asset(NAME, "plugin_api.py", profile="beta").status_code == 404
+ assert asset(NAME, "..%2F..%2F..%2Fconfig.yaml", profile="beta").status_code == 403
+
+ _plugins(daemon.beta, enabled=["same", NAME], disabled=["same"])
+ assert asset("same", profile="beta").status_code == 404
+ assert asset("same").text == daemon.launch.name
+ unknown = asset("no-such-plugin", profile="beta")
+ assert (asset(NAME, profile="nobody").status_code, asset(NAME, profile="nobody").json()) == (
+ unknown.status_code, unknown.json()) == (404, {"detail": "Plugin not found"})
+
+
+def test_profile_bearing_asset_path_keeps_relative_urls_in_that_profile(daemon):
+ """A relative URL in a stylesheet or bundle (``url("./icon.svg")``, a chunk import) drops the
+ sheet's query string, so the loader names the profile in the path: what it resolves to is still
+ that profile's copy, under the same consent, traversal and suffix checks."""
+ for home in (daemon.launch, daemon.beta):
+ _install(home, "same")
+ (home / "plugins" / "same" / "dashboard" / "icon.svg").write_text(home.name)
+ _install(daemon.beta, NAME)
+ _plugins(daemon.launch, enabled=["same"])
+ _plugins(daemon.beta, enabled=["same", NAME])
+ get = daemon.client.get
+ icon = urljoin("/dashboard-plugins/@beta/same/style.css", "./icon.svg")
+
+ assert (get(icon).status_code, get(icon).text) == (200, "beta")
+ assert get(f"/dashboard-plugins/@beta/{NAME}/index.js").status_code == 200
+ assert get("/dashboard-plugins/same/icon.svg").text == daemon.launch.name
+ assert get(f"/dashboard-plugins/@beta/{NAME}/plugin_api.py").status_code == 404
+ assert get(f"/dashboard-plugins/@beta/{NAME}/..%2F..%2F..%2Fconfig.yaml").status_code == 403
+ assert get(f"/dashboard-plugins/@nobody/{NAME}/index.js").json() == {"detail": "Plugin not found"}
+ _plugins(daemon.beta, enabled=["same", NAME], disabled=["same"])
+ assert get(icon).status_code == 404
+
+
+def test_launch_profile_consent_no_longer_gates_a_secondary_profiles_copy(daemon):
+ launch_imported = _install(daemon.launch, NAME)
+ beta_imported = _install(daemon.beta, NAME)
+ _plugins(daemon.launch, disabled=[NAME])
+ _plugins(daemon.beta, enabled=[NAME])
+
+ assert daemon.client.get(PING, headers=daemon.beta_ticket()).json() == {"hosted": True}
+ assert [Path(c.dir) for c in daemon.calls] == [daemon.beta / "plugins" / NAME / "dashboard"]
+ assert NAME in listed(daemon)
+ assert daemon.client.get(PING, headers=daemon.owner).status_code == 404
+
+ _plugins(daemon.beta, enabled=[NAME], disabled=[NAME]) # the secondary profile's own opt-out holds
+ assert daemon.client.get(PING, headers=daemon.beta_ticket()).status_code == 404
+ assert NAME not in listed(daemon)
+ assert len(daemon.calls) == 1
+ assert not launch_imported.exists() and not beta_imported.exists()
+
+
+def test_gateway_credentials_never_reach_a_secondary_profiles_host(daemon):
+ """The owner token and native grants are valid for every served profile: a profile's plugin code
+ must not receive them."""
+ _beta_plugin(daemon)
+ daemon.client.get(PING, headers=daemon.beta_ticket())
+ daemon.client.get(PING, params={"profile": "beta", "keep": "1"},
+ headers={**daemon.owner, "Authorization": "Bearer x", "Cookie": "a=b"})
+
+ assert len(daemon.calls) == 2
+ forbidden = {"x-hermes-gateway-ticket", web_server._SESSION_HEADER_NAME.lower(), "authorization", "cookie"}
+ for call in daemon.calls:
+ assert not call.headers & forbidden
+ assert "keep=1" in daemon.calls[1].query
+
+
[email protected]("selector", [False, True])
+def test_gateway_query_credentials_never_reach_a_secondary_profiles_host(daemon, selector):
+ """Every query credential the gateway accepts (``token``, ``ticket``, ``internal``,
+ ``display_ticket``, ``attach``) and the profile selector are dropped, repeated and URL-encoded
+ keys too; the plugin's own parameters pass through unchanged."""
+ _beta_plugin(daemon)
+ query = ("token=a&ticket=b&internal=c&display_ticket=d&attach=e&%74oken=f&ticket=g&tic%6Bet=h"
+ "&keep=1&keep=2&q=x%20y&tokenish=ok")
+ if selector:
+ response = daemon.client.get(f"{PING}?{query}&profile=beta", headers=daemon.owner)
+ else:
+ response = daemon.client.get(f"{PING}?{query}", headers=daemon.beta_ticket())
+
+ assert response.json() == {"hosted": True}
+ (call,) = daemon.calls
+ assert parse_qsl(call.query, keep_blank_values=True) == [
+ ("keep", "1"), ("keep", "2"), ("q", "x y"), ("tokenish", "ok")]
+
+
+def test_secondary_plugin_socket_gets_a_named_refusal(daemon):
+ """The host protocol carries no websockets yet: an admitted socket is refused by name (HTTP 501,
+ before accept), never run in-process. An unauthenticated dial gets the plain policy close."""
+ imported = _beta_plugin(daemon)
+
+ with pytest.raises(WebSocketDenialResponse) as denied, \
+ daemon.client.websocket_connect(EVENTS, headers=daemon.beta_ticket()):
+ pass
+ assert denied.value.status_code == 501
+ assert "plugin host" in denied.value.json()["detail"]
+
+ with pytest.raises(WebSocketDisconnect) as anonymous, \
+ daemon.client.websocket_connect(f"{EVENTS}?profile=beta"):
+ pass
+ assert not isinstance(anonymous.value, WebSocketDenialResponse) and anonymous.value.code == 1008
+ assert daemon.calls == [] and _never_imported(imported)
+
+
+def test_root_plugins_stay_available_to_a_secondary_profile_in_its_own_host(daemon):
+ """As a standalone ``hermes --profile beta serve`` did: beta scans its own ``plugins/``, then
+ the root's, then the bundled ones; its own copy wins a same-name conflict; its own lists decide;
+ the root copy runs in beta's host, never here. (The launch home is the root in this fixture.)"""
+ root_imported = _install(daemon.launch, NAME)
+ _plugins(daemon.launch) # the launch profile never enabled it
+ _plugins(daemon.beta, enabled=[NAME])
+
+ assert daemon.client.get(PING, headers=daemon.beta_ticket()).json() == {"hosted": True}
+ assert NAME in listed(daemon)
+ assert daemon.client.get(ASSET, headers=daemon.beta_ticket()).status_code == 200
+ assert daemon.client.get(PING, headers=daemon.owner).status_code == 404
+
+ beta_imported = _install(daemon.beta, NAME)
+ daemon.client.get("/api/dashboard/plugins/rescan", headers=daemon.beta_ticket())
+ assert daemon.client.get(PING, headers=daemon.beta_ticket()).json() == {"hosted": True}
+ assert [(c.home, Path(c.dir)) for c in daemon.calls] == [
+ (daemon.beta, daemon.launch / "plugins" / NAME / "dashboard"),
+ (daemon.beta, daemon.beta / "plugins" / NAME / "dashboard")]
+ assert not root_imported.exists() and not beta_imported.exists()
+
+
+def test_selected_profile_rescan_refreshes_that_profiles_cache_only(daemon):
+ """The browser's rescan names its profile with ``?profile=`` beside the owner token, so no native
+ grant binds the scope first: it still rescans and counts the selected profile's plugins, and the
+ launch profile's cache is left as it was."""
+ from hermes_cli.web_server_plugin_profiles import profile_dashboard_plugins
+ _install(daemon.beta, NAME)
+ _plugins(daemon.launch)
+ _plugins(daemon.beta, enabled=[NAME, "later"])
+ selected = {"params": {"profile": "beta"}, "headers": daemon.owner}
+ names = lambda **kw: {p["name"] for p in daemon.client.get("/api/dashboard/plugins", **kw).json()}
+ warmed, launch_listed = names(**selected), names(headers=daemon.owner)
+ assert NAME in warmed and NAME not in launch_listed
+ launch_cache = web_server._dashboard_plugins_cache
+ _install(daemon.beta, "later")
+ _install(daemon.launch, "launch-later")
+
+ rescan = daemon.client.get("/api/dashboard/plugins/rescan", **selected)
+
+ assert names(**selected) == warmed | {"later"}
+ assert rescan.json() == {"ok": True, "count": len(profile_dashboard_plugins(daemon.beta))}
+ assert web_server._dashboard_plugins_cache is launch_cache
+ assert names(headers=daemon.owner) == launch_listed
+
+
+def _refusal(daemon, path, headers):
+ """How a socket dial ends; any accept fails the test (refusals happen before accept)."""
+ with pytest.raises(WebSocketDisconnect) as closed, daemon.client.websocket_connect(path, headers=headers):
+ pytest.fail(f"{path} was accepted")
+ if isinstance(closed.value, WebSocketDenialResponse):
+ return "denied", closed.value.status_code
+ return "closed", closed.value.code
+
+
[email protected]("selector", [False, True])
+def test_secondary_consent_and_refusal_matrix(daemon, selector):
+ """Enabled, disabled, not enabled and unknown, over HTTP and websockets, for beta's ticket and for
+ the owner token with ``?profile=beta``: only an enabled plugin reaches beta's host, every refusal
+ comes before accept, and disabled, not enabled and unknown look the same."""
+ imported = _install(daemon.beta, NAME)
+ _plugins(daemon.launch)
+ token = f"token={web_server._SESSION_TOKEN}&profile=beta"
+
+ def outcome(name):
+ ping, events = f"/api/plugins/{name}/ping", f"/api/plugins/{name}/events"
+ if selector:
+ http = daemon.client.get(f"{ping}?profile=beta", headers=daemon.owner)
+ ws = _refusal(daemon, f"{events}?{token}", {})
+ else:
+ http = daemon.client.get(ping, headers=daemon.beta_ticket())
+ ws = _refusal(daemon, events, daemon.beta_ticket())
+ anonymous = daemon.client.get(f"{ping}?profile=beta"), _refusal(daemon, f"{events}?profile=beta", {})
+ return (http.status_code, http.json()), ws, (anonymous[0].status_code, anonymous[1])
+
+ outcomes = {}
+ for state, lists in {"enabled": {"enabled": [NAME]}, "disabled": {"enabled": [NAME], "disabled": [NAME]},
+ "not enabled": {}}.items():
+ _plugins(daemon.beta, **lists)
+ outcomes[state] = outcome(NAME)
+ outcomes["unknown"] = outcome("no-such-plugin")
+
+ enabled_http, enabled_ws, enabled_anonymous = outcomes.pop("enabled")
+ assert enabled_http == (200, {"hosted": True}) and enabled_ws == ("denied", 501)
+ refused = ((404, {"detail": "Plugin not found"}), ("closed", 1008), enabled_anonymous)
+ assert outcomes == dict.fromkeys(outcomes, refused)
+ assert enabled_anonymous[1] == ("closed", 1008)
+ assert [c.home for c in daemon.calls] == [daemon.beta]
+ assert _never_imported(imported)
+
+
+def _bundled(tmp_path, monkeypatch, name):
+ """A bundled plugin ``name``; returns its dashboard dir."""
+ _install(tmp_path / "bundled-home", name)
+ (tmp_path / "bundled-home" / "plugins").rename(tmp_path / "bundled")
+ monkeypatch.setattr(plugins_mod, "get_bundled_plugins_dir", lambda: tmp_path / "bundled")
+ return tmp_path / "bundled" / name / "dashboard"
+
+
+def _as_beta(daemon, selector):
+ """``(http kwargs, websocket url suffix, websocket headers)`` for beta's ticket or the owner token
+ with ``?profile=beta``."""
+ if selector:
+ return ({"params": {"profile": "beta"}, "headers": daemon.owner},
+ f"?token={web_server._SESSION_TOKEN}&profile=beta", {})
+ return {"headers": daemon.beta_ticket()}, "", daemon.beta_ticket()
+
+
[email protected]("selector", [False, True], ids=["ticket", "selector"])
[email protected]("mounted", [True, False], ids=["mounted", "cold"])
+def test_launch_user_copy_shadowing_a_bundled_name_never_serves_a_secondary_profile(
+ daemon, tmp_path, monkeypatch, mounted, selector):
+ """The router this process runs for a bundled name the launch profile overrides is the launch
+ profile's user code. A secondary profile whose own entry is the bundled copy gets that copy from
+ its own host (HTTP) or a named refusal (websocket), never the launch profile's code, whether that
+ router is mounted already or would be mounted by this request."""
+ from hermes_cli import profiles
+ monkeypatch.setattr(profiles, "_get_default_hermes_home", lambda: tmp_path / "root") # no root copy
+ bundled = _bundled(tmp_path, monkeypatch, "shadowed")
+ launch_imported = _install(daemon.launch, "shadowed")
+ _plugins(daemon.launch, enabled=["shadowed"])
+ _plugins(daemon.beta)
+ ping = "/api/plugins/shadowed/ping"
+ if mounted:
+ assert daemon.client.get(ping, headers=daemon.owner).json() == {"pong": True}
+ http, suffix, ws_headers = _as_beta(daemon, selector)
+
+ assert daemon.client.get(ping, **http).json() == {"hosted": True}
+ assert _refusal(daemon, f"/api/plugins/shadowed/events{suffix}", ws_headers) == ("denied", 501)
+ assert [(c.home, Path(c.dir)) for c in daemon.calls] == [(daemon.beta, bundled)]
+ assert launch_imported.exists() is mounted and not (bundled / "IMPORTED").exists()
+
+
[email protected]("selector", [False, True], ids=["ticket", "selector"])
+def test_disabled_launch_override_does_not_hide_the_bundled_copy_from_a_secondary_profile(
+ daemon, tmp_path, monkeypatch, selector):
+ """The launch profile disabled its own override of a bundled name, so this process has no router a
+ secondary profile may use for it: the secondary profile's bundled copy runs in its own host."""
+ from hermes_cli import profiles
+ monkeypatch.setattr(profiles, "_get_default_hermes_home", lambda: tmp_path / "root")
+ bundled = _bundled(tmp_path, monkeypatch, "hidden")
+ launch_imported = _install(daemon.launch, "hidden")
+ _plugins(daemon.launch, enabled=["hidden"], disabled=["hidden"])
+ _plugins(daemon.beta)
+ http, suffix, ws_headers = _as_beta(daemon, selector)
+
+ assert daemon.client.get("/api/plugins/hidden/ping", **http).json() == {"hosted": True}
+ assert _refusal(daemon, f"/api/plugins/hidden/events{suffix}", ws_headers) == ("denied", 501)
+ assert [(c.home, Path(c.dir)) for c in daemon.calls] == [(daemon.beta, bundled)]
+ assert not launch_imported.exists() and not (bundled / "IMPORTED").exists()
+
+
[email protected]("selector", [False, True], ids=["ticket", "selector"])
+def test_bundled_plugin_the_launch_profile_disabled_still_serves_a_secondary_profile(
+ daemon, tmp_path, monkeypatch, selector):
+ """Bundled plugins are Hermes code and stay in-process; the secondary profile's own lists decide,
+ also for the first request that mounts the router, whether its grant or ``?profile=`` names it."""
+ _bundled(tmp_path, monkeypatch, "bundled-probe")
+ _plugins(daemon.launch, disabled=["bundled-probe"])
+ _plugins(daemon.beta)
+ ping = "/api/plugins/bundled-probe/ping"
+ http, _, _ = _as_beta(daemon, selector)
+
+ assert daemon.client.get(ping, **http).json() == {"pong": True}
+ assert daemon.client.get(ping, headers=daemon.owner).status_code == 404
+ assert daemon.calls == []
+
+
[email protected]("selector", [False, True], ids=["ticket", "selector"])
+def test_secondary_profiles_opt_out_holds_on_a_cold_bundled_mount(daemon, tmp_path, monkeypatch, selector):
+ bundled = _bundled(tmp_path, monkeypatch, "bundled-optout")
+ _plugins(daemon.launch)
+ _plugins(daemon.beta, disabled=["bundled-optout"])
+ ping = "/api/plugins/bundled-optout/ping"
+ http, _, _ = _as_beta(daemon, selector)
+
+ assert daemon.client.get(ping, **http).status_code == 404
+ assert not (bundled / "IMPORTED").exists()
+ assert daemon.client.get(ping, headers=daemon.owner).json() == {"pong": True}
+
+
+_HOME_API = '''
+import os
+from fastapi import APIRouter
+
+router = APIRouter()
+
+
+async def whoami():
+ from hermes_constants import get_hermes_home
+ return {"pid": os.getpid(), "home": str(get_hermes_home())}
+'''
+
+
[email protected]("posix") # the host is a real child process
+def test_secondary_plugin_runs_in_a_real_host_bound_to_its_home(daemon, monkeypatch):
+ monkeypatch.setattr(PluginHost, "asgi_request", _REAL_ASGI_REQUEST)
+ imported = _beta_plugin(daemon)
+ (daemon.beta / "plugins" / NAME / "dashboard" / "plugin_api.py").write_text(_HOME_API)
+ try:
+ response = daemon.client.get(f"/api/plugins/{NAME}/whoami", headers=daemon.beta_ticket())
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["pid"] != os.getpid()
+ assert Path(body["home"]).resolve() == daemon.beta.resolve()
+ assert _never_imported(imported)
+ finally:
+ for manager in list(plugins_mod._plugin_managers_by_home.values()):
+ host = getattr(manager, "_plugin_host_instance", None)
+ if host is not None:
+ host.shutdown()
diff --git a/tests/hermes_cli/test_web_server.py b/tests/hermes_cli/test_web_server.py
index 97b41faa8c0..ecaa37ceb97 100644
--- a/tests/hermes_cli/test_web_server.py
+++ b/tests/hermes_cli/test_web_server.py
@@ -4804,92 +4804,6 @@ class TestPluginAPIAuth:
assert resp.status_code == 401
-class TestPluginAPISecretScopeProductionMount:
- """#120310: a plugin API handler's ``get_secret()`` must resolve the *requested*
- profile's credentials under multi-profile hosting, verified through the REAL mount
- path — discovery → import → ``_mount_plugin_api_routes()`` (which attaches
- ``_plugin_route_secret_scope``) → a live request against ``app`` — not a hand-built
- ``include_router``. The dedicated ``test_plugin_api_secret_scope.py`` suite proves the
- dependency in isolation; this closes the actual reported surface end-to-end and pins
- that the launch profile and a ``?profile=`` request read distinct secrets, that the
- request profile does not leak back into the launch profile, and that an unknown
- profile is rejected in the dependency before the handler runs.
- """
-
- _PROBE_KEY = "EXAMPLE_PLUGIN_PROBE_KEY"
-
- @pytest.fixture(autouse=True)
- def _setup(self, monkeypatch, _isolate_hermes_home, _install_example_plugin):
- try:
- from starlette.testclient import TestClient
- except ImportError:
- pytest.skip("fastapi/starlette not installed")
-
- import hermes_state
- from hermes_constants import get_hermes_home
- from hermes_cli import profiles
- from hermes_cli.web_server import app, _SESSION_HEADER_NAME, _SESSION_TOKEN
-
- default_home = get_hermes_home()
- monkeypatch.setattr(hermes_state, "DEFAULT_DB_PATH", default_home / "state.db")
-
- # Anchor the named-profiles root to the isolated home so ``?profile=workerb``
- # resolves inside the test sandbox (mirrors test_web_server_skills_profiles).
- profiles_root = default_home / "profiles"
- monkeypatch.setattr(profiles, "_get_default_hermes_home", lambda: default_home)
- monkeypatch.setattr(profiles, "_get_profiles_root", lambda: profiles_root)
-
- # Named profile B: a live profile with its OWN probe key value in ``.env`` (also its identity
- # marker); ``?profile=`` runs the plugin on B, so B has enabled it too (#134889).
- (worker_home := profiles_root / "workerb").mkdir(parents=True, exist_ok=True)
- (worker_home / ".env").write_text(f"{self._PROBE_KEY}=sk-workerb\n", encoding="utf-8")
- (worker_home / "config.yaml").write_text("plugins:\n enabled: [example]\n", encoding="utf-8")
-
- # Launch profile A: an env-only credential (systemd ``Environment=`` style), frozen
- # into the launch scope when multi-profile hosting activates.
- monkeypatch.setenv(self._PROBE_KEY, "sk-launch-a")
-
- import tui_gateway.launch_profile_policy as lpp
- from agent.secret_scope import is_multiplex_active, set_multiplex_active
-
- monkeypatch.setattr(lpp, "_snapshot", None) # freeze the launch env fresh
- self._previous_multiplex = is_multiplex_active()
- lpp.activate_multi_profile_hosting() # freezes os.environ + flips multiplex on
-
- self.client = TestClient(app)
- self.client.headers[_SESSION_HEADER_NAME] = _SESSION_TOKEN
- try:
- yield
- finally:
- set_multiplex_active(self._previous_multiplex)
-
- def _probe(self, profile=None):
- params = {"profile": profile} if profile is not None else None
- return self.client.get("/api/plugins/example/whoami", params=params)
-
- def test_launch_and_requested_profile_read_distinct_secrets(self):
- # No ``?profile=`` → the launch profile's frozen env-only credential.
- resp = self._probe()
- assert resp.status_code == 200
- assert resp.json() == {"ok": True, "key": "sk-launch-a"}
-
- # ``?profile=workerb`` → that profile's own credential, through the real mount.
- resp = self._probe("workerb")
- assert resp.status_code == 200
- assert resp.json() == {"ok": True, "key": "sk-workerb"}
-
- # Back to the launch profile: the request scope reset, so B never leaks into A.
- resp = self._probe()
- assert resp.status_code == 200
- assert resp.json() == {"ok": True, "key": "sk-launch-a"}
-
- def test_unknown_profile_rejected_before_handler(self):
- # The dependency raises HTTPException(404) before the handler runs, so this is a
- # 404 — NOT the handler's folded ``{"ok": False}`` no-data contract.
- resp = self._probe("ghost")
- assert resp.status_code == 404
-
-
class TestDashboardPluginManifestExtensions:
"""Tests for the extended plugin manifest fields (tab.override,
tab.hidden, slots) read by _discover_dashboard_plugins()."""
diff --git a/tests/hermes_cli/test_web_server_plugin_secret_scope.py b/tests/hermes_cli/test_web_server_plugin_secret_scope.py
new file mode 100644
index 00000000000..a40946b2859
--- /dev/null
+++ b/tests/hermes_cli/test_web_server_plugin_secret_scope.py
@@ -0,0 +1,104 @@
+"""A plugin API handler's ``get_secret()`` resolves the requested profile's credentials (#120310),
+through the real mount path: the launch profile's copy in-process, a ``?profile=`` profile's own copy
+in its plugin host (PLG-3). Moved out of ``test_web_server.py``.
+"""
+import shutil
+
+import pytest
+
+from tests.hermes_cli import test_web_server as web_server_tests
+
+_EXAMPLE_PLUGIN_FIXTURE = web_server_tests._EXAMPLE_PLUGIN_FIXTURE
+_install_example_plugin = web_server_tests._install_example_plugin # the fixture
+
+
+class TestPluginAPISecretScopeProductionMount:
+ """#120310: a plugin API handler's ``get_secret()`` must resolve the *requested*
+ profile's credentials under multi-profile hosting, verified through the REAL mount
+ path — discovery → import → ``_mount_plugin_api_routes()`` (which attaches
+ ``_plugin_route_secret_scope``) → a live request against ``app`` — not a hand-built
+ ``include_router``. The dedicated ``test_plugin_api_secret_scope.py`` suite proves the
+ dependency in isolation; this closes the actual reported surface end-to-end and pins
+ that the launch profile and a ``?profile=`` request read distinct secrets, that the
+ request profile does not leak back into the launch profile, and that an unknown
+ profile is rejected in the dependency before the handler runs.
+ """
+
+ _PROBE_KEY = "EXAMPLE_PLUGIN_PROBE_KEY"
+
+ @pytest.fixture(autouse=True)
+ def _setup(self, monkeypatch, _isolate_hermes_home, _install_example_plugin):
+ try:
+ from starlette.testclient import TestClient
+ except ImportError:
+ pytest.skip("fastapi/starlette not installed")
+
+ import hermes_state
+ from hermes_constants import get_hermes_home
+ from hermes_cli import profiles
+ from hermes_cli.web_server import app, _SESSION_HEADER_NAME, _SESSION_TOKEN
+
+ default_home = get_hermes_home()
+ monkeypatch.setattr(hermes_state, "DEFAULT_DB_PATH", default_home / "state.db")
+
+ # Anchor the named-profiles root to the isolated home so ``?profile=workerb``
+ # resolves inside the test sandbox (mirrors test_web_server_skills_profiles).
+ profiles_root = default_home / "profiles"
+ monkeypatch.setattr(profiles, "_get_default_hermes_home", lambda: default_home)
+ monkeypatch.setattr(profiles, "_get_profiles_root", lambda: profiles_root)
+
+ # Named profile B: a live profile with its OWN probe key value in ``.env`` (also its identity
+ # marker); ``?profile=`` runs B's own installed copy in B's plugin host (PLG-3, #134889).
+ (worker_home := profiles_root / "workerb").mkdir(parents=True, exist_ok=True)
+ (worker_home / ".env").write_text(f"{self._PROBE_KEY}=sk-workerb\n", encoding="utf-8")
+ (worker_home / "config.yaml").write_text("plugins:\n enabled: [example]\n", encoding="utf-8")
+ shutil.copytree(_EXAMPLE_PLUGIN_FIXTURE, worker_home / "plugins" / "example-dashboard")
+
+ # Launch profile A: an env-only credential (systemd ``Environment=`` style), frozen
+ # into the launch scope when multi-profile hosting activates.
+ monkeypatch.setenv(self._PROBE_KEY, "sk-launch-a")
+
+ import tui_gateway.launch_profile_policy as lpp
+ from agent.secret_scope import is_multiplex_active, set_multiplex_active
+
+ monkeypatch.setattr(lpp, "_snapshot", None) # freeze the launch env fresh
+ self._previous_multiplex = is_multiplex_active()
+ lpp.activate_multi_profile_hosting() # freezes os.environ + flips multiplex on
+
+ self.client = TestClient(app)
+ self.client.headers[_SESSION_HEADER_NAME] = _SESSION_TOKEN
+ try:
+ yield
+ finally:
+ set_multiplex_active(self._previous_multiplex)
+ from hermes_cli import plugins as plugins_mod
+ for manager in list(plugins_mod._plugin_managers_by_home.values()):
+ host = getattr(manager, "_plugin_host_instance", None)
+ if host is not None:
+ host.shutdown()
+
+ def _probe(self, profile=None):
+ params = {"profile": profile} if profile is not None else None
+ return self.client.get("/api/plugins/example/whoami", params=params)
+
+ def test_launch_and_requested_profile_read_distinct_secrets(self):
+ # No ``?profile=`` → the launch profile's frozen env-only credential.
+ resp = self._probe()
+ assert resp.status_code == 200
+ assert resp.json() == {"ok": True, "key": "sk-launch-a"}
+
+ # ``?profile=workerb`` → that profile's own credential, through the real mount.
+ resp = self._probe("workerb")
+ assert resp.status_code == 200
+ assert resp.json() == {"ok": True, "key": "sk-workerb"}
+
+ # Back to the launch profile: the request scope reset, so B never leaks into A.
+ resp = self._probe()
+ assert resp.status_code == 200
+ assert resp.json() == {"ok": True, "key": "sk-launch-a"}
+
+ def test_unknown_profile_rejected_before_handler(self):
+ # The dependency raises HTTPException(404) before the handler runs, so this is a
+ # 404 — NOT the handler's folded ``{"ok": False}`` no-data contract.
+ resp = self._probe("ghost")
+ assert resp.status_code == 404
diff --git a/web/src/App.tsx b/web/src/App.tsx
index 58dcea04ef0..49b23a4037e 100644
--- a/web/src/App.tsx
+++ b/web/src/App.tsx
@@ -68,7 +68,6 @@ import { useBelowBreakpoint } from "@nous-research/ui/hooks/use-below-breakpoint
import { useSidebarStatus } from "@/hooks/useSidebarStatus";
import { AuthWidget } from "@/components/AuthWidget";
import { PageHeaderProvider } from "@/contexts/PageHeaderProvider";
-import { ProfileProvider } from "@/contexts/ProfileProvider";
import { useProfileScope } from "@/contexts/useProfileScope";
import { ProfileSwitcher } from "@/components/ProfileSwitcher";
import { ProfileScopeBanner } from "@/components/ProfileScopeBanner";
@@ -375,7 +374,8 @@ const SIDEBAR_COLLAPSED_KEY = "hermes-sidebar-collapsed";
export default function App() {
const { t } = useI18n();
const { pathname } = useLocation();
- const { manifests, loading: pluginsLoading } = usePlugins();
+ const { profile } = useProfileScope();
+ const { manifests, loading: pluginsLoading } = usePlugins(profile);
const { theme } = useTheme();
const [mobileOpen, setMobileOpen] = useState(false);
const closeMobile = useCallback(() => setMobileOpen(false), []);
@@ -513,7 +513,6 @@ export default function App() {
}, []);
return (
- <ProfileProvider>
<div
data-layout-variant={layoutVariant}
className="flex h-dvh max-h-dvh min-h-0 flex-col overflow-hidden bg-background-base text-text-primary antialiased"
@@ -832,7 +831,6 @@ export default function App() {
<PluginSlot name="overlay" />
</div>
- </ProfileProvider>
);
}
diff --git a/web/src/lib/api.test.ts b/web/src/lib/api.test.ts
index abc5efad0d5..7020a993257 100644
--- a/web/src/lib/api.test.ts
+++ b/web/src/lib/api.test.ts
@@ -4,6 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
api,
authedFetch,
+ buildWsUrl,
fetchJSON,
getManagementProfile,
setManagementProfile,
@@ -206,6 +207,45 @@ describe("management profile scope", () => {
);
});
+describe("plugin SDK calls follow the selected profile (PLG-3)", () => {
+ // A plugin's bundle is the selected profile's copy; its backend calls must name that
+ // profile too, or they reach the launch profile's handlers (or 404 for a secondary-only one).
+ it.each([
+ ["fetchJSON", fetchJSON],
+ ["authedFetch", authedFetch],
+ ] as const)("%s scopes /api/plugins/ to the selected profile", async (_name, helper) => {
+ vi.stubGlobal("window", {});
+ const fetchMock = jsonFetchMock();
+ vi.stubGlobal("fetch", fetchMock);
+ setManagementProfile("beta");
+
+ await helper("/api/plugins/kanban/board?id=1");
+ await helper("/api/plugins/kanban/board?profile=alpha");
+
+ expect(fetchMock.mock.calls.map((c) => c[0])).toEqual([
+ "/api/plugins/kanban/board?id=1&profile=beta",
+ "/api/plugins/kanban/board?profile=alpha",
+ ]);
+ });
+
+ it("buildWsUrl names the selected profile on a plugin socket only", async () => {
+ vi.stubGlobal("window", {
+ __HERMES_SESSION_TOKEN__: "tok",
+ location: { protocol: "http:", host: "127.0.0.1:9119" },
+ });
+ setManagementProfile("beta");
+ const query = async (path: string, params?: Record<string, string>) =>
+ new URL(await buildWsUrl(path, params)).searchParams;
+
+ const plugin = await query("/api/plugins/kanban/events", { board: "b" });
+ expect([plugin.get("board"), plugin.getAll("profile"), plugin.get("token")]).toEqual([
+ "b", ["beta"], "tok",
+ ]);
+ expect((await query("/api/plugins/kanban/events", { profile: "alpha" })).getAll("profile")).toEqual(["alpha"]);
+ expect((await query("/api/events")).has("profile")).toBe(false);
+ });
+});
+
describe("api OAuth helpers", () => {
it("starts OAuth login in gated mode without requiring an injected session token", async () => {
vi.stubGlobal("window", { __HERMES_AUTH_REQUIRED__: true });
diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts
index 6aaac41b8e2..e352ae78698 100644
--- a/web/src/lib/api.ts
+++ b/web/src/lib/api.ts
@@ -143,6 +143,7 @@ const PROFILE_SCOPED_PREFIXES = [
"/api/dashboard/theme",
"/api/dashboard/font",
"/api/dashboard/plugins",
+ "/api/plugins/", // a plugin's backend: the selected profile's copy, as its bundle is (PLG-3)
// The shared-metrics answer is one per profile (telemetry.shared_metrics in its config.yaml).
"/api/shared-metrics",
];
@@ -354,12 +355,9 @@ export async function buildWsUrl(
path: string,
params?: Record<string, string>,
): Promise<string> {
- return buildHermesWebSocketUrl({
- authParam: await buildWsAuthParam(),
- basePath: BASE,
- params,
- path,
- });
+ const profile = getManagementProfile(); // a plugin socket names it as its REST calls do (PLG-3)
+ if (profile && path.startsWith("/api/plugins/") && !params?.profile) params = { ...params, profile };
+ return buildHermesWebSocketUrl({ authParam: await buildWsAuthParam(), basePath: BASE, params, path });
}
/** Build a ``?profile=<name>`` query suffix, or "" when unset.
@@ -1058,8 +1056,8 @@ export const api = {
),
// Dashboard plugins
- getPlugins: () =>
- fetchJSON<PluginManifestResponse[]>("/api/dashboard/plugins"),
+ getPlugins: (profile = getManagementProfile()) => // the profile the caller's asset URLs will name
+ fetchJSON<PluginManifestResponse[]>(`/api/dashboard/plugins${profile ? `?profile=${encodeURIComponent(profile)}` : ""}`),
rescanPlugins: () =>
fetchJSON<{ ok: boolean; count: number }>("/api/dashboard/plugins/rescan"),
diff --git a/web/src/main.tsx b/web/src/main.tsx
index e01f55b6f05..d0f448c3aa5 100644
--- a/web/src/main.tsx
+++ b/web/src/main.tsx
@@ -2,6 +2,7 @@ import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router";
import "./index.css";
import App from "./App";
+import { ProfileProvider } from "./contexts/ProfileProvider";
import { SystemActionsProvider } from "./contexts/SystemActions";
import { I18nProvider } from "./i18n";
import { exposePluginSDK } from "./plugins";
@@ -17,7 +18,10 @@ createRoot(document.getElementById("root")!).render(
<I18nProvider>
<ThemeProvider>
<SystemActionsProvider>
- <App />
+ {/* Above App, so its plugin loader follows the selected profile. */}
+ <ProfileProvider>
+ <App />
+ </ProfileProvider>
</SystemActionsProvider>
</ThemeProvider>
</I18nProvider>
diff --git a/web/src/plugins/registry.ts b/web/src/plugins/registry.ts
index df7c77d8d06..e1e0be20b91 100644
--- a/web/src/plugins/registry.ts
+++ b/web/src/plugins/registry.ts
@@ -37,7 +37,7 @@ import { Label } from "@nous-research/ui/ui/components/label";
import { Separator } from "@nous-research/ui/ui/components/separator";
import { Tabs, TabsList, TabsTrigger } from "@nous-research/ui/ui/components/tabs";
import { useI18n } from "@/i18n";
-import { registerSlot, PluginSlot } from "./slots";
+import { clearPluginSlots, registerSlot, PluginSlot } from "./slots";
// ---------------------------------------------------------------------------
// Plugin registry — plugins call register() to add their component.
@@ -60,8 +60,37 @@ export function notifyPluginRegistry() {
_notify();
}
+let _profile = "";
+
+/**
+ * Select the management profile whose plugin bundles the dashboard shows
+ * (PLG-3). Selecting another one forgets every component, load error and slot
+ * the previous profile's bundles registered; subscribers hear of it on the
+ * next microtask, never during the render that switched.
+ */
+export function selectPluginProfile(profile: string): void {
+ if (profile === _profile) return;
+ _profile = profile;
+ _registered.clear();
+ _loadErrors.clear();
+ clearPluginSlots();
+ queueMicrotask(_notify);
+}
+
+export function getPluginProfile(): string {
+ return _profile;
+}
+
+/** Whether the bundle now running was loaded for a profile no longer selected. */
+function _fromOtherProfile(): boolean {
+ const script = typeof document === "undefined" ? null : document.currentScript;
+ const owner = script?.getAttribute("data-hermes-profile");
+ return owner != null && owner !== _profile;
+}
+
/** Register a plugin component. Called by plugin JS bundles. */
function registerPlugin(name: string, component: React.ComponentType) {
+ if (_fromOtherProfile()) return;
_loadErrors.delete(name);
_registered.set(name, component);
_notify();
@@ -112,7 +141,9 @@ export const SDK_CONTRACT_VERSION = "1.1.0";
export function exposePluginSDK() {
window.__HERMES_PLUGINS__ = {
register: registerPlugin,
- registerSlot,
+ registerSlot: (plugin, slot, component) => {
+ if (!_fromOtherProfile()) registerSlot(plugin, slot, component);
+ },
};
window.__HERMES_PLUGIN_SDK__ = {
diff --git a/web/src/plugins/slots.ts b/web/src/plugins/slots.ts
index f040a589a03..4897d56a3c1 100644
--- a/web/src/plugins/slots.ts
+++ b/web/src/plugins/slots.ts
@@ -163,6 +163,14 @@ export function unregisterPluginSlots(plugin: string): void {
if (changed) _notifySlots();
}
+/** Clear every slot registration (the selected profile changed). Listeners
+ * hear of it on the next microtask, so this is safe during a render. */
+export function clearPluginSlots(): void {
+ if (_slotRegistry.size === 0) return;
+ _slotRegistry.clear();
+ queueMicrotask(_notifySlots);
+}
+
interface PluginSlotProps {
/** Slot identifier (e.g. `"sidebar"`, `"header-left"`). */
name: string;
diff --git a/web/src/plugins/usePlugins.profile.test.tsx b/web/src/plugins/usePlugins.profile.test.tsx
new file mode 100644
index 00000000000..c69dee1b98c
--- /dev/null
+++ b/web/src/plugins/usePlugins.profile.test.tsx
@@ -0,0 +1,172 @@
+// @vitest-environment jsdom
+// The plugin loader is bound to one profile: its list request, the asset URLs built from that
+// list, and the plugins it reports (PLG-3). A list for an older selection that lands after a
+// switch is dropped, and the previous profile's plugins are neither kept nor shown.
+
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { act, createElement, useEffect, type ComponentType } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import type { PluginManifest } from "./types";
+
+const pending = vi.hoisted(() => new Map<string, Array<(list: unknown) => void>>());
+
+vi.mock("@/lib/api", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@/lib/api")>();
+ return {
+ ...actual,
+ api: {
+ ...actual.api,
+ getPlugins: (profile: string) =>
+ new Promise((resolve) => {
+ pending.set(profile, [...(pending.get(profile) ?? []), resolve]);
+ }),
+ },
+ };
+});
+
+import { HERMES_BASE_PATH } from "@/lib/api";
+import { MANIFEST_CACHE_KEY, usePlugins } from "./usePlugins";
+import { exposePluginSDK, getPluginComponent } from "./registry";
+import { getSlotEntries } from "./slots";
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+function manifest(name: string, entry: string, css?: string): PluginManifest {
+ return {
+ name,
+ label: name,
+ description: "",
+ icon: "Puzzle",
+ version: "1.0.0",
+ tab: { path: `/${name}` },
+ entry,
+ css,
+ has_api: false,
+ source: "user",
+ };
+}
+
+let latest: ReturnType<typeof usePlugins>;
+function Probe({ profile }: { profile: string }) {
+ const result = usePlugins(profile);
+ useEffect(() => {
+ latest = result;
+ });
+ return null;
+}
+
+let root: Root;
+
+beforeEach(() => {
+ sessionStorage.clear();
+ pending.clear();
+ exposePluginSDK();
+ root = createRoot(document.createElement("div"));
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ document.head.innerHTML = "";
+ document.body.innerHTML = "";
+});
+
+async function show(profile: string) {
+ await act(async () => root.render(createElement(Probe, { profile })));
+}
+
+async function answer(profile: string, list: PluginManifest[]) {
+ const resolvers = pending.get(profile) ?? [];
+ expect(resolvers.length, `no plugin list request for ${profile}`).toBeGreaterThan(0);
+ await act(async () => resolvers.shift()!(list));
+}
+
+/** Run a registration as a plugin bundle loaded for ``profile`` does: from its own script. */
+function fromBundleOf(profile: string, register: () => void) {
+ const script = document.createElement("script");
+ script.setAttribute("data-hermes-profile", profile);
+ Object.defineProperty(document, "currentScript", { configurable: true, get: () => script });
+ try {
+ act(register);
+ } finally {
+ Reflect.deleteProperty(document, "currentScript");
+ }
+}
+
+const attrs = (selector: string, name: string) =>
+ [...document.querySelectorAll(selector)].map((el) => el.getAttribute(name) ?? "");
+const none: ComponentType<Record<string, never>> = () => null;
+
+describe("usePlugins across a profile switch", () => {
+ it("drops a list for the previous selection that lands after the switch", async () => {
+ await show("alpha");
+ await show("beta");
+ await answer("beta", [manifest("same", "beta.js", "beta.css"), manifest("beta-only", "b.js")]);
+ await answer("alpha", [manifest("same", "alpha.js", "alpha.css"), manifest("alpha-only", "a.js")]);
+
+ expect(latest.manifests.map((m) => m.entry)).toEqual(["beta.js", "b.js"]);
+ const scripts = attrs("script[data-hermes-plugin]", "src");
+ expect(scripts).toHaveLength(2);
+ expect(scripts.every((src) => src.includes("/dashboard-plugins/@beta/"))).toBe(true);
+ expect(attrs('link[rel="stylesheet"]', "href")).toEqual([
+ `${HERMES_BASE_PATH}/dashboard-plugins/@beta/same/beta.css`,
+ ]);
+ expect(sessionStorage.getItem(`${MANIFEST_CACHE_KEY}:alpha`)).toBeNull();
+ });
+
+ it("forgets the previous profile's plugins, assets and late registrations", async () => {
+ await show("beta");
+ await answer("beta", [manifest("same", "beta.js", "beta.css")]);
+ const betaTab: ComponentType<Record<string, never>> = () => null;
+ fromBundleOf("beta", () => {
+ window.__HERMES_PLUGINS__!.register("same", betaTab);
+ window.__HERMES_PLUGINS__!.registerSlot("same", "header-left", none);
+ });
+ expect(latest.plugins.map((p) => [p.manifest.entry, p.component])).toEqual([["beta.js", betaTab]]);
+ expect(getSlotEntries("header-left")).toHaveLength(1);
+
+ await show("alpha");
+
+ expect(latest.manifests).toEqual([]);
+ expect(latest.plugins).toEqual([]);
+ expect(getPluginComponent("same")).toBeUndefined();
+ expect(getSlotEntries("header-left")).toEqual([]);
+ expect(attrs('link[rel="stylesheet"]', "href")).toEqual([]);
+ expect(attrs("script[data-hermes-plugin]", "src")).toEqual([]);
+
+ // beta's bundle finishing after the switch registers nothing for alpha
+ fromBundleOf("beta", () => {
+ window.__HERMES_PLUGINS__!.register("same", betaTab);
+ window.__HERMES_PLUGINS__!.registerSlot("same", "header-left", none);
+ });
+ expect(getPluginComponent("same")).toBeUndefined();
+ expect(getSlotEntries("header-left")).toEqual([]);
+
+ await answer("alpha", [manifest("same", "alpha.js")]);
+ const alphaTab: ComponentType<Record<string, never>> = () => null;
+ fromBundleOf("alpha", () => window.__HERMES_PLUGINS__!.register("same", alphaTab));
+ expect(latest.plugins.map((p) => [p.manifest.entry, p.component])).toEqual([["alpha.js", alphaTab]]);
+ expect(attrs("script[data-hermes-plugin]", "src").every((s) => s.includes("/dashboard-plugins/@alpha/"))).toBe(true);
+ });
+
+ it("drops a profile's assets when it is left, even after its list emptied", async () => {
+ // The cached list injected a stylesheet; the server then says the plugin is gone.
+ sessionStorage.setItem(`${MANIFEST_CACHE_KEY}:beta`, JSON.stringify([manifest("gone", "g.js", "g.css")]));
+ await show("beta");
+ expect(attrs('link[rel="stylesheet"]', "data-hermes-profile")).toEqual(["beta"]);
+ await answer("beta", []);
+
+ await show("alpha");
+
+ expect(attrs("[data-hermes-profile]", "data-hermes-profile")).toEqual([]);
+ });
+
+ it("seeds a profile only from its own cached list", async () => {
+ sessionStorage.setItem(`${MANIFEST_CACHE_KEY}:beta`, JSON.stringify([manifest("cached", "c.js")]));
+
+ await show("alpha");
+ expect(latest.manifests).toEqual([]);
+ await show("beta");
+ expect(latest.manifests.map((m) => m.name)).toEqual(["cached"]);
+ });
+});
diff --git a/web/src/plugins/usePlugins.test.ts b/web/src/plugins/usePlugins.test.ts
index ac948374f0c..d7ed92b794f 100644
--- a/web/src/plugins/usePlugins.test.ts
+++ b/web/src/plugins/usePlugins.test.ts
@@ -4,7 +4,9 @@ import {
cacheManifests,
canSeedLoadedFromCache,
MANIFEST_CACHE_KEY,
+ pluginAssetUrl,
} from "./usePlugins";
+import { HERMES_BASE_PATH } from "@/lib/api";
import type { PluginManifest } from "./types";
function makeStorage(): Storage {
@@ -56,35 +58,41 @@ describe("plugin manifest cache helpers", () => {
});
it("getCachedManifests returns null when nothing is cached", () => {
- expect(getCachedManifests()).toBeNull();
+ expect(getCachedManifests("default")).toBeNull();
});
it("getCachedManifests returns null for invalid JSON", () => {
- storage.setItem(MANIFEST_CACHE_KEY, "not-json");
- expect(getCachedManifests()).toBeNull();
+ storage.setItem(`${MANIFEST_CACHE_KEY}:default`, "not-json");
+ expect(getCachedManifests("default")).toBeNull();
});
it("getCachedManifests returns null for non-array JSON", () => {
- storage.setItem(MANIFEST_CACHE_KEY, JSON.stringify({ foo: "bar" }));
- expect(getCachedManifests()).toBeNull();
+ storage.setItem(`${MANIFEST_CACHE_KEY}:default`, JSON.stringify({ foo: "bar" }));
+ expect(getCachedManifests("default")).toBeNull();
});
it("getCachedManifests returns a valid manifest array", () => {
const list: PluginManifest[] = [exampleManifest];
- cacheManifests(list);
- expect(getCachedManifests()).toEqual(list);
+ cacheManifests("default", list);
+ expect(getCachedManifests("default")).toEqual(list);
+ });
+
+ it("keeps each profile's list apart", () => {
+ cacheManifests("work", [exampleManifest]);
+ expect(getCachedManifests("default")).toBeNull();
+ expect(getCachedManifests("work")).toEqual([exampleManifest]);
});
it("cacheManifests overwrites a previous cache on refresh", () => {
const first: PluginManifest[] = [exampleManifest];
- cacheManifests(first);
- expect(getCachedManifests()).toEqual(first);
+ cacheManifests("default", first);
+ expect(getCachedManifests("default")).toEqual(first);
const second: PluginManifest[] = [
{ ...exampleManifest, name: "updated", label: "Updated" },
];
- cacheManifests(second);
- expect(getCachedManifests()).toEqual(second);
+ cacheManifests("default", second);
+ expect(getCachedManifests("default")).toEqual(second);
});
it("cacheManifests swallows storage errors", () => {
@@ -93,7 +101,7 @@ describe("plugin manifest cache helpers", () => {
throw new Error("QuotaExceededError");
};
vi.stubGlobal("sessionStorage", badStorage);
- expect(() => cacheManifests([exampleManifest])).not.toThrow();
+ expect(() => cacheManifests("default", [exampleManifest])).not.toThrow();
});
});
@@ -137,3 +145,28 @@ describe("canSeedLoadedFromCache (loading seed gate)", () => {
expect(canSeedLoadedFromCache(malformed)).toBe(true);
});
});
+
+describe("pluginAssetUrl", () => {
+ it("names the profile whose plugin list described the plugin in its path", () => {
+ expect(pluginAssetUrl("kanban", "dist/index.js", "work bench")).toBe(
+ `${HERMES_BASE_PATH}/dashboard-plugins/@work%20bench/kanban/dist/index.js`,
+ );
+ });
+
+ it("keeps the profile for URLs relative to a stylesheet or bundle", () => {
+ // url("./icon.svg") in a stylesheet, or a chunk import, drops the sheet's query string.
+ const sheet = new URL(pluginAssetUrl("kanban", "dist/style.css", "beta"), "http://127.0.0.1:9119");
+ expect(new URL("./icon.svg", sheet).pathname).toBe(
+ `${HERMES_BASE_PATH}/dashboard-plugins/@beta/kanban/dist/icon.svg`,
+ );
+ expect(new URL("../fonts/a.woff2", sheet).pathname).toBe(
+ `${HERMES_BASE_PATH}/dashboard-plugins/@beta/kanban/fonts/a.woff2`,
+ );
+ });
+
+ it("stays unscoped when no profile is known", () => {
+ expect(pluginAssetUrl("kanban", "style.css", "")).toBe(
+ `${HERMES_BASE_PATH}/dashboard-plugins/kanban/style.css`,
+ );
+ });
+});
diff --git a/web/src/plugins/usePlugins.ts b/web/src/plugins/usePlugins.ts
index f03a069839b..9476c8fd627 100644
--- a/web/src/plugins/usePlugins.ts
+++ b/web/src/plugins/usePlugins.ts
@@ -5,23 +5,36 @@
* 2. Injects CSS <link> tags for plugins that declare css
* 3. Loads plugin JS bundles via <script> tags
* 4. Waits for plugins to call register() and resolves them
+ *
+ * Everything is bound to the selected management profile (PLG-3): the list
+ * request names it, asset URLs name the profile whose list described them,
+ * and a list for an older selection is dropped. Switching profiles forgets
+ * the previous profile's manifests, assets and registered plugins.
*/
import { useState, useEffect, useRef } from "react";
import { api, HERMES_BASE_PATH } from "@/lib/api";
+import { dashboardServingProfile } from "@/lib/profile-bootstrap";
import type { PluginManifest, RegisteredPlugin } from "./types";
import {
getPluginComponent,
+ getPluginProfile,
onPluginRegistered,
notifyPluginRegistry,
+ selectPluginProfile,
setPluginLoadError,
} from "./registry";
export const MANIFEST_CACHE_KEY = "hermes:plugin-manifests";
-export function getCachedManifests(): PluginManifest[] | null {
+/** One profile's cached list: another profile's never seeds it. */
+function manifestCacheKey(profile: string): string {
+ return `${MANIFEST_CACHE_KEY}:${profile}`;
+}
+
+export function getCachedManifests(profile: string): PluginManifest[] | null {
try {
- const raw = sessionStorage.getItem(MANIFEST_CACHE_KEY);
+ const raw = sessionStorage.getItem(manifestCacheKey(profile));
if (!raw) return null;
const parsed = JSON.parse(raw);
return Array.isArray(parsed) ? (parsed as PluginManifest[]) : null;
@@ -30,9 +43,9 @@ export function getCachedManifests(): PluginManifest[] | null {
}
}
-export function cacheManifests(manifests: PluginManifest[]): void {
+export function cacheManifests(profile: string, manifests: PluginManifest[]): void {
try {
- sessionStorage.setItem(MANIFEST_CACHE_KEY, JSON.stringify(manifests));
+ sessionStorage.setItem(manifestCacheKey(profile), JSON.stringify(manifests));
} catch {
// sessionStorage unavailable (private browsing, storage full, etc.)
}
@@ -57,56 +70,113 @@ export function canSeedLoadedFromCache(
return !cached.some((m) => m.tab?.override === "/chat");
}
-export function usePlugins() {
- // Lazy initialisers run once at mount — safe to read sessionStorage here.
- // This avoids the "cannot access ref during render" lint error that would
- // occur if we stored the cached value in a useRef and read .current in the
- // useState initial value expression.
- const [manifests, setManifests] = useState<PluginManifest[]>(
- () => getCachedManifests() ?? [],
- );
+/**
+ * URL of one of a plugin's browser assets. It names the management profile
+ * whose GET /api/dashboard/plugins list described the plugin, so the server
+ * serves that profile's copy, not a same-named one of another profile. The
+ * profile is a path segment, so URLs relative to a stylesheet or bundle
+ * (`url("./icon.svg")`, chunk imports) keep it.
+ */
+export function pluginAssetUrl(
+ name: string,
+ file: string,
+ profile: string,
+): string {
+ const scope = profile ? `@${encodeURIComponent(profile)}/` : "";
+ return `${HERMES_BASE_PATH}/dashboard-plugins/${scope}${name}/${file}`;
+}
+
+/** The manifests of one profile and whether its plugins are still loading. */
+interface ProfileManifests {
+ profile: string;
+ manifests: PluginManifest[];
+ loading: boolean;
+}
+
+// Seeding from the profile's own cache registers plugin routes synchronously
+// on the first render after a refresh. The catch-all in App.tsx is only a
+// safety net for the very first visit (no cache yet). Exception: a cached
+// /chat override keeps loading=true (see canSeedLoadedFromCache).
+function seedManifests(profile: string): ProfileManifests {
+ const cached = getCachedManifests(profile);
+ return { profile, manifests: cached ?? [], loading: !canSeedLoadedFromCache(cached) };
+}
+
+/** State update ending the loading phase of ``owner``'s plugins (no-op for another profile). */
+function settled(owner: string) {
+ return (s: ProfileManifests) =>
+ s.profile === owner && s.loading ? { ...s, loading: false } : s;
+}
+
+/** Dashboard plugins of the selected management profile ("" = the dashboard's own). */
+export function usePlugins(selectedProfile: string) {
+ const profile = selectedProfile || dashboardServingProfile();
+ // Silent when unchanged; on a switch it forgets what the previous profile's
+ // bundles registered before anything renders under the new one.
+ selectPluginProfile(profile);
+ const [state, setState] = useState<ProfileManifests>(() => seedManifests(profile));
const [plugins, setPlugins] = useState<RegisteredPlugin[]>([]);
- // Start loading=false when the cache has manifests so plugin routes are
- // registered synchronously on the first render after a refresh.
- // The catch-all in App.tsx is only a safety net for the very first visit
- // (no cache yet). On subsequent visits this flag starts false immediately.
- //
- // Exception: if any cached manifest overrides /chat we must keep
- // loading=true — App.tsx's pluginsLoading gate around the persistent
- // ChatPage host is load-bearing (see canSeedLoadedFromCache).
- const [loading, setLoading] = useState<boolean>(
- () => !canSeedLoadedFromCache(getCachedManifests()),
- );
+ if (state.profile !== profile) {
+ setState(seedManifests(profile));
+ setPlugins([]);
+ }
const loadedScripts = useRef<Set<string>>(new Set());
+ // One asset lifetime per selected profile, apart from its list refreshes:
+ // leaving it drops its stylesheets and bundles, and lets them load again if
+ // it is selected again (the registry forgot what they registered).
+ useEffect(() => {
+ const loaded = loadedScripts.current;
+ return () => {
+ for (const el of document.querySelectorAll("[data-hermes-profile]")) {
+ if (el.getAttribute("data-hermes-profile") === profile) el.remove();
+ }
+ loaded.clear();
+ };
+ }, [profile]);
+
// Always re-fetch in the background to keep the cache fresh.
// This handles: new plugins added, plugins removed, manifest changes.
- // setManifests(list) will update routes if the server list differs from cache.
+ // A list that lands after the selection changed is dropped.
useEffect(() => {
+ let current = true;
api
- .getPlugins()
+ .getPlugins(profile)
.then((list) => {
- cacheManifests(list);
- setManifests(list);
- if (list.length === 0) setLoading(false);
+ if (!current) return;
+ cacheManifests(profile, list);
+ setState((s) =>
+ s.profile === profile
+ ? { profile, manifests: list, loading: s.loading && list.length > 0 }
+ : s,
+ );
})
- .catch(() => setLoading(false));
- }, []);
+ .catch(() => {
+ if (current) setState(settled(profile));
+ });
+ return () => {
+ current = false;
+ };
+ }, [profile]);
// Load plugin assets when manifests arrive.
+ const { profile: owner, manifests } = state;
useEffect(() => {
if (manifests.length === 0) return;
const injectedScripts: HTMLScriptElement[] = [];
+ const loaded = loadedScripts.current;
+ const stale = () => getPluginProfile() !== owner;
for (const manifest of manifests) {
// Inject CSS if specified.
if (manifest.css) {
- const cssUrl = `${HERMES_BASE_PATH}/dashboard-plugins/${manifest.name}/${manifest.css}`;
+ const cssUrl = pluginAssetUrl(manifest.name, manifest.css, owner);
if (!document.querySelector(`link[href="${cssUrl}"]`)) {
const link = document.createElement("link");
link.rel = "stylesheet";
link.href = cssUrl;
+ link.setAttribute("data-hermes-profile", owner);
document.head.appendChild(link);
}
}
@@ -114,17 +184,20 @@ export function usePlugins() {
// Load JS bundle. In dev, cache-bust so Vite HMR can clear the
// in-memory registry while the browser would otherwise never
// re-execute a previously cached <script> URL.
- const baseUrl = `${HERMES_BASE_PATH}/dashboard-plugins/${manifest.name}/${manifest.entry}`;
+ const baseUrl = pluginAssetUrl(manifest.name, manifest.entry, owner);
const scriptSrc = import.meta.env.DEV
- ? `${baseUrl}?hermes_dv=${Date.now()}`
+ ? `${baseUrl}${baseUrl.includes("?") ? "&" : "?"}hermes_dv=${Date.now()}`
: baseUrl;
if (!import.meta.env.DEV) {
- if (loadedScripts.current.has(baseUrl)) continue;
- loadedScripts.current.add(baseUrl);
+ if (loaded.has(baseUrl)) continue;
+ loaded.add(baseUrl);
}
const script = document.createElement("script");
script.setAttribute("data-hermes-plugin", manifest.name);
+ // The registry ignores register() calls from a bundle of a profile no
+ // longer selected.
+ script.setAttribute("data-hermes-profile", owner);
script.src = scriptSrc;
script.async = true;
// SRI integrity verification — defense against compromised plugin
@@ -138,12 +211,14 @@ export function usePlugins() {
script.crossOrigin = "anonymous";
}
script.onerror = () => {
+ if (stale()) return;
setPluginLoadError(manifest.name, "LOAD_FAILED");
console.warn(
`[plugins] Failed to load ${manifest.name} from ${scriptSrc} (open Network tab)`,
);
};
script.onload = () => {
+ if (stale()) return;
notifyPluginRegistry();
queueMicrotask(() => {
if (getPluginComponent(manifest.name)) return;
@@ -155,7 +230,7 @@ export function usePlugins() {
}
// Give plugins a moment to load and register, then stop loading state.
- const timeout = setTimeout(() => setLoading(false), 2000);
+ const timeout = setTimeout(() => setState(settled(owner)), 2000);
return () => {
clearTimeout(timeout);
if (import.meta.env.DEV) {
@@ -164,7 +239,7 @@ export function usePlugins() {
}
}
};
- }, [manifests]);
+ }, [owner, manifests]);
// Listen for plugin registrations and resolve them against manifests.
useEffect(() => {
@@ -179,14 +254,14 @@ export function usePlugins() {
setPlugins(resolved);
// If all plugins registered, stop loading early.
if (resolved.length === manifests.length && manifests.length > 0) {
- setLoading(false);
+ setState(settled(owner));
}
}
resolvePlugins();
const unsub = onPluginRegistered(resolvePlugins);
return unsub;
- }, [manifests]);
+ }, [owner, manifests]);
- return { plugins, manifests, loading };
+ return { plugins, manifests, loading: state.loading };
}
diff --git a/website/docs/user-guide/features/extending-the-dashboard.md b/website/docs/user-guide/features/extending-the-dashboard.md
index 3b63b41beec..b9614efbbf7 100644
--- a/website/docs/user-guide/features/extending-the-dashboard.md
+++ b/website/docs/user-guide/features/extending-the-dashboard.md
@@ -813,6 +813,13 @@ The dashboard scans three directories for `dashboard/manifest.json`:
| 2 | `<repo>/plugins/<name>/dashboard/` | `bundled` |
| 3 | `./.hermes/plugins/<name>/dashboard/` | `project` — only when `HERMES_ENABLE_PROJECT_PLUGINS` is set |
+On a gateway serving several profiles, a request for a profile other than the one the gateway started
+with sees that profile's own `plugins/<name>/dashboard/`, then the root `~/.hermes/plugins/<name>/dashboard/`
+(as a standalone `hermes --profile <name> dashboard` did; the profile's own copy wins a same-name
+conflict), then the bundled ones, gated by that profile's `plugins.enabled` / `plugins.disabled`. Its
+plugin API, a root plugin's included, runs in that profile's [plugin host](plugins.md#running-plugins-out-of-process-pluginsisolation),
+never inside the gateway.
+
Discovery results are cached per dashboard process. After adding a new plugin, either:
```bash
diff --git a/website/docs/user-guide/features/plugins.md b/website/docs/user-guide/features/plugins.md
index 795966f6f83..62ab0959534 100644
--- a/website/docs/user-guide/features/plugins.md
+++ b/website/docs/user-guide/features/plugins.md
@@ -835,6 +835,13 @@ provider objects (image/video generation, web search, browser, TTS/STT, memory,
model-provider profiles) exactly as before; Hermes registers matching entries on its side that call into
the host. Dashboard plugin APIs are served by the host too. Bundled plugins keep running in-process.
+On a gateway serving several profiles, every profile other than the one the gateway started with runs
+its own dashboard plugins (installed under its own `plugins/` folder or the root `~/.hermes/plugins/`,
+the profile's own copy winning a same-name conflict, and enabled in its own config) in its own plugin
+host, whatever its `plugins.isolation` says: another profile's plugin code never runs inside the
+gateway. The host does not carry websockets yet, so such a plugin's websocket routes are refused
+(HTTP 501) for that profile; its HTTP routes work.
+
What changes in `host` mode:
- **No shared interpreter.** A plugin's module never enters the Hermes process, so it cannot read
@@ -844,8 +851,8 @@ What changes in `host` mode:
flight returns a tool error and Hermes restarts the host and reloads its plugins (bounded retries).
- **A few surfaces need in-process code** and fail that plugin with a clear reason instead of loading:
gateway platform adapters (`register_platform`), approval transports, Telegram/platform handlers,
- model-provider profiles that build their own SDK client (`create_client`), streaming dashboard
- endpoints, and plugins that monkeypatch Hermes modules. Run those with `isolation: in_process`.
+ model-provider profiles that build their own SDK client (`create_client`), streaming and websocket
+ dashboard endpoints, and plugins that monkeypatch Hermes modules. Run those with `isolation: in_process`.
**Locking it for a shared deployment.** `plugins.isolation` is ordinary profile config, so whoever can
edit a profile's `config.yaml` can turn it off. When the profiles belong to people you are isolating from