Skip to content

The agent that grows with you

fix(uninstall): sweep both LaunchAgent labels and per-user app leftovers

Austin Pickett6846c6c88299
diff --git a/hermes_cli/uninstall.py b/hermes_cli/uninstall.py
index c13c264cdb3..951fe58cafa 100644
--- a/hermes_cli/uninstall.py
+++ b/hermes_cli/uninstall.py
@@ -294,16 +294,44 @@ def _remove_systemd_gateway() -> bool:
return removed_any
-def _remove_launchd_gateway() -> bool:
- """macOS: uninstall launchd plist."""
+# Both gateway LaunchAgent naming schemes: the current ``ai.hermes.gateway*``
+# label and the ``io.nousresearch.hermes-agent.gateway*`` label older builds
+# installed. An uninstall must sweep BOTH — a stale agent keeps respawning the
+# gateway after the code tree is gone (#62209).
+_LAUNCHD_GATEWAY_PLIST_PATTERNS = (
+ "ai.hermes.gateway*.plist",
+ "io.nousresearch.hermes-agent.gateway*.plist",
+)
+
+
+def _launchd_gateway_plists() -> "list[Path]":
+ """Every gateway LaunchAgent plist on disk, under the real account home."""
from hermes_cli.gateway import get_launchd_plist_path
- plist_path = get_launchd_plist_path()
- if not plist_path.exists():
- return False
- subprocess.run(["launchctl", "unload", str(plist_path)], capture_output=True, check=False)
- plist_path.unlink()
- log_success(f"Removed macOS gateway service ({plist_path})")
- return True
+
+ launch_agents = get_launchd_plist_path().parent
+ return sorted({p for pattern in _LAUNCHD_GATEWAY_PLIST_PATTERNS for p in launch_agents.glob(pattern)})
+
+
+def _remove_launchd_gateway() -> bool:
+ """macOS: boot out and uninstall every gateway LaunchAgent plist.
+
+ Sweeps BOTH label patterns (see ``_LAUNCHD_GATEWAY_PLIST_PATTERNS``):
+ uninstalling only the current label's plist left older-label agents
+ registered, and launchd kept respawning the gateway after removal.
+ ``bootout`` (both Aqua and per-user domains, whichever holds the job) plus
+ the legacy ``unload`` run before the unlink so launchd never respawns a
+ job whose plist is gone.
+ """
+ plists = _launchd_gateway_plists()
+ uid = os.getuid()
+ for plist_path in plists:
+ label = plist_path.stem
+ for domain in (f"gui/{uid}", f"user/{uid}"):
+ subprocess.run(["launchctl", "bootout", f"{domain}/{label}"], capture_output=True, check=False)
+ subprocess.run(["launchctl", "unload", str(plist_path)], capture_output=True, check=False)
+ plist_path.unlink()
+ log_success(f"Removed macOS gateway service ({plist_path})")
+ return bool(plists)
def _remove_windows_gateway() -> bool:
@@ -409,6 +437,64 @@ def remove_portable_tooling_windows(hermes_home: Path) -> list[Path]:
return _remove_each((t for t in targets if t.exists()), lambda t: shutil.rmtree(t) or True)
+def _xdg_leftover_paths(full_uninstall: bool) -> "tuple[list[Path], list[Path]]":
+ """The XDG cache/data dirs an install scatters outside HERMES_HOME.
+
+ Returns (removable, data_preserved): the cache dir is always removable;
+ the XDG data dir is user data, so it is only removed on a full uninstall
+ and otherwise reported as intentionally preserved.
+ """
+ home = Path.home()
+ cache = home / ".cache" / "hermes"
+ data = home / ".local" / "share" / "hermes"
+ removable = [cache] if cache.exists() else []
+ if data.exists() and full_uninstall:
+ removable.append(data)
+ preserved = [data] if data.exists() and not full_uninstall else []
+ return removable, preserved
+
+
+def remove_desktop_app_leftovers(*, full_uninstall: bool) -> list[Path]:
+ """Remove per-user app leftovers that live outside HERMES_HOME and the
+ checkout, which earlier uninstallers left behind (#62209): the macOS
+ Library caches/logs/browser-store/state entries the packaged app and
+ Electron scatter, and the XDG cache dir on every platform. On a full
+ uninstall the XDG data dir (``~/.local/share/hermes``) goes too.
+
+ Only well-known Hermes-named entries are touched — never a glob of the
+ whole Library.
+ """
+ import sys as _sys
+
+ targets: list[Path] = []
+ home = Path.home()
+ if _sys.platform == "darwin":
+ library = home / "Library"
+ for parent in ("Caches", "Logs", "WebKit", "HTTPStorages", "Saved Application State"):
+ parent_dir = library / parent
+ if not parent_dir.is_dir():
+ continue
+ try:
+ entries = list(parent_dir.iterdir())
+ except OSError:
+ continue
+ targets.extend(e for e in entries if "hermes" in e.name.lower())
+ removable, _ = _xdg_leftover_paths(full_uninstall=full_uninstall)
+ targets.extend(removable)
+ return _remove_each((t for t in targets if t.exists()), _remove_path_or_tree)
+
+
+def _remove_path_or_tree(path: Path) -> bool:
+ try:
+ if path.is_symlink() or path.is_file():
+ path.unlink()
+ else:
+ shutil.rmtree(path)
+ return True
+ except OSError:
+ return False
+
+
def remove_legacy_runtime_trees(hermes_home: Path) -> list[Path]:
"""Delete managed-runtime trees a PRE-SPLIT install left in HERMES_HOME.
@@ -959,6 +1045,17 @@ def _perform_uninstall(
except Exception as e:
log_warn(f"Could not remove desktop GUI artifacts: {e}")
+ # 3d. Per-user app leftovers outside HERMES_HOME: macOS Library caches/logs/
+ # browser-store/state entries, the XDG cache dir, and (full mode) the XDG
+ # data dir. Only Hermes-named entries are touched (#62209).
+ log_info("Removing app caches and leftovers outside the install...")
+ removed_leftovers = remove_desktop_app_leftovers(full_uninstall=full_uninstall)
+ if removed_leftovers:
+ for path in removed_leftovers:
+ log_success(f"Removed {path}")
+ else:
+ log_info("No app caches or leftovers found")
+
# 4. Remove installation directory (code) — we may be running from inside it.
log_info("Removing installation directory...")
_rmtree_step(project_root)
@@ -1021,6 +1118,9 @@ def _perform_uninstall(
from hermes_cli.gui_uninstall import desktop_userdata_dir
if (desktop_userdata := desktop_userdata_dir()).exists():
print(f" {desktop_userdata} (desktop app data)")
+ _, preserved = _xdg_leftover_paths(full_uninstall=False)
+ for path in preserved:
+ print(f" {path}/")
print()
print("To reinstall later with your existing settings:")
print(color(_REINSTALL_HINT[windows], Colors.DIM))
diff --git a/tests/hermes_cli/test_uninstall_leftovers.py b/tests/hermes_cli/test_uninstall_leftovers.py
new file mode 100644
index 00000000000..dcb7c0b1c0a
--- /dev/null
+++ b/tests/hermes_cli/test_uninstall_leftovers.py
@@ -0,0 +1,124 @@
+"""Uninstall sweeps every leftover: both LaunchAgent label patterns, macOS
+Library app-store entries and the XDG cache/data dirs outside HERMES_HOME
+(#62209 — uninstalls reported success yet launchd respawned the gateway and
+Library/XDG dirs survived until manually removed)."""
+from __future__ import annotations
+
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+from hermes_cli import uninstall
+
+
+def fake_home(tmp_path, monkeypatch):
+ home = tmp_path / "home"
+ home.mkdir()
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: home))
+ return home
+
+
+# ── LaunchAgent sweep: both label patterns ──────────────────────────────
+
+
+def launch_agents(fake_home, monkeypatch):
+ agents = fake_home / "Library" / "LaunchAgents"
+ agents.mkdir(parents=True)
+ monkeypatch.setattr(
+ uninstall, "get_launchd_plist_path",
+ lambda: agents / "ai.hermes.gateway.plist", raising=False,
+ )
+ # _remove_launchd_gateway imports it from hermes_cli.gateway at call time.
+ import hermes_cli.gateway as gateway
+ monkeypatch.setattr(gateway, "get_launchd_plist_path", lambda: agents / "ai.hermes.gateway.plist")
+ return agents
+
+
+def _fake_launchctl(monkeypatch, calls):
+ def fake_run(cmd, **kwargs):
+ calls.append(list(cmd))
+ return subprocess.CompletedProcess(cmd, 0)
+ monkeypatch.setattr(uninstall.subprocess, "run", fake_run)
+
+
+def test_remove_launchd_gateway_sweeps_both_label_patterns(launch_agents, monkeypatch):
+ current = launch_agents / "ai.hermes.gateway.plist"
+ profiled = launch_agents / "ai.hermes.gateway-work.plist"
+ legacy = launch_agents / "io.nousresearch.hermes-agent.gateway.plist"
+ unrelated = launch_agents / "com.other.agent.plist"
+ for p in (current, profiled, legacy, unrelated):
+ p.write_text("<plist/>", encoding="utf-8")
+
+ calls: list[list[str]] = []
+ _fake_launchctl(monkeypatch, calls)
+
+ assert uninstall._remove_launchd_gateway() is True
+ assert not current.exists() and not profiled.exists() and not legacy.exists()
+ assert unrelated.exists() # never touch another app's agent
+ labels = {c[-1].rsplit("/", 1)[-1] for c in calls if c[1] == "bootout"}
+ assert labels == {"ai.hermes.gateway", "ai.hermes.gateway-work",
+ "io.nousresearch.hermes-agent.gateway"}
+ assert all(c[1] == "unload" for c in calls if c[1] == "unload")
+
+
+def test_remove_launchd_gateway_returns_false_when_no_plists(launch_agents, monkeypatch):
+ calls: list[list[str]] = []
+ _fake_launchctl(monkeypatch, calls)
+ assert uninstall._remove_launchd_gateway() is False
+ assert calls == []
+
+
+# ── macOS Library + XDG leftovers ────────────────────────────────────────
+
+
[email protected](sys.platform != "darwin", reason="macOS Library layout")
+def test_remove_desktop_app_leftovers_removes_hermes_library_entries(fake_home):
+ library = fake_home / "Library"
+ ours = []
+ for parent, name in (
+ ("Caches", "com.nousresearch.hermes"),
+ ("Logs", "Hermes"),
+ ("WebKit", "com.nousresearch.hermes"),
+ ("HTTPStorages", "com.nousresearch.hermes"),
+ ("Saved Application State", "com.nousresearch.hermes.savedState"),
+ ):
+ d = library / parent / name
+ d.mkdir(parents=True)
+ ours.append(d)
+ (library / "Caches" / "com.other.vendor").mkdir(parents=True) # untouched
+
+ removed = uninstall.remove_desktop_app_leftovers(full_uninstall=False)
+
+ assert all(not d.exists() for d in ours)
+ assert (library / "Caches" / "com.other.vendor").exists()
+ assert len(removed) == len(ours)
+
+
+def test_xdg_cache_removed_and_data_mode_semantics(fake_home):
+ cache = fake_home / ".cache" / "hermes"
+ data = fake_home / ".local" / "share" / "hermes"
+ cache.mkdir(parents=True)
+ data.mkdir(parents=True)
+
+ assert uninstall._xdg_leftover_paths(full_uninstall=False) == ([cache], [data])
+ assert uninstall._xdg_leftover_paths(full_uninstall=True) == ([cache, data], [])
+
+ removed = uninstall.remove_desktop_app_leftovers(full_uninstall=False)
+ assert cache in removed and not cache.exists()
+ assert data.exists() # user data is preserved in keep-data mode
+
+
+def test_xdg_data_removed_on_full_uninstall(fake_home):
+ cache = fake_home / ".cache" / "hermes"
+ data = fake_home / ".local" / "share" / "hermes"
+ cache.mkdir(parents=True)
+ data.mkdir(parents=True)
+
+ removed = uninstall.remove_desktop_app_leftovers(full_uninstall=True)
+
+ assert not cache.exists() and not data.exists()
+ assert cache in removed and data in removed