The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): Linux launcher targets a CLI that can serve the app and skips the rebuild (#126650)
brooklyn!79a6fd3e996b
diff --git a/hermes_cli/linux_desktop_entry.py b/hermes_cli/linux_desktop_entry.pyindex fe022c1abc2..62d3fa7d657 100644--- a/hermes_cli/linux_desktop_entry.py+++ b/hermes_cli/linux_desktop_entry.py@@ -12,6 +12,7 @@ from __future__ import annotationsimport ioimport osimport re+import shleximport shutilimport structimport subprocess@@ -130,7 +131,7 @@ def resolve_exec_command(project_root: Optional[Path] = None) -> str:# lineage, commit 4150501f641) — cached here per-process so a desktop launch pays the subprocess# cost at most once.interpreter = _running_interpreter_fallback()- argv = [interpreter, "-m", "hermes_cli.main", "desktop"]+ argv = [interpreter, "-m", "hermes_cli.main", *_desktop_argv_tail(project_root)]if bin_path:resolved = Path(bin_path).resolve()# A Python launcher whose shebang points OUTSIDE the venv (e.g. the repo's `hermes` script@@ -138,10 +139,32 @@ def resolve_exec_command(project_root: Optional[Path] = None) -> str:# Terminal=false — run it under the venv interpreter explicitly.prefix = [interpreter] if _needs_interpreter(resolved) else []# See #90292.- argv = [*prefix, str(resolved), "desktop"]+ argv = [*prefix, str(resolved), *_desktop_argv_tail(project_root)]return " ".join(_quote_exec_arg(a) for a in argv)+def _desktop_argv_tail(project_root: Optional[Path]) -> list[str]:+ """The ``desktop`` subcommand arguments a persisted launcher should carry.++ A menu/taskbar click is a launch, not a build request: when a packaged+ Electron app already exists under the checkout it must start directly+ (``--skip-build``) instead of re-running the build-then-launch path, whose+ source-hash freshness check reports "stale" on any locally modified tree+ and makes every click pay a 60s+ rebuild that can fail outright (#126009).+ With no packaged app yet (first install), keep the build-then-launch+ default so the click still produces an app.+ """+ if project_root is None:+ return ["desktop"]+ release = project_root / "apps" / "desktop" / "release"+ packaged = any(+ (release / dist / name).exists()+ for dist in ("linux-unpacked", "linux-arm64-unpacked")+ for name in ("hermes", "Hermes")+ )+ return ["desktop", "--skip-build"] if packaged else ["desktop"]++def _is_interpreter(candidate: Path) -> bool:"""A python interpreter binary (``bin/python*``), not a launcher: strict basename match(rejects ``python3-config``, ``pythonw``) inside a bin/Scripts dir (rejects a stray script@@ -181,6 +204,27 @@ def _inside_checkout(candidate: str, checkout_root: Path, original_argv0: str) -return False+def _is_this_checkout_managed_cli(candidate: str, checkout_root: Path) -> bool:+ """True when *candidate* is this checkout's PM-managed console script.++ That script lives under ``installs/<key>/environments`` and imports a+ generated workspace that does not ship ``apps/desktop``. It sits outside+ the checkout, so the external-primary rule would persist it and the+ desktop launcher would exit with the GUI source missing.+ """+ try:+ path = Path(candidate).resolve()+ except OSError:+ return False+ try:+ from pm.environments import install_state_dir++ generations = (install_state_dir(Path(checkout_root)) / "environments").resolve()+ except (OSError, RuntimeError, ValueError):+ return False+ return path == generations or generations in path.parents++def _resolve_hermes_bin_for_desktop_entry(resolve_fn=None,checkout_root: Optional[Path] = None,@@ -190,8 +234,10 @@ def _resolve_hermes_bin_for_desktop_entry(Wraps :func:`hermes_cli.relaunch.resolve_hermes_bin` with one rule: an ``argv[0]`` inside thischeckout is a launch-context artifact, not a durable installed launcher — persisting it makesthe entry depend on how the previous launch happened (a bootstrap loop). Skip such candidates- and fall through to PATH, then to the installer's known wrapper locations. ``resolve_fn`` is- injectable for tests.+ and fall through to PATH, then to the installer's known wrapper locations. A candidate that+ provably cannot serve ``hermes desktop`` (a code tree carrying ``hermes_cli`` but no desktop+ app beside it — a managed runtime env's console script) is skipped the same way: its entry+ would only ever die with "Desktop GUI source not found". ``resolve_fn`` is injectable for tests.See #90492."""@@ -212,7 +258,17 @@ def _resolve_hermes_bin_for_desktop_entry(# installation. Only rerun the resolver with argv[0] hidden when the primary could actually# be checkout-internal (also shortens the window a concurrent reader sees mutated sys.argv).primary = resolve_fn()- if primary and not _inside_checkout(primary, checkout_root, original_argv0):+ # A managed-environment console script is outside the checkout but is not a durable desktop+ # launcher: its workspace has no apps/desktop (#122438). The same holds for any launcher+ # that provably cannot serve `hermes desktop` (another install's managed env, #122485).+ # Fall through so the durable-wrapper probe below can still find a working one.+ if (+ primary+ and not _inside_checkout(primary, checkout_root, original_argv0)+ and not _is_this_checkout_managed_cli(primary, checkout_root)+ and not _is_this_checkout_managed_cli(primary, module_lexical_root)+ and _can_serve_desktop(primary) is not False+ ):return primary# A primary that is NOT checkout-internal and not the invoking interpreter is an external launcher (e.g.@@ -234,8 +290,13 @@ def _resolve_hermes_bin_for_desktop_entry(# gnome-shell 50.x crashes when the entry changes while its ShellApp is STARTING (#110885).# ``primary is None`` implies ``rerouted is None`` (the rerun only hides argv[0]), so only the# probe can still find anything.- if primary and rerouted is not None and not _inside_checkout(- rerouted, checkout_root, original_argv0+ if (+ primary+ and rerouted is not None+ and not _inside_checkout(rerouted, checkout_root, original_argv0)+ and not _is_this_checkout_managed_cli(rerouted, checkout_root)+ and not _is_this_checkout_managed_cli(rerouted, module_lexical_root)+ and _can_serve_desktop(rerouted) is not False):return rerouted# A PATH hit inside this checkout is the same launch-context artifact as argv[0]: the@@ -346,6 +407,100 @@ def _wrapper_targets_checkout(wrapper: Path, checkout_root: Path) -> bool:)+_HERMES_CODE_MARKERS = ("hermes_cli", "workspace/hermes_cli")+_DESKTOP_APP_ENTRIES = ("apps/desktop/package.json", "workspace/apps/desktop/package.json")+++def _launcher_tree(path: Path) -> Path:+ """Install tree a ``bin`` launcher belongs to: ``<tree>/venv/bin/x`` → ``<tree>``."""+ parent = path.parent+ if parent.name not in ("bin", "Scripts", "scripts"):+ return parent+ tree = parent.parent+ return tree.parent if tree.name in ("venv", ".venv", "env") else tree+++def _tree_desktop_state(tree: Path) -> Optional[bool]:+ """``True`` when *tree* can serve ``hermes desktop``, ``False`` when it provably cannot, else ``None``.++ ``False`` is reserved for a tree that IS a hermes code tree (carries ``hermes_cli``) yet has no+ desktop app beside it — the managed runtime env layout, whose launcher runs but dies with+ "Desktop GUI source not found". Unfamiliar shapes stay ``None`` (accepted) so no install+ method is rejected for looking exotic.+ """+ if any((tree / entry).is_file() for entry in _DESKTOP_APP_ENTRIES):+ return True+ from hermes_cli.steward import is_bundled_payload++ if is_bundled_payload(tree):+ return True+ if any((tree / marker).is_dir() for marker in _HERMES_CODE_MARKERS):+ return False+ return None+++def _embedded_launcher_target(wrapper: Path) -> Optional[Path]:+ """First absolute path to an existing ``bin`` launcher embedded in a shell wrapper script."""+ head = _read_head(wrapper)+ if head is None:+ return None+ for match in re.finditer(r"""["'\s](/[^\s"'$;)\\]+)""", head.decode("utf-8", errors="replace")):+ if "/bin/" in match.group(1) and Path(match.group(1)).is_file():+ return Path(match.group(1))+ return None+++def _can_serve_desktop(candidate: str, _depth: int = 2) -> Optional[bool]:+ """Desktop-capability of a launcher path; shell wrappers followed to their target.++ Native binaries, unreadable files, interpreters, and shapes without markers stay ``None``;+ only a launcher whose tree provably lacks the desktop app is rejected (``False``).+ """+ try:+ path = Path(candidate)+ if not path.is_file():+ return None+ head = _read_head(path, 256)+ except OSError:+ return None+ if head is None or not head.startswith(b"#!"):+ return None+ tokens = _shebang_tokens(head.decode("utf-8", errors="replace").splitlines()[0])+ if _depth and tokens and (Path(tokens[0]).name in _SHELL_NAMES or Path(tokens[0]).name == "env"):+ # The installer's shim (any shell launcher) execs its real target; judge THAT tree.+ target = _embedded_launcher_target(path)+ if target is not None:+ verdict = _can_serve_desktop(str(target), _depth - 1)+ if verdict is not None:+ return verdict+ return _tree_desktop_state(_launcher_tree(path))+++def _persisted_exec_serves_desktop(exec_command: str) -> Optional[bool]:+ """Desktop-capability of a rendered ``Exec`` line, ignoring an interpreter prefix.++ ``[<interpreter>, <launcher>, desktop]`` is judged by the launcher. The module fallback+ ``[<interpreter>, -m, hermes_cli.main, desktop]`` passes: it is only ever written by a+ process that already passed the desktop launch checks.+ """+ try:+ tokens = shlex.split(exec_command)+ except ValueError:+ return None+ if not tokens:+ return None+ candidate = tokens[0]+ if _is_interpreter(Path(candidate)):+ if len(tokens) > 1 and tokens[1] != "-m":+ candidate = tokens[1] # `[<interpreter>, <launcher>, desktop]` prefix form+ else:+ # Module fallback `[<interpreter>, -m, hermes_cli.main, desktop]`: only a process+ # that already passed the desktop launch checks writes it, so it is not+ # second-guessed here.+ return None+ return _can_serve_desktop(candidate)++def _known_wrapper_candidates():"""Durable installed-launcher locations, most likely first.@@ -647,8 +802,8 @@ def install_desktop_entry(project_root: Path) -> Optional[Path]:Only the app-id entry is written; a pre-rename ``hermes.desktop`` beside it is convertedinto a hidden alias once the new entry exists, and only while launcher management isenabled — deleting it instead would silently kill existing taskbar pins (#124492).- ``None`` on non-Linux platforms or when the write fails — a convenience, never a reason- to fail a launch.+ ``None`` on non-Linux platforms, when the write fails, or when the resolved ``Exec``+ provably cannot serve ``hermes desktop`` — a convenience, never a reason to fail a launch."""if not is_supported():return None@@ -661,6 +816,13 @@ def install_desktop_entry(project_root: Path) -> Optional[Path]:if entry_path.is_file() and not manage_enabled:return entry_path+ exec_command = resolve_exec_command(project_root)+ # Never persist an Exec the entry provably cannot launch from: a dead entry looks broken+ # (a click that does nothing) while skipping leaves whatever is already on disk instead of+ # churning it. Unknown shapes still write — only a proven mismatch skips.+ if _persisted_exec_serves_desktop(exec_command) is False:+ return None+icon = icon_path(project_root)# Prefer the themed name: the icon is COPIED into the hicolor tree, so the entry outlives the# checkout (an absolute Icon= path breaks when the checkout moves). Absolute path only when@@ -668,7 +830,6 @@ def install_desktop_entry(project_root: Path) -> Optional[Path]:icon_value = str(icon) if icon.is_file() else "hermes"if icon.is_file() and _install_icon_to_hicolor(icon):icon_value = "hermes"- exec_command = resolve_exec_command(project_root)contents = render_desktop_entry(exec_command, icon_value)try:diff --git a/tests/hermes_cli/test_linux_desktop_entry.py b/tests/hermes_cli/test_linux_desktop_entry.pyindex e0cfa57074d..bad70da88c3 100644--- a/tests/hermes_cli/test_linux_desktop_entry.py+++ b/tests/hermes_cli/test_linux_desktop_entry.py@@ -476,6 +476,52 @@ def test_exec_never_persists_a_checkout_internal_path_hit(tmp_path, xdg_home, moassert entry2.read_text(encoding="utf-8") == entry.read_text(encoding="utf-8")+def test_exec_skips_managed_environment_cli_without_desktop(+ tmp_path, xdg_home, monkeypatch+):+ """A PM-managed console script is outside the checkout but cannot launch Desktop.++ Its generated workspace has no ``apps/desktop``. Treating it as the durable+ external primary persists ``Exec=`` at that script, and the grid launcher+ exits with "Desktop GUI source not found". The entry must keep the+ checkout's installed wrapper instead.+ """+ from pm.environments import install_key++ root = _make_project(tmp_path)+ installs = tmp_path / "installs"+ monkeypatch.setattr("pm.environments.installs_root", lambda: installs)+ generation = installs / install_key(root) / "environments" / "gen"+ workspace = generation / "workspace"+ workspace.mkdir(parents=True)+ managed = generation / "venv" / "bin" / "hermes"+ managed.parent.mkdir(parents=True)+ managed.write_text("#!/usr/bin/env bash\nexec true\n", encoding="utf-8")+ managed.chmod(0o755)++ known_wrapper = tmp_path / ".local" / "bin" / "hermes"+ known_wrapper.parent.mkdir(parents=True)+ known_wrapper.write_text(+ f'#!/usr/bin/env bash\nexec {root / "venv" / "bin" / "python"} {root / "hermes"} "$@"\n',+ encoding="utf-8",+ )+ known_wrapper.chmod(0o755)++ def fake_resolve():+ return str(managed)++ monkeypatch.setattr("hermes_cli.relaunch.resolve_hermes_bin", fake_resolve)+ _argv0_context(monkeypatch, str(managed))+ monkeypatch.setattr(lde, "refresh_desktop_databases", lambda _dir: [])++ entry = lde.install_desktop_entry(root)+ assert entry is not None+ exec_line = _parse(entry.read_text(encoding="utf-8"))["Exec"]++ assert exec_line == f"{known_wrapper} desktop"+ assert str(managed) not in exec_line++def test_exec_finds_known_wrapper_when_resolver_has_no_candidate(tmp_path, xdg_home, monkeypatch):@@ -1292,3 +1338,182 @@ def test_deferred_install_skips_heal_after_exit_without_reveal():deferred.finish()assert calls == []assert not deferred._thread.is_alive()+++# --- desktop-capability of the persisted Exec (managed runtime env launchers) ------------------+++def _write_script(path: Path, text: str) -> Path:+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(text, encoding="utf-8")+ path.chmod(0o755)+ return path+++def _env_shaped_tree(tmp_path: Path, name: str = "managed-env") -> Path:+ """The runtime env layout: a code tree (workspace/hermes_cli) with no desktop app in it."""+ tree = tmp_path / name+ (tree / "workspace" / "hermes_cli").mkdir(parents=True)+ (tree / "workspace" / "hermes_cli" / "main.py").write_text("", encoding="utf-8")+ _write_script(tree / "venv" / "bin" / "hermes", "#!/bin/sh\nexit 0\n")+ python_bin = tree / "venv" / "bin" / "python"+ python_bin.write_bytes(b"\x7fELF fake") # real interpreters are binaries, never scripts+ python_bin.chmod(0o755)+ return tree+++def _full_tree(tmp_path: Path, name: str = "install") -> Path:+ """A checkout that carries the desktop app beside hermes_cli."""+ tree = tmp_path / name+ (tree / "hermes_cli").mkdir(parents=True)+ (tree / "apps" / "desktop" / "assets").mkdir(parents=True)+ (tree / "apps" / "desktop" / "package.json").write_text("{}", encoding="utf-8")+ _write_script(tree / "venv" / "bin" / "hermes", "#!/bin/sh\nexit 0\n")+ python_bin = tree / "venv" / "bin" / "python"+ python_bin.write_bytes(b"\x7fELF fake") # real interpreters are binaries, never scripts+ python_bin.chmod(0o755)+ return tree+++def test_capability_rejects_env_shaped_launcher_and_accepts_full_tree(tmp_path):+ env_tree = _env_shaped_tree(tmp_path)+ full_tree = _full_tree(tmp_path)+ assert lde._can_serve_desktop(str(env_tree / "venv" / "bin" / "hermes")) is False+ assert lde._can_serve_desktop(str(full_tree / "venv" / "bin" / "hermes")) is True+ # Interpreters are not judged: a launcher execing one is followed to its own tree instead.+ assert lde._can_serve_desktop(str(env_tree / "venv" / "bin" / "python")) is None+ assert lde._can_serve_desktop(str(full_tree / "venv" / "bin" / "python")) is None+++def test_capability_unknown_shapes_pass(tmp_path):+ missing = tmp_path / "nowhere" / "bin" / "hermes"+ assert lde._can_serve_desktop(str(missing)) is None+ native = _write_script(tmp_path / "opt" / "bin" / "hermes", "")+ assert lde._can_serve_desktop(str(native)) is None+++def test_capability_follows_wrapper_to_its_target(tmp_path):+ env_tree = _env_shaped_tree(tmp_path)+ full_tree = _full_tree(tmp_path)+ bad_wrapper = _write_script(+ tmp_path / "shims" / "hermes",+ f'#!/usr/bin/env bash\nexec "{env_tree}/venv/bin/hermes" "$@"\n',+ )+ good_wrapper = _write_script(+ tmp_path / "shims" / "hermes-good",+ f'#!/usr/bin/env bash\nexec "{full_tree}/venv/bin/hermes" "$@"\n',+ )+ assert lde._can_serve_desktop(str(bad_wrapper)) is False+ assert lde._can_serve_desktop(str(good_wrapper)) is True+++def test_resolver_skips_incapable_primary_for_wrapper(tmp_path, xdg_home):+ """A PATH-first launcher from an env-shaped tree must not win over the durable wrapper."""+ env_tree = _env_shaped_tree(tmp_path)+ checkout = _full_tree(tmp_path, "checkout")+ wrapper = _write_script(+ tmp_path / ".local" / "bin" / "hermes",+ f'#!/usr/bin/env bash\nexec "{checkout}/venv/bin/hermes" "$@"\n',+ )+ resolution = lde._resolve_hermes_bin_for_desktop_entry(+ resolve_fn=lambda: str(env_tree / "venv" / "bin" / "hermes"),+ checkout_root=checkout,+ )+ assert resolution == str(wrapper)+++def test_install_skips_write_when_exec_provably_cannot_serve_desktop(tmp_path, xdg_home, monkeypatch):+ """The fallback must not create a dead entry: no entry on disk stays that way."""+ root = _make_project(tmp_path)+ env_tree = _env_shaped_tree(tmp_path)+ monkeypatch.setattr(lde, "_launcher_entry_management_enabled", lambda: True)+ monkeypatch.setattr(+ lde,+ "resolve_exec_command",+ lambda project_root=None: f"{env_tree / 'venv' / 'bin' / 'hermes'} desktop",+ )+ monkeypatch.setattr(lde, "refresh_desktop_databases", lambda _dir: [])++ assert lde.install_desktop_entry(root) is None+ assert not lde.desktop_entry_path().exists()+++def test_install_leaves_existing_entry_untouched_when_exec_incapable(tmp_path, xdg_home, monkeypatch):+ """A provably dead Exec skips instead of churning an entry that is already on disk."""+ root = _make_project(tmp_path)+ env_tree = _env_shaped_tree(tmp_path)+ entry_path = lde.desktop_entry_path()+ entry_path.parent.mkdir(parents=True, exist_ok=True)+ entry_path.write_text("hand-tuned\n", encoding="utf-8")+ monkeypatch.setattr(lde, "_launcher_entry_management_enabled", lambda: True)+ monkeypatch.setattr(+ lde,+ "resolve_exec_command",+ lambda project_root=None: f"{env_tree / 'venv' / 'bin' / 'hermes'} desktop",+ )+ monkeypatch.setattr(lde, "refresh_desktop_databases", lambda _dir: [])++ assert lde.install_desktop_entry(root) is None+ assert entry_path.read_text(encoding="utf-8") == "hand-tuned\n"+++def test_module_form_passes_the_gate(tmp_path):+ """The module fallback is not second-guessed: only a process that already passed the desktop+ launch checks (or the bundled payload) ever writes it."""+ env_tree = _env_shaped_tree(tmp_path)+ module_form = f'"{env_tree / "venv" / "bin" / "python"}" -m hermes_cli.main desktop'+ assert lde._persisted_exec_serves_desktop(module_form) is None+++def test_install_through_wrapper_when_primary_is_incapable(tmp_path, xdg_home, monkeypatch):+ """End to end: the PATH-first env launcher is skipped and the wrapper's Exec is persisted."""+ root = _full_tree(tmp_path, "checkout")+ (root / "apps" / "desktop" / "assets" / "icon.png").write_bytes(b"\x89PNG fake")+ env_tree = _env_shaped_tree(tmp_path)+ wrapper = _write_script(+ tmp_path / ".local" / "bin" / "hermes",+ f'#!/usr/bin/env bash\nexec "{root}/venv/bin/hermes" "$@"\n',+ )+ monkeypatch.setattr(lde, "_launcher_entry_management_enabled", lambda: True)+ monkeypatch.setattr(+ "hermes_cli.relaunch.resolve_hermes_bin",+ lambda: str(env_tree / "venv" / "bin" / "hermes"),+ )+ monkeypatch.setattr(lde, "refresh_desktop_databases", lambda _dir: [])++ entry = lde.install_desktop_entry(root)+ assert entry == lde.desktop_entry_path()+ assert _parse(entry.read_text(encoding="utf-8"))["Exec"] == f"{wrapper} desktop"+++# #126009: the persisted launcher is a menu/taskbar click — a launch, not a+# build request. With a packaged Electron app already present, the Exec line+# must carry --skip-build (start the packaged app in seconds) instead of the+# build-then-launch default, whose source-hash freshness check reports+# "stale" on any locally modified tree and pays a 60s+ rebuild per click.+def test_exec_appends_skip_build_when_packaged_app_exists(tmp_path, xdg_home, monkeypatch):+ root = _make_project(tmp_path)+ unpacked = root / "apps" / "desktop" / "release" / "linux-unpacked"+ unpacked.mkdir(parents=True)+ (unpacked / "hermes").write_text("", encoding="utf-8")+ monkeypatch.setattr("hermes_cli.relaunch.resolve_hermes_bin", lambda: None)+ monkeypatch.setattr(lde, "refresh_desktop_databases", lambda _dir: [])++ entry = lde.install_desktop_entry(root)+ exec_line = _parse(entry.read_text(encoding="utf-8"))["Exec"]++ assert exec_line.endswith("desktop --skip-build")+++def test_exec_keeps_build_then_launch_when_no_packaged_app(tmp_path, xdg_home, monkeypatch):+ # First install (nothing packaged yet): the click must still build and+ # launch — --skip-build would exit with "no packaged desktop app found".+ root = _make_project(tmp_path)+ monkeypatch.setattr("hermes_cli.relaunch.resolve_hermes_bin", lambda: None)+ monkeypatch.setattr(lde, "refresh_desktop_databases", lambda _dir: [])++ entry = lde.install_desktop_entry(root)+ exec_line = _parse(entry.read_text(encoding="utf-8"))["Exec"]++ assert exec_line.endswith("desktop")+ assert "--skip-build" not in exec_line