Skip to content

The agent that grows with you

fix: standalone tui_gateway.entry refuses a home a gateway already owns

Teknium9595c3f34565
diff --git a/hermes_cli/web_server_chat.py b/hermes_cli/web_server_chat.py
index bb60dc4acca..266aedac63d 100644
--- a/hermes_cli/web_server_chat.py
+++ b/hermes_cli/web_server_chat.py
@@ -391,7 +391,7 @@ def _resolve_chat_argv(
through ``HERMES_TUI_RESUME`` (``ui-tui`` does not parse argv), resolved to
the newest descendant; ``HERMES_TUI_GATEWAY_URL`` attaches to this process's
in-memory gateway but is SKIPPED for profile-scoped chats (that gateway runs
- under the dashboard's own profile, so a scoped chat spawns its own);
+ under the dashboard's own profile, so a scoped chat attaches to its profile's gateway);
``profile`` scopes the ENTIRE chat by pointing ``HERMES_HOME`` at the profile
dir, the same propagation ``hermes -p <name>`` performs. ``workspace_cwd``
(an already-validated host directory, ``chat_workspaces.resolve_chat_cwd``)
@@ -464,8 +464,9 @@ def _resolve_chat_argv(
if active_session_file:
env["HERMES_TUI_ACTIVE_SESSION_FILE"] = active_session_file
- # Without the attach URL, gatewayClient spawns its own `tui_gateway.entry`,
- # which inherits the profile HERMES_HOME set above.
+ # Without the attach URL, gatewayClient bootstraps through the profile's own
+ # gateway (ui-tui/scripts/gateway_bootstrap.py) under the HERMES_HOME set above;
+ # it never spawns a standalone `tui_gateway.entry` writer.
if profile_dir is None and (gateway_ws_url := _build_gateway_ws_url()):
env["HERMES_TUI_GATEWAY_URL"] = gateway_ws_url
diff --git a/scripts/probe_active_session_exclusivity.py b/scripts/probe_active_session_exclusivity.py
index 54fa2952ba0..d4195414301 100644
--- a/scripts/probe_active_session_exclusivity.py
+++ b/scripts/probe_active_session_exclusivity.py
@@ -9,13 +9,15 @@ Run against the fork's own HERMES_HOME so nothing here touches a real profile:
python scripts/probe_active_session_exclusivity.py
-It drives two real ``python -m tui_gateway.entry`` processes over stdio JSON-RPC
-and asserts the sequence the reviewer specified:
+It drives real ``python -m tui_gateway.entry`` processes over stdio JSON-RPC.
+The standalone entry now reserves the home's ``gateway.lock`` (the gateway's own
+owner reservation) before it opens ``state.db``, so the second writer is refused
+before it exists rather than per turn:
- A resume S, submit -> claims the session
- B resume S, submit -> typed SESSION_NOT_OWNED, no row, no turn
- A exits -> its lease is pruned as a dead owner
- B submit again -> succeeds
+ A create S, submit -> claims the session
+ B start on the same home -> refused at startup (exit 1), never ready
+ A exits -> its reservation dies with it
+ B start, resume S, submit -> succeeds
No provider is required. The fence is checked BEFORE the agent is built, so a
submit that later fails for want of a model still proves who owns the session --
@@ -108,10 +110,6 @@ class Gateway:
pass
-def reason_of(response: dict):
- return (response.get("error") or {}).get("data", {}).get("reason")
-
-
def registry(home: Path):
path = home / "runtime" / "active_sessions.json"
try:
@@ -159,31 +157,25 @@ def main() -> int:
check("the lease is keyed on the STORED session, not the runtime handle",
bool(key) and key != sid_a, f"key={key} runtime={sid_a}")
- b = Gateway("B", home)
- resumed = b.call("session.resume", {"session_id": key})
- check("B may still RESUME (reading is never fenced)", "result" in resumed,
- json.dumps(resumed.get("error", ""))[:160])
- sid_b = resumed.get("result", {}).get("session_id")
-
- before = len(registry(home))
- refused = b.call("prompt.submit", {"session_id": sid_b, "text": "probe: B must not write"})
- check("B's submit is refused", refused.get("error") is not None,
- json.dumps(refused.get("result", ""))[:120])
- check("refusal is typed SESSION_NOT_OWNED", reason_of(refused) == "SESSION_NOT_OWNED",
- str(reason_of(refused)))
- check("refusal left the registry untouched", len(registry(home)) == before)
+ refused_b = subprocess.run(
+ [str(PYTHON), "-u", "-m", "tui_gateway.entry"], cwd=str(REPO),
+ env={**os.environ, "HERMES_HOME": str(home)}, stdin=subprocess.DEVNULL,
+ capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=180)
+ check("B cannot start a second writer on A's home", refused_b.returncode == 1
+ and "gateway.ready" not in refused_b.stdout, (refused_b.stderr or "")[-200:])
# A dies without releasing -- the crash case, not a clean handoff.
a.proc.kill()
a.proc.wait(timeout=30)
- time.sleep(1.0)
+ b = Gateway("B", home)
+ resumed = b.call("session.resume", {"session_id": key})
+ check("after A dies, B may resume", "result" in resumed,
+ json.dumps(resumed.get("error", ""))[:160])
+ sid_b = resumed.get("result", {}).get("session_id")
retried = b.call("prompt.submit", {"session_id": sid_b, "text": "probe: B may write now"})
- check("after A dies, B's retry is accepted", retried.get("error") is None,
+ check("and B's submit is accepted", retried.get("error") is None,
json.dumps(retried.get("error", ""))[:200])
- held = registry(home)
- check("and B now owns the session", len(held) == 1 and held[0].get("session_id") == key,
- json.dumps(held)[:160])
finally:
if b is not None:
b.close()
diff --git a/tests/tui_gateway/test_entry_home_ownership.py b/tests/tui_gateway/test_entry_home_ownership.py
new file mode 100644
index 00000000000..b772164b566
--- /dev/null
+++ b/tests/tui_gateway/test_entry_home_ownership.py
@@ -0,0 +1,57 @@
+"""The standalone stdio entry is never a second state.db writer beside a gateway."""
+from __future__ import annotations
+
+import io
+
+import pytest
+
+from gateway.runtime_ownership import OwnershipConflict, ProfileOwnership
+from tui_gateway import entry
+
+
+def _stub_startup(monkeypatch, opened):
+ monkeypatch.setattr(entry, "_install_sidecar_publisher", lambda: None)
+ monkeypatch.setattr(entry.server, "_stdio_is_rpc_channel", False, raising=False)
+ monkeypatch.setattr(entry, "ensure_mcp_discovery_started", lambda: None)
+ monkeypatch.setattr(entry, "resolve_skin", lambda: "default")
+ monkeypatch.setattr(entry.server, "_start_backend_heartbeat_refresher", lambda: opened.append("state.db"))
+ monkeypatch.setattr(entry.server, "_schedule_startup_orphan_sweep", lambda: None)
+ monkeypatch.setattr(entry.server, "_ensure_skin_watcher", lambda: None)
+ monkeypatch.setattr(entry, "handle_spurious_eof", lambda *_a: False)
+ monkeypatch.setattr(entry, "_log_exit", lambda reason: opened.append(reason))
+ monkeypatch.setattr(entry, "write_json", lambda payload: True)
+
+
+def test_entry_refuses_an_owned_home_and_owns_a_free_one(monkeypatch, tmp_path):
+ home = tmp_path / "home"
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ opened: list[str] = []
+ _stub_startup(monkeypatch, opened)
+ gateway = ProfileOwnership()
+ gateway.reserve([home])
+ try:
+ monkeypatch.setattr(entry.sys, "stdin", io.StringIO(""))
+ with pytest.raises(SystemExit) as refused:
+ entry.main()
+ assert refused.value.code == 1
+ assert "state.db" not in opened and "owned by a running gateway" in opened[-1]
+ finally:
+ gateway.release(home)
+
+ # A free home: the entry holds the gateway's own reservation while it serves, so a
+ # gateway starting on that home is refused instead of becoming a second writer.
+ contender = []
+
+ def dispatch(req):
+ with pytest.raises(OwnershipConflict):
+ ProfileOwnership().reserve([home])
+ contender.append("refused")
+ return {"jsonrpc": "2.0", "id": req["id"], "result": {}}
+
+ monkeypatch.setattr(entry, "dispatch", dispatch)
+ monkeypatch.setattr(entry.sys, "stdin", io.StringIO('{"jsonrpc":"2.0","id":1,"method":"ping"}\n'))
+ entry.main()
+ assert contender == ["refused"]
+ after = ProfileOwnership()
+ after.reserve([home]) # released at exit
+ after.release(home)
diff --git a/tui_gateway/entry.py b/tui_gateway/entry.py
index b09f0acb3e0..d7f99d6b7bc 100644
--- a/tui_gateway/entry.py
+++ b/tui_gateway/entry.py
@@ -270,7 +270,37 @@ def _write_or_exit(payload: dict, reason: str) -> None:
sys.exit(0)
+def _claim_launch_home():
+ """Reserve the launch home exactly as the gateway does, or None when it is already owned.
+
+ No product surface launches this standalone stdio server any more: Ink and Desktop attach to
+ the profile's gateway over WS (``ui-tui/scripts/gateway_bootstrap.py``). Dev harnesses still
+ run it against a sandbox home (``apps/desktop/e2e/real-session-builder.ts``), and it opens that
+ home's ``state.db`` as a writer, so it must be the home's only owner: the gateway's
+ ``gateway.lock`` reservation refuses it beside a live gateway (or a second entry), and holding
+ that lock keeps a gateway from starting on the home while this process writes."""
+ from gateway.runtime_ownership import OwnershipConflict, process_ownership
+ home = server._launch_home()
+ try:
+ process_ownership.reserve([home])
+ except OwnershipConflict:
+ return None
+ return home
+
+
def main():
+ home = _claim_launch_home()
+ if home is None:
+ _log_exit(f"refused: {server._launch_home()} is owned by a running gateway; attach to it instead")
+ sys.exit(1)
+ try:
+ _serve()
+ finally:
+ from gateway.runtime_ownership import process_ownership
+ process_ownership.release(home)
+
+
+def _serve():
# stdout is this process's JSON-RPC client channel: peer-less global broadcasts belong on it.
server._stdio_is_rpc_channel = True
try: