linux_desktop_entry.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  1. """Install and remove the Linux desktop entry (``<app_id>.desktop``).
  2. The entry must be launch-context independent: ``Exec=`` is an absolute launcher that survives the
  3. venv (no ``#!/usr/bin/env python3`` escapes, no checkout-internal argv[0]), and ``Icon=`` is the
  4. themed name backed by a copy in the user's hicolor tree. Cache refresh is best-effort and
  5. tool-gated (``update-desktop-database``, ``gtk-update-icon-cache``, ``kbuildsycoca6``/``5``); a
  6. missing tool is not an error.
  7. """
  8. from __future__ import annotations
  9. import io
  10. import os
  11. import re
  12. import shlex
  13. import shutil
  14. import struct
  15. import subprocess
  16. import sys
  17. import threading
  18. import time
  19. from pathlib import Path
  20. from typing import Callable, Mapping, Optional
  21. # Identity the packaged app claims for its window: electron-builder bakes product-identity.cjs's
  22. # `appId` into extraMetadata.desktopName, and Electron hands that string to the compositor
  23. # verbatim (Wayland app_id, CHROME_DESKTOP). GNOME links a window to a launcher by StartupWMClass
  24. # or by a `<app_id>.desktop` file name, so the entry has to carry the same id — under the old
  25. # "hermes.desktop" name a packaged launch matches neither rung and lands on the placeholder icon.
  26. APP_ID = "com.nousresearch.hermes"
  27. DESKTOP_ENTRY_NAME = f"{APP_ID}.desktop"
  28. # Entry name written before the app-id rename; a successful install converts it into a hidden
  29. # alias (NoDisplay=true) so pre-rename taskbar pins keep resolving (see _alias_legacy_desktop_entry).
  30. LEGACY_DESKTOP_ENTRY_NAME = "hermes.desktop"
  31. # XDG startup notification: set by an app-grid / menu launch, absent for terminal and detached
  32. # (updater relaunch) launches. See launched_from_shell().
  33. SHELL_LAUNCH_ENV_VAR = "DESKTOP_STARTUP_ID"
  34. # Write end of the reveal pipe handed to Electron; one byte means "main window is on screen".
  35. READY_FD_ENV_VAR = "HERMES_DESKTOP_READY_FD"
  36. REVEAL_BYTE = b"r" # what linux-launcher-ready.ts writes; anything else is finish()'s wake-up
  37. _SHELL_NAMES = ("bash", "sh", "dash", "zsh", "ksh")
  38. def is_supported() -> bool:
  39. """XDG desktop entries exist only on Linux and BSD."""
  40. return sys.platform.startswith(("linux", "freebsd", "openbsd", "netbsd"))
  41. def _xdg_data_home() -> Path:
  42. raw = os.environ.get("XDG_DATA_HOME")
  43. return Path(raw).expanduser() if raw and raw.strip() else Path.home() / ".local" / "share"
  44. def desktop_entry_path() -> Path:
  45. return _xdg_data_home() / "applications" / DESKTOP_ENTRY_NAME
  46. def icon_path(project_root: Path) -> Path:
  47. return project_root / "apps" / "desktop" / "assets" / "icon.png"
  48. def _running_interpreter() -> str:
  49. """Venv-semantic interpreter path for the persisted ``Exec=`` line.
  50. ``sys.executable`` inside a venv is commonly a SYMLINK into a shared base-interpreter tree
  51. (uv, pyenv, conda). ``resolve()`` follows it out of the venv, and CPython discovers
  52. ``pyvenv.cfg`` from the *lexical* argv[0] — so a dereferenced path boots without the venv's
  53. site-packages. Keep the lexical form when any ancestor holds a ``pyvenv.cfg``.
  54. See #80547, #90292.
  55. Idea credit: the lexical-preservation rule was independently proposed in #92516/#94115/#94544 and by
  56. nosliwhtes' review of this PR; the pyvenv.cfg-detection refinement here keeps both properties.
  57. """
  58. lexical = os.path.abspath(sys.executable)
  59. path = Path(lexical)
  60. if any((base / "pyvenv.cfg").is_file() for base in (path.parent, *path.parent.parents)):
  61. return lexical
  62. return str(path.resolve())
  63. _probe_cache: dict[str, bool] = {}
  64. def _can_import_hermes_cli(interpreter: Path) -> bool:
  65. """Whether *interpreter* can import ``hermes_cli.main`` unaided.
  66. Runs under ``-I`` (no user site, no PYTHONPATH, no cwd on ``sys.path``) from a neutral cwd, so
  67. the answer matches a cold desktop environment. Cached per process; an unprobeable interpreter
  68. (missing binary, spawn failure, timeout) is assumed capable and deliberately NOT cached, so one
  69. transient hiccup doesn't freeze the assumption for the session.
  70. Probe design per @nosliwhtes' isolated-mode capability check (#92122 lineage, commit 4150501f641).
  71. """
  72. key = str(interpreter)
  73. if key in _probe_cache:
  74. return _probe_cache[key]
  75. ok = _run_quiet(
  76. [key, "-I", "-c", "import hermes_cli.main"],
  77. cwd=os.path.abspath(os.sep), timeout=15, on_error=None,
  78. )
  79. if ok is None:
  80. return True
  81. _probe_cache[key] = ok
  82. return ok
  83. def _running_interpreter_fallback() -> str:
  84. """The RUNNING interpreter — it has ``hermes_cli`` importable by definition."""
  85. return os.path.abspath(sys.executable)
  86. def resolve_exec_command(project_root: Optional[Path] = None) -> str:
  87. """Build the absolute ``Exec=`` command line for ``hermes desktop``.
  88. Prefer the real ``hermes`` launcher; fall back to ``<python> -m hermes_cli.main desktop``.
  89. """
  90. from hermes_cli.relaunch import resolve_hermes_bin
  91. bin_path = _resolve_hermes_bin_for_desktop_entry(resolve_hermes_bin, checkout_root=project_root)
  92. interpreter = _running_interpreter()
  93. if not _can_import_hermes_cli(Path(interpreter)):
  94. # Persisting an interpreter that can't import the CLI writes a dead entry (the DE spawns
  95. # Exec in a cold environment where exactly this import must succeed).
  96. # The candidate interpreter cannot actually import hermes_cli.main (checked in isolated mode from a
  97. # neutral cwd — so the probe can't be fooled by a checkout cwd or an inherited PYTHONPATH). Fall
  98. # back to the module form under the RUNNING interpreter, which by definition has the CLI importable.
  99. # Probe design follows the isolated-mode capability check proposed by @nosliwhtes (#92122 review
  100. # lineage, commit 4150501f641) — cached here per-process so a desktop launch pays the subprocess
  101. # cost at most once.
  102. interpreter = _running_interpreter_fallback()
  103. argv = [interpreter, "-m", "hermes_cli.main", *_desktop_argv_tail(project_root)]
  104. if bin_path:
  105. resolved = Path(bin_path).resolve()
  106. # A Python launcher whose shebang points OUTSIDE the venv (e.g. the repo's `hermes` script
  107. # with `#!/usr/bin/env python3`) would die silently on the first third-party import under
  108. # Terminal=false — run it under the venv interpreter explicitly.
  109. prefix = [interpreter] if _needs_interpreter(resolved) else []
  110. # See #90292.
  111. argv = [*prefix, str(resolved), *_desktop_argv_tail(project_root)]
  112. return " ".join(_quote_exec_arg(a) for a in argv)
  113. def _desktop_argv_tail(project_root: Optional[Path]) -> list[str]:
  114. """The ``desktop`` subcommand arguments a persisted launcher should carry.
  115. A menu/taskbar click is a launch, not a build request: when a packaged
  116. Electron app already exists under the checkout it must start directly
  117. (``--skip-build``) instead of re-running the build-then-launch path, whose
  118. source-hash freshness check reports "stale" on any locally modified tree
  119. and makes every click pay a 60s+ rebuild that can fail outright (#126009).
  120. With no packaged app yet (first install), keep the build-then-launch
  121. default so the click still produces an app.
  122. """
  123. if project_root is None:
  124. return ["desktop"]
  125. release = project_root / "apps" / "desktop" / "release"
  126. packaged = any(
  127. (release / dist / name).exists()
  128. for dist in ("linux-unpacked", "linux-arm64-unpacked")
  129. for name in ("hermes", "Hermes")
  130. )
  131. return ["desktop", "--skip-build"] if packaged else ["desktop"]
  132. def _is_interpreter(candidate: Path) -> bool:
  133. """A python interpreter binary (``bin/python*``), not a launcher: strict basename match
  134. (rejects ``python3-config``, ``pythonw``) inside a bin/Scripts dir (rejects a stray script
  135. named ``python`` elsewhere).
  136. Regex approach proposed independently in 94051; kept here with the parent-dir guard so a script named
  137. ``python`` outside a bin/Scripts tree is not misclassified. See #94051.
  138. """
  139. return bool(re.fullmatch(r"python[23]?(\d+)?(\.\d+)?", candidate.name.lower())) and (
  140. candidate.parent.name in {"bin", "scripts"}
  141. )
  142. def _inside_checkout(candidate: str, checkout_root: Path, original_argv0: str) -> bool:
  143. """Whether a launcher candidate is a launch-context artifact rather than a durable launcher."""
  144. try:
  145. path = Path(candidate).resolve()
  146. except OSError:
  147. return False
  148. # Anything shipped in the tree (e.g. the repo `hermes` script) is checkout-internal. Compare
  149. # against BOTH the lexical and resolved roots: candidates resolve, so a symlinked home needs
  150. # the resolved comparison too.
  151. try:
  152. resolved_root = checkout_root.resolve()
  153. except OSError:
  154. resolved_root = None
  155. for root in {checkout_root, resolved_root}:
  156. if root is not None and (path == root or root in path.parents):
  157. return True
  158. # The `python -m hermes_cli.main` relaunch context surfaces the invoking interpreter as
  159. # argv[0]; an interpreter is never a launchable entry target (it would persist a bare
  160. # `<python> desktop`). Compare against argv[0]'s own file, not sys.executable — under test
  161. # harnesses they differ.
  162. try:
  163. return path.samefile(original_argv0) and _is_interpreter(path)
  164. except OSError:
  165. return False
  166. def _is_this_checkout_managed_cli(candidate: str, checkout_root: Path) -> bool:
  167. """True when *candidate* is this checkout's PM-managed console script.
  168. That script lives under ``installs/<key>/environments`` and imports a
  169. generated workspace that does not ship ``apps/desktop``. It sits outside
  170. the checkout, so the external-primary rule would persist it and the
  171. desktop launcher would exit with the GUI source missing.
  172. """
  173. try:
  174. path = Path(candidate).resolve()
  175. except OSError:
  176. return False
  177. try:
  178. from pm.environments import install_state_dir
  179. generations = (install_state_dir(Path(checkout_root)) / "environments").resolve()
  180. except (OSError, RuntimeError, ValueError):
  181. return False
  182. return path == generations or generations in path.parents
  183. def _resolve_hermes_bin_for_desktop_entry(
  184. resolve_fn=None,
  185. checkout_root: Optional[Path] = None,
  186. ) -> Optional[str]:
  187. """Resolve the launcher binary for the persisted ``.desktop`` entry.
  188. Wraps :func:`hermes_cli.relaunch.resolve_hermes_bin` with one rule: an ``argv[0]`` inside this
  189. checkout is a launch-context artifact, not a durable installed launcher — persisting it makes
  190. the entry depend on how the previous launch happened (a bootstrap loop). Skip such candidates
  191. and fall through to PATH, then to the installer's known wrapper locations. A candidate that
  192. provably cannot serve ``hermes desktop`` (a code tree carrying ``hermes_cli`` but no desktop
  193. app beside it — a managed runtime env's console script) is skipped the same way: its entry
  194. would only ever die with "Desktop GUI source not found". ``resolve_fn`` is injectable for tests.
  195. See #90492.
  196. """
  197. if resolve_fn is None:
  198. from hermes_cli.relaunch import resolve_hermes_bin as resolve_fn
  199. if checkout_root is None:
  200. checkout_root = _project_root()
  201. # Keep the LEXICAL root: the installer writes $INSTALL_DIR lexically into the shim text, so a
  202. # symlinked home would otherwise mismatch. Callers pass main.py's realpath'd PROJECT_ROOT; the
  203. # module-lexical root is tried alongside it.
  204. checkout_root = Path(os.path.abspath(checkout_root))
  205. module_lexical_root = _project_root()
  206. original_argv0 = sys.argv[0]
  207. # An external primary (another install's /opt/.../bin/hermes, a venv console script) wins
  208. # BEFORE any known-location probing, which could silently switch the entry to a different
  209. # installation. Only rerun the resolver with argv[0] hidden when the primary could actually
  210. # be checkout-internal (also shortens the window a concurrent reader sees mutated sys.argv).
  211. primary = resolve_fn()
  212. # A managed-environment console script is outside the checkout but is not a durable desktop
  213. # launcher: its workspace has no apps/desktop (#122438). The same holds for any launcher
  214. # that provably cannot serve `hermes desktop` (another install's managed env, #122485).
  215. # Fall through so the durable-wrapper probe below can still find a working one.
  216. if (
  217. primary
  218. and not _inside_checkout(primary, checkout_root, original_argv0)
  219. and not _is_this_checkout_managed_cli(primary, checkout_root)
  220. and not _is_this_checkout_managed_cli(primary, module_lexical_root)
  221. and _can_serve_desktop(primary) is not False
  222. ):
  223. return primary
  224. # A primary that is NOT checkout-internal and not the invoking interpreter is an external launcher (e.g.
  225. # /opt/.../bin/hermes from another install method, or a venv console script). It must be evaluated
  226. # BEFORE any known-location probing: probing first could silently switch the entry to a different
  227. # installation (#94443 review case 3).
  228. # Only reroute when argv[0] actually drove the resolution: re-run the resolver with argv[0] hidden and
  229. # compare. If PATH yields nothing, keep the resolver's original answer (its fallback chain stays
  230. # authoritative; #90492 semantics preserved).
  231. sys.argv[0] = ""
  232. try:
  233. rerouted = resolve_fn()
  234. finally:
  235. sys.argv[0] = original_argv0
  236. # A resolver miss (argv[0] is ``-c`` under ``python -m`` on a cold relaunch AND PATH has no
  237. # ``hermes``) must NOT return None here: that skipped the durable-wrapper probe below and persisted
  238. # the module form, so the entry's bytes flipped on every alternating launch context — and
  239. # gnome-shell 50.x crashes when the entry changes while its ShellApp is STARTING (#110885).
  240. # ``primary is None`` implies ``rerouted is None`` (the rerun only hides argv[0]), so only the
  241. # probe can still find anything.
  242. if (
  243. primary
  244. and rerouted is not None
  245. and not _inside_checkout(rerouted, checkout_root, original_argv0)
  246. and not _is_this_checkout_managed_cli(rerouted, checkout_root)
  247. and not _is_this_checkout_managed_cli(rerouted, module_lexical_root)
  248. and _can_serve_desktop(rerouted) is not False
  249. ):
  250. return rerouted
  251. # A PATH hit inside this checkout is the same launch-context artifact as argv[0]: the
  252. # desktop-update hand-off hands the updater <checkout>/venv/bin at the front of PATH, so
  253. # persisting a reroute to the venv console script pins the entry to WHO wrote it. The next
  254. # DE-launched context re-resolves to the durable wrapper and flips the bytes back — and
  255. # every flip rewrites the entry, which arms the gnome-shell 50.x crash this function's
  256. # callers guard against when the write lands inside a launch's STARTING window. Fall
  257. # through to the durable probe below, exactly as a PATH miss does.
  258. # argv[0] was checkout-internal AND PATH yielded no DURABLE launcher (miss, or a hit inside
  259. # this checkout) — common in stripped systemd user sessions, autostart relaunches, and the
  260. # update hand-off with <checkout>/venv/bin on PATH. Probe the installer's known wrapper
  261. # locations; each
  262. # candidate must be DE-safe and target THIS checkout (a foreign wrapper would make the entry
  263. # stable-but-wrong). No durable wrapper → None, so resolve_exec_command emits its runnable
  264. # module fallback instead of the self-regenerating checkout-internal form.
  265. for candidate in _known_wrapper_candidates():
  266. if (
  267. candidate.is_file()
  268. and os.access(candidate, os.X_OK)
  269. and _wrapper_shebang_safe(candidate)
  270. and (
  271. _wrapper_targets_checkout(candidate, checkout_root)
  272. or _wrapper_targets_checkout(candidate, module_lexical_root)
  273. )
  274. ):
  275. return str(candidate)
  276. return None
  277. def _shebang_tokens(shebang: str) -> list[str]:
  278. return shebang[2:].strip().split()
  279. def _is_native_binary(head: bytes) -> bool:
  280. return head[:4] == b"\x7fELF" or head.startswith(b"MZ")
  281. def _read_head(path: Path, size: int = 4096) -> Optional[bytes]:
  282. try:
  283. with open(path, "rb") as fh:
  284. return fh.read(size)
  285. except OSError:
  286. return None
  287. def _wrapper_shebang_safe(wrapper: Path) -> bool:
  288. """Whether an executable wrapper can actually run in the DE context.
  289. Native binaries and shell launchers are safe by construction (the shell script execs the right
  290. interpreter itself). A python-shebang wrapper is safe only when its interpreter stays inside
  291. the RUNNING venv; anything unknown fails safe toward the module fallback.
  292. """
  293. head = _read_head(wrapper)
  294. if head is None:
  295. return False
  296. if _is_native_binary(head):
  297. return True
  298. if not head.startswith(b"#!"):
  299. return False
  300. shebang = head.decode("utf-8", errors="replace").splitlines()[0]
  301. tokens = _shebang_tokens(shebang)
  302. if not tokens:
  303. return False
  304. interp = Path(tokens[0])
  305. if interp.name == "env":
  306. # `#!/usr/bin/env bash` is the installer's own launcher form; skip env's flags (-S, -u
  307. # VAR) and inspect the first real token. Only python-flavored `env` shebangs escape.
  308. target = next((Path(t) for t in tokens[1:] if not t.startswith("-")), Path(""))
  309. return target.name in _SHELL_NAMES or not _shebang_escapes_running_env(shebang)
  310. if interp.name in _SHELL_NAMES:
  311. return True
  312. if "python" not in interp.name.lower():
  313. return False
  314. return not _shebang_escapes_running_env(shebang)
  315. _ROOT_TERMINATORS = ('"', "'", " ", "\n", "\t", "\r", "$", "\x00", "/")
  316. def _wrapper_targets_checkout(wrapper: Path, checkout_root: Path) -> bool:
  317. """Whether a candidate launcher script actually launches THIS checkout.
  318. Boundary-aware: a bare substring test would also accept sibling paths that EXTEND this
  319. checkout's path (``<checkout>-old``, ``<checkout>.bak``), so the root must end at a quote /
  320. whitespace / EOL or continue INTO the tree (``<root>/``). Both lexical and resolved roots are
  321. tried: the installer writes $INSTALL_DIR lexically, so with a symlinked home the shim text
  322. carries the lexical path while the caller may pass a resolved one.
  323. """
  324. head = _read_head(wrapper)
  325. if head is None:
  326. return False
  327. if _is_native_binary(head):
  328. # Native binary: cannot verify, cannot be another checkout's bash shim either — accept.
  329. return True
  330. text = head.decode("utf-8", errors="replace")
  331. lexical_root = os.path.abspath(str(checkout_root))
  332. roots = {str(checkout_root), lexical_root}
  333. try:
  334. roots.add(str(Path(lexical_root).resolve()))
  335. except OSError:
  336. pass
  337. stripped = text.rstrip("\r\n")
  338. return any(
  339. stripped.endswith(root) or any(root + t in text for t in _ROOT_TERMINATORS)
  340. for root in roots
  341. )
  342. _HERMES_CODE_MARKERS = ("hermes_cli", "workspace/hermes_cli")
  343. _DESKTOP_APP_ENTRIES = ("apps/desktop/package.json", "workspace/apps/desktop/package.json")
  344. def _launcher_tree(path: Path) -> Path:
  345. """Install tree a ``bin`` launcher belongs to: ``<tree>/venv/bin/x`` → ``<tree>``."""
  346. parent = path.parent
  347. if parent.name not in ("bin", "Scripts", "scripts"):
  348. return parent
  349. tree = parent.parent
  350. return tree.parent if tree.name in ("venv", ".venv", "env") else tree
  351. def _tree_desktop_state(tree: Path) -> Optional[bool]:
  352. """``True`` when *tree* can serve ``hermes desktop``, ``False`` when it provably cannot, else ``None``.
  353. ``False`` is reserved for a tree that IS a hermes code tree (carries ``hermes_cli``) yet has no
  354. desktop app beside it — the managed runtime env layout, whose launcher runs but dies with
  355. "Desktop GUI source not found". Unfamiliar shapes stay ``None`` (accepted) so no install
  356. method is rejected for looking exotic.
  357. """
  358. if any((tree / entry).is_file() for entry in _DESKTOP_APP_ENTRIES):
  359. return True
  360. from hermes_cli.steward import is_bundled_payload
  361. if is_bundled_payload(tree):
  362. return True
  363. if any((tree / marker).is_dir() for marker in _HERMES_CODE_MARKERS):
  364. return False
  365. return None
  366. def _embedded_launcher_target(wrapper: Path) -> Optional[Path]:
  367. """First absolute path to an existing ``bin`` launcher embedded in a shell wrapper script."""
  368. head = _read_head(wrapper)
  369. if head is None:
  370. return None
  371. for match in re.finditer(r"""["'\s](/[^\s"'$;)\\]+)""", head.decode("utf-8", errors="replace")):
  372. if "/bin/" in match.group(1) and Path(match.group(1)).is_file():
  373. return Path(match.group(1))
  374. return None
  375. def _can_serve_desktop(candidate: str, _depth: int = 2) -> Optional[bool]:
  376. """Desktop-capability of a launcher path; shell wrappers followed to their target.
  377. Native binaries, unreadable files, interpreters, and shapes without markers stay ``None``;
  378. only a launcher whose tree provably lacks the desktop app is rejected (``False``).
  379. """
  380. try:
  381. path = Path(candidate)
  382. if not path.is_file():
  383. return None
  384. head = _read_head(path, 256)
  385. except OSError:
  386. return None
  387. if head is None or not head.startswith(b"#!"):
  388. return None
  389. tokens = _shebang_tokens(head.decode("utf-8", errors="replace").splitlines()[0])
  390. if _depth and tokens and (Path(tokens[0]).name in _SHELL_NAMES or Path(tokens[0]).name == "env"):
  391. # The installer's shim (any shell launcher) execs its real target; judge THAT tree.
  392. target = _embedded_launcher_target(path)
  393. if target is not None:
  394. verdict = _can_serve_desktop(str(target), _depth - 1)
  395. if verdict is not None:
  396. return verdict
  397. return _tree_desktop_state(_launcher_tree(path))
  398. def _persisted_exec_serves_desktop(exec_command: str) -> Optional[bool]:
  399. """Desktop-capability of a rendered ``Exec`` line, ignoring an interpreter prefix.
  400. ``[<interpreter>, <launcher>, desktop]`` is judged by the launcher. The module fallback
  401. ``[<interpreter>, -m, hermes_cli.main, desktop]`` passes: it is only ever written by a
  402. process that already passed the desktop launch checks.
  403. """
  404. try:
  405. tokens = shlex.split(exec_command)
  406. except ValueError:
  407. return None
  408. if not tokens:
  409. return None
  410. candidate = tokens[0]
  411. if _is_interpreter(Path(candidate)):
  412. if len(tokens) > 1 and tokens[1] != "-m":
  413. candidate = tokens[1] # `[<interpreter>, <launcher>, desktop]` prefix form
  414. else:
  415. # Module fallback `[<interpreter>, -m, hermes_cli.main, desktop]`: only a process
  416. # that already passed the desktop launch checks writes it, so it is not
  417. # second-guessed here.
  418. return None
  419. return _can_serve_desktop(candidate)
  420. def _known_wrapper_candidates():
  421. """Durable installed-launcher locations, most likely first.
  422. Mirrors the installer's ``get_command_link_dir()`` layouts: Termux (``$PREFIX/bin``), root FHS
  423. (``/usr/local/bin``), and user (``~/.local/bin``). The wrapper is always named ``hermes``.
  424. """
  425. candidates = []
  426. prefix = os.environ.get("PREFIX")
  427. if prefix:
  428. candidates.append(Path(prefix) / "bin" / "hermes")
  429. if hasattr(os, "geteuid") and os.geteuid() == 0:
  430. candidates.append(Path("/usr/local/bin/hermes"))
  431. candidates.append(Path.home() / ".local" / "bin" / "hermes")
  432. return candidates
  433. def _project_root() -> Path:
  434. """``<checkout>`` from this file's location — lexical (no ``.resolve()``) so shim-text matching
  435. against the installer's lexically-written $INSTALL_DIR works on symlinked homes."""
  436. return Path(os.path.abspath(__file__)).parent.parent
  437. def _needs_interpreter(bin_path: Path) -> bool:
  438. """Whether ``bin_path`` is a Python script whose shebang escapes the running venv.
  439. Native binaries (uv shim, PyInstaller, distro package) and shell wrappers (the installer's
  440. bash launcher execs the venv python itself) never need one.
  441. """
  442. head = _read_head(bin_path, 256)
  443. if head is None or not head.startswith(b"#!"):
  444. return False
  445. shebang = head.decode("utf-8", errors="replace").splitlines()[0].strip()
  446. if "python" not in shebang.lower():
  447. return False
  448. return _shebang_escapes_running_env(shebang)
  449. def _shebang_escapes_running_env(shebang: str) -> bool:
  450. """Whether a python shebang resolves OUTSIDE the running interpreter's directory.
  451. Compares PATH COMPONENTS, never substrings: ``<venv>/bin-extra/python`` is not inside
  452. ``<venv>/bin``. ``env`` shebangs ALWAYS escape — ``env`` resolves through the DE's cold PATH,
  453. not the shell that installed the venv — except the rare ``env -S <abs-interpreter>`` form,
  454. which is judged by its absolute target.
  455. Tokenizes the shebang (interpreter path plus any flags) and compares PATH COMPONENTS, never substrings:
  456. ``<venv>/bin-extra/python`` is not inside ``<venv>/bin`` even though it starts with it
  457. (sibling-directory confusion; independently surfaced in nosliwhtes' #92122 hardening ``b96427d0`` —
  458. reimplemented here with two extensions).
  459. The comparison uses the LEXICAL interpreter directory (abspath, not resolve()): on uv venvs the resolved
  460. parent is the base interpreter's dir, which makes a valid ``.venv/bin/python`` shebang look foreign
  461. (#94443 review case 1). Both sides use the SAME case operation (``.lower()``): interpreter paths
  462. legitimately carry uppercase (conda env names, usernames, uv's ephemeral build dirs) and an asymmetric
  463. compare would flag the venv's own console script as foreign.
  464. """
  465. tokens = _shebang_tokens(shebang)
  466. if not tokens:
  467. return True # bare "#!python": resolves via PATH
  468. interp = Path(tokens[0])
  469. if interp.name in ("env", "env.exe"):
  470. rest = [t for t in tokens[1:] if not t.startswith("-")]
  471. if not (rest and Path(rest[0]).is_absolute()):
  472. return True
  473. interp = Path(rest[0])
  474. running_dir = os.path.dirname(os.path.abspath(sys.executable)).lower()
  475. return str(interp.parent).lower() != running_dir
  476. def _quote_exec_arg(arg: str) -> str:
  477. """Quote one ``Exec`` argument per the desktop entry spec."""
  478. if not any(c in arg for c in " \t\n\"'\\><~|&;$*?#()`"):
  479. return arg
  480. escaped = arg.replace("\\", "\\\\").replace('"', '\\"')
  481. return f'"{escaped}"'
  482. def render_desktop_entry(exec_command: str, icon: str) -> str:
  483. """The app-id entry: identity lives in the file name and ``StartupWMClass``."""
  484. return (
  485. "[Desktop Entry]\n"
  486. "Type=Application\n"
  487. "Name=Hermes\n"
  488. "GenericName=Hermes Desktop\n"
  489. "Comment=Launch Hermes Desktop\n"
  490. f"Exec={exec_command}\n"
  491. f"Icon={icon}\n"
  492. "Terminal=false\n"
  493. "Categories=Utility;\n"
  494. "StartupNotify=true\n"
  495. f"StartupWMClass={APP_ID}\n"
  496. )
  497. def _render_legacy_alias_entry(exec_command: str, icon: str) -> str:
  498. """The app-id entry, hidden from the app grid; ``StartupWMClass`` still groups old pins."""
  499. return render_desktop_entry(exec_command, icon) + "NoDisplay=true\n"
  500. def refresh_desktop_databases(applications_dir: Path) -> list[str]:
  501. """Reindex the menu caches. Run each tool only when it exists."""
  502. ran: list[str] = []
  503. update_db = shutil.which("update-desktop-database")
  504. if update_db and _run_quiet([update_db, str(applications_dir)]):
  505. ran.append("update-desktop-database")
  506. # Plasma 6 first, then Plasma 5. Only one of them is ever installed.
  507. for tool in ("kbuildsycoca6", "kbuildsycoca5"):
  508. resolved = shutil.which(tool)
  509. if resolved:
  510. if _run_quiet([resolved, "--noincremental"]):
  511. ran.append(tool)
  512. break
  513. return ran
  514. def _run_quiet(cmd: list[str], *, timeout: int = 60, on_error: Optional[bool] = False, **kwargs) -> Optional[bool]:
  515. """Exit-status success of a silenced subprocess; ``on_error`` when it could not be run at all."""
  516. try:
  517. result = subprocess.run(
  518. cmd,
  519. stdout=subprocess.DEVNULL,
  520. stderr=subprocess.DEVNULL,
  521. check=False,
  522. timeout=timeout,
  523. **kwargs,
  524. )
  525. except (OSError, subprocess.SubprocessError):
  526. return on_error
  527. return result.returncode == 0
  528. # Sizes a typical hicolor ``index.theme`` lists. ``scalable`` is SVG-only — a raster PNG there is
  529. # what Cinnamon's panel draws as a mangled low-res blob. The shipped asset is 1024×1024 (not an
  530. # indexed dir name), so a copy-only fallback lands in ``256x256``.
  531. _HICOLOR_INDEXED_SIZES = (16, 22, 24, 32, 36, 48, 64, 72, 96, 128, 192, 256, 512)
  532. # Cinnamon's panel is ~24–32px: write exact rasters so the theme needn't downscale a 1024px PNG.
  533. _HICOLOR_INSTALL_SIZES = (24, 32, 48, 256)
  534. def _png_dimensions(raw: bytes) -> Optional[tuple[int, int]]:
  535. """``(width, height)`` from a PNG IHDR, or ``None`` if unreadable."""
  536. if len(raw) >= 24 and raw[:8] == b"\x89PNG\r\n\x1a\n" and raw[12:16] == b"IHDR":
  537. return struct.unpack(">II", raw[16:24])
  538. return None
  539. def _hicolor_subdir(dimensions: Optional[tuple[int, int]]) -> str:
  540. """Pick a fixed-size hicolor dir the theme indexes. Never ``scalable``."""
  541. if dimensions is None:
  542. return "256x256"
  543. width, height = dimensions
  544. if width in _HICOLOR_INDEXED_SIZES and width == height:
  545. return f"{width}x{width}"
  546. if width != height or width <= 0 or width > 256:
  547. return "256x256"
  548. nearest = min(_HICOLOR_INDEXED_SIZES, key=lambda size: abs(size - width))
  549. return f"{nearest}x{nearest}"
  550. def _hicolor_icon_dest(subdir: str) -> Path:
  551. return _xdg_data_home() / "icons" / "hicolor" / subdir / "apps" / "hermes.png"
  552. def _remove_stale_scalable_icon() -> bool:
  553. """Drop a leftover PNG from ``scalable/`` (the pre-fix install path); True if removed."""
  554. stale = _hicolor_icon_dest("scalable")
  555. try:
  556. removed = stale.is_file()
  557. if removed:
  558. stale.unlink()
  559. return removed
  560. except OSError:
  561. return False
  562. def _refresh_hicolor_cache() -> None:
  563. """Best-effort reindex of the user hicolor tree. Missing tool is fine."""
  564. hicolor = _xdg_data_home() / "icons" / "hicolor"
  565. for tool in ("gtk-update-icon-cache", "gtk4-update-icon-cache"):
  566. resolved = shutil.which(tool)
  567. if resolved:
  568. _run_quiet([resolved, "-f", "-t", str(hicolor)])
  569. return
  570. def _resized_hicolor_pngs(raw: bytes) -> Optional[dict[str, bytes]]:
  571. """Lanczos-resize *raw* to each panel size; ``None`` when it will not decode (truncated/fake
  572. PNG) so the caller falls back to a copy. Pillow is imported lazily to keep the uninstaller
  573. import-light."""
  574. try:
  575. from PIL import Image
  576. except ImportError:
  577. return None
  578. try:
  579. with Image.open(io.BytesIO(raw)) as im:
  580. rgba = im.convert("RGBA")
  581. out: dict[str, bytes] = {}
  582. for size in _HICOLOR_INSTALL_SIZES:
  583. buf = io.BytesIO()
  584. rgba.resize((size, size), Image.Resampling.LANCZOS).save(buf, format="PNG")
  585. out[f"{size}x{size}"] = buf.getvalue()
  586. return out
  587. except (OSError, ValueError):
  588. return None
  589. def _write_hicolor_pngs(files: dict[str, bytes]) -> bool:
  590. """Write *files* keyed by hicolor size dir. Return True if any file changed."""
  591. wrote = False
  592. for subdir, data in files.items():
  593. dest = _hicolor_icon_dest(subdir)
  594. if dest.is_file() and dest.read_bytes() == data:
  595. continue
  596. dest.parent.mkdir(parents=True, exist_ok=True)
  597. dest.write_bytes(data)
  598. wrote = True
  599. return wrote
  600. def _install_icon_to_hicolor(icon: Path) -> bool:
  601. """Install the app icon into the user's hicolor tree so ``Icon=hermes`` resolves without an
  602. absolute checkout path. Raster PNGs go to indexed fixed-size dirs, never ``scalable``."""
  603. try:
  604. raw = icon.read_bytes()
  605. resized = _resized_hicolor_pngs(raw)
  606. if resized is not None:
  607. wrote = _write_hicolor_pngs(resized)
  608. else:
  609. dest = _hicolor_icon_dest(_hicolor_subdir(_png_dimensions(raw)))
  610. wrote = not (dest.is_file() and dest.read_bytes() == raw)
  611. if wrote:
  612. dest.parent.mkdir(parents=True, exist_ok=True)
  613. shutil.copyfile(icon, dest)
  614. if _remove_stale_scalable_icon() or wrote:
  615. _refresh_hicolor_cache()
  616. return True
  617. except OSError:
  618. return False
  619. def _launcher_entry_management_enabled() -> bool:
  620. """Whether config.yaml allows touching an EXISTING launcher entry.
  621. ``desktop.manage_launcher_entry: false`` opts out of the every-launch
  622. rewrite: a hand-edited entry is then left alone instead
  623. of silently reverting (#101097's clobber complaint), and the pre-rename
  624. retirement is skipped with it — deletion is management too. A MISSING
  625. entry is still created regardless — the opt-out protects user edits,
  626. not first-run presence. Any config error reads as enabled (default).
  627. """
  628. try:
  629. from hermes_cli.config import load_config_readonly
  630. desktop_cfg = (load_config_readonly() or {}).get("desktop") or {}
  631. raw = desktop_cfg.get("manage_launcher_entry", True)
  632. if isinstance(raw, bool):
  633. return raw
  634. if isinstance(raw, str):
  635. return raw.strip().lower() not in ("false", "0", "no", "off")
  636. return True
  637. except Exception:
  638. return True
  639. def _alias_legacy_desktop_entry(applications_dir: Path, exec_command: str, icon: str) -> bool:
  640. """Keep the pre-rename ``hermes.desktop`` as a hidden alias of the app-id entry.
  641. Shells resolve a taskbar pin by the entry file name it was pinned against: deleting the
  642. file makes GNOME drop the favourite and Plasma leave an inert item, and nothing can
  643. re-pin for the user. The alias stays launchable for old pins without listing Hermes
  644. twice. Only a file that still names this app is converted; anything else at that path
  645. is left alone. True when the legacy file was (re)written.
  646. """
  647. legacy = applications_dir / LEGACY_DESKTOP_ENTRY_NAME
  648. try:
  649. text = legacy.read_text(encoding="utf-8-sig")
  650. except OSError:
  651. return False
  652. if not any(line.strip() == "Name=Hermes" for line in text.splitlines()):
  653. return False
  654. alias_contents = _render_legacy_alias_entry(exec_command, icon)
  655. if text == alias_contents:
  656. return False
  657. try:
  658. from utils import atomic_write_text
  659. atomic_write_text(legacy, alias_contents, create_mode=0o755)
  660. legacy.chmod(0o755)
  661. except OSError:
  662. return False
  663. return True
  664. def install_desktop_entry(project_root: Path) -> Optional[Path]:
  665. """Create or refresh the app-id entry, respecting the opt-out for existing entries.
  666. Only the app-id entry is written; a pre-rename ``hermes.desktop`` beside it is converted
  667. into a hidden alias once the new entry exists, and only while launcher management is
  668. enabled — deleting it instead would silently kill existing taskbar pins (#124492).
  669. ``None`` on non-Linux platforms, when the write fails, or when the resolved ``Exec``
  670. provably cannot serve ``hermes desktop`` — a convenience, never a reason to fail a launch.
  671. """
  672. if not is_supported():
  673. return None
  674. entry_path = desktop_entry_path()
  675. # Opt-out honored only for an entry that already exists: the flag
  676. # stops the every-launch clobber, not first-run creation.
  677. manage_enabled = _launcher_entry_management_enabled()
  678. if entry_path.is_file() and not manage_enabled:
  679. return entry_path
  680. exec_command = resolve_exec_command(project_root)
  681. # Never persist an Exec the entry provably cannot launch from: a dead entry looks broken
  682. # (a click that does nothing) while skipping leaves whatever is already on disk instead of
  683. # churning it. Unknown shapes still write — only a proven mismatch skips.
  684. if _persisted_exec_serves_desktop(exec_command) is False:
  685. return None
  686. icon = icon_path(project_root)
  687. # Prefer the themed name: the icon is COPIED into the hicolor tree, so the entry outlives the
  688. # checkout (an absolute Icon= path breaks when the checkout moves). Absolute path only when
  689. # the copy is impossible (read-only tree); themed name when the checkout has no icon at all.
  690. icon_value = str(icon) if icon.is_file() else "hermes"
  691. if icon.is_file() and _install_icon_to_hicolor(icon):
  692. icon_value = "hermes"
  693. contents = render_desktop_entry(exec_command, icon_value)
  694. try:
  695. entry_path.parent.mkdir(parents=True, exist_ok=True)
  696. # When nothing changed, skip the rewrite. Then a launch does not
  697. # churn the menu caches.
  698. unchanged = entry_path.is_file() and entry_path.read_text(encoding="utf-8-sig") == contents
  699. if not unchanged:
  700. # Atomic replace: an interrupted plain write leaves a zero-byte entry, which permanently
  701. # breaks the taskbar pin (nothing later rewrites a file that exists at the right path).
  702. # The temp+rename dance in utils.atomic_write_text is the codebase's shared implementation — ported
  703. # from #80547, which closed unmerged with this piece unlanded.
  704. from utils import atomic_write_text
  705. atomic_write_text(entry_path, contents, create_mode=0o755)
  706. # Some launchers (and older Plasma) offer the entry only when it is executable.
  707. entry_path.chmod(0o755)
  708. except OSError:
  709. return None
  710. # Converting the old entry is management too: with the opt-out set, an existing
  711. # launcher stays untouched even here, in the missing-entry path where the new
  712. # entry is still created.
  713. aliased = manage_enabled and _alias_legacy_desktop_entry(entry_path.parent, exec_command, icon_value)
  714. if aliased or not unchanged:
  715. refresh_desktop_databases(entry_path.parent)
  716. return entry_path
  717. def launched_from_shell(environ: Optional[Mapping[str, str]] = None) -> bool:
  718. """True when this process was started from the app grid / menu (XDG startup notification).
  719. A grid launch has a gnome-shell ShellApp in STARTING until our window maps; unpatched
  720. shells (before GNOME MR !4428) drop that app's last reference when its own ``.desktop``
  721. entry changes, and the next idle GC kills the whole Wayland session (#111906). A false
  722. negative degrades to the pre-#111906 behaviour; a false positive only delays a heal.
  723. """
  724. env = os.environ if environ is None else environ
  725. return bool(env.get(SHELL_LAUNCH_ENV_VAR))
  726. class DeferredDesktopEntryInstall:
  727. """Install the entry once the desktop window is on screen — never while the shell's
  728. ShellApp is STARTING.
  729. The launcher hands Electron the write end of a pipe (``HERMES_DESKTOP_READY_FD``); Electron
  730. writes one byte when the main window is revealed and a worker thread then installs the entry.
  731. An exit without a reveal (boot crash, early quit) does NOT heal: gnome-shell keeps the ShellApp
  732. in STARTING until the startup-notification sequence completes or times out (mutter, ~15 s),
  733. not until the process dies, so a write right after such an exit still lands in the arming
  734. window. The next terminal/updater launch or revealed grid launch installs the entry instead.
  735. Terminal and detached launches never build one of these: they install immediately, as before.
  736. """
  737. def __init__(
  738. self,
  739. project_root: Path,
  740. install: Optional[Callable[[Path], Optional[Path]]] = None,
  741. settle_seconds: float = 2.0,
  742. ) -> None:
  743. self._project_root = project_root
  744. self._install = install or install_desktop_entry
  745. # Electron reports the reveal before the compositor has necessarily mapped the surface;
  746. # a short settle after the signal keeps the write on the RUNNING side. It is a margin
  747. # after the condition, not a substitute for it.
  748. self._settle_seconds = settle_seconds
  749. self._read_fd, self.write_fd = os.pipe()
  750. self._thread = threading.Thread(target=self._wait_for_reveal, name="desktop-entry-install", daemon=True)
  751. def child_env(self, env: dict) -> dict:
  752. env[READY_FD_ENV_VAR] = str(self.write_fd)
  753. return env
  754. @property
  755. def pass_fds(self) -> tuple[int, ...]:
  756. return (self.write_fd,)
  757. def start(self) -> None:
  758. self._thread.start()
  759. def _wait_for_reveal(self) -> None:
  760. try:
  761. data = os.read(self._read_fd, 1)
  762. except OSError:
  763. return
  764. if data != REVEAL_BYTE: # woken by finish(): the app exited without a reveal, skip the heal
  765. return
  766. if self._settle_seconds:
  767. time.sleep(self._settle_seconds)
  768. try:
  769. entry = self._install(self._project_root)
  770. if entry:
  771. print(f"✓ Desktop launcher entry installed: {entry}")
  772. except Exception as exc: # never fail a launch on launcher plumbing
  773. print(f"⚠ Could not install the desktop launcher entry: {exc}")
  774. def finish(self) -> None:
  775. """Electron exited: let a heal already triggered by the reveal complete, never start one."""
  776. try:
  777. os.write(self.write_fd, b"x") # wake a still-waiting reader so join() returns promptly
  778. except OSError:
  779. pass
  780. self._thread.join(timeout=15)
  781. for fd in (self._read_fd, self.write_fd):
  782. try:
  783. os.close(fd)
  784. except OSError:
  785. pass