The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): stage-and-swap the Desktop rebuild so a failed pack never removes the working app
Teknium1398c0f5ca3f
diff --git a/.gitignore b/.gitignoreindex 2d5279bca4c..7cf39fcfc9d 100644--- a/.gitignore+++ b/.gitignore@@ -109,6 +109,9 @@ apps/shared/src/**/*.jsapps/shared/src/**/*.js.mapapps/shared/src/**/*.d.tsapps/desktop/release/+# stage-and-swap Desktop rebuild output (#86443); removed after the swap, but+# a killed build must not leave the checkout dirty+apps/desktop/.staging-*/*.tsbuildinfo# Web UI assets — synced from @nous-research/ui at build time viadiff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex 6325f4bc709..1f3c15d8a2a 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -462,6 +462,7 @@ import shutilimport statimport subprocessimport tempfile+import time as _time_modfrom pathlib import Pathfrom typing import Optional@@ -7010,7 +7011,15 @@ def _write_desktop_build_stamp(project_root: Path, *, source_mode: bool) -> Nonedef _desktop_packaged_executable(desktop_dir: Path) -> Optional[Path]:"""Return the current platform's unpacked Electron app executable."""- release_dir = desktop_dir / "release"+ return _desktop_packaged_executable_in(desktop_dir / "release")+++def _desktop_packaged_executable_in(release_dir: Path) -> Optional[Path]:+ """Return the unpacked Electron app executable under *release_dir*.++ *release_dir* is electron-builder's ``directories.output`` — the live+ ``apps/desktop/release`` or a stage-and-swap staging dir (#86443).+ """if sys.platform == "darwin":candidates = list(release_dir.glob("mac*/Hermes.app/Contents/MacOS/Hermes"))elif sys.platform == "win32":@@ -7044,6 +7053,91 @@ def _desktop_packaged_executable(desktop_dir: Path) -> Optional[Path]:return max(existing, key=lambda p: p.stat().st_mtime)+# ─── Desktop stage-and-swap pack (#86443) ───────────────────────────────────+#+# electron-builder packs IN PLACE: before-pack.mjs wipes ``release/<platform>-+# unpacked`` (or the mac ``Hermes.app``) and the Electron unpack + asar + rename+# then rebuild it. Any failure after that wipe — corrupt cached zip, blocked+# download, missing dep, disk full — leaves the user with NO app, and+# ``hermes update`` used to report "partially complete" over an empty+# release/. Fix the class, not the predicate: build into a STAGING output+# dir next to release/, verify the staged result, and only then swap it over+# the live tree with renames. On any failure the live app is untouched.++_DESKTOP_STAGING_PREFIX = ".staging-"+_DESKTOP_PREVIOUS_SUFFIX = ".previous"+++def _desktop_staging_dir(desktop_dir: Path) -> Path:+ """Fresh, unique staging output dir: ``apps/desktop/.staging-<pid>-<ts>``.++ A sibling of ``release/`` (same filesystem → the swap is a rename, not a+ copy) but NOT inside it, so nothing globbing ``release/*-unpacked`` or+ ``release/mac*`` can mistake the half-built tree for the live app.+ Leftovers from a killed earlier build are swept first (best-effort).+ """+ for stale in desktop_dir.glob(f"{_DESKTOP_STAGING_PREFIX}*"):+ shutil.rmtree(stale, ignore_errors=True)+ return desktop_dir / f"{_DESKTOP_STAGING_PREFIX}{os.getpid()}-{int(_time_mod.time())}"+++def _desktop_unpacked_root(exe: Path, release_dir: Path) -> Path:+ """The directory directly under *release_dir* that holds *exe*+ (``linux-unpacked``, ``win-unpacked``, ``mac-arm64``…) — electron-builder's+ ``appOutDir``, the unit that gets swapped as a whole."""+ unpacked = exe+ while unpacked.parent != release_dir:+ if unpacked.parent == unpacked:+ raise ValueError(f"{exe} is not under {release_dir}")+ unpacked = unpacked.parent+ return unpacked+++def _swap_staged_desktop_app(desktop_dir: Path, staging_dir: Path) -> Optional[Path]:+ """Promote a VERIFIED staged pack over the live ``release/`` app.++ ``release/<unpacked>`` → ``release/<unpacked>.previous``,+ ``<staging>/<unpacked>`` → ``release/<unpacked>``, then drop ``.previous``.+ Two renames; the only window with no live app is between them, and a+ failure there rolls ``.previous`` back. Returns the live executable, or+ ``None`` (live app untouched or restored) when the swap could not happen.+ Best-effort cleanup of the staging dir; never raises.+ """+ staged_exe = _desktop_packaged_executable_in(staging_dir)+ if staged_exe is None:+ shutil.rmtree(staging_dir, ignore_errors=True)+ return None+ release_dir = desktop_dir / "release"+ try:+ staged_root = _desktop_unpacked_root(staged_exe, staging_dir)+ live_root = release_dir / staged_root.name+ previous = release_dir / (staged_root.name + _DESKTOP_PREVIOUS_SUFFIX)+ release_dir.mkdir(parents=True, exist_ok=True)+ shutil.rmtree(previous, ignore_errors=True)+ moved_aside = False+ if live_root.exists():+ os.rename(live_root, previous)+ moved_aside = True+ try:+ os.rename(staged_root, live_root)+ except OSError:+ if moved_aside:+ os.rename(previous, live_root) # restore; live app back as it was+ raise+ if moved_aside:+ shutil.rmtree(previous, ignore_errors=True)+ except (OSError, ValueError) as exc:+ logger.warning("desktop stage-and-swap failed, live app kept: %s", exc)+ return None+ finally:+ shutil.rmtree(staging_dir, ignore_errors=True)+ return live_root / staged_exe.relative_to(staged_root)+++def _discard_desktop_staging(staging_dir: Path) -> None:+ shutil.rmtree(staging_dir, ignore_errors=True)++# ─── Desktop exe integrity gate (#69179) ────────────────────────────────────## The desktop self-update chain (Desktop → hermes-setup --update →@@ -7360,8 +7454,10 @@ def _ensure_desktop_exe_launchable(# Self-heal setup for the retry: drop the (likely corrupt) cached Electron# zip and the content stamp so the next rebuild is a genuine re-download +- # re-stage rather than a replay of the same broken extraction.- _purge_electron_build_cache(desktop_dir)+ # re-stage rather than a replay of the same broken extraction. Only the+ # exe's OWN output dir is purged (a stage-and-swap staging dir, #86443),+ # never the live release/ tree that still holds the last working app.+ _purge_electron_build_cache(desktop_dir, release_dir=packaged_executable.parent.parent)try:_desktop_stamp_path().unlink()except OSError:@@ -7417,7 +7513,9 @@ def _electron_download_cache_dirs() -> list[Path]:return out-def _purge_electron_build_cache(desktop_dir: Path) -> list[Path]:+def _purge_electron_build_cache(+ desktop_dir: Path, release_dir: Optional[Path] = None+) -> list[Path]:"""Clear the cached Electron download + half-written unpacked dir so thenext ``pack`` re-downloads and re-stages from scratch.@@ -7463,8 +7561,11 @@ def _purge_electron_build_cache(desktop_dir: Path) -> list[Path]:# Drop the half-written unpacked dir too: an interrupted prior pack leaves# a partial tree that poisons the rename even after the zip is fixed.# (before-pack.cjs also handles this, but clearing it here makes the retry- # robust even if the hook is somehow skipped.)- release_dir = desktop_dir / "release"+ # robust even if the hook is somehow skipped.) ``release_dir`` lets a+ # stage-and-swap caller point this at its STAGING output so a mid-retry+ # purge never touches the live app under ``release/`` (#86443).+ if release_dir is None:+ release_dir = desktop_dir / "release"if release_dir.is_dir():for unpacked in release_dir.glob("*-unpacked"):try:@@ -7843,6 +7944,7 @@ def _desktop_macos_relaunchable_fixup(desktop_dir: Path,*,publisher_signing_configured: Optional[bool] = None,+ release_dir: Optional[Path] = None,) -> bool:"""Make a locally-built macOS desktop app survive in-place self-updatewithout resetting the user's TCC permission grants.@@ -7874,7 +7976,9 @@ def _desktop_macos_relaunchable_fixup()if publisher_signing_configured:return True- exe = _desktop_packaged_executable(desktop_dir)+ # ``release_dir`` (stage-and-swap, #86443): sign the STAGED bundle before+ # it is promoted, so the live app is never touched mid-sign.+ exe = _desktop_packaged_executable_in(release_dir or (desktop_dir / "release"))if exe is None:return True# exe = .../Hermes.app/Contents/MacOS/Hermes -> app bundle = .../Hermes.app@@ -8556,7 +8660,16 @@ def cmd_gui(args: argparse.Namespace):print(" → No Developer ID configured; ad-hoc signing this local rebuild ""(CSC_IDENTITY_AUTO_DISCOVERY=false)")npm_build_env = _npm_lifecycle_env(env)+ # Stage-and-swap (#86443): electron-builder packs IN PLACE and+ # before-pack.mjs wipes release/<unpacked> first, so a pack that+ # fails afterwards used to leave the user with NO app. Build into+ # a fresh staging output dir instead; the live release/ tree is+ # only replaced — by rename — after the staged result verifies.+ staging_dir: Optional[Path] = None+ build_cmd = [npm, "run", build_script]if not source_mode:+ staging_dir = _desktop_staging_dir(desktop_dir)+ build_cmd += ["--", f"-c.directories.output={staging_dir}"]# A running desktop instance launched from release/win-unpacked# holds Hermes.exe locked on Windows, so the pack can't replace# it ("Access is denied" / ERR_ELECTRON_BUILDER_CANNOT_EXECUTE).@@ -8565,13 +8678,17 @@ def cmd_gui(args: argparse.Namespace):stopped = _stop_desktop_processes_locking_build(desktop_dir)if stopped:print(f" ⚠ Stopped running desktop app to free the build output (pid {', '.join(map(str, stopped))})")++ def _staged_exe() -> Optional[Path]:+ return _desktop_packaged_executable_in(staging_dir) if staging_dir else None+build_result = subprocess.run(- [npm, "run", build_script], cwd=desktop_dir, env=npm_build_env, check=False+ build_cmd, cwd=desktop_dir, env=npm_build_env, check=False)if (build_result.returncode != 0and not source_mode- and _desktop_packaged_executable(desktop_dir) is None+ and _staged_exe() is None):# Corrupt cached Electron zip → partial unpack → ENOENT on rename.# stdlib zipfile won't catch the common concat-junk case, so purge@@ -8585,7 +8702,7 @@ def cmd_gui(args: argparse.Namespace):purged: list[Path] = []restored = Falseif not _electron_dist_ok(PROJECT_ROOT):- purged = _purge_electron_build_cache(desktop_dir)+ purged = _purge_electron_build_cache(desktop_dir, release_dir=staging_dir)restored = _redownload_electron_dist(PROJECT_ROOT, env)if restored:print(" ⚠ Desktop build failed; refreshed the Electron download and retrying once...")@@ -8595,13 +8712,13 @@ def cmd_gui(args: argparse.Namespace):# is still locked by a running instance; stop it before retry._stop_desktop_processes_locking_build(desktop_dir)build_result = subprocess.run(- [npm, "run", build_script], cwd=desktop_dir, env=npm_build_env, check=False+ build_cmd, cwd=desktop_dir, env=npm_build_env, check=False)if (build_result.returncode != 0and not source_modeand not env.get("ELECTRON_MIRROR")- and _desktop_packaged_executable(desktop_dir) is None+ and _staged_exe() is None):print(" ⚠ Desktop build still failing; the Electron download from ""GitHub looks blocked. Re-downloading via a public mirror "@@ -8612,9 +8729,13 @@ def cmd_gui(args: argparse.Namespace):if not _electron_dist_ok(PROJECT_ROOT):_redownload_electron_dist(PROJECT_ROOT, env, mirror=mirror)_stop_desktop_processes_locking_build(desktop_dir)- build_result = subprocess.run([npm, "run", build_script], cwd=desktop_dir, env=mirror_env, check=False)+ build_result = subprocess.run(build_cmd, cwd=desktop_dir, env=mirror_env, check=False)if build_result.returncode != 0:print("✗ Desktop GUI build failed")+ if staging_dir is not None:+ _discard_desktop_staging(staging_dir)+ if _desktop_packaged_executable(desktop_dir) is not None:+ print(" ↩ The previous desktop app was left untouched and still works.")print(f" Run manually: cd apps/desktop && npm run {build_script}")if sys.platform == "win32":print(" If this says \"Access is denied\" on Hermes.exe, close any")@@ -8622,28 +8743,37 @@ def cmd_gui(args: argparse.Namespace):print(" If the log shows Electron download retries, rebuild via a mirror:")print(" ELECTRON_MIRROR=<mirror-base-url> hermes desktop --force-build")sys.exit(build_result.returncode or 1)- packaged_executable = _desktop_packaged_executable(desktop_dir)if not source_mode:+ assert staging_dir is not None+ staged_executable = _staged_exe()# Locally-built apps are ad-hoc signed; make them relaunchable after# an in-place self-update (otherwise macOS reports "Hermes is# damaged"). No-op on non-macOS and on real-identity builds.- _desktop_macos_relaunchable_fixup(desktop_dir)+ # Signs the STAGED bundle so the live app is never half-signed.+ _desktop_macos_relaunchable_fixup(desktop_dir, release_dir=staging_dir)# Windows integrity gate (#69179): never declare the rebuild a# success on a Hermes.exe Windows cannot load (truncated PE from# a corrupt cached Electron zip, wrong-arch tree, interrupted- # rcedit rewrite). Roll back to the .bak tree preserved by- # before-pack.mjs when possible, then fail loudly so the- # updater's retry-once rebuilds from a fresh Electron download- # instead of silently shipping the broken exe.+ # rcedit rewrite). Verified on the STAGED exe: a failure here+ # simply discards the staging dir — the live app was never+ # touched — and fails loudly so the updater's retry-once+ # rebuilds from a fresh Electron download.verified_executable, rolled_back = _ensure_desktop_exe_launchable(- desktop_dir, packaged_executable+ desktop_dir, staged_executable)- if packaged_executable is not None and (- rolled_back or verified_executable is None- ):+ if staged_executable is None or rolled_back or verified_executable is None:+ _discard_desktop_staging(staging_dir)+ if staged_executable is None:+ print(f"✗ Desktop build produced no launchable app in {staging_dir}")+ print(" ↩ The previous desktop app was left untouched and still works.")+ sys.exit(1)+ # Verified: swap the staged tree over the live one (rename).+ packaged_executable = _swap_staged_desktop_app(desktop_dir, staging_dir)+ if packaged_executable is None:+ print(f"✗ Could not install the rebuilt desktop app into {desktop_dir / 'release'}")+ print(" ↩ The previous desktop app was left untouched and still works.")sys.exit(1)- packaged_executable = verified_executable# Build succeeded — write the stamp so next run can skip_write_desktop_build_stamp(PROJECT_ROOT, source_mode=source_mode)diff --git a/tests/hermes_cli/test_gui_command.py b/tests/hermes_cli/test_gui_command.pyindex 85348f9a6e4..c9f6e483e2d 100644--- a/tests/hermes_cli/test_gui_command.py+++ b/tests/hermes_cli/test_gui_command.py@@ -99,6 +99,41 @@ def _make_packaged_executable(root: Path, monkeypatch) -> Path:return exe+def _staging_dir_from(cmd) -> Path:+ """Extract the ``-c.directories.output=<dir>`` electron-builder override+ ``cmd_gui`` appends to ``npm run pack`` (stage-and-swap, #86443)."""+ for arg in cmd:+ if isinstance(arg, str) and arg.startswith("-c.directories.output="):+ return Path(arg.split("=", 1)[1])+ raise AssertionError(f"no staging output override in {cmd!r}")+++def _packaged_exe_rel() -> Path:+ """Packaged-exe path relative to electron-builder's output dir on THIS host."""+ if sys.platform == "darwin":+ return Path("mac-arm64") / "Hermes.app" / "Contents" / "MacOS" / "Hermes"+ if sys.platform == "win32":+ return Path("win-unpacked") / "Hermes.exe"+ return Path("linux-unpacked") / "hermes"+++def _pack_into_staging(root: Path, content: str = "", returncode: int = 0):+ """``subprocess.run`` side effect mimicking a real ``npm run pack``: lays+ the packaged app down inside the STAGING dir named on the command line+ (never in release/), then returns *returncode*. Non-pack commands (the+ launch) return success."""+ def _run(cmd, **kwargs):+ if len(cmd) >= 3 and cmd[1:3] == ["run", "pack"]:+ exe = _staging_dir_from(cmd) / _packaged_exe_rel()+ exe.parent.mkdir(parents=True, exist_ok=True)+ exe.write_text(content, encoding="utf-8")+ if sys.platform not in ("darwin", "win32"):+ (exe.parent / "chrome-sandbox").write_text("", encoding="utf-8")+ return subprocess.CompletedProcess(cmd, returncode)+ return subprocess.CompletedProcess(cmd, 0)+ return _run++def test_gui_installs_packages_and_launches_desktop_app(tmp_path, monkeypatch):root = _make_desktop_tree(tmp_path)desktop_dir = root / "apps" / "desktop"@@ -116,7 +151,7 @@ def test_gui_installs_packages_and_launches_desktop_app(tmp_path, monkeypatch):patch("hermes_cli.main._desktop_macos_relaunchable_fixup"), \patch("hermes_cli.main._desktop_linux_sandbox_fixup", return_value=True), \patch("hermes_cli.main._register_linux_desktop_entry"), \- patch("hermes_cli.main.subprocess.run", side_effect=[pack_ok, launch_ok]) as mock_run, \+ patch("hermes_cli.main.subprocess.run", side_effect=_pack_into_staging(root)) as mock_run, \pytest.raises(SystemExit) as exc:cli_main.cmd_gui(_ns())@@ -128,7 +163,13 @@ def test_gui_installs_packages_and_launches_desktop_app(tmp_path, monkeypatch):assert mock_install.call_args.kwargs["capture_output"] is Falseinstall_env = mock_install.call_args.kwargs["env"]assert install_env is not None and "PATH" in install_env- assert mock_run.call_args_list[0].args[0] == ["/usr/bin/npm", "run", "pack"]+ pack_cmd = mock_run.call_args_list[0].args[0]+ assert pack_cmd[:4] == ["/usr/bin/npm", "run", "pack", "--"]+ # Stage-and-swap (#86443): the pack targets a staging dir beside release/,+ # never release/ itself.+ staging = _staging_dir_from(pack_cmd)+ assert staging.parent == desktop_dir and staging.name.startswith(".staging-")+ assert not staging.exists() # swapped into release/ and cleaned upassert mock_run.call_args_list[0].kwargs["cwd"] == desktop_dirlaunched = mock_run.call_args_list[1].args[0]if sys.platform.startswith("linux"):@@ -258,23 +299,29 @@ def test_gui_does_not_retry_after_packaged_executable_exists(tmp_path, monkeypat"""root = _make_desktop_tree(tmp_path)monkeypatch.setattr(cli_main, "PROJECT_ROOT", root)- # Executable EXISTS at failure time → late failure, not a corrupt download.- _make_packaged_executable(root, monkeypatch)+ live_exe = _make_packaged_executable(root, monkeypatch)+ live_exe.write_text("good build", encoding="utf-8")monkeypatch.delenv("ELECTRON_MIRROR", raising=False)install_ok = subprocess.CompletedProcess(["npm", "ci"], 0)- pack_fail = subprocess.CompletedProcess(["npm", "run", "pack"], 1)+ # Executable EXISTS in the STAGING output at failure time → late failure+ # (e.g. signing), not a corrupt download. With stage-and-swap (#86443) the+ # discriminator reads the staging dir, so the fake pack lays it down there.+ pack_fail = _pack_into_staging(root, content="half-signed", returncode=1)with patch("hermes_cli.main.shutil.which", return_value="/usr/bin/npm"), \patch("hermes_cli.main._run_npm_install_deterministic", return_value=install_ok), \patch("hermes_cli.main._desktop_macos_relaunchable_fixup"), \patch("hermes_cli.main._purge_electron_build_cache", return_value=[Path("/c/electron.zip")]) as mock_purge, \patch("hermes_cli.main._redownload_electron_dist", return_value=True) as mock_dl, \- patch("hermes_cli.main.subprocess.run", return_value=pack_fail) as mock_run, \+ patch("hermes_cli.main.subprocess.run", side_effect=pack_fail) as mock_run, \pytest.raises(SystemExit) as exc:cli_main.cmd_gui(_ns())assert exc.value.code == 1+ # The live app was never touched by the failed pack (#86443).+ assert live_exe.read_text(encoding="utf-8") == "good build"+ assert not list((root / "apps" / "desktop").glob(".staging-*"))# Neither destructive recovery runs, and there is exactly ONE pack attempt.mock_purge.assert_not_called()mock_dl.assert_not_called()@@ -1062,7 +1109,7 @@ def test_gui_bridges_ozone_hint_to_launch_env(tmp_path, monkeypatch):patch("hermes_cli.main._desktop_linux_sandbox_fixup", return_value=True), \patch("hermes_cli.config.load_config", return_value=cfg), \patch("hermes_cli.linux_desktop_entry.install_desktop_entry", return_value=None), \- patch("hermes_cli.main.subprocess.run", side_effect=[ok, ok]) as mock_run, \+ patch("hermes_cli.main.subprocess.run", side_effect=_pack_into_staging(root)) as mock_run, \pytest.raises(SystemExit):cli_main.cmd_gui(_ns())@@ -1078,7 +1125,7 @@ def test_gui_bridges_ozone_hint_to_launch_env(tmp_path, monkeypatch):patch("hermes_cli.main._desktop_linux_sandbox_fixup", return_value=True), \patch("hermes_cli.config.load_config", return_value=cfg), \patch("hermes_cli.linux_desktop_entry.install_desktop_entry", return_value=None), \- patch("hermes_cli.main.subprocess.run", side_effect=[ok, ok]) as mock_run2, \+ patch("hermes_cli.main.subprocess.run", side_effect=_pack_into_staging(root)) as mock_run2, \pytest.raises(SystemExit):cli_main.cmd_gui(_ns())@@ -1160,7 +1207,7 @@ def test_gui_linux_packaged_launch_bridges_detected_password_store(tmp_path, monpatch("hermes_cli.config.load_config", return_value={}), \patch("hermes_cli.linux_desktop_entry.install_desktop_entry", return_value=None), \patch("hermes_cli.main._detect_linux_password_store", return_value="gnome-libsecret"), \- patch("hermes_cli.main.subprocess.run", side_effect=[ok, ok]) as mock_run, \+ patch("hermes_cli.main.subprocess.run", side_effect=_pack_into_staging(root)) as mock_run, \pytest.raises(SystemExit):cli_main.cmd_gui(_ns())@@ -1183,7 +1230,7 @@ def test_gui_linux_source_launch_bridges_detected_password_store(tmp_path, monkepatch("hermes_cli.config.load_config", return_value={}), \patch("hermes_cli.linux_desktop_entry.install_desktop_entry", return_value=None), \patch("hermes_cli.main._detect_linux_password_store", return_value="kwallet6"), \- patch("hermes_cli.main.subprocess.run", side_effect=[ok, ok]) as mock_run, \+ patch("hermes_cli.main.subprocess.run", side_effect=_pack_into_staging(root)) as mock_run, \pytest.raises(SystemExit):cli_main.cmd_gui(_ns(source=True))@@ -1211,7 +1258,7 @@ def test_gui_config_password_store_skips_detection(tmp_path, monkeypatch):patch("hermes_cli.config.load_config", return_value=cfg), \patch("hermes_cli.linux_desktop_entry.install_desktop_entry", return_value=None), \patch("hermes_cli.main._detect_linux_password_store") as mock_detect, \- patch("hermes_cli.main.subprocess.run", side_effect=[ok, ok]) as mock_run, \+ patch("hermes_cli.main.subprocess.run", side_effect=_pack_into_staging(root)) as mock_run, \pytest.raises(SystemExit):cli_main.cmd_gui(_ns())@@ -1240,7 +1287,7 @@ def test_gui_explicit_password_store_env_wins_over_config_and_detection(tmp_pathpatch("hermes_cli.config.load_config", return_value=cfg), \patch("hermes_cli.linux_desktop_entry.install_desktop_entry", return_value=None), \patch("hermes_cli.main._detect_linux_password_store") as mock_detect, \- patch("hermes_cli.main.subprocess.run", side_effect=[ok, ok]) as mock_run, \+ patch("hermes_cli.main.subprocess.run", side_effect=_pack_into_staging(root)) as mock_run, \pytest.raises(SystemExit):cli_main.cmd_gui(_ns())@@ -1266,10 +1313,178 @@ def test_gui_password_store_bridge_is_linux_only(tmp_path, monkeypatch):patch("hermes_cli.config.load_config", return_value={}), \patch("hermes_cli.linux_desktop_entry.install_desktop_entry", return_value=None), \patch("hermes_cli.main._detect_linux_password_store") as mock_detect, \- patch("hermes_cli.main.subprocess.run", side_effect=[ok, ok]) as mock_run, \+ patch("hermes_cli.main.subprocess.run", side_effect=_pack_into_staging(root)) as mock_run, \pytest.raises(SystemExit):cli_main.cmd_gui(_ns())mock_detect.assert_not_called()launch_env = mock_run.call_args_list[1].kwargs["env"]assert "HERMES_DESKTOP_PASSWORD_STORE" not in launch_env+++# ---------------------------------------------------------------------------+# #86443: stage-and-swap — a failed Desktop rebuild must never remove the+# working app. electron-builder packs IN PLACE (before-pack.mjs wipes+# release/<unpacked> first), so cmd_gui now packs into a staging dir and only+# renames it over release/ after the staged result verifies.+# ---------------------------------------------------------------------------+++def _gui_build_patches(root: Path, run_side_effect):+ return [+ patch("hermes_cli.main.shutil.which", return_value="/usr/bin/npm"),+ patch("hermes_cli.main._run_npm_install_deterministic",+ return_value=subprocess.CompletedProcess(["npm", "ci"], 0)),+ patch("hermes_cli.main._desktop_build_needed", return_value=True),+ patch("hermes_cli.main._write_desktop_build_stamp"),+ patch("hermes_cli.main._desktop_macos_relaunchable_fixup"),+ patch("hermes_cli.main._register_linux_desktop_entry"),+ patch("hermes_cli.main._stop_desktop_processes_locking_build", return_value=[]),+ patch("hermes_cli.main._purge_electron_build_cache", return_value=[]),+ patch("hermes_cli.main._redownload_electron_dist", return_value=False),+ patch("hermes_cli.main.subprocess.run", side_effect=run_side_effect),+ ]+++def test_swap_staged_desktop_app_promotes_staged_tree_and_drops_previous(tmp_path):+ root = _make_desktop_tree(tmp_path)+ desktop_dir = root / "apps" / "desktop"+ live_exe = desktop_dir / "release" / _packaged_exe_rel()+ live_exe.parent.mkdir(parents=True)+ live_exe.write_text("old", encoding="utf-8")+ staging = cli_main._desktop_staging_dir(desktop_dir)+ staged_exe = staging / _packaged_exe_rel()+ staged_exe.parent.mkdir(parents=True)+ staged_exe.write_text("new", encoding="utf-8")++ promoted = cli_main._swap_staged_desktop_app(desktop_dir, staging)++ assert promoted == live_exe+ assert live_exe.read_text(encoding="utf-8") == "new"+ assert not staging.exists()+ assert sorted(p.name for p in (desktop_dir / "release").iterdir()) == [_packaged_exe_rel().parts[0]]+++def test_swap_staged_desktop_app_without_staged_exe_keeps_live_app(tmp_path):+ """Zero-exit pack that produced nothing: live app untouched, staging gone."""+ root = _make_desktop_tree(tmp_path)+ desktop_dir = root / "apps" / "desktop"+ live_exe = desktop_dir / "release" / _packaged_exe_rel()+ live_exe.parent.mkdir(parents=True)+ live_exe.write_text("old", encoding="utf-8")+ staging = cli_main._desktop_staging_dir(desktop_dir)+ (staging / "linux-unpacked" / "resources").mkdir(parents=True) # partial tree, no exe++ assert cli_main._swap_staged_desktop_app(desktop_dir, staging) is None+ assert live_exe.read_text(encoding="utf-8") == "old"+ assert not staging.exists()+++def test_swap_staged_desktop_app_rolls_back_when_second_rename_fails(tmp_path, monkeypatch):+ root = _make_desktop_tree(tmp_path)+ desktop_dir = root / "apps" / "desktop"+ live_exe = desktop_dir / "release" / _packaged_exe_rel()+ live_exe.parent.mkdir(parents=True)+ live_exe.write_text("old", encoding="utf-8")+ staging = cli_main._desktop_staging_dir(desktop_dir)+ staged_exe = staging / _packaged_exe_rel()+ staged_exe.parent.mkdir(parents=True)+ staged_exe.write_text("new", encoding="utf-8")++ real_rename = cli_main.os.rename+ calls = {"n": 0}++ def flaky_rename(src, dst):+ calls["n"] += 1+ if calls["n"] == 2: # staged → live+ raise OSError("EXDEV simulated")+ return real_rename(src, dst)++ monkeypatch.setattr(cli_main.os, "rename", flaky_rename)+ assert cli_main._swap_staged_desktop_app(desktop_dir, staging) is None+ assert live_exe.read_text(encoding="utf-8") == "old"+ assert not (live_exe.parent.parent / (live_exe.parent.name + ".previous")).exists()+++def test_gui_failed_pack_leaves_previous_app_untouched(tmp_path, monkeypatch, capsys):+ """Every pack attempt fails → the pre-existing app is exactly as it was,+ no staging dir remains, exit is non-zero."""+ root = _make_desktop_tree(tmp_path)+ desktop_dir = root / "apps" / "desktop"+ monkeypatch.setattr(cli_main, "PROJECT_ROOT", root)+ live_exe = _make_packaged_executable(root, monkeypatch)+ live_exe.write_text("good build", encoding="utf-8")+ monkeypatch.setenv("ELECTRON_MIRROR", "https://example.test/electron/")++ def failing_pack(cmd, **kwargs):+ # Mimic before-pack.mjs wiping appOutDir inside the OUTPUT dir it was+ # given, then dying (corrupt Electron zip → ENOENT on rename).+ out = _staging_dir_from(cmd) / _packaged_exe_rel().parts[0]+ out.mkdir(parents=True, exist_ok=True)+ (out / "resources").mkdir(exist_ok=True)+ return subprocess.CompletedProcess(cmd, 1)++ patches = _gui_build_patches(root, failing_pack)+ for p in patches:+ p.start()+ try:+ with pytest.raises(SystemExit) as exc:+ cli_main.cmd_gui(_ns(build_only=True))+ finally:+ for p in patches:+ p.stop()++ assert exc.value.code == 1+ assert live_exe.read_text(encoding="utf-8") == "good build"+ assert not list(desktop_dir.glob(".staging-*"))+ assert not list((desktop_dir / "release").glob("*.previous"))+ out = capsys.readouterr().out+ assert "previous desktop app was left untouched" in out+++def test_gui_successful_pack_swaps_new_app_into_release(tmp_path, monkeypatch):+ root = _make_desktop_tree(tmp_path)+ desktop_dir = root / "apps" / "desktop"+ monkeypatch.setattr(cli_main, "PROJECT_ROOT", root)+ live_exe = _make_packaged_executable(root, monkeypatch)+ live_exe.write_text("old build", encoding="utf-8")++ patches = _gui_build_patches(root, _pack_into_staging(root, content="new build"))+ for p in patches:+ p.start()+ try:+ cli_main.cmd_gui(_ns(build_only=True))+ finally:+ for p in patches:+ p.stop()++ assert live_exe.read_text(encoding="utf-8") == "new build"+ assert not list(desktop_dir.glob(".staging-*"))+ assert not list((desktop_dir / "release").glob("*.previous"))+++def test_gui_zero_exit_pack_without_artifact_keeps_previous_app(tmp_path, monkeypatch, capsys):+ root = _make_desktop_tree(tmp_path)+ desktop_dir = root / "apps" / "desktop"+ monkeypatch.setattr(cli_main, "PROJECT_ROOT", root)+ live_exe = _make_packaged_executable(root, monkeypatch)+ live_exe.write_text("good build", encoding="utf-8")++ def empty_pack(cmd, **kwargs):+ _staging_dir_from(cmd).mkdir(parents=True, exist_ok=True)+ return subprocess.CompletedProcess(cmd, 0)++ patches = _gui_build_patches(root, empty_pack)+ for p in patches:+ p.start()+ try:+ with pytest.raises(SystemExit) as exc:+ cli_main.cmd_gui(_ns(build_only=True))+ finally:+ for p in patches:+ p.stop()++ assert exc.value.code == 1+ assert live_exe.read_text(encoding="utf-8") == "good build"+ assert not list(desktop_dir.glob(".staging-*"))+ assert "produced no launchable app" in capsys.readouterr().outdiff --git a/website/docs/getting-started/updating.md b/website/docs/getting-started/updating.mdindex 5ae1f14787f..8c20bc1558d 100644--- a/website/docs/getting-started/updating.md+++ b/website/docs/getting-started/updating.md@@ -29,7 +29,8 @@ When you run `hermes update`, the following steps occur:3. **Post-pull syntax validation + auto-rollback** — after the pull, Hermes compiles the nine critical files every `hermes` invocation imports at startup. If any fails to parse (e.g. an orphan merge-conflict marker, an accidentally truncated file), Hermes runs `git reset --hard <pre-pull-sha>` to roll the install back so your shell stays bootable. Re-run `hermes update` once the upstream fix lands.4. **Dependency install** — runs `uv pip install -e ".[all]"` to pick up new or changed dependencies5. **Config migration** — detects new config options added since your version and prompts you to set them-6. **Gateway auto-restart** — running gateways are refreshed after the update completes so the new code takes effect immediately. Service-managed gateways (systemd on Linux, launchd on macOS) are restarted through the service manager. Manual gateways are relaunched automatically when Hermes can map the running PID back to a profile. Manually-launched `hermes serve` / `hermes dashboard` backends (for example a network-bound serve powering a remote Desktop) are handled the same way: each backend records its bind address in the install's spawn ledger at startup, so the update stops it before the code swap and relaunches it afterward on the **same host and port** — a remote Desktop pointed at that endpoint reconnects instead of stranding. Backends owned by a running Desktop app are left to the app's own respawn.+6. **Desktop rebuild (stage-and-swap)** — if the Hermes Desktop app was built from this checkout, it is rebuilt so the GUI matches the new code. The rebuild packs into a temporary staging directory next to `apps/desktop/release/`, verifies the staged app, and only then renames it over the previous build. A rebuild that fails at any point — corrupt Electron download, missing dependency, disk full — leaves the previous app untouched and launchable; the update reports `⚠ Update partially complete` and `hermes desktop` retries the rebuild.+7. **Gateway auto-restart** — running gateways are refreshed after the update completes so the new code takes effect immediately. Service-managed gateways (systemd on Linux, launchd on macOS) are restarted through the service manager. Manual gateways are relaunched automatically when Hermes can map the running PID back to a profile. Manually-launched `hermes serve` / `hermes dashboard` backends (for example a network-bound serve powering a remote Desktop) are handled the same way: each backend records its bind address in the install's spawn ledger at startup, so the update stops it before the code swap and relaunches it afterward on the **same host and port** — a remote Desktop pointed at that endpoint reconnects instead of stranding. Backends owned by a running Desktop app are left to the app's own respawn.### Updating against a non-default branch: `--branch`