Skip to content

The agent that grows with you

fix(cli): name the real state when cooperative attach is unavailable

Konstantin Khlopkov4b39c5558aac
diff --git a/hermes_cli/active_sessions.py b/hermes_cli/active_sessions.py
index 7a9bb61356e..2be0ccad5a4 100644
--- a/hermes_cli/active_sessions.py
+++ b/hermes_cli/active_sessions.py
@@ -148,18 +148,23 @@ def _is_same_writer(entry: dict[str, Any], metadata: Optional[dict[str, Any]]) -
return bool(existing_live and incoming_live) and existing_live == incoming_live
+def session_owner_details(session_id: str, entry: dict[str, Any]) -> str:
+ """The ``Details:`` line shared by every owner-refusal message."""
+ surface = str(entry.get("surface") or "another surface")
+ started = _optional_float(entry.get("started_at"))
+ age = f" {format_age(time.time() - started)} ago" if started else ""
+ return f"Details: session {session_id} opened by {surface}{age}."
+
+
def session_already_owned_message(session_id: str, entry: dict[str, Any]) -> str:
"""Refusal text for a session another live process holds.
Contract shared with the TUI/Desktop surfaces: the FIRST line is the plain user sentence
(no lease/pid/owner jargon); the second line is ``Details: ...`` for logs and bug reports.
"""
- surface = str(entry.get("surface") or "another surface")
- started = _optional_float(entry.get("started_at"))
- age = f" {format_age(time.time() - started)} ago" if started else ""
return (
"This chat is open in another Hermes window/terminal. Use it there, or start a new chat here.\n"
- f"Details: session {session_id} opened by {surface}{age}."
+ + session_owner_details(session_id, entry)
)
diff --git a/hermes_cli/shared_session_attach.py b/hermes_cli/shared_session_attach.py
index 9282c08f7bd..e399910efb1 100644
--- a/hermes_cli/shared_session_attach.py
+++ b/hermes_cli/shared_session_attach.py
@@ -13,7 +13,7 @@ from urllib.parse import urlencode, urlsplit
import httpx
from hermes_constants import get_hermes_home
-from hermes_cli.active_sessions import active_session_registry_snapshot, session_already_owned_message
+from hermes_cli.active_sessions import active_session_registry_snapshot, session_owner_details
def _local_origin(url: str, scheme: str) -> tuple[str, int]:
@@ -46,8 +46,10 @@ def discover_attach_url(session_id: str, *, registry_home: str | Path | None = N
owner = owners[0]
endpoint = (owner.get("metadata") or {}).get("shared_runtime_url")
if not isinstance(endpoint, str) or not endpoint:
- raise ValueError("The live owner does not advertise cooperative attachment. "
- + session_already_owned_message(session_id, owner))
+ raise ValueError("This chat is open in another Hermes window/terminal, and attaching "
+ "this terminal to it is not available in this build. Close the chat "
+ "there and run hermes --resume " + session_id + " here to take it over.\n"
+ + session_owner_details(session_id, owner))
origin = _local_origin(endpoint, "http")
parts = urlsplit(endpoint)
if parts.path not in ("", "/") or parts.query:
@@ -68,8 +70,10 @@ def discover_attach_url(session_id: str, *, registry_home: str | Path | None = N
reply = json.loads(body)
except (httpx.HTTPError, json.JSONDecodeError) as exc:
# Never include a remote body or authenticated URL in diagnostics.
- raise ValueError("The live owner could not authorize cooperative attachment; "
- "its lease was left intact.") from exc
+ raise ValueError("This chat is open in another Hermes window/terminal, and attaching "
+ "this terminal to it just failed. Use the chat where it is open, or "
+ "close it there and run hermes --resume " + session_id + " here.\n"
+ + session_owner_details(session_id, owner)) from exc
if not isinstance(reply, dict) or any(reply.get(key) != value for key, value in {
"session_id": session_id, "lease_id": owner["lease_id"], "profile_home": str(home),
}.items()):
diff --git a/tests/hermes_cli/test_shared_session_attach.py b/tests/hermes_cli/test_shared_session_attach.py
index abff77b0ecb..b1a01a0715f 100644
--- a/tests/hermes_cli/test_shared_session_attach.py
+++ b/tests/hermes_cli/test_shared_session_attach.py
@@ -71,8 +71,11 @@ def test_discovery_refuses_unsupported_owner_without_releasing_lease(tmp_path, m
)
assert error is None
try:
- with pytest.raises(ValueError, match="does not advertise"):
+ with pytest.raises(ValueError, match="not available in this build") as caught:
discover_attach_url("old", registry_home=tmp_path)
+ first, details = str(caught.value).splitlines()
+ assert "hermes --resume old" in first
+ assert details.startswith("Details: ")
assert active_session_registry_snapshot(tmp_path)[0]["lease_id"] == lease.lease_id
registry = tmp_path / "runtime" / "active_sessions.json"
before = registry.read_bytes()
@@ -85,3 +88,37 @@ def test_discovery_refuses_unsupported_owner_without_releasing_lease(tmp_path, m
assert registry.read_bytes() == before
finally:
lease.release()
+
+
+def test_discovery_failure_message_names_state_and_resume_path(tmp_path):
+ """A refused handshake keeps the lease and points at the working alternative."""
+ from hermes_cli.shared_session_attach import discover_attach_url
+
+ class Handler(BaseHTTPRequestHandler):
+ def do_GET(self):
+ self.send_response(500)
+ self.end_headers()
+
+ def log_message(self, *args):
+ pass
+
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ origin = f"http://127.0.0.1:{server.server_port}"
+ lease, error = try_acquire_active_session(
+ session_id="held", surface="desktop", config={}, registry_home=tmp_path,
+ metadata={"live_session_id": "live", "shared_runtime_url": origin},
+ )
+ assert error is None
+ try:
+ with pytest.raises(ValueError, match="just failed") as caught:
+ discover_attach_url("held", registry_home=tmp_path)
+ first, details = str(caught.value).splitlines()
+ assert "hermes --resume held" in first
+ assert details.startswith("Details: ")
+ finally:
+ lease.release()
+ server.shutdown()
+ server.server_close()
+ thread.join()