The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(webapp): a tab installs a mixed package once; tag pins and read-only trees install
Tekniumc95dfcb3ae18
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 1cb3b9b6232..551fb5f7b5e 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@@ -234,21 +234,35 @@ describe('Plugin install in the browser-hosted app with a backend that installsawait waitFor(() => expect($pluginInstallRequest.get()).toBeNull())})- it('installs both halves of a mixed package', async () => {- desktopBackend({ ok: true, agent: true, agent_name: 'pkg', desktop: true, desktop_name: 'pkg', warnings: [] },- { ok: true, plugin_name: 'pkg', paired_with_agent: true },- { ok: true, plugin_name: 'pkg', enabled: true })-- renderModal()- act(() => openPluginInstallRequest({ repo: 'https://github.com/example/pkg' }))-- await waitFor(() => expect(installButton()?.disabled).toBe(false))- fireEvent.click(installButton()!)-- await waitFor(() => expect(callsFor('install')).toHaveLength(1))- await waitFor(() => expect(callsFor('install_desktop')).toHaveLength(1))- await waitFor(() => expect($notifications.get().some(n => n.message === 'Desktop plugin pkg installed')).toBe(true))- expect($notifications.get().some(n => n.message === DESKTOP_UNAVAILABLE)).toBe(false)+ it('installs a mixed package once and has the host copy its desktop half out of that checkout', async () => {+ const reviewed = 'e404b6816b20237a82f6fbe2749b5a576cf75dba'+ // The browser bridge's door to the host's desktop-plugins folder (browser-desktop-plugins.ts).+ const reconcileDesktopPlugins = vi.fn(async () => [] as string[])+ window.hermesDesktop = { reconcileDesktopPlugins } as unknown as Window['hermesDesktop']++ try {+ desktopBackend(+ { ok: true, agent: true, agent_name: 'pkg', desktop: true, desktop_name: 'pkg', sha: reviewed, warnings: [] },+ { ok: true, plugin_name: 'pkg', paired_with_agent: true },+ { ok: true, plugin_name: 'pkg', enabled: true }+ )++ renderModal()+ act(() => openPluginInstallRequest({ repo: 'https://github.com/example/pkg' }))++ await waitFor(() => expect(installButton()?.disabled).toBe(false))+ fireEvent.click(installButton()!)++ await waitFor(() => expect($notifications.get().some(n => n.message === 'Desktop plugin pkg installed')).toBe(true))+ expect(callsFor('install')).toHaveLength(1)+ expect(callsFor('install')[0][1]).toMatchObject({ action: 'install', identifier: 'https://github.com/example/pkg' })+ // One checkout: no second clone of the same repository racing the host's scan into the same folder.+ expect(callsFor('install_desktop')).toHaveLength(0)+ expect(reconcileDesktopPlugins).toHaveBeenCalled()+ expect($notifications.get().some(n => n.message === DESKTOP_UNAVAILABLE)).toBe(false)+ } finally {+ delete (window as { hermesDesktop?: unknown }).hermesDesktop+ }})it('says the install is unavailable when the backend predates the action', async () => {@@ -274,7 +288,7 @@ describe('Plugin install in the browser-hosted app with a backend that installsawait waitFor(() => expect(installButton()?.disabled).toBe(false))fireEvent.click(installButton()!)- await waitFor(() => expect(screen.findByText(DESKTOP_UNAVAILABLE)).toBeTruthy())+ expect(await screen.findByText(DESKTOP_UNAVAILABLE)).toBeTruthy()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 648bbed4814..7350f17d585 100644--- a/apps/desktop/src/app/settings/plugin-install-run.ts+++ b/apps/desktop/src/app/settings/plugin-install-run.ts@@ -53,10 +53,12 @@ export function skipsDesktopHalf(request: PluginInstallRequest, probe: ProbeResu}/** A unified package installed into a local backend carries its own desktop half; the app copies that half- * out of the package folder. Only a remote backend (whose plugins/ folder this machine cannot read) or a- * desktop-only repo needs a separate desktop clone. */+ * out of the package folder. A browser tab's backend is the host that serves it, so the package lands on+ * the disk the tab's plugins load from and that host copies the half the same way: one checkout, never a+ * second clone racing its scan. Only native Desktop on a remote backend (whose plugins/ folder this+ * machine cannot read) or a desktop-only repo needs a separate desktop clone. */export function desktopHalfFromPackage(components: InstallComponents, remote: boolean): boolean {- return components.agent && !remote+ return components.agent && (!remote || isBrowserHostedDesktop())}export interface InstallPlan {@@ -143,7 +145,8 @@ async function installAgentHalf(plan: InstallPlan, deps: InstallDeps, report: Reasync function cloneDesktopHalf(plan: InstallPlan, copy: InstallModalCopy, report: Report, deps: InstallDeps): Promise<void> {// Native Desktop clones it in Electron; a browser-hosted tab asks the host that serves it, and the- // plugin lands in the folder this Webapp already loads.+ // plugin lands in the folder this Webapp already loads. A tab installing a package's agent half never+ // clones the desktop half here: the host copies it out of that one checkout (`desktopHalfFromPackage`).const installFn = window.hermesDesktop?.installDesktopPluginconst result: { error?: string; ok: boolean; pluginName?: string; unsupported?: boolean } = installFndiff --git a/hermes_cli/desktop_plugin_halves.py b/hermes_cli/desktop_plugin_halves.pyindex cff7a617e56..d0c5419d2e6 100644--- a/hermes_cli/desktop_plugin_halves.py+++ b/hermes_cli/desktop_plugin_halves.py@@ -26,6 +26,8 @@ import tempfileimport threadingfrom pathlib import Path+from utils import rmtree_readonly+logger = logging.getLogger(__name__)PACKAGE_MARKER = ".hermes-package.json"@@ -123,7 +125,7 @@ def publish_desktop_tree(source_dir: Path, target: Path, marker: dict | None) ->if target.is_symlink():target.unlink()elif target.exists():- shutil.rmtree(target)+ rmtree_readonly(target)os.rename(staged, target)finally:shutil.rmtree(staging, ignore_errors=True)diff --git a/hermes_cli/desktop_plugin_install.py b/hermes_cli/desktop_plugin_install.pyindex bd8c122c218..e0733c9f19f 100644--- a/hermes_cli/desktop_plugin_install.py+++ b/hermes_cli/desktop_plugin_install.py@@ -16,13 +16,13 @@ from __future__ import annotationsimport osimport re-import shutilimport tempfilefrom pathlib import Pathfrom typing import Any, Optionalfrom hermes_cli import desktop_plugin_halves as halvesfrom hermes_constants import get_default_hermes_root+from utils import rmtree_readonlyDESKTOP_PLUGINS_DIR = "desktop-plugins"_COMMIT = re.compile(r"[0-9a-f]{40}")@@ -108,12 +108,18 @@ def install_desktop_plugin(identifier: str, *, ref: Optional[str], catalog_name: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"- pc._clone_plugin_repo(clone, git_url, sha, subdir)+ # A catalog entry is fetched at its own pin, as the agent installer fetches it: an+ # annotated-tag pin names the tag object, and only its peeled commit is what the dialog read.+ head = pc._clone_plugin_repo(clone, git_url, catalog_sha or sha, subdir)+ if head != sha:+ raise pc.PluginOperationError(+ "The catalog's reviewed commit changed since the dialog read it; inspect it again.")+ # Nothing reads a plugin's Git metadata, and Git's read-only object files would make the+ # published folder one that Windows cannot delete.+ rmtree_readonly(clone / ".git")plugin_root = pc._resolve_subdir_within(clone, subdir) if subdir else clonefallback = subdir.rstrip("/").rsplit("/", 1)[-1] if subdir else pc._repo_name_from_url(git_url)found = detect_components(plugin_root, fallback)@@ -185,7 +191,7 @@ def remove_desktop_plugin(name: str, *, force: bool = False) -> dict[str, Any]:f"'{folder}' is the desktop half of an agent plugin — uninstall that plugin instead.")try:- shutil.rmtree(target)+ rmtree_readonly(target)except OSError as exc:return _failure(f"Could not remove the desktop plugin: {exc}")diff --git a/tests/hermes_cli/test_desktop_plugin_install.py b/tests/hermes_cli/test_desktop_plugin_install.pyindex 320d080676c..e8454be848a 100644--- a/tests/hermes_cli/test_desktop_plugin_install.py+++ b/tests/hermes_cli/test_desktop_plugin_install.py@@ -7,8 +7,11 @@ agent row, a standalone plugin carries none, and nothing installs twice without"""import json+import os+import statimport subprocessfrom pathlib import Path+from types import SimpleNamespaceimport pytest@@ -200,3 +203,85 @@ def test_remove_leaves_a_linked_plugin_alone_and_names_nothing_outside_the_root(assert "folder name" in install.remove_desktop_plugin("../config.yaml")["error"]assert "No desktop plugin named 'ghost'" in install.remove_desktop_plugin("ghost")["error"]+++def _catalog(monkeypatch, sha: str) -> None:+ from hermes_cli import plugins_cmd_catalog+ entry = SimpleNamespace(install_identifier=URL, sha=sha)+ monkeypatch.setattr(plugins_cmd_catalog, "get_live_catalog_entry", lambda name: entry if name == "gizmo" else None)+++def test_a_catalog_pin_naming_an_annotated_tag_installs_the_commit_it_points_at(home, repo, monkeypatch):+ # The catalog publishes `git rev-parse v1.0` (the tag object); inspect reports the commit it peels to.+ reviewed = _commit(repo, {"plugin.js": "export default { v: 1 }\n"})+ _git(repo, "-c", "[email protected]", "-c", "user.name=t", "tag", "-a", "v1.0", reviewed, "-m", "v1.0")+ _commit(repo, {"plugin.js": "export default { v: 2 }\n"})+ tag_object = _git(repo, "rev-parse", "v1.0")+ assert tag_object != reviewed+ _catalog(monkeypatch, tag_object)++ result = install.install_desktop_plugin(URL, ref=reviewed, catalog_name="gizmo")++ assert result["ok"] is True, result+ assert "v: 1" in (_root(home) / "gizmo" / "plugin.js").read_text(encoding="utf-8")+++def test_a_catalog_pin_that_moved_since_the_review_is_refused(home, repo, monkeypatch):+ reviewed = _commit(repo, {"plugin.js": "export default { v: 1 }\n"})+ _catalog(monkeypatch, _commit(repo, {"plugin.js": "export default { v: 2 }\n"}))++ result = install.install_desktop_plugin(URL, ref=reviewed, catalog_name="gizmo")++ assert result["ok"] is False and "inspect it again" in result["error"], result+ assert not (_root(home) / "gizmo").exists()+++def test_the_published_plugin_carries_no_git_metadata(home, repo):+ sha = _commit(repo, {"plugin.js": "export default {}\n"})++ assert install.install_desktop_plugin(URL, ref=sha)["ok"] is True++ folder = _root(home) / "gizmo"+ assert (folder / "plugin.js").is_file()+ assert not (folder / ".git").exists()+++def _read_only_git_objects(folder: Path) -> Path:+ """What a root-level plugin cloned by native Desktop (or by hand) carries: Git's loose object files+ are read-only, which a plain ``shutil.rmtree`` cannot delete on Windows. The folder holding them is+ made read-only too, which stops the same delete on POSIX (package-manager installs ship ``0555``)."""+ obj = folder / ".git" / "objects" / "ab" / "cdef"+ obj.parent.mkdir(parents=True)+ obj.write_bytes(b"x")+ os.chmod(obj, stat.S_IREAD)+ os.chmod(obj.parent, stat.S_IREAD | stat.S_IEXEC)+ return obj+++def _replace_then_remove_a_plugin_holding_read_only_git_objects(home: Path, repo: Path) -> None:+ sha = _commit(repo, {"plugin.js": "export default { v: 1 }\n"})+ folder = _root(home) / "gizmo"+ assert install.install_desktop_plugin(URL, ref=sha)["ok"] is True+ _read_only_git_objects(folder)++ replaced = install.install_desktop_plugin(URL, ref=sha, force=True)++ assert replaced["ok"] is True, replaced+ assert not (folder / ".git").exists()++ _read_only_git_objects(folder)+ result = install.remove_desktop_plugin("gizmo")++ assert result["ok"] is True, result+ assert not folder.exists()++[email protected]("windows")+def test_windows_force_replaces_and_removes_a_plugin_holding_read_only_git_objects(home, repo):+ _replace_then_remove_a_plugin_holding_read_only_git_objects(home, repo)++[email protected]("posix")[email protected](hasattr(os, "geteuid") and os.geteuid() == 0, reason="root deletes from read-only folders")+def test_posix_force_replaces_and_removes_a_plugin_holding_read_only_git_objects(home, repo):+ _replace_then_remove_a_plugin_holding_read_only_git_objects(home, repo)diff --git a/website/docs/user-guide/desktop.md b/website/docs/user-guide/desktop.mdindex f248207bb1e..18d9a094218 100644--- a/website/docs/user-guide/desktop.md+++ b/website/docs/user-guide/desktop.md@@ -722,10 +722,12 @@ an agent+desktop package is copied into the folder by the host itself, so it alsheadless host that native Desktop never runs on.**Install** works from the Webapp too: **Capabilities → Plugins → Install** inspects the repository-first, 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 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://`+first, then has the host that serves the tab clone a desktop-only repository into that folder, under+the same folder name 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. A package that also ships an agent+plugin is installed once, as an agent plugin on that host, and the host copies its desktop half out of+that checkout, as native Desktop does with a local backend. Because a browser tab asks for it, the+desktop-only clone takes `https://`repositories only (no `http://`, `ssh`/`git@` or `file://` sources), refuses a plugin folder thatcontains 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