The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): the Windows update tail never stops the Desktop it runs under
John Paul Soliva5188378e25ac
diff --git a/hermes_cli/main_desktop.py b/hermes_cli/main_desktop.pyindex c53d5b8ec49..9453fa2c464 100644--- a/hermes_cli/main_desktop.py+++ b/hermes_cli/main_desktop.py@@ -410,6 +410,32 @@ def _electron_dir(project_root: Path) -> Path:return project_root / "node_modules" / "electron"+def _runs_from(proc, release_dir: Path) -> bool:+ """True when *proc*'s executable lives inside *release_dir* (False when it cannot be read)."""+ try:+ return release_dir in Path(proc.exe()).resolve().parents+ except Exception:+ return False+++def _desktop_ancestor_in(desktop_dir: Path) -> Optional[int]:+ """PID of a Desktop from this build's ``release`` tree that is one of OUR ancestors, else None.++ That Desktop is running this process (its backend's launch-time update tail, or a+ `hermes update` it spawned). On Windows it holds the exe lock the promotion rename+ needs, and it cannot be stopped without killing this process first. Never raises."""+ try:+ import psutil+ release_dir = (desktop_dir / "release").resolve()+ ancestors = list(psutil.Process(os.getpid()).parents())+ except Exception:+ return None+ for parent in ancestors:+ if _runs_from(parent, release_dir):+ return int(parent.pid)+ return None++def _stop_desktop_processes_locking_build(desktop_dir: Path, *, also_posix: bool = False) -> list[int]:"""Terminate a running desktop app whose exe lives INSIDE this build's ``release`` tree.@@ -429,13 +455,17 @@ def _stop_desktop_processes_locking_build(desktop_dir: Path, *, also_posix: boolreturn []me = os.getpid()- # On POSIX, never stop a Desktop that is one of OUR ancestors. A- # historical Desktop (v2026.7.1 Linux in-app update) runs `hermes update`- # as a child with piped stdout/stderr and owns the post-update rebuild and- # relaunch. Killing it breaks those pipes (EPIPE fails the update) and- # leaves nobody to relaunch. It also outlives the swap safely because it- # relaunches itself afterwards. Windows keeps stopping it: there, the exe- # lock would make the rename fail anyway.+ # Never stop a Desktop that is one of OUR ancestors, on any platform: this+ # process lives in its tree. A historical Desktop (v2026.7.1 Linux in-app+ # update) runs `hermes update` as a child with piped stdout/stderr and owns+ # the post-update rebuild and relaunch. Killing it breaks those pipes (EPIPE+ # fails the update) and leaves nobody to relaunch. On Windows the same holds+ # for the launch-time tail a Desktop's own backend runs+ # (venv_sync._finish_source_update): stopping that Desktop took the whole+ # tree down with it before the tail could clear its markers, so every+ # launch repeated it (#123499). The exe lock that stop was meant to free+ # cannot be freed by the process that holds it alive; build_prepared_desktop+ # skips that doomed build instead (_desktop_ancestor_in).## Spare that Desktop's whole process tree, not just its main process. Its# zygote, renderer, GPU and network-service helpers run the same release@@ -444,23 +474,18 @@ def _stop_desktop_processes_locking_build(desktop_dir: Path, *, also_posix: bool# quit, so it outlives the update forever. (That is the v2026.7.1 Linux# in-app update E2E: the receipt succeeds and then the app hangs.)spared: set[int] = set()- if sys.platform != "win32":- try:- ancestors = list(psutil.Process(me).parents())- except Exception:- ancestors = []- for parent in ancestors:- spared.add(parent.pid)- try:- parent_exe = Path(parent.exe()).resolve()- except Exception:- continue- # Only a Desktop ancestor's descendants. Every process descends from- # init, so sparing all ancestors' trees would spare everything.- if release_dir not in parent_exe.parents:- continue- with contextlib.suppress(Exception):- spared.update(child.pid for child in parent.children(recursive=True))+ try:+ ancestors = list(psutil.Process(me).parents())+ except Exception:+ ancestors = []+ for parent in ancestors:+ spared.add(parent.pid)+ # Only a Desktop ancestor's descendants. Every process descends from+ # init, so sparing all ancestors' trees would spare everything.+ if not _runs_from(parent, release_dir):+ continue+ with contextlib.suppress(Exception):+ spared.update(child.pid for child in parent.children(recursive=True))victims = []try:proc_iter = psutil.process_iter(["pid", "exe"])@@ -1326,6 +1351,16 @@ def build_prepared_desktop(desktop_dir: Path, *, source_mode: bool, npm: str, en"""Build prepared desktop sources, then publish the verified staged app."""from pm.progress import run_contained+ if not source_mode and sys.platform == "win32" and (ancestor := _desktop_ancestor_in(desktop_dir)):+ # The Desktop running this build holds the exe lock the promotion rename needs,+ # and stopping it would kill this process first (#123499). Packing would only+ # produce a build that cannot be installed; leave the app as it is. Its content+ # stamp stays stale, so `hermes desktop` run outside the app rebuilds it+ # (_desktop_build_needed).+ print(f" ⚠ Skipped rebuilding the desktop app: this update is running inside it (pid {ancestor}),")+ print(" and Windows locks a running app's files. Quit Hermes Desktop, then run")+ print(" `hermes desktop` from a terminal to rebuild and reopen it.")+ return Nonebuild_label = "source build" if source_mode else "packaged app"build_env = dict(env)if sys.platform == "win32":diff --git a/tests/hermes_cli/test_gui_command.py b/tests/hermes_cli/test_gui_command.pyindex 66466edbdf5..5f22d39d6dd 100644--- a/tests/hermes_cli/test_gui_command.py+++ b/tests/hermes_cli/test_gui_command.py@@ -1397,13 +1397,17 @@ def test_stop_desktop_processes_locking_build_posix_swap_bypasses_early_return(tassert main_desktop._stop_desktop_processes_locking_build(desktop_dir, also_posix=True) == [100][email protected]("posix") # Windows must stop the exe-locking ancestor too-def test_posix_swap_spares_the_desktop_driving_this_update(tmp_path, monkeypatch):[email protected]("host, also_posix", [("linux", True), ("win32", False), ("win32", True)])+def test_the_stop_spares_the_desktop_driving_this_update(tmp_path, monkeypatch, host, also_posix):"""A historical Desktop runs `hermes update` as a piped child and relaunches- itself afterwards; stopping it breaks the update's stdout (EPIPE). Its- renderer/GPU/zygote helpers run the same exe but are not our ancestors;- stopping them leaves a main process that can neither draw nor quit. Only an- unrelated Desktop from the same release tree is stopped."""+ itself afterwards; stopping it breaks the update's stdout (EPIPE). On Windows+ a Desktop's own backend runs the launch-time update tail, and stopping that+ Desktop killed the tail with it before it could clear its markers, so every+ launch repeated it (#123499). Its renderer/GPU/zygote helpers run the same+ exe but are not our ancestors; stopping them leaves a main process that can+ neither draw nor quit. Only an unrelated Desktop from the same release tree+ is stopped, at the pack-time call and the swap alike."""+ monkeypatch.setattr(main_desktop.sys, "platform", host)root = _make_desktop_tree(tmp_path)desktop_dir = root / "apps" / "desktop"live_exe = desktop_dir / "release" / _packaged_exe_rel()@@ -1449,7 +1453,67 @@ def test_posix_swap_spares_the_desktop_driving_this_update(tmp_path, monkeypatchmonkeypatch.setitem(sys.modules, "psutil", _FakePsutil)- assert main_desktop._stop_desktop_processes_locking_build(desktop_dir, also_posix=True) == [300]+ assert main_desktop._stop_desktop_processes_locking_build(desktop_dir, also_posix=also_posix) == [300]+++def _ancestry(monkeypatch, *parents):+ """Install a fake psutil whose view of this process's ancestors is *parents* (outermost last)."""+ monkeypatch.setitem(sys.modules, "psutil", types.SimpleNamespace(+ Process=lambda pid: types.SimpleNamespace(parents=lambda: list(parents))))+++def _proc(pid, exe):+ return types.SimpleNamespace(pid=pid, exe=lambda: exe)+++def test_desktop_ancestor_names_only_a_desktop_from_this_release_tree(tmp_path, monkeypatch):+ desktop_dir = _make_desktop_tree(tmp_path) / "apps" / "desktop"+ live_exe = desktop_dir / "release" / _packaged_exe_rel()+ live_exe.parent.mkdir(parents=True)+ live_exe.write_text("old", encoding="utf-8")+ elsewhere = tmp_path / "other" / "Hermes.exe"++ _ancestry(monkeypatch, _proc(40, str(tmp_path / "python.exe")), _proc(41, str(live_exe)))+ assert main_desktop._desktop_ancestor_in(desktop_dir) == 41+ _ancestry(monkeypatch, _proc(40, str(tmp_path / "python.exe")), _proc(42, str(elsewhere)))+ assert main_desktop._desktop_ancestor_in(desktop_dir) is None+++def test_windows_build_under_its_own_desktop_skips_instead_of_killing_it(tmp_path, monkeypatch, capsys):+ """#123499: a Desktop's backend runs the interrupted-update tail at launch. Packing there+ can only end in a promotion the Desktop's exe lock refuses, and stopping that Desktop+ kills the tail first. The build is skipped, so the tail finishes and clears its markers."""+ monkeypatch.setattr(main_desktop.sys, "platform", "win32")+ desktop_dir = _make_desktop_tree(tmp_path) / "apps" / "desktop"+ monkeypatch.setattr(main_desktop, "_desktop_ancestor_in", lambda d: 4242)+ monkeypatch.setattr(main_desktop, "_stop_desktop_processes_locking_build",+ lambda *a, **k: pytest.fail("must not stop the Desktop running this build"))+ monkeypatch.setattr("pm.progress.run_contained", lambda *a, **k: pytest.fail("must not pack"))++ assert main_desktop.build_prepared_desktop(desktop_dir, source_mode=False, npm="npm", env={}) is None+ assert "Skipped rebuilding the desktop app" in capsys.readouterr().out+ assert not list(desktop_dir.glob(f"{main_desktop._DESKTOP_STAGING_PREFIX}*"))++[email protected]("host, source_mode", [("linux", False), ("win32", True)])+def test_the_skip_is_only_for_a_windows_packaged_build(tmp_path, monkeypatch, host, source_mode):+ """POSIX can rename a running app away and the Desktop relaunches itself, and a+ source build never touches release/: both still build under a Desktop ancestor."""+ monkeypatch.setattr(main_desktop.sys, "platform", host)+ desktop_dir = _make_desktop_tree(tmp_path) / "apps" / "desktop"+ monkeypatch.setattr(main_desktop, "_desktop_ancestor_in", lambda d: 4242)+ monkeypatch.setattr(main_desktop, "_stop_desktop_processes_locking_build", lambda *a, **k: [])+ monkeypatch.setattr("pm.ensure", lambda tool, base_env: types.SimpleNamespace(env=base_env))++ class _Packed(Exception):+ pass++ def _run(*a, **k):+ raise _Packed++ monkeypatch.setattr("pm.progress.run_contained", _run)+ with pytest.raises(_Packed):+ main_desktop.build_prepared_desktop(desktop_dir, source_mode=source_mode, npm="npm", env={})def test_gui_failed_pack_leaves_previous_app_untouched(tmp_path, monkeypatch, capsys):