The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(update): stream long update stages into the desktop hand-off UI
ethernetaaf588920779
diff --git a/hermes_cli/_update_takeover.py b/hermes_cli/_update_takeover.pyindex c072aec6572..b14db5360a2 100644--- a/hermes_cli/_update_takeover.py+++ b/hermes_cli/_update_takeover.py@@ -11,6 +11,12 @@ def prepare(request: dict) -> tuple[Path, dict[str, str]]:"""Provision the new graph before entering its application interpreter."""root = Path(request["root"])sys.path.insert(0, str(root))+ # The old shim's UI has been frozen since the pull; from here the new+ # tree can publish stages (and pop the panel the old shim couldn't).+ from hermes_cli.update_stage import ensure_panel, publish_stage++ ensure_panel(root)+ publish_stage("Updating Python dependencies (PM)")from pm import paths, receiptfrom pm.client import ensure, sync_venv, venv_is_currentfrom pm.lock import Lockfilediff --git a/hermes_cli/source_build.py b/hermes_cli/source_build.pyindex 8850b6c5a8e..d3b64459305 100644--- a/hermes_cli/source_build.py+++ b/hermes_cli/source_build.py@@ -85,16 +85,21 @@ def build_update_products(project_root: Path, *, desktop: bool) -> None:# Both current updates and historical takeover reach this in a fresh target# interpreter, never in the updater's pre-sync import graph.from hermes_cli.main_install_repair import _warn_configured_features_missing_deps+ from hermes_cli.update_stage import publish_stage_warn_configured_features_missing_deps()env = source_build_env(explicit=True)workspaces = ("ui-tui", "web") + (("apps/desktop",) if desktop else ())+ publish_stage("Updating Node dependencies")prepare_source_dependencies(project_root, workspaces, env=env, explicit=True)+ publish_stage("Building the TUI")build_source_tui(project_root, env=env)+ publish_stage("Building the web UI")build_source_web(project_root, env=env, explicit=True)if desktop:from hermes_cli.main_desktop import build_prepared_desktop+ publish_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, explicit=True,diff --git a/hermes_cli/update_stage.py b/hermes_cli/update_stage.pynew file mode 100644index 00000000000..8e85147fcc0--- /dev/null+++ b/hermes_cli/update_stage.py@@ -0,0 +1,132 @@+"""Stage updates to a desktop hand-off UI, if one is watching.++The desktop-update shim (scripts/desktop-update/posix.sh) renders update+progress from a status JSON file. The shim only writes stages it gates on+itself; the takeover children (_update_takeover.py, update_finish.py and the+PM sync / build stages they drive) can run for minutes with nothing on+screen. These helpers let long stages publish through the same file so the+window keeps moving.++Two discovery paths, because the status file's name embeds the shim's pid:++- ``HERMES_UPDATE_STATUS_FILE``: exported by the current posix.sh — covers+ new-shim → new-children directly.+- Marker fallback: an OLD shim (pre-env-var checkout, i.e. every old→new+ update) never exports the path, but it writes the marker whose first line+ is its own pid, and its status file is deterministic:+ ``${TMPDIR:-/tmp}/hermes-update-status.<pid>``.++Stdlib-only (importable under ``-I -S -B``) and never raises: a missing/+stale/unwritable file means no UI, which is exactly the pre-shim behavior —+a progress hiccup must never fail an update.+"""++from __future__ import annotations++import json+import os+import tempfile+from pathlib import Path++STATUS_FILE_ENV = "HERMES_UPDATE_STATUS_FILE"+UI_SPAWNED_ENV = "HERMES_UPDATE_UI_ACTIVE"+MARKER_NAME = ".hermes-update-in-progress"+++def status_file() -> Path | None:+ """The watching shim's status file, or None when no UI is discoverable."""+ exported = os.environ.get(STATUS_FILE_ENV, "").strip()+ if exported:+ return Path(exported)+ return _status_from_marker()+++def _status_from_marker() -> Path | None:+ """Derive the shim's status file from the update marker's owner pid.++ The marker's first line is the hand-off shim's ``$$`` (update_lock.py+ adopts rather than rewrites it, so it still names the shim here). The+ shim's status file lives beside it, pid-suffixed. No marker (plain CLI+ update) or no matching file → no UI.+ """+ home = os.environ.get("HERMES_HOME") or str(Path.home() / ".hermes")+ try:+ pid = int((Path(home) / MARKER_NAME).read_text(encoding="utf-8-sig")+ .splitlines()[0].strip())+ except (OSError, ValueError, IndexError):+ return None+ if pid <= 0:+ return None+ tmpdir = os.environ.get("TMPDIR") or "/tmp"+ candidate = Path(tmpdir) / f"hermes-update-status.{pid}"+ return candidate if candidate.is_file() else None+++def publish_stage(message: str) -> None:+ """Report a running stage to the watching UI. Best-effort, never raises.++ Only ever writes ``status=running``: terminal states belong to the shim,+ which publishes them after this process has exited. The atomic replace+ mirrors the shim's write_status — a polling reader must never observe a+ half-written file.+ """+ path = status_file()+ if path is None:+ return+ payload = json.dumps({"status": "running", "message": message})+ try:+ fd, tmp = tempfile.mkstemp(dir=str(path.parent), prefix=".update-stage-")+ with os.fdopen(fd, "w", encoding="utf-8") as fh:+ fh.write(payload)+ os.replace(tmp, path)+ except OSError:+ pass+++def _ui_present_in_log(log_text: str) -> bool:+ """True when THIS hand-off run started a browser/panel window.++ Reads the shim's own log lines from the tail (the run's shim logs 'shim:+ app window …' or 'shim: status panel pid=…' when a renderer exists,+ '… skipping UI' when it does not). Unparseable → False: spawning a+ duplicate panel is cosmetic; leaving a Safari user with no UI at all is+ the bug being fixed.+ """+ tail = "\n".join(log_text.splitlines()[-40:])+ return "app window" in tail or "status panel pid=" in tail+++def ensure_panel(update_root: Path) -> None:+ """Pop the native status panel when no renderer is up (macOS, old→new).++ An old shim has no panel of its own and skipped its browser window on a+ non-Chromium default — its whole update then runs invisible. The freshly+ pulled tree ships update-panel.applescript, so the takeover child can+ start it against the discovered status file. Best-effort end to end: any+ failure leaves the update running exactly as UI-less as before.+ """+ if os.environ.get(UI_SPAWNED_ENV) or os.name != "posix" or os.uname().sysname != "Darwin":+ return+ if status_file() is None:+ return+ panel = update_root / "scripts" / "desktop-update" / "update-panel.applescript"+ if not panel.is_file():+ return+ try:+ home = os.environ.get("HERMES_HOME") or str(Path.home() / ".hermes")+ log = Path(home) / "logs" / "desktop-update-handoff.log"+ if log.is_file() and _ui_present_in_log(log.read_text(encoding="utf-8", errors="replace")[-8000:]):+ return+ import subprocess++ # Own session + devnull stdio: the panel must outlive this child the+ # same way the shim-spawned UI outlives the shim's stages, and it+ # self-exits when the shim publishes a terminal state.+ subprocess.Popen(+ ["/usr/bin/osascript", str(panel), str(status_file())],+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL, start_new_session=True,+ )+ os.environ[UI_SPAWNED_ENV] = "1" # inherited: never spawn twice per chain+ except OSError:+ passdiff --git a/hermes_cli/venv_sync.py b/hermes_cli/venv_sync.pyindex ba949b510ff..66beb66daf2 100644--- a/hermes_cli/venv_sync.py+++ b/hermes_cli/venv_sync.py@@ -86,6 +86,8 @@ def publish_launchers(project_root: Path, *, create: bool = True) -> None:def sync(project_root: Path | None = None, *, check: bool = False) -> dict:"""Report or sync dependencies. A malformed install stamp is a build error."""+ from hermes_cli.update_stage import publish_stage+root = Path(project_root) if project_root is not None else _project_root()if _is_sealed(root):return {"state": "sealed", "ok": True}@@ -100,6 +102,7 @@ def sync(project_root: Path | None = None, *, check: bool = False) -> dict:return {"state": "current", "ok": True}if check:return {"state": "would-sync", "ok": True}+ publish_stage("Updating Python dependencies")pm.sync_venv(explicit=True, project_root=root)publish_launchers(root)return {"state": "synced", "ok": True}diff --git a/scripts/desktop-update/posix.sh b/scripts/desktop-update/posix.shindex a96078977fb..94c8067bc29 100755--- a/scripts/desktop-update/posix.sh+++ b/scripts/desktop-update/posix.sh@@ -818,6 +818,11 @@ cd "$INSTALL_ROOT" || {log "$FINAL_MSG"; exit 3}export PYTHONUNBUFFERED=1+# The takeover children (hermes update -> _update_takeover/update_finish and+# the PM sync / build stages they drive) publish their stages back into the+# shim's UI through this file; without a watching UI the variable is simply+# absent and the helper no-ops.+export HERMES_UPDATE_STATUS_FILE="$STATUS"# --keep-stash: never re-apply local source edits after the update (they stay# parked in git stash). Probe --help first: older installed backends don't# know the flag and argparse would abort with exit 2, which collides with thediff --git a/tests/hermes_cli/test_update_stage.py b/tests/hermes_cli/test_update_stage.pynew file mode 100644index 00000000000..994cb8153e4--- /dev/null+++ b/tests/hermes_cli/test_update_stage.py@@ -0,0 +1,92 @@+"""Stage publishing into a watching desktop-update UI (hermes_cli.update_stage).++The desktop hand-off shim renders progress from a status JSON file. The+regression: during an old→new checkout transition the OLD shim never exports+the status path, so the takeover children (PM sync, builds) ran for minutes+while the shim's UI sat frozen on its last stage — the user's only signal+that anything was happening. update_stage must discover the file through+both the exported env var (new shim) and the marker-pid fallback (old shim),+and must be inert when neither exists (plain CLI update, no UI at all).+"""++from __future__ import annotations++import json+import os+import time++import pytest++from hermes_cli import update_stage+++def status_file(tmp_path):+ return tmp_path / "hermes-update-status.80335"++[email protected](autouse=True)+def clean_env(monkeypatch):+ monkeypatch.delenv(update_stage.STATUS_FILE_ENV, raising=False)+ monkeypatch.delenv(update_stage.UI_SPAWNED_ENV, raising=False)+++def _assert_running(payload: str, message: str) -> None:+ data = json.loads(payload)+ assert data["status"] == "running", "only the shim publishes terminal states"+ assert data["message"] == message+++def test_publishes_through_exported_env_var(status_file, monkeypatch):+ monkeypatch.setenv(update_stage.STATUS_FILE_ENV, str(status_file))++ update_stage.publish_stage("Building the web UI")++ _assert_running(status_file.read_text(encoding="utf-8"), "Building the web UI")+++def test_marker_fallback_covers_the_old_shim(status_file, tmp_path, monkeypatch):+ """The old→new transition: no env var, but the marker names the shim pid.++ The shim's status file is ${TMPDIR}/hermes-update-status.<shim pid> and+ the marker's first line IS that pid (update_lock adopts, never rewrites).+ """+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ (tmp_path / update_stage.MARKER_NAME).write_text(+ f"80335\n{int(time.time())}\n", encoding="utf-8")+ status_file.write_text('{"status":"running","message":"old"}', encoding="utf-8")+ monkeypatch.setenv("TMPDIR", str(tmp_path))++ update_stage.publish_stage("Updating Python dependencies (PM)")++ _assert_running(status_file.read_text(encoding="utf-8"),+ "Updating Python dependencies (PM)")+++def test_no_ui_sources_is_inert(status_file, tmp_path, monkeypatch):+ """A plain CLI update has no env var and no marker: publish must no-op."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path)) # no marker inside+ monkeypatch.setenv("TMPDIR", str(tmp_path))++ update_stage.publish_stage("anything")++ assert not status_file.exists()+++def test_publish_never_raises_on_unwritable_target(monkeypatch, tmp_path):+ monkeypatch.setenv(update_stage.STATUS_FILE_ENV, str(tmp_path / "no" / "such" / "dir" / "f"))++ update_stage.publish_stage("boom") # must not raise+++def test_ensure_panel_skipped_off_macos(status_file, tmp_path, monkeypatch):+ """ensure_panel is a macOS-only fallback; elsewhere it must not spawn."""+ monkeypatch.setenv(update_stage.STATUS_FILE_ENV, str(status_file))+ called = []+ monkeypatch.setattr(update_stage, "_ui_present_in_log", lambda text: False)++ # os.uname() on Linux reports Linux; the guard must reject before spawn.+ update_stage.ensure_panel(tmp_path)++ assert called == []+ assert update_stage.UI_SPAWNED_ENV not in os.environ