Skip to content

The agent that grows with you

fix(profiles): delete/rename also remove the system-scope unit and Windows task (#124401, #97897 class)

teknium11f5b70ee95dc
diff --git a/hermes_cli/profiles.py b/hermes_cli/profiles.py
index f072acdd3e4..71a90fa9469 100644
--- a/hermes_cli/profiles.py
+++ b/hermes_cli/profiles.py
@@ -1889,7 +1889,10 @@ def _cleanup_gateway_service(name: str, profile_dir: Path) -> bool:
def _run(*cmd: str) -> None:
subprocess.run(list(cmd), capture_output=True, check=False, timeout=10)
+ from hermes_cli.profiles_service_cleanup import remove_system_systemd_unit, remove_windows_task
+
system = _platform.system()
+ removed = False
if system == "Linux":
svc_name = get_service_name()
svc_file = user_systemd_unit_dir() / f"{svc_name}.service"
@@ -1899,14 +1902,20 @@ def _cleanup_gateway_service(name: str, profile_dir: Path) -> bool:
svc_file.unlink(missing_ok=True)
_run("systemctl", "--user", "daemon-reload")
print(f"✓ Service {svc_name} removed")
- return True
+ removed = True
+ # `gateway install --system` writes the same name under /etc; a survivor there
+ # restarts the removed profile at boot exactly like the user unit at login.
+ removed = remove_system_systemd_unit() or removed
elif system == "Darwin":
plist_path = get_launchd_plist_path()
if plist_path.exists():
_run("launchctl", "unload", str(plist_path))
plist_path.unlink(missing_ok=True)
print("✓ Launchd service removed")
- return True
+ removed = True
+ elif system == "Windows":
+ removed = remove_windows_task()
+ return removed
except Exception as e:
print(f"⚠ Service cleanup: {e}")
finally:
diff --git a/hermes_cli/profiles_service_cleanup.py b/hermes_cli/profiles_service_cleanup.py
new file mode 100644
index 00000000000..a3a2119f00a
--- /dev/null
+++ b/hermes_cli/profiles_service_cleanup.py
@@ -0,0 +1,58 @@
+"""Profile delete/rename: remove the OLD name's supervisor registrations that live outside
+the user systemd / launchd arms in ``profiles._cleanup_gateway_service``.
+
+Every registration is keyed on the profile name and starts ``--profile <old>`` with
+``HERMES_HOME`` pinned to a directory that the delete removed or the rename moved, so a
+survivor crash-loops (KeepAlive / Restart= / Task Scheduler retry) at the next boot or login.
+Callers bind the profile's home (``set_hermes_home_override``) before calling so the
+name-deriving helpers resolve THAT profile, never the ambient one.
+"""
+from __future__ import annotations
+
+import os
+import subprocess
+
+
+def remove_system_systemd_unit() -> bool:
+ """Remove ``/etc/systemd/system/hermes-gateway-<profile>.service`` when root; otherwise
+ name the leftover and the exact command, because the profile dir the ``gateway uninstall
+ --system`` verb would need to resolve the name from is about to vanish."""
+ from hermes_cli import gateway
+ svc_name = gateway.get_service_name()
+ unit = gateway._SYSTEM_UNIT_DIR / f"{svc_name}.service"
+ if not unit.exists():
+ return False
+ if os.geteuid() != 0:
+ print(f"⚠ System service {svc_name} remains at {unit}; it will restart the removed profile at boot.")
+ print(f" Remove it with: sudo systemctl disable --now {svc_name} && sudo rm {unit} && sudo systemctl daemon-reload")
+ return False
+ for cmd in (["disable", svc_name], ["stop", svc_name]):
+ subprocess.run(["systemctl", *cmd], capture_output=True, check=False, timeout=30)
+ unit.unlink(missing_ok=True)
+ subprocess.run(["systemctl", "daemon-reload"], capture_output=True, check=False, timeout=30)
+ print(f"✓ System service {svc_name} removed")
+ return True
+
+
+def remove_windows_task() -> bool:
+ """Delete the profile's Scheduled Task and Startup-folder login item. Direct ``schtasks
+ /Delete`` rather than ``gateway_windows.uninstall()``: that verb may open a UAC prompt,
+ which a dashboard DELETE or a scripted rename must never block on."""
+ from hermes_cli import gateway_windows as gw
+ task_name = gw.get_task_name()
+ removed = False
+ if gw.is_task_registered():
+ code, _out, err = gw._exec_schtasks(["/Delete", "/F", "/TN", task_name])
+ if code == 0:
+ removed = True
+ print(f"✓ Removed Scheduled Task {task_name!r}")
+ else:
+ print(f"⚠ Scheduled Task {task_name!r} remains (schtasks code {code}): {err.strip()}")
+ for path in (gw.get_startup_entry_path(), gw._legacy_startup_entry_path()):
+ try:
+ path.unlink()
+ except FileNotFoundError:
+ continue
+ removed = True
+ print(f"✓ Removed Windows login item: {path}")
+ return removed
diff --git a/tests/hermes_cli/test_profile_service_cleanup_scopes.py b/tests/hermes_cli/test_profile_service_cleanup_scopes.py
new file mode 100644
index 00000000000..ca8b2c4700b
--- /dev/null
+++ b/tests/hermes_cli/test_profile_service_cleanup_scopes.py
@@ -0,0 +1,71 @@
+"""Deleting or renaming a profile removes its system-scope systemd unit and Windows Scheduled
+Task, not only the user unit / launchd plist. Both carry ``--profile <old>`` with HERMES_HOME
+pinned to a dir that no longer exists, so a survivor restarts the removed profile at boot.
+"""
+from __future__ import annotations
+
+import sys
+import types
+from pathlib import Path
+
+import pytest
+
+from hermes_cli import gateway, profiles
+
+
+def victim(tmp_path, monkeypatch):
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ launch = tmp_path / ".hermes"
+ victim_dir = launch / "profiles" / "victim"
+ victim_dir.mkdir(parents=True)
+ monkeypatch.setenv("HERMES_HOME", str(launch))
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "xdg"))
+ return victim_dir
+
+
[email protected]("euid", [0, 1000])
+def test_cleanup_handles_the_system_scope_unit(victim, tmp_path, monkeypatch, capsys, euid):
+ system_dir = tmp_path / "etc-systemd-system"
+ system_dir.mkdir()
+ unit = system_dir / "hermes-gateway-victim.service"
+ unit.write_text("[Service]\n")
+ monkeypatch.setattr(gateway, "_SYSTEM_UNIT_DIR", system_dir)
+ monkeypatch.setattr(profiles.os, "geteuid", lambda: euid)
+ calls: list[list[str]] = []
+ import hermes_cli.profiles_service_cleanup as psc
+ monkeypatch.setattr(psc.subprocess, "run", lambda cmd, **kw: calls.append(list(cmd)))
+ monkeypatch.setattr(profiles.subprocess, "run", lambda cmd, **kw: calls.append(list(cmd)))
+
+ removed = profiles._cleanup_gateway_service("victim", victim)
+
+ if euid == 0:
+ assert removed and not unit.exists()
+ assert ["systemctl", "disable", "hermes-gateway-victim"] in calls
+ else:
+ # Not root: the unit cannot be unlinked, so the exact leftover and command are named.
+ assert not removed and unit.exists()
+ out = capsys.readouterr().out
+ assert str(unit) in out and "sudo systemctl disable --now hermes-gateway-victim" in out
+
+
+def test_cleanup_deletes_the_windows_scheduled_task(victim, tmp_path, monkeypatch):
+ registered = {"HermesGateway_victim"}
+ startup = tmp_path / "Startup" / "HermesGateway_victim.vbs"
+ startup.parent.mkdir()
+ startup.write_text("")
+ fake = types.SimpleNamespace(
+ get_task_name=lambda: "HermesGateway_victim",
+ is_task_registered=lambda: bool(registered),
+ _exec_schtasks=lambda args: (registered.discard(args[-1]), (0, "", ""))[1],
+ get_startup_entry_path=lambda: startup,
+ _legacy_startup_entry_path=lambda: tmp_path / "Startup" / "legacy.vbs",
+ )
+ monkeypatch.setitem(sys.modules, "hermes_cli.gateway_windows", fake)
+ import platform
+ monkeypatch.setattr(platform, "system", lambda: "Windows")
+
+ assert profiles._cleanup_gateway_service("victim", victim) is True
+ assert registered == set()
+ assert not startup.exists()