The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(bot-screen): cross-process lease changes reach Desktop clients as display.lease
teknium1c7a0773f3f87
diff --git a/tests/tui_gateway/test_display_watch.py b/tests/tui_gateway/test_display_watch.pynew file mode 100644index 00000000000..b9248724c9d--- /dev/null+++ b/tests/tui_gateway/test_display_watch.py@@ -0,0 +1,80 @@+"""Lease transitions made by ANOTHER process reach `hermes serve` clients as ``display.lease``.++The agent lives in whatever process hosts it (messaging gateway, ``hermes chat``, a cron worker);+``lease.on_change`` is in-process only, so the serve backend must notice the file move itself.+"""++from __future__ import annotations++import os+import subprocess+import sys+import time+from pathlib import Path++REPO = Path(__file__).resolve().parents[2]+++def _other_process(home: Path, stmt: str) -> None:+ env = {**os.environ, "HERMES_HOME": str(home)}+ subprocess.run( # noqa: S603+ [sys.executable, "-c", f"import sys; sys.path.insert(0, {str(REPO)!r}); "+ f"from tools.bot_desktop import lease; {stmt}"],+ cwd=str(REPO), env=env, check=True, timeout=60, stdin=subprocess.DEVNULL)+++def _wait_for(pred, timeout: float = 3.0) -> bool:+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if pred():+ return True+ time.sleep(0.05)+ return pred()+++def _watching(server, home: Path, monkeypatch) -> list:+ from hermes_constants import hermes_home_key+ events: list = []+ monkeypatch.setattr(server, "_broadcast_global_event", lambda ev, payload=None: events.append((ev, payload)))+ monkeypatch.setattr(server, "_hermes_home", str(home))+ server._ensure_lease_watcher()+ assert _wait_for(lambda: hermes_home_key(home) in server._lease_epochs), "watcher never seeded the home"+ return events+++def _lease_events(events, **want):+ return [p for ev, p in events if ev == "display.lease" and all(p["lease"].get(k) == v for k, v in want.items())]+++def test_handoff_requested_in_another_process_is_broadcast(tmp_path, monkeypatch):+ import tui_gateway.server as server+ from hermes_constants import hermes_home_key+ home = tmp_path / "home"+ home.mkdir()+ events = _watching(server, home, monkeypatch)++ _other_process(home, 'lease.request_handoff("probe")')++ assert _wait_for(lambda: _lease_events(events, pending_handoff="probe")), events+ (payload,) = _lease_events(events, pending_handoff="probe")+ assert payload["profile_key"] == hermes_home_key(home)+++def test_release_in_another_process_is_broadcast_and_local_transition_not_duplicated(tmp_path, monkeypatch):+ import tui_gateway.server as server+ from tools.bot_desktop import lease+ home = tmp_path / "home"+ home.mkdir()+ events = _watching(server, home, monkeypatch)+ server._install_lease_listener() # what display.status does: in-process transitions broadcast here++ lease.acquire("viewer-1", profile_key=str(home))+ assert _wait_for(lambda: _lease_events(events, holder="human"))+ before = len(events)+ server._poll_lease_files() # the file moved too, but the watcher saw that epoch locally: no re-broadcast+ assert len(events) == before++ _other_process(home, 'lease.release("viewer-1")')++ assert _wait_for(lambda: _lease_events(events, holder="agent")), events+ assert len(_lease_events(events, holder="agent")) == 1diff --git a/tui_gateway/methods_display_watch.py b/tui_gateway/methods_display_watch.pynew file mode 100644index 00000000000..7c0efb16221--- /dev/null+++ b/tui_gateway/methods_display_watch.py@@ -0,0 +1,86 @@+"""Cross-process lease watcher: ``display.lease`` for transitions made OUTSIDE ``hermes serve``.++The lease (``tools.bot_desktop.lease``) lives on disk and is changed by whatever process hosts the+agent — the messaging gateway's ``request_handoff``, a ``hermes chat`` takeover, a cron worker's+release. ``lease.on_change`` only fires in the writing process, so ``methods_display``'s in-process+listener never sees those; the Desktop's "Bot needs you" badge and hero tone stayed stale until the+pane was reopened. One daemon thread stats every served home's ``bot-desktop/lease.json`` (launch+home + ``_served_profile_homes``) every 0.5s and broadcasts the SAME ``display.lease`` payload when+the epoch moves. Bodies are rebound onto server.py's globals (method_ctx.bind_module).+"""++from __future__ import annotations++import threading+import time+from pathlib import Path++from .method_ctx import bind_module++_LEASE_POLL_S = 0.5+_lease_watcher_started = threading.Event()+# profile key → last epoch broadcast or seen (in-process transitions record theirs too, so a change+# made by THIS process is not re-broadcast when its file write is noticed a tick later).+_lease_epochs: dict[str, int] = {}+_lease_mtimes: dict[str, int | None] = {}+++def _lease_event_payload(profile_key: str, lease) -> dict:+ # Mirrors methods_display._install_lease_listener's nested payload; keep the two in step.+ return {"profile_key": profile_key, "lease": lease.as_dict()}+++def _watched_lease_homes() -> list[Path]:+ return [Path(_hermes_home), *_served_profile_homes]+++def _poll_lease_files() -> None:+ """One pass: read a home's lease only when its file mtime moved; broadcast when the epoch did."""+ from hermes_constants import hermes_home_key+ from tools.bot_desktop import lease as _bd_lease+ for home in _watched_lease_homes():+ key = hermes_home_key(home)+ try:+ mtime = (home / "bot-desktop" / "lease.json").stat().st_mtime_ns+ except OSError:+ mtime = None+ if mtime == _lease_mtimes.get(key, 0):+ continue+ _lease_mtimes[key] = mtime+ lease = _bd_lease.get(str(home))+ if key not in _lease_epochs: # first sighting seeds silently: display.status carries it+ _lease_epochs[key] = lease.epoch+ continue+ if lease.epoch == _lease_epochs[key]:+ continue+ _lease_epochs[key] = lease.epoch+ _broadcast_global_event("display.lease", _lease_event_payload(key, lease))+++def _ensure_lease_watcher() -> None:+ """Once per process, from the first display.* call: start the lease-file poll thread and mark+ in-process transitions as seen so they broadcast exactly once (via the in-process listener)."""+ if _lease_watcher_started.is_set():+ return+ _lease_watcher_started.set()+ from tools.bot_desktop import lease as _bd_lease++ def _seen_locally(profile_key: str, lease) -> None:+ # methods_display's listener broadcasts in-process transitions; only then is the file+ # move ours to skip. Before display.status installed it, the poll below carries them.+ if _lease_listener_installed.is_set():+ _lease_epochs[profile_key] = lease.epoch+ _bd_lease.on_change(_seen_locally)++ def _loop() -> None:+ while True:+ try:+ _poll_lease_files()+ except Exception: # noqa: BLE001 - a torn read must not kill the watcher+ logger.debug("lease watcher poll failed", exc_info=True)+ time.sleep(_LEASE_POLL_S)+ threading.Thread(target=_loop, name="hermes-lease-watcher", daemon=True).start()+++def register(server) -> None:+ bind_module(globals(), server, skip=("_",))diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex dcc55c923f3..b5101afc0ba 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -3230,7 +3230,8 @@ from . import ( # noqa: E402methods_projects as _methods_projects, methods_session_foreign as _methods_session_foreign,methods_session_control as _methods_session_control, methods_subagents as _methods_subagents,methods_vault as _methods_vault, methods_free_tier as _methods_free_tier,- methods_connectors as _methods_connectors, methods_display as _methods_display)+ methods_connectors as _methods_connectors, methods_display as _methods_display,+ methods_display_watch as _methods_display_watch)for _m in (_session_transports, _session_reaper, _session_lifecycle, _session_workdir, _compute_host_bridge, _model_switch,@@ -3241,6 +3242,6 @@ for _m in (_methods_config_set, _methods_complete, _methods_tools, _methods_profiles, _methods_images,_methods_bot_relay, _prompt_turn, _billing_view, _methods_projects, _methods_session_foreign,_methods_session_control, _methods_subagents, _methods_vault, _methods_free_tier, _methods_connectors,- _methods_display):+ _methods_display, _methods_display_watch):_m.register(sys.modules[__name__])del _mdiff --git a/tui_gateway/ws.py b/tui_gateway/ws.pyindex 480ed366369..448224fab1a 100644--- a/tui_gateway/ws.py+++ b/tui_gateway/ws.py@@ -304,6 +304,7 @@ async def handle_ws(ws: Any, *, auth_identity: dict | None = None, subprotocol:# Live-apply skins Hermes activates mid-conversation, and track this peer for session-less# global broadcasts write_json can't route.server._ensure_skin_watcher()+ server._ensure_lease_watcher() # cross-process lease moves → display.leaseserver.register_live_transport(transport)# Cross-backend liveness: a heartbeat row lets the startup orphan sweep tell "live but idle# backend" from "truly orphaned". Idempotent and once-per-process, like the orphan sweep (the