The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): serialize the mutable build preflight behind a cross-process lock
Brooklyn Nicholson749ef18b16ec
diff --git a/hermes_cli/desktop_build_lock.py b/hermes_cli/desktop_build_lock.pynew file mode 100644index 00000000000..52be66e0931--- /dev/null+++ b/hermes_cli/desktop_build_lock.py@@ -0,0 +1,97 @@+"""Cross-process serialization for the mutable Desktop build preflight."""++from __future__ import annotations++import hashlib+import os+from pathlib import Path+from typing import IO+++class DesktopBuildLock:+ """Advisory lock held while npm installs and packages Hermes Desktop.++ ``node_modules`` and ``apps/desktop/release`` are checkout-scoped even+ when two commands use different Hermes profiles. The lock therefore+ lives under the profile-common Hermes root and is keyed by the resolved+ checkout path. Keeping it out of the checkout preserves ``--skip-build``+ launches from read-only/prebuilt source trees. The open handle owns the+ lock, so the OS releases it automatically if a builder crashes.+ """++ def __init__(self, project_root: Path) -> None:+ from hermes_constants import get_default_hermes_root++ resolved = os.path.normcase(str(project_root.resolve(strict=False)))+ checkout_key = hashlib.sha256(resolved.encode("utf-8")).hexdigest()[:24]+ self.path = get_default_hermes_root() / "locks" / f"desktop-build-{checkout_key}.lock"+ self._handle: IO[str] | None = None++ def acquire(self, *, wait: bool = False) -> bool:+ """Acquire the lock; queue behind the current holder when ``wait``.++ Returns ``False`` only when another process owns the lock and ``wait``+ is unset. Filesystem errors propagate so callers fail explicitly+ instead of silently falling back to the corrupting concurrent+ behavior.+ """+ if self._handle is not None:+ return True++ from gateway.status import _try_acquire_file_lock++ self.path.parent.mkdir(parents=True, exist_ok=True)+ handle = self.path.open("a+", encoding="utf-8")+ if _try_acquire_file_lock(handle):+ self._handle = handle+ return True+ if not wait:+ handle.close()+ return False++ # Blocking mode queues behind the holder; say so instead of appearing+ # to hang with no output (the update path would rather wait for the+ # in-flight build it depends on than fail the update).+ print("→ Waiting for another Hermes desktop dependency install or build to finish...")+ print(f" Lock: {self.path}")+ from gateway.status import _release_file_lock++ try:+ import fcntl++ fcntl.flock(handle.fileno(), fcntl.LOCK_EX)+ except ImportError:+ # Windows has no fcntl; gateway.status's non-blocking try below is+ # the best-effort serialization there (msvcrt.locking), so poll it.+ import time++ while True:+ if _try_acquire_file_lock(handle):+ self._handle = handle+ return True+ _release_file_lock(handle)+ time.sleep(1.0)+ self._handle = handle+ return True++ def release(self) -> None:+ """Release the lock when held. Safe to call more than once."""+ handle = self._handle+ if handle is None:+ return+ self._handle = None++ try:+ from gateway.status import _release_file_lock++ _release_file_lock(handle)+ finally:+ handle.close()++ def __enter__(self) -> "DesktopBuildLock":+ if not self.acquire():+ raise RuntimeError("desktop build lock is already held")+ return self++ def __exit__(self, *_exc: object) -> None:+ self.release()diff --git a/hermes_cli/main_desktop.py b/hermes_cli/main_desktop.pyindex 172e5d005ce..6b59fa966ad 100644--- a/hermes_cli/main_desktop.py+++ b/hermes_cli/main_desktop.py@@ -1792,6 +1792,27 @@ def cmd_gui(args: argparse.Namespace):packaged_executable = _desktop_packaged_executable(desktop_dir)+ # The mutable preflight (freshness check → npm install → pack) mutates+ # checkout-scoped node_modules and apps/desktop/release. Serialize it+ # across processes so a manual `hermes desktop` racing `hermes update`'s+ # rebuild cannot corrupt either (#93940). The lock lives outside the+ # checkout, keyed by the resolved checkout path.+ from hermes_cli.desktop_build_lock import DesktopBuildLock++ build_lock: DesktopBuildLock | None = None+ if not bundled and not skip_build:+ build_lock = DesktopBuildLock(PROJECT_ROOT)+ try:+ acquired = build_lock.acquire()+ except OSError as exc:+ print(f"✗ Could not create the desktop build lock: {exc}")+ print(" Refusing to run npm without serialization; check the checkout permissions and retry.")+ sys.exit(1)+ if not acquired:+ print("✗ Another Hermes desktop dependency install or build is already running.")+ print(" Wait for it to finish, then retry.")+ sys.exit(2)+needs_build = not skip_build and (force_build or _desktop_build_needed(desktop_dir, PROJECT_ROOT, source_mode=source_mode))@@ -1817,6 +1838,8 @@ def cmd_gui(args: argparse.Namespace):desktop_launch_notice(f"✓ Desktop {build_label} is up to date (content stamp matches)", source_mode=source_mode)except (OSError, subprocess.SubprocessError, RuntimeError) as exc:print(f"✗ Desktop GUI build failed: {exc}")+ if build_lock is not None:+ build_lock.release()raise SystemExit(1) from exc# Best-effort and idempotent; a failure must never stop the app from launching.@@ -1844,6 +1867,8 @@ def cmd_gui(args: argparse.Namespace):sys.exit(1)else:print(f"✓ Desktop packaged app ready: {packaged_executable} (not launching; --build-only)")+ if build_lock is not None:+ build_lock.release()returnif source_mode:@@ -1878,6 +1903,11 @@ def cmd_gui(args: argparse.Namespace):launch_command.extend(_explicit_profile_args())if not source_mode:desktop_launch_notice(f"→ Launching packaged Hermes Desktop: {' '.join(launch_command)}")+ # The launch target is ready; the fixups above finished mutating the+ # packaged tree. Electron is the long-lived handoff, so release the build+ # lock now — an open Desktop window must never block a future rebuild.+ if build_lock is not None:+ build_lock.release()pass_fds: tuple[int, ...] = ()if deferred_entry is not None:env = deferred_entry.child_env(env)diff --git a/hermes_cli/source_build.py b/hermes_cli/source_build.pyindex e9eae057937..d7a6e0743da 100644--- a/hermes_cli/source_build.py+++ b/hermes_cli/source_build.py@@ -124,10 +124,22 @@ def build_update_products(project_root: Path, *, desktop: bool) -> None:from hermes_cli.main_desktop import _refresh_installed_desktop_apps, build_prepared_desktoppublish_stage("Building the desktop app")- build_prepared_desktop(- project_root / "apps/desktop", source_mode=False,- npm=shutil.which("npm", path=env["PATH"]), env=env, icons=project_root,- )+ # The desktop build mutates checkout-scoped node_modules and+ # apps/desktop/release; serialize it against a concurrent manual+ # `hermes desktop` (#93940). The update path waits rather than exits:+ # the in-flight build it queues behind produces the same fresh tree+ # this update needs.+ from hermes_cli.desktop_build_lock import DesktopBuildLock++ build_lock = DesktopBuildLock(project_root)+ build_lock.acquire(wait=True)+ try:+ build_prepared_desktop(+ project_root / "apps/desktop", source_mode=False,+ npm=shutil.which("npm", path=env["PATH"]), env=env, icons=project_root,+ )+ finally:+ build_lock.release()# A current release/ can still sit beside a stale installed copy (an earlier# update rebuilt but never installed); healing must not wait for the next build._refresh_installed_desktop_apps(project_root / "apps/desktop")diff --git a/tests/hermes_cli/test_desktop_build_lock.py b/tests/hermes_cli/test_desktop_build_lock.pynew file mode 100644index 00000000000..af4f73ce367--- /dev/null+++ b/tests/hermes_cli/test_desktop_build_lock.py@@ -0,0 +1,231 @@+"""Behavior tests for the Desktop build's cross-process lock."""++from __future__ import annotations++import argparse+import subprocess+import sys+from pathlib import Path+from unittest.mock import patch++import pytest++from hermes_cli import main_desktop as cli_desktop+from hermes_cli.desktop_build_lock import DesktopBuildLock+++def _checkout(tmp_path: Path) -> Path:+ root = tmp_path / "hermes-agent"+ desktop_dir = root / "apps" / "desktop"+ desktop_dir.mkdir(parents=True)+ (desktop_dir / "package.json").write_text("{}", encoding="utf-8")+ return root+++def _args(**overrides) -> argparse.Namespace:+ base = dict(+ build_only=False,+ cwd=None,+ fake_boot=False,+ force_build=False,+ hermes_root=None,+ ignore_existing=False,+ local=False,+ skip_build=False,+ source=False,+ setup_tcc_identity=False,+ )+ base.update(overrides)+ return argparse.Namespace(**base)+++def test_desktop_build_lock_is_exclusive_and_reacquirable(tmp_path):+ first = DesktopBuildLock(tmp_path)+ contender = DesktopBuildLock(tmp_path)++ assert first.acquire() is True+ try:+ assert contender.acquire() is False+ finally:+ first.release()++ assert contender.acquire() is True+ contender.release()+++def test_desktop_build_lock_excludes_another_process(tmp_path):+ holder = DesktopBuildLock(tmp_path)+ assert holder.acquire() is True++ probe = (+ "import sys\n"+ "from pathlib import Path\n"+ "from hermes_cli.desktop_build_lock import DesktopBuildLock\n"+ "lock = DesktopBuildLock(Path(sys.argv[1]))\n"+ "raise SystemExit(0 if lock.acquire() else 23)\n"+ )+ try:+ result = subprocess.run(+ [sys.executable, "-c", probe, str(tmp_path)],+ check=False,+ )+ finally:+ holder.release()++ assert result.returncode == 23+++def test_desktop_build_lock_releases_after_exception(tmp_path):+ try:+ with DesktopBuildLock(tmp_path):+ raise ValueError("build failed")+ except ValueError:+ pass++ successor = DesktopBuildLock(tmp_path)+ assert successor.acquire() is True+ successor.release()+++def test_desktop_build_lock_is_keyed_by_checkout(tmp_path):+ """Two different checkouts must not share one lock: node_modules and release/ are checkout-scoped."""+ other = tmp_path / "hermes-agent-2"+ other.mkdir()+ first = DesktopBuildLock(tmp_path)+ second = DesktopBuildLock(other)++ assert first.acquire() is True+ try:+ assert second.acquire() is True+ finally:+ first.release()+ second.release()+ assert first.path != second.path+++def test_gui_reports_missing_source_before_constructing_build_lock(tmp_path, monkeypatch, capsys):+ root = tmp_path / "broken-hermes-agent"+ monkeypatch.setattr("hermes_cli.main.PROJECT_ROOT", root, raising=False)++ args = argparse.Namespace()+ with patch(+ "hermes_cli.desktop_build_lock.DesktopBuildLock",+ side_effect=AssertionError("build lock constructed before source validation"),+ ), pytest.raises(SystemExit) as exc:+ cli_desktop.cmd_gui(args)++ assert exc.value.code == 1+ assert capsys.readouterr().out.strip() == (+ f"Desktop GUI source not found at: {root / 'apps' / 'desktop'}"+ )+++def test_gui_refuses_contended_build_before_checking_freshness(tmp_path, monkeypatch):+ root = _checkout(tmp_path)+ monkeypatch.setattr("hermes_cli.main.PROJECT_ROOT", root, raising=False)++ holder = DesktopBuildLock(root)+ assert holder.acquire() is True+ try:+ with patch(+ "hermes_cli.main_desktop._desktop_build_needed",+ side_effect=AssertionError("freshness check ran without the build lock"),+ ), pytest.raises(SystemExit) as exc:+ cli_desktop.cmd_gui(_args())+ finally:+ holder.release()++ assert exc.value.code == 2+++def test_gui_releases_lock_before_packaged_electron_handoff(tmp_path, monkeypatch):+ root = _checkout(tmp_path)+ desktop_dir = root / "apps" / "desktop"++ if sys.platform == "darwin":+ executable = desktop_dir / "release" / "mac-arm64" / "Hermes.app" / "Contents" / "MacOS" / "Hermes"+ elif sys.platform == "win32":+ executable = desktop_dir / "release" / "win-unpacked" / "Hermes.exe"+ else:+ executable = desktop_dir / "release" / "linux-unpacked" / "hermes"+ executable.parent.mkdir(parents=True)+ executable.write_text("", encoding="utf-8")++ monkeypatch.setattr("hermes_cli.main.PROJECT_ROOT", root, raising=False)++ def launch_after_lock_release(*_args, **_kwargs):+ handoff_probe = DesktopBuildLock(root)+ assert handoff_probe.acquire() is True, "build lock was not released before the Electron handoff"+ handoff_probe.release()+ return subprocess.CompletedProcess([], 0)++ with patch("hermes_cli.main_desktop._desktop_launch_env", return_value=({}, [])), \+ patch("hermes_cli.main_desktop._register_linux_desktop_entry", return_value=None), \+ patch("hermes_cli.main_desktop.subprocess.run", side_effect=launch_after_lock_release), \+ patch("hermes_cli.main_desktop._desktop_build_needed", return_value=False), \+ pytest.raises(SystemExit) as exc:+ cli_desktop.cmd_gui(_args(skip_build=True))++ assert exc.value.code == 0+++def test_gui_releases_lock_after_build_failure(tmp_path, monkeypatch, capsys):+ """A failed build must not deadlock the next `hermes desktop`."""+ root = _checkout(tmp_path)+ monkeypatch.setattr("hermes_cli.main.PROJECT_ROOT", root, raising=False)++ def failing_build(*_args, **_kwargs):+ raise RuntimeError("tsc missing: ENOTEMPTY node_modules race")++ with patch("hermes_cli.main_desktop._desktop_launch_env", return_value=({}, [])), \+ patch("hermes_cli.main_desktop._desktop_build_needed", return_value=True), \+ patch("hermes_cli.main_desktop.build_prepared_desktop", side_effect=failing_build), \+ pytest.raises(SystemExit) as exc:+ cli_desktop.cmd_gui(_args(build_only=True))++ assert exc.value.code == 1+ successor = DesktopBuildLock(root)+ assert successor.acquire() is True, "build lock was not released after a failed build"+ successor.release()+++def test_update_path_waits_for_a_held_lock(tmp_path, monkeypatch, capsys):+ """`hermes update`'s desktop rebuild queues behind a holder instead of failing the update."""+ from hermes_cli import source_build as source_build_mod+ from hermes_cli.main_desktop import _refresh_installed_desktop_apps++ root = _checkout(tmp_path)++ holder = DesktopBuildLock(root)+ assert holder.acquire() is True++ release_calls: list[bool] = []++ class _ReleaseOnEnter(DesktopBuildLock):+ def acquire(self, *, wait: bool = False) -> bool:+ release_calls.append(wait)+ # Simulate the holder finishing while we wait: release, then succeed.+ holder.release()+ return super().acquire(wait=wait)++ built: list[bool] = []++ def fake_build_prepared_desktop(desktop_dir, *, source_mode, npm, env, icons=None):+ built.append(True)+ return None++ monkeypatch.setattr(source_build_mod, "_install_configured_features_missing_deps", lambda *_: None, raising=False)+ monkeypatch.setattr(source_build_mod, "source_frontends", lambda _root: ("ui-tui", "web"), raising=False)+ monkeypatch.setattr(source_build_mod, "source_build_env", lambda **_kw: {"PATH": "/usr/bin"}, raising=False)+ monkeypatch.setattr(source_build_mod, "prepare_source_dependencies", lambda *_a, **_kw: None, raising=False)+ monkeypatch.setattr(source_build_mod, "build_source_tui", lambda *_a, **_kw: None, raising=False)+ monkeypatch.setattr(source_build_mod, "build_source_web", lambda *_a, **_kw: None, raising=False)+ monkeypatch.setattr(source_build_mod, "_refresh_installed_desktop_apps", lambda *_a, **_kw: None, raising=False)+ monkeypatch.setattr("hermes_cli.desktop_build_lock.DesktopBuildLock", _ReleaseOnEnter)+ monkeypatch.setattr("hermes_cli.main_desktop.build_prepared_desktop", fake_build_prepared_desktop)+ monkeypatch.setattr("hermes_cli.update_stage.publish_stage", lambda _s: None, raising=False)++ source_build_mod.build_update_products(root, desktop=True)++ assert release_calls == [True], "update path must acquire the lock in wait mode"+ assert built == [True]