The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(webapp): a tab's desktop-plugin install takes only the reviewed https commit
Teknium8c5895cec134
diff --git a/apps/desktop/src/app/settings/plugin-install-modal.browser.test.tsx b/apps/desktop/src/app/settings/plugin-install-modal.browser.test.tsxindex 7583da0d21e..1cb3b9b6232 100644--- a/apps/desktop/src/app/settings/plugin-install-modal.browser.test.tsx+++ b/apps/desktop/src/app/settings/plugin-install-modal.browser.test.tsx@@ -208,8 +208,10 @@ describe('Plugin install in the browser-hosted app with a backend that installsreturn params?.action === 'install' ? install : { plugins: [] }})- it('installs a desktop-only package on the host through the backend', async () => {- desktopBackend({ ok: true, agent: false, desktop: true, desktop_name: 'ui', warnings: [] },+ it('installs a desktop-only package on the host through the backend, at the reviewed commit', async () => {+ const reviewed = 'e404b6816b20237a82f6fbe2749b5a576cf75dba'++ desktopBackend({ ok: true, agent: false, desktop: true, desktop_name: 'ui', sha: reviewed, warnings: [] },{ ok: true, plugin_name: 'ui', paired_with_agent: false })renderModal()@@ -223,7 +225,8 @@ describe('Plugin install in the browser-hosted app with a backend that installsexpect(callsFor('install_desktop')[0][1]).toMatchObject({action: 'install_desktop',identifier: 'https://github.com/example/ui',- force: false+ force: false,+ ref: reviewed})// No agent half exists in this repository: nothing is installed into the plugins folder.expect(callsFor('install')).toHaveLength(0)diff --git a/apps/desktop/src/app/settings/plugin-install-run.ts b/apps/desktop/src/app/settings/plugin-install-run.tsindex fe5ae37eb10..648bbed4814 100644--- a/apps/desktop/src/app/settings/plugin-install-run.ts+++ b/apps/desktop/src/app/settings/plugin-install-run.ts@@ -152,7 +152,10 @@ async function cloneDesktopHalf(plan: InstallPlan, copy: InstallModalCopy, reporidentifier: plan.request.repo,catalogName: plan.request.catalogName,force: plan.force,- profile: plan.profile+ profile: plan.profile,+ // The pin the user typed, else the commit the dialog showed: the host installs exactly that tree+ // or refuses.+ ref: plan.ref ?? plan.probe.sha})if (!result.ok) {diff --git a/apps/desktop/src/store/agent-plugins.ts b/apps/desktop/src/store/agent-plugins.tsindex 7e6b5d7c6ad..d5b15939200 100644--- a/apps/desktop/src/store/agent-plugins.ts+++ b/apps/desktop/src/store/agent-plugins.ts@@ -450,7 +450,7 @@ export async function inspectAgentPlugin(* already loads. Never rejects. */export async function installDesktopPluginHalf(request: GatewayRequest,- opts: { identifier: string; catalogName?: string; force?: boolean; profile?: string | null }+ opts: { identifier: string; catalogName?: string; force?: boolean; profile?: string | null; ref?: string }): Promise<{ok: booleanpairedWithAgent?: boolean@@ -474,7 +474,8 @@ export async function installDesktopPluginHalf(action: 'install_desktop',identifier: opts.identifier,force: Boolean(opts.force),- ...(opts.catalogName ? { catalog_name: opts.catalogName } : {})+ ...(opts.catalogName ? { catalog_name: opts.catalogName } : {}),+ ...(opts.ref ? { ref: opts.ref } : {})},opts.profile),diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex 71549b79cb6..652e7064d69 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -4388,7 +4388,7 @@ export interface PluginToolsetRow {label: stringdescription: string}-/** ``toggle``: ``key``/``name`` + ``enable``; ``install``: ``identifier``/``repo`` or ``catalog_name`` (+ ``force``, ``enable``, ``ref``); ``inspect``: ``identifier``/``repo`` or ``catalog_name``; ``install_desktop``: ``identifier``/``repo`` or ``catalog_name`` (+ ``force``) — the desktop half onto the host that serves this client, held to the commit ``inspect`` read; ``remove_desktop``: ``name`` (+ ``force`` for a package's own half); ``update``: ``name`` (+ ``accept_capabilities`` to apply a re-pin that widened the plugin after the user confirmed the ``delta``, + ``force`` to apply an update whose security scan returned caution after the user saw the findings); ``remove``: ``name`` (user installs only); ``settings``: ``key`` + ``values`` (``{setting_key: value}``, non-secret schema keys only); ``presence``: ``names`` (catalog names, answered in that order). */+/** ``toggle``: ``key``/``name`` + ``enable``; ``install``: ``identifier``/``repo`` or ``catalog_name`` (+ ``force``, ``enable``, ``ref``); ``inspect``: ``identifier``/``repo`` or ``catalog_name``; ``install_desktop``: ``identifier``/``repo`` (https only) or ``catalog_name`` + ``ref`` (the commit ``inspect`` read and the dialog showed; another commit is refused) (+ ``force``) — the desktop half onto the host that serves this client; ``remove_desktop``: ``name`` (+ ``force`` for a package's own half); ``update``: ``name`` (+ ``accept_capabilities`` to apply a re-pin that widened the plugin after the user confirmed the ``delta``, + ``force`` to apply an update whose security scan returned caution after the user saw the findings); ``remove``: ``name`` (user installs only); ``settings``: ``key`` + ``values`` (``{setting_key: value}``, non-secret schema keys only); ``presence``: ``names`` (catalog names, answered in that order). */export interface PluginsManageParams {profile?: string | nullaction?: PluginsActiondiff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex 626110a07da..89a922b684b 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -27775,7 +27775,7 @@},"PluginsManageParams": {"additionalProperties": false,- "description": "``toggle``: ``key``/``name`` + ``enable``; ``install``: ``identifier``/``repo`` or ``catalog_name``\n(+ ``force``, ``enable``, ``ref``); ``inspect``: ``identifier``/``repo`` or ``catalog_name``;\n``install_desktop``: ``identifier``/``repo`` or ``catalog_name`` (+ ``force``) \u2014 the desktop half onto\nthe host that serves this client, held to the commit ``inspect`` read; ``remove_desktop``: ``name``\n(+ ``force`` for a package's own half); ``update``: ``name`` (+ ``accept_capabilities`` to apply a re-pin\nthat widened the plugin after the user confirmed the ``delta``, + ``force`` to apply an update whose\nsecurity scan returned caution after the user saw the findings); ``remove``: ``name`` (user installs only);\n``settings``: ``key`` + ``values`` (``{setting_key: value}``, non-secret schema keys only);\n``presence``: ``names`` (catalog names, answered in that order).",+ "description": "``toggle``: ``key``/``name`` + ``enable``; ``install``: ``identifier``/``repo`` or ``catalog_name``\n(+ ``force``, ``enable``, ``ref``); ``inspect``: ``identifier``/``repo`` or ``catalog_name``;\n``install_desktop``: ``identifier``/``repo`` (https only) or ``catalog_name`` + ``ref`` (the commit\n``inspect`` read and the dialog showed; another commit is refused) (+ ``force``) \u2014 the desktop half onto\nthe host that serves this client; ``remove_desktop``: ``name``\n(+ ``force`` for a package's own half); ``update``: ``name`` (+ ``accept_capabilities`` to apply a re-pin\nthat widened the plugin after the user confirmed the ``delta``, + ``force`` to apply an update whose\nsecurity scan returned caution after the user saw the findings); ``remove``: ``name`` (user installs only);\n``settings``: ``key`` + ``values`` (``{setting_key: value}``, non-secret schema keys only);\n``presence``: ``names`` (catalog names, answered in that order).","properties": {"profile": {"anyOf": [diff --git a/hermes_cli/desktop_plugin_halves.py b/hermes_cli/desktop_plugin_halves.pyindex 451fa0f76d1..cff7a617e56 100644--- a/hermes_cli/desktop_plugin_halves.py+++ b/hermes_cli/desktop_plugin_halves.py@@ -69,7 +69,7 @@ def _package_origin(package_dir: Path) -> dict:return {"repo": match.group(1)} if match else {}-def _mtime_ms(st: os.stat_result) -> float:+def mtime_ms(st: os.stat_result) -> float:"""``Stats.mtimeMs`` exactly as Node computes it (seconds * 1e3 + nanoseconds / 1e6). Bothwriters compare this number against the marker the other may have written, so a value one ulpoff would make each pass see the other's copy as stale and re-copy it."""@@ -77,7 +77,7 @@ def _mtime_ms(st: os.stat_result) -> float:return seconds * 1e3 + nanoseconds / 1e6-def _read_marker(folder: Path) -> dict | None:+def read_package_marker(folder: Path) -> dict | None:try:marker = json.loads((folder / PACKAGE_MARKER).read_text(encoding="utf-8-sig"))except (OSError, ValueError):@@ -104,7 +104,7 @@ def _same_file(a: Path, b: Path) -> bool:return False-def _publish(source_dir: Path, target: Path, marker: dict | None) -> None:+def publish_desktop_tree(source_dir: Path, target: Path, marker: dict | None) -> None:"""Copy through a staging sibling and rename the finished tree into place, marker included, so afailure leaves the old folder or none: never a partial, marker-less one that a later pass wouldtake for a hand install. A standalone plugin is published with no marker (``None``): one would@@ -114,7 +114,11 @@ def _publish(source_dir: Path, target: Path, marker: dict | None) -> None:staged = staging / target.nametry:shutil.copytree(source_dir, staged, symlinks=True)- if marker is not None:+ if marker is None:+ # Only an installer writes the marker: one shipped in the repository would claim+ # another package's agent half (Electron's ``installDesktopPluginFromGit`` drops it too).+ (staged / PACKAGE_MARKER).unlink(missing_ok=True)+ else:_write_marker(staged, marker)if target.is_symlink():target.unlink()@@ -125,23 +129,6 @@ def _publish(source_dir: Path, target: Path, marker: dict | None) -> None:shutil.rmtree(staging, ignore_errors=True)-def publish_desktop_tree(source_dir: Path, target: Path, marker: dict | None) -> None:- """Publish a desktop plugin folder into the app root: staged copy, optional package marker, atomic- rename. The caller holds :data:`ROOT_WRITER` around its existence check and this call, so a- concurrent reconcile pass cannot copy the same folder underneath it."""- _publish(source_dir, target, marker)---def read_package_marker(folder: Path) -> dict | None:- """The package marker on an installed folder, if it is one this root's writers put down."""- return _read_marker(folder)---def mtime_ms(st: os.stat_result) -> float:- """``Stats.mtimeMs`` as Node computes it, for markers written outside :func:`materialize_desktop_half`."""- return _mtime_ms(st)--def materialize_desktop_half(package_dir: Path, app_root: Path, name: str) -> Path | None:"""Copy *package_dir*'s ``desktop/`` half to ``<app_root>/<name>/``. Returns the folder when itwas copied or adopted, ``None`` when it is already current, absent, or a user's own plugin."""@@ -158,12 +145,12 @@ def materialize_desktop_half(package_dir: Path, app_root: Path, name: str) -> Pareturn Nonetarget = app_root / name- existing = _read_marker(target)+ existing = read_package_marker(target)linked = package_dir.is_symlink()marker = {"package": name,"source": str(source_dir),- "sourceMtimeMs": _mtime_ms(entry_stat),+ "sourceMtimeMs": mtime_ms(entry_stat),**({"linked": True} if linked else {}),**_package_origin(package_dir),}@@ -188,7 +175,7 @@ def materialize_desktop_half(package_dir: Path, app_root: Path, name: str) -> Pa):return None- _publish(source_dir, target, marker)+ publish_desktop_tree(source_dir, target, marker)return target@@ -230,7 +217,7 @@ def reconcile_desktop_halves(hermes_root: Path, app_root: Path) -> list[str]:for name in _list_dirs(app_root):folder = app_root / name- marker = _read_marker(folder)+ marker = read_package_marker(folder)if marker and _source_gone(name, Path(marker["source"]) / "plugin.js"):shutil.rmtree(folder, ignore_errors=True)touched.append(str(folder))diff --git a/hermes_cli/desktop_plugin_install.py b/hermes_cli/desktop_plugin_install.pyindex e459fceaec3..bd8c122c218 100644--- a/hermes_cli/desktop_plugin_install.py+++ b/hermes_cli/desktop_plugin_install.py@@ -14,6 +14,8 @@ the way any other installed plugin does, on the next scan of ``desktop-plugins/`from __future__ import annotations+import os+import reimport shutilimport tempfilefrom pathlib import Path@@ -23,6 +25,9 @@ from hermes_cli import desktop_plugin_halves as halvesfrom hermes_constants import get_default_hermes_rootDESKTOP_PLUGINS_DIR = "desktop-plugins"+_COMMIT = re.compile(r"[0-9a-f]{40}")+#: The whole published folder; the loader reads at most a 16 MB ``plugin.js`` from it.+_TREE_MAX_BYTES = 64 * 1024 * 1024def desktop_plugins_root() -> Path:@@ -53,113 +58,105 @@ def _checked_name(name: Optional[str]) -> str:or "/" in candidate or "\\" in candidate or "\0" in candidateor any(ord(char) < 32 for char in candidate) or len(candidate) > 128):raise _pc().PluginOperationError(- f"Cannot install a desktop plugin under the folder name '{name}': "- "it must be a plain folder name, not a path."+ f"'{name}' is not a desktop plugin folder name: it must be a plain folder name, not a path.")return candidate-def _source(identifier: str, catalog_name: Optional[str]) -> tuple[str, Optional[str], str, Optional[str]]:- """``(git_url, subdir, resolved_identifier, revision)`` — the installer's own resolution, with the- catalog's reviewed pin when *catalog_name* is given (its repository replaces *identifier*)."""+def _https_source(identifier: str, catalog_name: Optional[str]) -> tuple[str, Optional[str], Optional[str]]:+ """``(git_url, subdir, catalog_sha)`` through the installer's own resolution and kill list, with the+ catalog's reviewed pin when *catalog_name* is given (its repository replaces *identifier*).++ A browser tab asks for this clone, so it is https only: ``file://`` would copy any folder of the+ host, ``ssh``/``git@`` would spend the host's keys, and ``http://`` can be rewritten in transit.+ Native Desktop's install keeps those for a user at their own machine."""pc = _pc()- resolved = identifierrevision = Noneif catalog_name:from hermes_cli import plugins_cmd_catalog as catalogentry = catalog.get_live_catalog_entry(catalog_name)if entry is None:raise pc.PluginOperationError(f"'{catalog_name}' is not in the Hermes plugin catalog.")- resolved = entry.install_identifier- revision = entry.sha or None- git_url, subdir = pc._resolve_git_url(resolved)+ identifier, revision = entry.install_identifier, entry.sha or None+ try:+ git_url, subdir = pc._resolve_git_url(identifier)+ except ValueError as exc:+ raise pc.PluginOperationError(str(exc)) from exc+ if not git_url.startswith("https://"):+ raise pc.PluginOperationError("A desktop plugin is installed from the Webapp over https:// only.")from hermes_cli.plugins_cmd_catalog import raise_if_removed- raise_if_removed(resolved, git_url, *((catalog_name,) if catalog_name else ()))- return git_url, subdir, resolved, revision+ raise_if_removed(identifier, git_url, *((catalog_name,) if catalog_name else ()))+ return git_url, subdir, revision-def install_desktop_plugin(identifier: str, *, catalog_name: Optional[str] = None,+def install_desktop_plugin(identifier: str, *, ref: Optional[str], catalog_name: Optional[str] = None,force: bool = False) -> dict[str, Any]:"""Clone a repository's desktop half into ``desktop-plugins/<name>`` on this host.- Returns ``{ok, plugin_name, path, sha, paired_with_agent, warnings}``, or ``ok: False`` with- ``error``. The clone is held to the commit the inspection read, so a repository that moves after- review cannot install a tree nobody looked at. A package carrying both halves lands under its- *agent* name with the package marker Electron writes, so the Plugins page pairs the two rows; a- desktop-only repository keeps its Git-derived folder name and carries no marker (it would claim- another package's agent half).+ *ref* is the commit the install dialog showed (``inspect``'s ``sha``): the clone is checked out at+ exactly that commit, so a repository that moved after review is refused rather than installed. The+ halves are read from that same checkout. Returns ``{ok, plugin_name, path, sha, paired_with_agent,+ warnings}``, or ``ok: False`` with ``error``. A package carrying both halves lands under its *agent*+ name with the package marker Electron writes, so the Plugins page pairs the two rows; a desktop-only+ repository keeps its Git-derived folder name and carries no marker."""- from hermes_cli.plugins_cmd_inspect import forget_inspection, inspect_plugin_source-- if force:- # A forced reinstall means "the repository moved": answer from a fresh clone, not the check- # that named the tree now being replaced.- forget_inspection(identifier, catalog_name=catalog_name)- probe = inspect_plugin_source(identifier, catalog_name=catalog_name)- if not probe.get("ok"):- return _failure(probe.get("error") or "Could not read this plugin repository.")- if not probe.get("desktop"):- return _failure("This package ships no desktop plugin to install here.")-- agent_name = probe.get("agent_name") if probe.get("agent") else None- try:- package_name = _checked_name(agent_name) if agent_name else None- folder = package_name or _checked_name(probe.get("desktop_name"))- git_url, subdir, _resolved, revision = _source(identifier, catalog_name)- except _pc().PluginOperationError as exc:- return _failure(str(exc))+ from hermes_cli.plugins_cmd_inspect import _desktop_folder_name, detect_components- root = desktop_plugins_root()- target = root / folder+ pc = _pc()+ sha = (ref or "").strip().lower()try:+ if not _COMMIT.fullmatch(sha):+ raise pc.PluginOperationError("Installing a desktop plugin needs the commit the install dialog reviewed.")+ git_url, subdir, catalog_sha = _https_source(identifier, catalog_name)+ if catalog_sha and catalog_sha.lower() != sha:+ raise pc.PluginOperationError("The catalog's reviewed commit changed since the dialog read it; inspect it again.")+ root = desktop_plugins_root()with tempfile.TemporaryDirectory(prefix="hermes-plugin-install-") as tmp:clone = Path(tmp) / "plugin"- # The commit the inspection named, when it named one: the install must be the tree that- # was reviewed, not whatever the branch moved to since.- sha = _pc()._clone_plugin_repo(clone, git_url, probe.get("sha") or revision, subdir)- plugin_root = _pc()._resolve_subdir_within(clone, subdir) if subdir else clone+ pc._clone_plugin_repo(clone, git_url, sha, subdir)+ plugin_root = pc._resolve_subdir_within(clone, subdir) if subdir else clone+ fallback = subdir.rstrip("/").rsplit("/", 1)[-1] if subdir else pc._repo_name_from_url(git_url)+ found = detect_components(plugin_root, fallback)+ if not found["desktop"]:+ return _failure("This package ships no desktop plugin to install here.")+ package_name = _checked_name(found["agent_name"]) if found["agent"] else None+ folder = package_name or _checked_name(_desktop_folder_name(git_url, subdir))source_dir = _desktop_tree(plugin_root)-- if source_dir is None:- return _failure("No desktop plugin.js found in this repository.")-- # A package's half keeps the marker Electron writes (the Plugins page pairs it to the- # agent row); a standalone plugin carries none.- marker = None- if package_name:- marker = {- "package": package_name,- "repo": git_url,- "source": str(target),- "sourceMtimeMs": halves.mtime_ms((source_dir / "plugin.js").stat()),- }-- # Under the root's writer lock: the exists check and the publish must not interleave with- # a reconcile pass copying the same package's folder.+ target = root / folder+ # A package's half keeps the marker Electron writes (the Plugins page pairs it to the agent+ # row); a standalone plugin carries none.+ marker = {"package": package_name, "repo": git_url, "source": str(target),+ "sourceMtimeMs": halves.mtime_ms((source_dir / "plugin.js").stat())} if package_name else None+ # The exists check and the publish must not interleave with a reconcile pass.with halves.ROOT_WRITER:- if target.is_symlink() or target.exists():- if not force:- return _failure(- f"Desktop plugin '{folder}' already exists. Enable force reinstall to replace it."- )+ if (target.is_symlink() or target.exists()) and not force:+ return _failure(f"Desktop plugin '{folder}' already exists. Enable force reinstall to replace it.")halves.publish_desktop_tree(source_dir, target, marker)- except _pc().PluginOperationError as exc:+ except pc.PluginOperationError as exc:return _failure(str(exc))except OSError as exc:return _failure(f"Could not install the desktop plugin: {exc}")return {"ok": True, "plugin_name": folder, "path": str(target), "sha": sha,- "paired_with_agent": bool(package_name), "warnings": list(probe.get("warnings") or [])}+ "paired_with_agent": bool(package_name), "warnings": []}-def _desktop_tree(plugin_root: Path) -> Optional[Path]:+def _desktop_tree(plugin_root: Path) -> Path:"""The folder that is the desktop plugin: the repository root when ``plugin.js`` sits there, else- its ``desktop/`` subfolder — Electron's ``findDesktopEntry`` search, narrowed to those two."""- if (plugin_root / "plugin.js").is_file():- return plugin_root- if (plugin_root / "desktop" / "plugin.js").is_file():- return plugin_root / "desktop"- return None+ its ``desktop/`` subfolder (Electron's ``findDesktopEntry``, narrowed to those two). It must be a+ plain tree inside the clone: a link could publish any folder of the host, and the copy is capped."""+ source = plugin_root if (plugin_root / "plugin.js").is_file() else plugin_root / "desktop"+ total = 0+ for folder, dirs, files in os.walk(source):+ for entry in (Path(folder), *(Path(folder) / n for n in dirs + files)):+ if entry.is_symlink():+ raise _pc().PluginOperationError(+ f"The desktop plugin contains a link ({entry.relative_to(plugin_root)}); links are not installed.")+ total += sum((Path(folder) / n).stat().st_size for n in files)+ if total > _TREE_MAX_BYTES:+ raise _pc().PluginOperationError(+ f"The desktop plugin is larger than {_TREE_MAX_BYTES // (1024 * 1024)} MB.")+ return sourcedef remove_desktop_plugin(name: str, *, force: bool = False) -> dict[str, Any]:diff --git a/hermes_cli/plugins_cmd_inspect.py b/hermes_cli/plugins_cmd_inspect.pyindex dba22d52de4..7391e55b1a8 100644--- a/hermes_cli/plugins_cmd_inspect.py+++ b/hermes_cli/plugins_cmd_inspect.py@@ -140,15 +140,6 @@ def inspect_plugin_source(identifier: str, *, catalog_name: Optional[str] = Nonereturn _copy(result)-def forget_inspection(identifier: str, *, catalog_name: Optional[str] = None) -> None:- """Drop any cached answer for this source, so the next inspection clones afresh. A forced reinstall- must not install the tree a ten-minute-old check named: the point of forcing it is that the- repository moved."""- from hermes_constants import get_hermes_home- with _inspections_lock:- _inspections.pop((str(get_hermes_home()), catalog_name or "", identifier), None)--def _copy(result: dict[str, Any]) -> dict[str, Any]:"""Each caller gets its own answer: one shared by joined requests must not be edited through another."""return {**result, "warnings": list(result["warnings"])}diff --git a/tests/hermes_cli/test_desktop_plugin_install.py b/tests/hermes_cli/test_desktop_plugin_install.pyindex 9bac327bc26..320d080676c 100644--- a/tests/hermes_cli/test_desktop_plugin_install.py+++ b/tests/hermes_cli/test_desktop_plugin_install.py@@ -1,8 +1,9 @@"""``hermes_cli.desktop_plugin_install``: cloning a desktop plugin onto the host that serves the Webapp.-Real local Git repositories, a throwaway ``HERMES_HOME``: the folder lands where the Webapp's read-routes serve it, a package's half carries the marker that pairs it to its agent row, a standalone-plugin carries none, and nothing installs twice without ``force``.+Real local Git repositories behind an https identifier (only the clone's network leg is pointed at the+local repository), a throwaway ``HERMES_HOME``: the folder lands where the Webapp's read routes serve+it, at exactly the commit the dialog reviewed; a package's half carries the marker that pairs it to its+agent row, a standalone plugin carries none, and nothing installs twice without ``force``."""import json@@ -13,22 +14,22 @@ import pytestfrom hermes_cli import desktop_plugin_install as install+URL = "https://example.invalid/acme/gizmo.git"+def _git(path: Path, *args: str) -> str:return subprocess.run(["git", *args], cwd=path, check=True, capture_output=True, text=True,encoding="utf-8").stdout.strip()-def _repo(path: Path, files: dict[str, str]) -> Path:- path.mkdir()+def _commit(path: Path, files: dict[str, str]) -> str:for rel, text in files.items():target = path / reltarget.parent.mkdir(parents=True, exist_ok=True)target.write_text(text, encoding="utf-8")- _git(path, "init", "-q", "-b", "main")_git(path, "add", "-A")_git(path, "-c", "[email protected]", "-c", "user.name=t", "commit", "-q", "-m", "c")- return path+ return _git(path, "rev-parse", "HEAD")@pytest.fixture()@@ -41,31 +42,43 @@ def home(tmp_path, monkeypatch):return hermes_home+def repo(tmp_path, monkeypatch):+ """A local repository the https identifier clones from."""+ from hermes_cli import plugins_cmd+ path = tmp_path / "gizmo"+ path.mkdir()+ _git(path, "init", "-q", "-b", "main")+ real = plugins_cmd._clone_plugin_repo+ monkeypatch.setattr(plugins_cmd, "_clone_plugin_repo",+ lambda dest, _url, revision, subdir=None: real(dest, path.as_uri(), revision, subdir))+ return path++def _root(home: Path) -> Path:return home / "desktop-plugins"-def test_desktop_only_repo_lands_under_its_own_name_without_a_marker(tmp_path, home):- repo = _repo(tmp_path / "gizmo", {"plugin.js": "export default { id: 'gizmo' }\n",- "panel.js": "export const x = 1\n"})+def test_desktop_only_repo_lands_under_its_own_name_without_a_marker(home, repo):+ # The repository ships its own package marker naming another package: only an installer writes one.+ sha = _commit(repo, {"plugin.js": "export default { id: 'gizmo' }\n", "panel.js": "export const x = 1\n",+ ".hermes-package.json": json.dumps({"package": "victim", "source": "/x"})})- result = install.install_desktop_plugin(repo.as_uri())+ result = install.install_desktop_plugin(URL, ref=sha)assert result["ok"] is True, result- assert result["plugin_name"] == "gizmo"- assert result["paired_with_agent"] is False+ assert (result["plugin_name"], result["paired_with_agent"], result["sha"]) == ("gizmo", False, sha)folder = _root(home) / "gizmo"assert (folder / "plugin.js").read_text(encoding="utf-8").startswith("export default")assert (folder / "panel.js").is_file()- # A standalone plugin carries no package marker: one would claim another package's agent half.assert not (folder / ".hermes-package.json").exists()-def test_package_lands_its_desktop_half_under_the_agent_name_with_a_marker(tmp_path, home):- repo = _repo(tmp_path / "pkg", {"plugin.yaml": "name: pkg\nversion: 1.0.0\n", "__init__.py": "",- "desktop/plugin.js": "export default { id: 'pkg' }\n"})+def test_package_lands_its_desktop_half_under_the_agent_name_with_a_marker(home, repo):+ sha = _commit(repo, {"plugin.yaml": "name: pkg\nversion: 1.0.0\n", "__init__.py": "",+ "desktop/plugin.js": "export default { id: 'pkg' }\n"})- result = install.install_desktop_plugin(repo.as_uri())+ result = install.install_desktop_plugin(URL, ref=sha)assert result["ok"] is True, resultassert (result["plugin_name"], result["paired_with_agent"]) == ("pkg", True)@@ -74,72 +87,83 @@ def test_package_lands_its_desktop_half_under_the_agent_name_with_a_marker(tmp_p# Only the desktop half is copied: the agent payload stays in the repository.assert not (folder / "plugin.yaml").exists()marker = json.loads((folder / ".hermes-package.json").read_text(encoding="utf-8"))- assert marker["package"] == "pkg"- assert marker["repo"] == repo.as_uri()- assert marker["source"] == str(folder)+ assert (marker["package"], marker["repo"], marker["source"]) == ("pkg", URL, str(folder))assert marker["sourceMtimeMs"] > 0-def test_a_second_install_refuses_until_force_replaces_it(tmp_path, home):- repo = _repo(tmp_path / "gizmo", {"plugin.js": "export default { v: 1 }\n"})- assert install.install_desktop_plugin(repo.as_uri())["ok"] is True+def test_the_install_is_the_reviewed_commit_and_nothing_else(home, repo):+ reviewed = _commit(repo, {"plugin.js": "export default { v: 1 }\n"})+ _commit(repo, {"plugin.js": "export default { v: 2 }\n"})++ assert install.install_desktop_plugin(URL, ref=None)["ok"] is False+ assert install.install_desktop_plugin(URL, ref="1" * 40)["ok"] is False+ assert not _root(home).joinpath("gizmo").exists()++ result = install.install_desktop_plugin(URL, ref=reviewed)++ assert result["ok"] is True, result+ assert "v: 1" in (_root(home) / "gizmo" / "plugin.js").read_text(encoding="utf-8")+++def test_a_second_install_refuses_until_force_replaces_it(home, repo):+ first = _commit(repo, {"plugin.js": "export default { v: 1 }\n"})+ assert install.install_desktop_plugin(URL, ref=first)["ok"] is True- again = install.install_desktop_plugin(repo.as_uri())+ again = install.install_desktop_plugin(URL, ref=first)assert again["ok"] is Falseassert "already exists" in again["error"] and "force" in again["error"]- (repo / "plugin.js").write_text("export default { v: 2 }\n", encoding="utf-8")- _git(repo, "-c", "[email protected]", "-c", "user.name=t", "commit", "-qam", "v2")- forced = install.install_desktop_plugin(repo.as_uri(), force=True)- assert forced["ok"] is True, forced- assert (repo / "plugin.js").read_text(encoding="utf-8") in \- (_root(home) / "gizmo" / "plugin.js").read_text(encoding="utf-8")+ second = _commit(repo, {"plugin.js": "export default { v: 2 }\n"})+ assert install.install_desktop_plugin(URL, ref=second, force=True)["ok"] is True+ assert "v: 2" in (_root(home) / "gizmo" / "plugin.js").read_text(encoding="utf-8")-def test_the_install_is_held_to_the_commit_the_inspection_read(tmp_path, home, monkeypatch):- repo = _repo(tmp_path / "gizmo", {"plugin.js": "export default { v: 1 }\n"})- reviewed = _git(repo, "rev-parse", "HEAD")- (repo / "plugin.js").write_text("export default { v: 2 }\n", encoding="utf-8")- _git(repo, "-c", "[email protected]", "-c", "user.name=t", "commit", "-qam", "moved on")+def test_only_an_https_source_is_installed(home, repo):+ sha = _commit(repo, {"plugin.js": "export default {}\n"})- from hermes_cli import plugins_cmd_inspect- monkeypatch.setattr(plugins_cmd_inspect, "inspect_plugin_source", lambda *a, **k: {- "ok": True, "agent": False, "desktop": True, "agent_name": None, "desktop_name": "gizmo",- "sha": reviewed, "warnings": [], "insecure": True})+ for source in (repo.as_uri(), "http://example.invalid/acme/gizmo.git", "[email protected]:acme/gizmo.git"):+ result = install.install_desktop_plugin(source, ref=sha)+ assert result["ok"] is False and "https://" in result["error"], (source, result)+ assert not _root(home).joinpath("gizmo").exists()- result = install.install_desktop_plugin(repo.as_uri())- assert result["ok"] is True, result- assert result["sha"] == reviewed- assert "v: 1" in (_root(home) / "gizmo" / "plugin.js").read_text(encoding="utf-8")+def test_a_link_out_of_the_clone_is_refused(home, repo, tmp_path):+ outside = tmp_path / "secrets"+ outside.mkdir()+ (outside / "plugin.js").write_text("// any folder of the host\n", encoding="utf-8")+ (repo / "desktop").symlink_to(outside, target_is_directory=True)+ sha = _commit(repo, {"README.md": "x\n"})++ result = install.install_desktop_plugin(URL, ref=sha)+ assert result["ok"] is False and "link" in result["error"], result+ assert not _root(home).joinpath("gizmo").exists()-def test_a_repository_with_no_desktop_half_is_refused(tmp_path, home):- repo = _repo(tmp_path / "agently", {"plugin.yaml": "name: agently\n", "__init__.py": ""})- result = install.install_desktop_plugin(repo.as_uri())+def test_a_repository_with_no_desktop_half_is_refused(home, repo):+ sha = _commit(repo, {"plugin.yaml": "name: agently\n", "__init__.py": ""})++ result = install.install_desktop_plugin(URL, ref=sha)assert result["ok"] is Falseassert "no desktop plugin" in result["error"]- assert not (_root(home) / "agently").exists()+ assert not _root(home).joinpath("gizmo").exists()-def test_a_name_that_is_a_path_is_refused(tmp_path, home, monkeypatch):- from hermes_cli import plugins_cmd_inspect- monkeypatch.setattr(plugins_cmd_inspect, "inspect_plugin_source", lambda *a, **k: {- "ok": True, "agent": False, "desktop": True, "agent_name": None, "desktop_name": "../escape",- "sha": None, "warnings": [], "insecure": False})+def test_a_name_that_is_a_path_is_refused(home, repo):+ sha = _commit(repo, {"plugin.yaml": "name: ../escape\n", "__init__.py": "",+ "desktop/plugin.js": "export default {}\n"})- result = install.install_desktop_plugin("https://github.com/x/y.git")+ result = install.install_desktop_plugin(URL, ref=sha)assert result["ok"] is Falseassert "folder name" in result["error"]assert not (home / "escape").exists()-def test_remove_takes_a_standalone_plugin_away(tmp_path, home):- repo = _repo(tmp_path / "gizmo", {"plugin.js": "export default {}\n"})- assert install.install_desktop_plugin(repo.as_uri())["ok"] is True+def test_remove_takes_a_standalone_plugin_away(home, repo):+ sha = _commit(repo, {"plugin.js": "export default {}\n"})+ assert install.install_desktop_plugin(URL, ref=sha)["ok"] is Trueresult = install.remove_desktop_plugin("gizmo")@@ -148,10 +172,9 @@ def test_remove_takes_a_standalone_plugin_away(tmp_path, home):assert not (_root(home) / "gizmo").exists()-def test_remove_refuses_a_packages_own_half_until_forced(tmp_path, home):- repo = _repo(tmp_path / "pkg", {"plugin.yaml": "name: pkg\n", "__init__.py": "",- "desktop/plugin.js": "export default {}\n"})- assert install.install_desktop_plugin(repo.as_uri())["ok"] is True+def test_remove_refuses_a_packages_own_half_until_forced(home, repo):+ sha = _commit(repo, {"plugin.yaml": "name: pkg\n", "__init__.py": "", "desktop/plugin.js": "export default {}\n"})+ assert install.install_desktop_plugin(URL, ref=sha)["ok"] is Truerefused = install.remove_desktop_plugin("pkg")assert refused["ok"] is False@@ -159,26 +182,21 @@ def test_remove_refuses_a_packages_own_half_until_forced(tmp_path, home):assert (_root(home) / "pkg" / "plugin.js").is_file()forced = install.remove_desktop_plugin("pkg", force=True)- assert forced["ok"] is True- assert forced["unpaired_from"] == "pkg"+ assert (forced["ok"], forced["unpaired_from"]) == (True, "pkg")assert not (_root(home) / "pkg").exists()-def test_remove_leaves_a_linked_plugin_alone(tmp_path, home):- checkout = _repo(tmp_path / "dev", {"plugin.js": "export default {}\n"})+def test_remove_leaves_a_linked_plugin_alone_and_names_nothing_outside_the_root(home, tmp_path):+ checkout = tmp_path / "dev"+ checkout.mkdir()+ (checkout / "plugin.js").write_text("export default {}\n", encoding="utf-8")root = _root(home)root.mkdir(parents=True)(root / "dev").symlink_to(checkout, target_is_directory=True)- result = install.remove_desktop_plugin("dev")-- assert result["ok"] is False- assert "linked" in result["error"]+ linked = install.remove_desktop_plugin("dev")+ assert linked["ok"] is False and "linked" in linked["error"]assert (root / "dev" / "plugin.js").is_file()--def test_remove_of_something_not_installed_says_so(tmp_path, home):- result = install.remove_desktop_plugin("ghost")-- assert result["ok"] is False- assert "No desktop plugin named 'ghost'" in result["error"]+ assert "folder name" in install.remove_desktop_plugin("../config.yaml")["error"]+ assert "No desktop plugin named 'ghost'" in install.remove_desktop_plugin("ghost")["error"]diff --git a/tests/hermes_cli/test_webapp_desktop_plugins.py b/tests/hermes_cli/test_webapp_desktop_plugins.pyindex e1d4df295af..56c2ac72f7a 100644--- a/tests/hermes_cli/test_webapp_desktop_plugins.py+++ b/tests/hermes_cli/test_webapp_desktop_plugins.py@@ -205,15 +205,24 @@ def _git_plugin_repo(path, files):return path-def test_a_plugin_installed_through_the_backend_is_served_to_the_browser(webapp, hermes_root, tmp_path):+def test_a_plugin_installed_through_the_backend_is_served_to_the_browser(webapp, hermes_root, tmp_path,+ monkeypatch):# The whole trip the dialog makes: `plugins.manage install_desktop` clones onto this host, then the# browser's loader reads exactly what the Webapp serves.+ import subprocess++ from hermes_cli import plugins_cmdfrom hermes_cli.desktop_plugin_install import install_desktop_pluginrepo = _git_plugin_repo(tmp_path / "gizmo", {"plugin.js": "export default { id: 'gizmo' }\n","panel.js": "export const x = 1\n"})+ sha = subprocess.run(["git", "rev-parse", "HEAD"], cwd=repo, check=True, capture_output=True,+ text=True, encoding="utf-8").stdout.strip()+ real = plugins_cmd._clone_plugin_repo+ monkeypatch.setattr(plugins_cmd, "_clone_plugin_repo",+ lambda dest, _url, revision, subdir=None: real(dest, repo.as_uri(), revision, subdir))- result = install_desktop_plugin(repo.as_uri())+ result = install_desktop_plugin("https://example.invalid/acme/gizmo.git", ref=sha)assert result["ok"] is True, resultfolders = webapp.get("/api/desktop-plugins/root").json()["root"]diff --git a/tests/tui_gateway/test_plugins_manage_install_desktop.py b/tests/tui_gateway/test_plugins_manage_install_desktop.pyindex 20ae4e67fc1..cbc7b948c8b 100644--- a/tests/tui_gateway/test_plugins_manage_install_desktop.py+++ b/tests/tui_gateway/test_plugins_manage_install_desktop.py@@ -1,8 +1,9 @@"""Gateway ``plugins.manage install_desktop`` / ``remove_desktop``: the browser-hosted app's install.-Drives the real RPC dispatch and a real local clone: a desktop plugin lands in the host's-``desktop-plugins/`` (where the Webapp's read routes serve it), a second install is refused until-``force``, and removal round-trips — all through the same ``plugins.manage`` action the dialog calls.+Drives the real RPC dispatch and a real clone of a local repository (only the clone's network leg is+pointed at it): a desktop plugin lands in the host's ``desktop-plugins/`` at the reviewed commit, a+second install is an RPC error until ``force``, and removal round-trips — all through the same+``plugins.manage`` action the dialog calls."""import subprocess@@ -14,86 +15,34 @@ def _manage(**params):return server.handle_request({"id": "1", "method": "plugins.manage", "params": params})-def _repo(path, files):- path.mkdir()- for rel, text in files.items():- target = path / rel- target.parent.mkdir(parents=True, exist_ok=True)- target.write_text(text, encoding="utf-8")- for args in (("init", "-q", "-b", "main"), ("add", "-A"),- ("-c", "[email protected]", "-c", "user.name=t", "commit", "-q", "-m", "c")):- subprocess.run(["git", *args], cwd=path, check=True, capture_output=True)- return path---def test_install_desktop_lands_the_folder_the_webapp_serves(tmp_path, monkeypatch):+def test_install_desktop_round_trips_through_the_rpc(tmp_path, monkeypatch):+ from hermes_cli import plugins_cmdhome = tmp_path / "home"home.mkdir()monkeypatch.setenv("HERMES_HOME", str(home))- repo = _repo(tmp_path / "gizmo", {"plugin.js": "export default { id: 'gizmo' }\n"})-- result = _manage(action="install_desktop", identifier=repo.as_uri())["result"]-- assert result["ok"] is True- assert result["plugin_name"] == "gizmo"- assert result["paired_with_agent"] is False- folder = home / "desktop-plugins" / "gizmo"- assert (folder / "plugin.js").is_file()- assert not (folder / ".hermes-package.json").exists()---def test_a_package_installs_its_desktop_half_under_the_agent_name(tmp_path, monkeypatch):- home = tmp_path / "home"- home.mkdir()- monkeypatch.setenv("HERMES_HOME", str(home))- repo = _repo(tmp_path / "pkg", {"plugin.yaml": "name: pkg\n", "__init__.py": "",- "desktop/plugin.js": "export default {}\n"})-- result = _manage(action="install_desktop", identifier=repo.as_uri())["result"]-- assert (result["plugin_name"], result["paired_with_agent"]) == ("pkg", True)- assert (home / "desktop-plugins" / "pkg" / ".hermes-package.json").is_file()---def test_a_second_install_is_an_rpc_error_until_force(tmp_path, monkeypatch):- home = tmp_path / "home"- home.mkdir()- monkeypatch.setenv("HERMES_HOME", str(home))- repo = _repo(tmp_path / "gizmo", {"plugin.js": "export default {}\n"})- assert _manage(action="install_desktop", identifier=repo.as_uri())["result"]["ok"] is True-- refused = _manage(action="install_desktop", identifier=repo.as_uri())-- assert "error" in refused and refused["error"]["code"] == 5026- assert "already exists" in refused["error"]["message"]- assert _manage(action="install_desktop", identifier=repo.as_uri(), force=True)["result"]["ok"] is True---def test_remove_desktop_round_trips(tmp_path, monkeypatch):- home = tmp_path / "home"- home.mkdir()- monkeypatch.setenv("HERMES_HOME", str(home))- repo = _repo(tmp_path / "gizmo", {"plugin.js": "export default {}\n"})- _manage(action="install_desktop", identifier=repo.as_uri())-- result = _manage(action="remove_desktop", name="gizmo")["result"]-- assert result["ok"] is True+ repo = tmp_path / "gizmo"+ repo.mkdir()+ (repo / "plugin.js").write_text("export default { id: 'gizmo' }\n", encoding="utf-8")+ for args in (("init", "-q", "-b", "main"), ("add", "-A"),+ ("-c", "[email protected]", "-c", "user.name=t", "commit", "-q", "-m", "c")):+ subprocess.run(["git", *args], cwd=repo, check=True, capture_output=True)+ sha = subprocess.run(["git", "rev-parse", "HEAD"], cwd=repo, check=True, capture_output=True,+ text=True, encoding="utf-8").stdout.strip()+ real = plugins_cmd._clone_plugin_repo+ monkeypatch.setattr(plugins_cmd, "_clone_plugin_repo",+ lambda dest, _url, revision, subdir=None: real(dest, repo.as_uri(), revision, subdir))+ source = {"identifier": "https://example.invalid/acme/gizmo.git", "ref": sha}++ result = _manage(action="install_desktop", **source)["result"]+ assert (result["ok"], result["plugin_name"], result["sha"]) == (True, "gizmo", sha)+ assert (home / "desktop-plugins" / "gizmo" / "plugin.js").is_file()++ refused = _manage(action="install_desktop", **source)+ assert refused["error"]["code"] == 5026 and "already exists" in refused["error"]["message"]++ assert _manage(action="remove_desktop", name="gizmo")["result"]["ok"] is Trueassert not (home / "desktop-plugins" / "gizmo").exists()def test_install_desktop_requires_a_source():- response = _manage(action="install_desktop")-- assert response["error"]["code"] == 4019---def test_a_failed_clone_is_an_rpc_error_with_reason(tmp_path, monkeypatch):- home = tmp_path / "home"- home.mkdir()- monkeypatch.setenv("HERMES_HOME", str(home))-- response = _manage(action="install_desktop", identifier=(tmp_path / "missing").as_uri())-- assert response["error"]["code"] == 5026- assert response["error"]["message"]+ assert _manage(action="install_desktop")["error"]["code"] == 4019diff --git a/tui_gateway/contracts/tools_mcp_plugins.py b/tui_gateway/contracts/tools_mcp_plugins.pyindex 3f922b94b59..25f9e6cf692 100644--- a/tui_gateway/contracts/tools_mcp_plugins.py+++ b/tui_gateway/contracts/tools_mcp_plugins.py@@ -629,8 +629,9 @@ class PluginsAction(WireEnum):class PluginsManageParams(ProfileParams):"""``toggle``: ``key``/``name`` + ``enable``; ``install``: ``identifier``/``repo`` or ``catalog_name``(+ ``force``, ``enable``, ``ref``); ``inspect``: ``identifier``/``repo`` or ``catalog_name``;- ``install_desktop``: ``identifier``/``repo`` or ``catalog_name`` (+ ``force``) — the desktop half onto- the host that serves this client, held to the commit ``inspect`` read; ``remove_desktop``: ``name``+ ``install_desktop``: ``identifier``/``repo`` (https only) or ``catalog_name`` + ``ref`` (the commit+ ``inspect`` read and the dialog showed; another commit is refused) (+ ``force``) — the desktop half onto+ the host that serves this client; ``remove_desktop``: ``name``(+ ``force`` for a package's own half); ``update``: ``name`` (+ ``accept_capabilities`` to apply a re-pinthat widened the plugin after the user confirmed the ``delta``, + ``force`` to apply an update whosesecurity scan returned caution after the user saw the findings); ``remove``: ``name`` (user installs only);diff --git a/tui_gateway/methods_tools.py b/tui_gateway/methods_tools.pyindex 3bdb2e590d9..47853e0f536 100644--- a/tui_gateway/methods_tools.py+++ b/tui_gateway/methods_tools.py@@ -1783,15 +1783,14 @@ def _plugins_inspect(rid, params):def _plugins_install_desktop(rid, params):"""Install a repository's desktop half onto this host (``desktop-plugins/<name>``) — what Electron's- ``installDesktopPlugin`` does, for a browser-hosted client with no disk of its own. Held to the- commit the inspection read; the folder lands optionally enabled because the loader picks it up on- its next scan."""+ ``installDesktopPlugin`` does, for a browser-hosted client with no disk of its own. ``ref`` is the+ commit the install dialog reviewed; the loader picks the folder up on its next scan."""ident = (params.get("identifier") or params.get("repo") or "").strip()catalog_name = str(params.get("catalog_name") or "").strip()if not ident and not catalog_name:return _err(rid, 4019, "plugins.manage install_desktop requires 'identifier', 'repo', or 'catalog_name'")result = _tools_mod("hermes_cli.desktop_plugin_install").install_desktop_plugin(- ident, catalog_name=catalog_name or None, force=bool(params.get("force")))+ ident, ref=params.get("ref"), catalog_name=catalog_name or None, force=bool(params.get("force")))return _ok(rid, result) if result.get("ok") else _err(rid, 5026, result.get("error") or "desktop install failed")diff --git a/website/docs/user-guide/desktop.md b/website/docs/user-guide/desktop.mdindex e3d1316939c..f248207bb1e 100644--- a/website/docs/user-guide/desktop.md+++ b/website/docs/user-guide/desktop.md@@ -723,9 +723,13 @@ headless host that native Desktop never runs on.**Install** works from the Webapp too: **Capabilities → Plugins → Install** inspects the repositoryfirst, then has the host that serves the tab clone the plugin into that folder (a desktop-only-repository, or the desktop half of a package) — the same install native Desktop makes in Electron, and-the same folder name and package marker. A plugin installed this way loads on the next scan; nothing-else has to be done on the server by hand. Removing one from **Capabilities → Plugins** deletes the+repository, or the desktop half of a package) — the same folder name and package marker native Desktop+uses. The host installs exactly the commit the dialog showed (or the one you pinned) and refuses if+that commit cannot be fetched. Because a browser tab asks for it, this install takes `https://`+repositories only (no `http://`, `ssh`/`git@` or `file://` sources), refuses a plugin folder that+contains symbolic links or is larger than 64 MB, and never replaces an installed plugin unless+**Force reinstall** is checked. A plugin installed this way loads on the next scan; a plugin that+starts disabled is turned on from its card. Removing one from **Capabilities → Plugins** deletes thefolder on that host; the desktop half of a package is removed with the package. A plugin's folderaccess (`ctx.files`) is not available in a browser.