gui_uninstall.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. """Hermes Desktop (Chat GUI) uninstaller: removes only GUI state — built Electron artifacts, the packaged
  2. app, and the desktop's own ``userData`` — never agent source, venv, config, sessions or .env."""
  3. import os
  4. import shutil
  5. import sys
  6. from pathlib import Path
  7. from hermes_constants import get_hermes_home
  8. from hermes_cli.colors import Colors, color
  9. def _logger(mark: str, col: str):
  10. return lambda msg: print(f"{color(mark, col)} {msg}")
  11. log_info, log_success = _logger("→", Colors.CYAN), _logger("✓", Colors.GREEN)
  12. log_warn = _logger("⚠", Colors.YELLOW)
  13. def _env_dir(var: str, fallback: Path) -> Path:
  14. """``Path($var)`` when the env var is set, else *fallback*."""
  15. return Path(value) if (value := os.environ.get(var)) else fallback
  16. def desktop_userdata_dir() -> Path:
  17. """Electron ``app.getPath('userData')`` for an app named "Hermes" on each platform (GUI-only state)."""
  18. home = Path.home()
  19. if sys.platform == "darwin":
  20. return home / "Library" / "Application Support" / "Hermes"
  21. if sys.platform == "win32":
  22. return _env_dir("APPDATA", home / "AppData" / "Roaming") / "Hermes"
  23. return _env_dir("XDG_CONFIG_HOME", home / ".config") / "Hermes"
  24. def source_built_gui_artifacts(hermes_home: Path) -> list[Path]:
  25. """GUI build artifacts produced by ``hermes desktop`` inside the checkout (same ``hermes-agent/`` layout
  26. install.sh uses). The workspace-root node_modules is shared with the TUI, dashboard and other
  27. workspaces, so only the desktop workspace's own dependencies belong to GUI removal."""
  28. agent_root = hermes_home / "hermes-agent"
  29. desktop_dir = agent_root / "apps" / "desktop"
  30. return [desktop_dir / "dist", desktop_dir / "release", desktop_dir / "node_modules",
  31. hermes_home / "desktop-build-stamp.json"]
  32. def desktop_install_record() -> Path:
  33. """Where ``hermes update`` records the installed ``Hermes.app`` copies it keeps current. The apps
  34. are machine-wide, so the record sits under the default root whichever profile runs; deleting it
  35. is what stops an uninstalled app from being put back by the next update."""
  36. from hermes_constants import get_default_hermes_root
  37. return get_default_hermes_root() / "desktop-installed-apps.json"
  38. def packaged_gui_app_paths() -> list[Path]:
  39. """Standard install locations of the packaged desktop distributable for the current OS. Every candidate
  40. is returned; the caller filters to those that exist. Never globs system-wide — only the well-known
  41. electron-builder output locations for the "Hermes" product."""
  42. home = Path.home()
  43. if sys.platform == "darwin":
  44. return [Path("/Applications/Hermes.app"), home / "Applications" / "Hermes.app"]
  45. if sys.platform == "win32":
  46. local_base = _env_dir("LOCALAPPDATA", home / "AppData" / "Local")
  47. # NSIS per-user install (perMachine=false), an older/alternate layout, NSIS per-machine (needs admin).
  48. program_files = os.environ.get("ProgramFiles")
  49. return [local_base / "Programs" / "Hermes", local_base / "hermes-desktop"] + (
  50. [Path(program_files) / "Hermes"] if program_files else [])
  51. # Linux: an AppImage lives wherever the user put it and deb/rpm files belong to the package manager
  52. # (see the hint in ``uninstall_gui``), so only the desktop entry + hicolor icons are cleaned here.
  53. from hermes_cli.linux_desktop_entry import LEGACY_DESKTOP_ENTRY_NAME, desktop_entry_path
  54. data_base = _env_dir("XDG_DATA_HOME", home / ".local" / "share")
  55. icons = data_base / "icons" / "hicolor"
  56. # "scalable" plus every fixed-size dir the installer may have written (panel sizes + older native copies).
  57. # The legacy entry is a hidden alias of the app-id entry since #124492 — remove it with the real one.
  58. return [desktop_entry_path(),
  59. data_base / "applications" / LEGACY_DESKTOP_ENTRY_NAME,
  60. data_base / "applications" / "Hermes.desktop"] + [
  61. icons / size / "apps" / "hermes.png"
  62. for size in ("scalable", "24x24", "32x32", "48x48", "256x256", "512x512", "1024x1024")]
  63. def agent_is_installed(hermes_home: Path) -> bool:
  64. """True when a usable Python agent install exists under HERMES_HOME (gates the desktop UI's options).
  65. Package source or a venv alone is enough — a source checkout without a venv is still "the agent is here"."""
  66. return any((hermes_home / "hermes-agent" / sub).is_dir() for sub in ("hermes_cli", "venv", ".venv"))
  67. def gui_is_installed(hermes_home: Path) -> bool:
  68. """Return True when any desktop GUI artifact or install record exists."""
  69. return any(p.exists() for p in (
  70. *source_built_gui_artifacts(hermes_home), *packaged_gui_app_paths(),
  71. desktop_userdata_dir(), desktop_install_record(),
  72. ))
  73. def gui_install_summary(hermes_home: Path | None = None) -> dict:
  74. """JSON-serializable snapshot of what's installed, for the desktop UI to render via IPC."""
  75. home: Path = hermes_home if hermes_home is not None else get_hermes_home()
  76. userdata = desktop_userdata_dir()
  77. # Steward facts, so the UI can gate its destructive options on the same
  78. # ladder the CLI uninstaller uses: only a git checkout may have its code
  79. # removed; sealed trees (nix / desktop-app / docker) get data-only.
  80. from hermes_cli import steward as steward_mod
  81. steward, code_removal_allowed = steward_mod.classify_install(home / "hermes-agent")
  82. return {
  83. "hermes_home": str(home),
  84. "agent_installed": agent_is_installed(home),
  85. "gui_installed": gui_is_installed(home),
  86. "source_built_artifacts": [str(p) for p in source_built_gui_artifacts(home) if p.exists()],
  87. "packaged_app_paths": [str(p) for p in packaged_gui_app_paths() if p.exists()],
  88. "userdata_dir": str(userdata),
  89. "userdata_exists": userdata.exists(),
  90. "platform": sys.platform,
  91. "steward": steward,
  92. "code_removal_allowed": code_removal_allowed,
  93. }
  94. def _remove_path(path: Path) -> bool:
  95. """Remove a file or directory tree. Returns True when something was removed."""
  96. try:
  97. if path.is_symlink() or path.is_file():
  98. path.unlink()
  99. elif path.is_dir():
  100. shutil.rmtree(path)
  101. else:
  102. return False
  103. return True
  104. except Exception as e:
  105. log_warn(f"Could not remove {path}: {e}")
  106. return False
  107. def uninstall_gui(hermes_home: Path | None = None, *, remove_userdata: bool = True) -> list[Path]:
  108. """Remove the desktop GUI's artifacts, leaving the agent + user data intact."""
  109. home: Path = hermes_home if hermes_home is not None else get_hermes_home()
  110. removed: list[Path] = []
  111. def _remove_existing(paths) -> bool:
  112. """Remove every existing path; True when at least one existed."""
  113. found = False
  114. for path in (p for p in paths if p.exists()):
  115. found = True
  116. if _remove_path(path):
  117. log_success(f"Removed {path}")
  118. removed.append(path)
  119. return found
  120. log_info("Removing built GUI artifacts (renderer, release, node_modules)...")
  121. _remove_existing([*source_built_gui_artifacts(home), desktop_install_record()])
  122. log_info("Removing installed desktop app...")
  123. if not _remove_existing(packaged_gui_app_paths()):
  124. log_info("No packaged desktop app found in standard locations")
  125. if remove_userdata and (userdata := desktop_userdata_dir()).exists():
  126. log_info("Removing desktop app data (Electron userData)...")
  127. _remove_existing([userdata])
  128. if not removed:
  129. log_info("No desktop GUI artifacts found to remove")
  130. if sys.platform.startswith("linux"):
  131. # The desktop entry was removed above but the menu caches still list it; reindex so Hermes
  132. # disappears from the launcher.
  133. try:
  134. from hermes_cli.linux_desktop_entry import desktop_entry_path, refresh_desktop_databases
  135. entry = desktop_entry_path()
  136. if entry in removed:
  137. for tool in refresh_desktop_databases(entry.parent):
  138. log_success(f"Refreshed the application menu cache ({tool})")
  139. except Exception as e:
  140. log_warn(f"Could not refresh the application menu cache: {e}")
  141. log_info("If you installed the desktop via a .deb / .rpm package, remove it with your package manager "
  142. "(e.g. 'sudo apt remove hermes' or 'sudo dnf remove hermes'). AppImage builds are a single "
  143. "file you can delete from wherever you saved it.")
  144. return removed