The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(webapp): serve the host's desktop plugins to the Webapp's plugin loader
Adolanium17b56cbbeaf8
diff --git a/hermes_cli/web_routers/desktop_plugins.py b/hermes_cli/web_routers/desktop_plugins.pynew file mode 100644index 00000000000..cfc1f64d479--- /dev/null+++ b/hermes_cli/web_routers/desktop_plugins.py@@ -0,0 +1,84 @@+"""The Webapp's door to this host's desktop plugins (``<root>/desktop-plugins/<name>/plugin.js``).++Native Desktop reads that folder from its own disk (``desktopPluginsRoot`` in Electron's+``fs-ipc.ts``). The Webapp's renderer runs in a browser whose only disk is this server, so the+browser bridge asks here instead, and the same runtime loader scans, loads and polls it.++The routes answer only what the loader reads: the root, its plugin folders, and each folder's+``plugin.js`` and ``.hermes-package.json``, resolved through symlinks to inside the root. They never+go through ``/api/fs``, which follows the profile's SSH workspace and truncates at the preview cap.+Webapp only (``SurfacePolicy.desktop_plugins``; 404 elsewhere).+"""++from __future__ import annotations++import asyncio+from pathlib import Path++from fastapi import APIRouter, HTTPException++from hermes_constants import get_default_hermes_root++router = APIRouter()++DESKTOP_PLUGINS_DIR = "desktop-plugins"+#: The files the loader reads in a plugin folder: its entry and the unified-package marker.+_READABLE_FILES = frozenset({"plugin.js", ".hermes-package.json"})+#: Electron's ``PLUGIN_SOURCE_MAX_BYTES``: a plugin loads whole or not at all, never truncated.+PLUGIN_SOURCE_MAX_BYTES = 16 * 1024 * 1024+++def desktop_plugins_root() -> Path:+ """App-level, like Electron's: the Hermes root's folder, whichever profile the request names.+ Created on demand as Electron does, and resolved, so it prefixes every path the routes return."""+ root = get_default_hermes_root() / DESKTOP_PLUGINS_DIR+ root.mkdir(parents=True, exist_ok=True)+ return root.resolve()+++def _inside_root(raw: str) -> tuple[Path, tuple[str, ...]]:+ """*raw* resolved, and its parts below the root. Anything that resolves outside is a 404."""+ root = desktop_plugins_root()+ try:+ target = Path(raw).resolve(strict=True)+ parts = target.relative_to(root).parts+ except (OSError, RuntimeError, ValueError):+ raise HTTPException(status_code=404, detail="Not a desktop plugin path") from None+ return target, parts+++def _list(raw: str) -> dict:+ target, parts = _inside_root(raw)+ if len(parts) > 1 or not target.is_dir():+ raise HTTPException(status_code=404, detail="Not a desktop plugin folder")+ entries = [+ {"name": child.name, "path": str(target / child.name), "isDirectory": child.is_dir()}+ for child in sorted(target.iterdir(), key=lambda child: child.name)+ ]+ return {"entries": entries}+++def _read(raw: str) -> dict:+ target, parts = _inside_root(raw)+ if len(parts) != 2 or parts[1] not in _READABLE_FILES or not target.is_file():+ raise HTTPException(status_code=404, detail="Not a desktop plugin file")+ size = target.stat().st_size+ if size > PLUGIN_SOURCE_MAX_BYTES:+ raise HTTPException(status_code=413, detail="Plugin source exceeds 16 MiB")+ text = target.read_text(encoding="utf-8-sig", errors="replace")+ return {"byteSize": size, "path": str(target), "text": text, "truncated": False}++[email protected]("/api/desktop-plugins/root")+async def desktop_plugins_root_route() -> dict:+ return {"root": str(await asyncio.to_thread(desktop_plugins_root))}++[email protected]("/api/desktop-plugins/list")+async def list_desktop_plugins(path: str) -> dict:+ return await asyncio.to_thread(_list, path)++[email protected]("/api/desktop-plugins/read")+async def read_desktop_plugin_file(path: str) -> dict:+ return await asyncio.to_thread(_read, path)diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.pyindex 73323b965e9..f31a6c1d610 100644--- a/hermes_cli/web_server.py+++ b/hermes_cli/web_server.py@@ -801,6 +801,7 @@ from hermes_cli.web_routers import (webapp_access as _webapp_access_routes,)+import hermes_cli.web_routers.desktop_plugins as _desktop_plugin_routesimport hermes_cli.web_routers.uploads as _upload_routesfrom fastapi import Depends as _Dependsfrom hermes_cli.web_server_surface import route_on as _route_on@@ -808,6 +809,7 @@ from hermes_cli.web_server_surface import route_on as _route_onapp.include_router(_files_routes.router)# The Webapp's routes exist only on the surfaces whose policy names them (404 elsewhere).app.include_router(_upload_routes.router, dependencies=[_Depends(_route_on("browser_files"))])+app.include_router(_desktop_plugin_routes.router, dependencies=[_Depends(_route_on("desktop_plugins"))])app.include_router(_git_routes.router)app.include_router(_local_models_routes.router)app.include_router(_status_routes.router)diff --git a/hermes_cli/web_server_surface.py b/hermes_cli/web_server_surface.pyindex c4a76259e1c..31b4806774f 100644--- a/hermes_cli/web_server_surface.py+++ b/hermes_cli/web_server_surface.py@@ -41,21 +41,28 @@ class SurfacePolicy:#: ``/api/files/ticket`` mints the path-bound tickets for downloads and media links, and chat#: upload bodies are capped before they are parsed (``web_upload_limit``).browser_files: bool+ #: ``/api/desktop-plugins/*`` serves this host's desktop plugins to the browser's plugin loader;+ #: native Desktop reads its own disk.+ desktop_plugins: boolPOLICIES: dict[str, SurfacePolicy] = {"serve": SurfacePolicy(serves_spa=False, html_token=True, host_terminal=False, launch_link=False, gateway_ticket=False,- own_origin_cookie_writes=False, web_access=False, browser_files=False),+ own_origin_cookie_writes=False, web_access=False, browser_files=False,+ desktop_plugins=False),"dashboard": SurfacePolicy(serves_spa=True, html_token=True, host_terminal=False, launch_link=False, gateway_ticket=False,- own_origin_cookie_writes=False, web_access=False, browser_files=False),+ own_origin_cookie_writes=False, web_access=False, browser_files=False,+ desktop_plugins=False),"gateway": SurfacePolicy(serves_spa=True, html_token=True, host_terminal=False, launch_link=False, gateway_ticket=False,- own_origin_cookie_writes=False, web_access=True, browser_files=False),+ own_origin_cookie_writes=False, web_access=True, browser_files=False,+ desktop_plugins=False),"webapp": SurfacePolicy(serves_spa=True, html_token=False, host_terminal=True, launch_link=True, gateway_ticket=True,- own_origin_cookie_writes=True, web_access=True, browser_files=True),+ own_origin_cookie_writes=True, web_access=True, browser_files=True,+ desktop_plugins=True),}diff --git a/tests/hermes_cli/test_webapp_desktop_plugins.py b/tests/hermes_cli/test_webapp_desktop_plugins.pynew file mode 100644index 00000000000..87517224ee3--- /dev/null+++ b/tests/hermes_cli/test_webapp_desktop_plugins.py@@ -0,0 +1,99 @@+"""The Webapp serves this host's desktop plugins to the browser's plugin loader.++Native Desktop reads ``<root>/desktop-plugins`` from its own disk. A browser tab's only disk is the+server, so ``/api/desktop-plugins/*`` answers the same three reads the loader makes (the root, its+folders, a folder's ``plugin.js`` and package marker), whole, and nothing else. The renderer half is+pinned in ``apps/desktop/src/lib/browser-desktop-plugins.test.ts``.+"""+import json++import pytest+from starlette.testclient import TestClient++from hermes_cli import web_server+++def _client(monkeypatch, surface):+ for key, value in (("auth_required", False), ("bound_host", None), ("ui_surface", surface)):+ monkeypatch.setattr(web_server.app.state, key, value, raising=False)+ client = TestClient(web_server.app)+ client.headers[web_server._SESSION_HEADER_NAME] = web_server._SESSION_TOKEN+ return client+++def hermes_root(monkeypatch, tmp_path):+ """A custom Hermes root, served through one of its named profiles."""+ root = tmp_path / "hermes"+ (root / "profiles" / "work").mkdir(parents=True)+ monkeypatch.setenv("HERMES_HOME", str(root / "profiles" / "work"))+ return root+++def webapp(monkeypatch, hermes_root):+ client = _client(monkeypatch, "webapp")+ yield client+ client.close()+++def _install(root, name, source, marker=None):+ folder = root / "desktop-plugins" / name+ folder.mkdir(parents=True)+ (folder / "plugin.js").write_text(source, encoding="utf-8")+ if marker is not None:+ (folder / ".hermes-package.json").write_text(json.dumps(marker), encoding="utf-8")+ return folder+++def test_webapp_loads_the_app_level_plugins_folder_whole(webapp, hermes_root):+ # Larger than the 512 KiB /api/fs preview cap, which would hand the loader half a module.+ source = "export default { id: 'big' }\n" + "// pad\n" * 120_000+ folder = _install(hermes_root, "big", source, marker={"package": "big-pkg"})++ root = webapp.get("/api/desktop-plugins/root").json()["root"]+ # App-level like Electron's: the root's folder, not the served profile's.+ assert root == str((hermes_root / "desktop-plugins").resolve())++ listed = webapp.get("/api/desktop-plugins/list", params={"path": root}).json()["entries"]+ assert listed == [{"name": "big", "path": str(folder.resolve()), "isDirectory": True}]++ names = {e["name"] for e in webapp.get("/api/desktop-plugins/list", params={"path": listed[0]["path"]}).json()["entries"]}+ assert names == {"plugin.js", ".hermes-package.json"}++ read = webapp.get("/api/desktop-plugins/read", params={"path": str(folder.resolve() / "plugin.js")}).json()+ assert (read["text"], read["truncated"]) == (source, False)+ marker = webapp.get("/api/desktop-plugins/read", params={"path": str(folder.resolve() / ".hermes-package.json")})+ assert json.loads(marker.json()["text"]) == {"package": "big-pkg"}+++def test_webapp_reads_nothing_but_plugin_entries_and_markers(webapp, hermes_root):+ folder = _install(hermes_root, "notes", "export default {}")+ (folder / "secrets.txt").write_text("token", encoding="utf-8")+ (folder / "lib").mkdir()+ (folder / "lib" / "plugin.js").write_text("export default {}", encoding="utf-8")+ (hermes_root / ".env").write_text("OPENAI_API_KEY=sk-test", encoding="utf-8")+ (hermes_root / "desktop-plugins" / "plugin.js").write_text("loose", encoding="utf-8")+ plugins = (hermes_root / "desktop-plugins").resolve()++ for path in (+ folder.resolve() / "secrets.txt",+ folder.resolve() / "lib" / "plugin.js",+ plugins / "plugin.js",+ plugins / ".." / ".env",+ hermes_root.resolve() / ".env",+ ):+ assert webapp.get("/api/desktop-plugins/read", params={"path": str(path)}).status_code == 404, path++ for path in (folder.resolve() / "lib", plugins / ".."):+ assert webapp.get("/api/desktop-plugins/list", params={"path": str(path)}).status_code == 404, path++[email protected]("surface", ["gateway", "dashboard", "serve"])+def test_only_the_webapp_serves_desktop_plugins(monkeypatch, hermes_root, surface):+ _install(hermes_root, "notes", "export default {}")+ client = _client(monkeypatch, surface)+ try:+ assert client.get("/api/desktop-plugins/root").status_code == 404+ finally:+ client.close()