The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): install rebuilt app to system location after CLI hermes update
Yingliang Zhangd49fda1d15e4
diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex 8d5dbed0302..49a9c35a5ae 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -808,9 +808,11 @@ from hermes_cli.main_desktop import ()from hermes_cli.main_desktop import ( # frozen updater surface: update_cmd*.py resolve these via _m()_desktop_build_needed,+ _desktop_bundle_install_supported,_desktop_dist_exists,_desktop_macos_relaunchable_fixup,_desktop_packaged_executable,+ _install_rebuilt_desktop_app,)from hermes_cli.main_web_build import (_sweep_stale_bytecode_if_checkout_changed,diff --git a/hermes_cli/main_desktop.py b/hermes_cli/main_desktop.pyindex 8c3a25b89bc..3d5aa5df025 100644--- a/hermes_cli/main_desktop.py+++ b/hermes_cli/main_desktop.py@@ -7,6 +7,7 @@ are imported lazily inside the functions that use them (avoids an import cycle).import loggingimport contextlibimport argparse+import hashlibimport osimport reimport shlex@@ -1048,6 +1049,181 @@ def _desktop_macos_setup_tcc_identity(identity: str = "Hermes Local Signing") ->return True+def _app_asar_hash(app_path: Path) -> str | None:+ """Return the SHA-256 hex digest of an app bundle's app.asar, or None."""+ asar = app_path / "Contents" / "Resources" / "app.asar"+ if not asar.is_file():+ return None+ h = hashlib.sha256()+ try:+ with open(asar, "rb") as f:+ for chunk in iter(lambda: f.read(65536), b""):+ h.update(chunk)+ return h.hexdigest()+ except (OSError, IOError):+ return None+++def _macos_adhoc_sign_bundle(app: Path) -> None:+ """Clear quarantine and apply a deep ad-hoc signature on a macOS .app bundle.++ Mirrors what ``_desktop_macos_relaunchable_fixup`` does for the release/+ copy, but operates on an arbitrary bundle path (e.g. /Applications/Hermes.app).+ No-op when a real signing identity is configured or off-macOS. Best-effort.+ """+ if sys.platform != "darwin":+ return+ if os.environ.get("CSC_LINK") or os.environ.get("APPLE_SIGNING_IDENTITY"):+ return+ if not str(app).endswith(".app") or not app.is_dir():+ return+ codesign = shutil.which("codesign")+ if not codesign:+ return+ try:+ subprocess.run(["xattr", "-cr", str(app)], check=False)+ subprocess.run([codesign, "--force", "--deep", "--sign", "-", str(app)], check=False)+ except Exception as exc:+ logger.debug("macOS ad-hoc signing of %s skipped: %s", app, exc)+++def _desktop_bundle_install_supported() -> bool:+ """Return whether the current platform has a copyable installed bundle."""+ platform = sys.platform+ return platform == "darwin" or platform == "win32"+++def _swap_in_new_macos_bundle(tmp: Path, target: Path, old: Path) -> None:+ """Move a staged macOS bundle into place without losing the old bundle."""+ moved_old = False+ if target.exists():+ try:+ target.rename(old)+ except OSError:+ shutil.rmtree(tmp, ignore_errors=True)+ raise+ moved_old = True++ try:+ tmp.rename(target)+ except OSError as install_error:+ rollback_error: OSError | None = None+ if moved_old:+ try:+ old.rename(target)+ except OSError as exc:+ rollback_error = exc+ shutil.rmtree(tmp, ignore_errors=True)+ if rollback_error is not None:+ raise OSError(+ f"installing the staged bundle failed and rollback remains at {old}: "+ f"{rollback_error}"+ ) from install_error+ raise++ shutil.rmtree(old, ignore_errors=True)+++def _install_rebuilt_desktop_app(desktop_dir: Path) -> Path | None:+ """Install the freshly rebuilt desktop app to the system install location.++ ``hermes desktop --build-only`` (called by ``hermes update``) rebuilds the+ Electron app into ``apps/desktop/release/`` but does NOT copy it to the+ standard install location (e.g. ``/Applications/Hermes.app``). The+ in-app updater in ``main.cjs`` handles the swap via a detached script;+ this function covers the CLI ``hermes update`` path so the installed app+ does not go stale.++ Only installs when the current platform has a copyable installed bundle+ (a macOS ``.app`` or Windows NSIS directory), a rebuilt package exists,+ and an installed copy already exists at a standard location. Linux+ AppImage/deb/rpm installs remain owned by their original package mechanism;+ ``packaged_gui_app_paths`` only returns ``.desktop`` launchers there.++ Compares the macOS ``app.asar`` SHA-256 to avoid unnecessary copies, then+ clears quarantine and re-applies ad-hoc signing. Returns the installed path+ on success, or ``None`` when no install was needed or possible.+ """+ if not _desktop_bundle_install_supported():+ logger.debug(+ "Skipping post-update Desktop bundle install on unsupported platform %s",+ sys.platform,+ )+ return None++ rebuilt_exe = _desktop_packaged_executable(desktop_dir)+ if rebuilt_exe is None:+ return None++ # Resolve the rebuilt .app bundle directory+ rebuilt_app: Path | None = None+ if sys.platform == "darwin":+ # exe = .../Hermes.app/Contents/MacOS/Hermes -> app = .../Hermes.app+ if len(rebuilt_exe.parents) >= 2 and str(rebuilt_exe.parents[2]).endswith(".app"):+ rebuilt_app = rebuilt_exe.parents[2]+ elif sys.platform == "win32":+ # win-unpacked is a directory, not a .app bundle+ rebuilt_app = rebuilt_exe.parent+ else:+ return None++ if rebuilt_app is None or not rebuilt_app.is_dir():+ return None++ # Find existing installed copies at standard locations+ from hermes_cli.gui_uninstall import packaged_gui_app_paths++ installed_apps = [+ path+ for path in packaged_gui_app_paths()+ if path.is_dir()+ and (sys.platform == "win32" or path.suffix.casefold() == ".app")+ ]+ if not installed_apps:+ return None # nothing installed → nothing to update++ rebuilt_hash = _app_asar_hash(rebuilt_app) if sys.platform == "darwin" else None++ for installed_app in installed_apps:+ # Skip if the installed copy is already current+ if sys.platform == "darwin" and rebuilt_hash:+ installed_hash = _app_asar_hash(installed_app)+ if installed_hash and installed_hash == rebuilt_hash:+ continue # already up to date++ # On macOS, use ditto for a metadata-preserving staged copy, then move+ # the installed bundle aside and atomically-as-possible swap the staged+ # copy in. The old bundle is restored if either rename fails. Windows+ # installs are directories, so copytree replaces their contents.+ try:+ if sys.platform == "darwin":+ ditto = shutil.which("ditto")+ if not ditto:+ continue+ tmp = installed_app.parent / f"{installed_app.name}.hermes-update-new"+ old = installed_app.parent / f"{installed_app.name}.hermes-update-old"+ shutil.rmtree(tmp, ignore_errors=True)+ shutil.rmtree(old, ignore_errors=True)+ subprocess.run([ditto, str(rebuilt_app), str(tmp)], check=True, capture_output=True)+ _swap_in_new_macos_bundle(tmp, installed_app, old)+ else:+ if installed_app.is_dir():+ shutil.rmtree(installed_app, ignore_errors=True)+ shutil.copytree(rebuilt_app, installed_app, dirs_exist_ok=True)++ # Apply macOS quarantine clear + ad-hoc signing directly on+ # the installed bundle (not the release/ copy).+ if sys.platform == "darwin":+ _macos_adhoc_sign_bundle(installed_app)++ return installed_app+ except Exception as exc:+ logger.debug("Desktop app install to %s failed: %s", installed_app, exc)+ continue++ return None++def _force_adhoc_macos_signing(env: dict, *, source_mode: bool) -> bool:"""Force ad-hoc signing for the local packaged rebuild: with ``CSC_IDENTITY_AUTO_DISCOVERY`` on,electron-builder grabs any personal keychain cert and stalls the sign step or clobbers adiff --git a/hermes_cli/update_cmd_deps.py b/hermes_cli/update_cmd_deps.pyindex 0452d0f5b72..f93d6b3e321 100644--- a/hermes_cli/update_cmd_deps.py+++ b/hermes_cli/update_cmd_deps.py@@ -900,7 +900,22 @@ def _rebuild_desktop_after_update(from hermes_constants import display_hermes_home as _dhhprint(f" Full build log: {_dhh()}/logs/update.log")return False- print(" ✓ Desktop app up to date")+ # The build succeeded. `--build-only` rebuilds into the+ # release/ tree but does NOT install the rebuilt app to the+ # system location (e.g. /Applications/Hermes.app). The+ # in-app updater handles that swap itself, but a CLI+ # `hermes update` otherwise leaves the installed app stale.+ if _m()._desktop_bundle_install_supported():+ installed = _m()._install_rebuilt_desktop_app(desktop_dir)+ if installed:+ print(f" ✓ Desktop app updated at {installed}")+ else:+ print(" ✓ Desktop app up to date")+ else:+ print(+ " ✓ Desktop app rebuilt; automatic installed-package "+ f"replacement is unsupported on {sys.platform}"+ )return Truediff --git a/tests/hermes_cli/test_desktop_install_after_update.py b/tests/hermes_cli/test_desktop_install_after_update.pynew file mode 100644index 00000000000..77958baa2cb--- /dev/null+++ b/tests/hermes_cli/test_desktop_install_after_update.py@@ -0,0 +1,343 @@+"""Tests for _install_rebuilt_desktop_app — CLI update installs rebuilt app.++Verifies that ``hermes update`` (via ``_install_rebuilt_desktop_app``) copies+the freshly rebuilt desktop app to the system install location when the+installed copy is stale, and skips when hashes already match.+"""++import hashlib+import shutil+import sys+from pathlib import Path+from unittest.mock import patch, MagicMock++import pytest+++def fake_desktop_dir(tmp_path):+ """A fake desktop_dir with a rebuilt macOS app bundle."""+ release = tmp_path / "apps" / "desktop" / "release" / "mac-arm64" / "Hermes.app"+ # Mimic the real structure: Contents/MacOS/Hermes + Contents/Resources/app.asar+ exe = release / "Contents" / "MacOS" / "Hermes"+ exe.parent.mkdir(parents=True)+ exe.write_bytes(b"\xcf\xfa\xed\xfe") # minimal Mach-O magic+ asar = release / "Contents" / "Resources" / "app.asar"+ asar.parent.mkdir(parents=True)+ asar.write_bytes(b"rebuilt-asar-content")+ return tmp_path / "apps" / "desktop"+++def fake_installed_app(tmp_path):+ """A fake installed Hermes.app with a DIFFERENT app.asar."""+ installed = tmp_path / "Applications" / "Hermes.app"+ exe = installed / "Contents" / "MacOS" / "Hermes"+ exe.parent.mkdir(parents=True)+ exe.write_bytes(b"\xcf\xfa\xed\xfe")+ asar = installed / "Contents" / "Resources" / "app.asar"+ asar.parent.mkdir(parents=True)+ asar.write_bytes(b"stale-asar-content")+ return installed+++def _sha256(data: bytes) -> str:+ return hashlib.sha256(data).hexdigest()+++def _copy_ditto_bundle(command, **_kwargs):+ """Emulate ``ditto SOURCE DEST`` with an ordinary directory copy."""+ shutil.copytree(Path(command[1]), Path(command[2]))+ return MagicMock(returncode=0)++[email protected](sys.platform != "darwin", reason="macOS .app bundle test")+def test_install_when_stale(fake_desktop_dir, fake_installed_app):+ """_install_rebuilt_desktop_app copies the rebuilt app when hashes differ."""+ from hermes_cli.main_desktop import _install_rebuilt_desktop_app++ # Patch _desktop_packaged_executable to find our fake rebuilt app+ fake_rebuilt_exe = (+ fake_desktop_dir+ / "release"+ / "mac-arm64"+ / "Hermes.app"+ / "Contents"+ / "MacOS"+ / "Hermes"+ )+ with (+ patch(+ "hermes_cli.main._desktop_packaged_executable",+ return_value=fake_rebuilt_exe,+ ),+ patch(+ "hermes_cli.gui_uninstall.packaged_gui_app_paths",+ return_value=[fake_installed_app],+ ),+ patch("hermes_cli.main_desktop._macos_adhoc_sign_bundle") as mock_sign,+ ):+ # Let ditto/codesign run for real — they exist on macOS+ result = _install_rebuilt_desktop_app(fake_desktop_dir)++ assert result == fake_installed_app+ mock_sign.assert_called_once_with(fake_installed_app)+ # The installed app.asar should now match the rebuilt one+ rebuilt_asar = (+ fake_desktop_dir+ / "release"+ / "mac-arm64"+ / "Hermes.app"+ / "Contents"+ / "Resources"+ / "app.asar"+ ).read_bytes()+ installed_asar = (+ fake_installed_app / "Contents" / "Resources" / "app.asar"+ ).read_bytes()+ assert rebuilt_asar == installed_asar++[email protected](sys.platform != "darwin", reason="macOS .app bundle test")+def test_skip_when_hashes_match(fake_desktop_dir, tmp_path):+ """_install_rebuilt_desktop_app returns None when hashes already match."""+ from hermes_cli.main_desktop import _install_rebuilt_desktop_app, _app_asar_hash++ # Create an installed app with the SAME app.asar as the rebuilt one+ rebuilt_asar = (+ fake_desktop_dir+ / "release"+ / "mac-arm64"+ / "Hermes.app"+ / "Contents"+ / "Resources"+ / "app.asar"+ ).read_bytes()++ installed = tmp_path / "Applications" / "Hermes.app"+ asar = installed / "Contents" / "Resources" / "app.asar"+ asar.parent.mkdir(parents=True)+ asar.write_bytes(rebuilt_asar)++ fake_rebuilt_exe = (+ fake_desktop_dir+ / "release"+ / "mac-arm64"+ / "Hermes.app"+ / "Contents"+ / "MacOS"+ / "Hermes"+ )++ with (+ patch(+ "hermes_cli.main._desktop_packaged_executable",+ return_value=fake_rebuilt_exe,+ ),+ patch(+ "hermes_cli.gui_uninstall.packaged_gui_app_paths",+ return_value=[installed],+ ),+ patch("shutil.which", return_value="/usr/bin/ditto"),+ patch("subprocess.run") as mock_run,+ ):+ result = _install_rebuilt_desktop_app(fake_desktop_dir)++ assert result is None+ # ditto should NOT have been called+ mock_run.assert_not_called()+++def test_returns_none_when_no_installed_app(fake_desktop_dir):+ """_install_rebuilt_desktop_app returns None when nothing is installed."""+ from hermes_cli.main_desktop import _install_rebuilt_desktop_app++ fake_rebuilt_exe = (+ fake_desktop_dir+ / "release"+ / "mac-arm64"+ / "Hermes.app"+ / "Contents"+ / "MacOS"+ / "Hermes"+ )++ with (+ patch(+ "hermes_cli.main._desktop_packaged_executable",+ return_value=fake_rebuilt_exe,+ ),+ patch(+ "hermes_cli.gui_uninstall.packaged_gui_app_paths",+ return_value=[],+ ),+ ):+ result = _install_rebuilt_desktop_app(fake_desktop_dir)++ assert result is None+++def test_returns_none_when_no_rebuilt_app(fake_desktop_dir):+ """_install_rebuilt_desktop_app returns None when no rebuilt app exists."""+ from hermes_cli.main_desktop import _install_rebuilt_desktop_app++ with patch(+ "hermes_cli.main._desktop_packaged_executable",+ return_value=None,+ ):+ result = _install_rebuilt_desktop_app(fake_desktop_dir)++ assert result is None+++def test_app_asar_hash_consistency(fake_desktop_dir):+ """_app_asar_hash returns consistent hashes for the same content."""+ from hermes_cli.main_desktop import _app_asar_hash++ rebuilt_app = fake_desktop_dir / "release" / "mac-arm64" / "Hermes.app"+ h1 = _app_asar_hash(rebuilt_app)+ h2 = _app_asar_hash(rebuilt_app)+ assert h1 is not None+ assert h1 == h2+ assert len(h1) == 64 # SHA-256 hex+++def test_app_asar_hash_none_for_missing(tmp_path):+ """_app_asar_hash returns None when app.asar doesn't exist."""+ from hermes_cli.main_desktop import _app_asar_hash++ fake_app = tmp_path / "Fake.app"+ fake_app.mkdir()+ assert _app_asar_hash(fake_app) is None+++def test_backup_rename_failure_leaves_installed_bundle_untouched(+ fake_desktop_dir, fake_installed_app, monkeypatch+):+ """Failure to park the old bundle must not delete or replace it."""+ from hermes_cli import main_desktop as hermes_main++ rebuilt_exe = (+ fake_desktop_dir+ / "release"+ / "mac-arm64"+ / "Hermes.app"+ / "Contents"+ / "MacOS"+ / "Hermes"+ )+ original_rename = Path.rename++ def fail_backup_rename(path, target):+ if path == fake_installed_app:+ raise OSError("cannot move installed bundle aside")+ return original_rename(path, target)++ monkeypatch.setattr(Path, "rename", fail_backup_rename)+ with (+ patch.object(hermes_main.sys, "platform", "darwin"),+ patch.object(+ hermes_main,+ "_desktop_packaged_executable",+ return_value=rebuilt_exe,+ ),+ patch(+ "hermes_cli.gui_uninstall.packaged_gui_app_paths",+ return_value=[fake_installed_app],+ ),+ patch.object(hermes_main.shutil, "which", return_value="/usr/bin/ditto"),+ patch.object(hermes_main.subprocess, "run", side_effect=_copy_ditto_bundle),+ patch.object(hermes_main, "_macos_adhoc_sign_bundle") as mock_sign,+ ):+ result = hermes_main._install_rebuilt_desktop_app(fake_desktop_dir)++ assert result is None+ assert (+ fake_installed_app / "Contents" / "Resources" / "app.asar"+ ).read_bytes() == b"stale-asar-content"+ assert not fake_installed_app.with_name("Hermes.app.hermes-update-new").exists()+ assert not fake_installed_app.with_name("Hermes.app.hermes-update-old").exists()+ mock_sign.assert_not_called()+++def test_new_bundle_rename_failure_restores_installed_bundle(+ fake_desktop_dir, fake_installed_app, monkeypatch+):+ """Failure to install the staged bundle must roll the old bundle back."""+ from hermes_cli import main_desktop as hermes_main++ rebuilt_exe = (+ fake_desktop_dir+ / "release"+ / "mac-arm64"+ / "Hermes.app"+ / "Contents"+ / "MacOS"+ / "Hermes"+ )+ tmp = fake_installed_app.with_name("Hermes.app.hermes-update-new")+ old = fake_installed_app.with_name("Hermes.app.hermes-update-old")+ original_rename = Path.rename++ def fail_new_bundle_rename(path, target):+ if path == tmp and target == fake_installed_app:+ raise OSError("cannot move staged bundle into place")+ return original_rename(path, target)++ monkeypatch.setattr(Path, "rename", fail_new_bundle_rename)+ with (+ patch.object(hermes_main.sys, "platform", "darwin"),+ patch.object(+ hermes_main,+ "_desktop_packaged_executable",+ return_value=rebuilt_exe,+ ),+ patch(+ "hermes_cli.gui_uninstall.packaged_gui_app_paths",+ return_value=[fake_installed_app],+ ),+ patch.object(hermes_main.shutil, "which", return_value="/usr/bin/ditto"),+ patch.object(hermes_main.subprocess, "run", side_effect=_copy_ditto_bundle),+ patch.object(hermes_main, "_macos_adhoc_sign_bundle") as mock_sign,+ ):+ result = hermes_main._install_rebuilt_desktop_app(fake_desktop_dir)++ assert result is None+ assert (+ fake_installed_app / "Contents" / "Resources" / "app.asar"+ ).read_bytes() == b"stale-asar-content"+ assert not tmp.exists()+ assert not old.exists()+ mock_sign.assert_not_called()+++def test_linux_desktop_launchers_are_not_install_payloads(fake_desktop_dir, tmp_path):+ """Linux .desktop launchers must never be copytree destinations."""+ from hermes_cli import main_desktop as hermes_main++ rebuilt_exe = fake_desktop_dir / "release" / "linux-unpacked" / "hermes"+ rebuilt_exe.parent.mkdir(parents=True)+ rebuilt_exe.write_bytes(b"linux executable")+ launcher = tmp_path / "share" / "applications" / "hermes.desktop"+ launcher.parent.mkdir(parents=True)+ launcher.write_text("[Desktop Entry]\nExec=hermes\n", encoding="utf-8")++ with (+ patch.object(hermes_main.sys, "platform", "linux"),+ patch.object(+ hermes_main,+ "_desktop_packaged_executable",+ return_value=rebuilt_exe,+ ),+ patch(+ "hermes_cli.gui_uninstall.packaged_gui_app_paths",+ return_value=[launcher],+ ) as mock_paths,+ patch.object(hermes_main.shutil, "copytree") as mock_copytree,+ ):+ result = hermes_main._install_rebuilt_desktop_app(fake_desktop_dir)++ assert result is None+ assert launcher.read_text(encoding="utf-8") == "[Desktop Entry]\nExec=hermes\n"+ mock_paths.assert_not_called()+ mock_copytree.assert_not_called()diff --git a/tests/hermes_cli/test_update_desktop_stale_warning.py b/tests/hermes_cli/test_update_desktop_stale_warning.pyindex 012a40df6e2..1f01bc8a1c4 100644--- a/tests/hermes_cli/test_update_desktop_stale_warning.py+++ b/tests/hermes_cli/test_update_desktop_stale_warning.py@@ -52,6 +52,14 @@ def desktop_env(tmp_path, monkeypatch):calls["builds"] += 1return _Result(1, stdout="Error: [stage-native-deps] boom")+ @staticmethod+ def _desktop_bundle_install_supported():+ return True++ @staticmethod+ def _install_rebuilt_desktop_app(_desktop_dir):+ return None+monkeypatch.setattr(update_cmd, "_m", lambda: _FakeMain)monkeypatch.setattr("hermes_constants.with_hermes_node_path", lambda: {}, raising=False