The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(webapp): hermes webapp --sign-out waits for a gateway that is still starting
emozilla91cc2f63dbee
diff --git a/hermes_cli/webapp_launcher.py b/hermes_cli/webapp_launcher.pyindex ee4696ad818..a00565bde13 100644--- a/hermes_cli/webapp_launcher.py+++ b/hermes_cli/webapp_launcher.py@@ -10,12 +10,15 @@ one-use link cannot be redeemed, it prints the gateway's private link for the usfrom __future__ import annotationsimport json+import timefrom pathlib import PathRESTART_COMMAND = "hermes gateway restart"# The gateway reads the Webapp's settings and sign-in providers only when it starts.RETRY_AFTER_FIX = f"The gateway reads these settings when it starts: after fixing them, run {RESTART_COMMAND}."STARTED_BEFORE_ON = f"The gateway started before the Webapp was turned on. Restart it to serve the Webapp: {RESTART_COMMAND}"+# How long --sign-out waits for a gateway that is still starting to answer (30 s).+_START_WAIT_ATTEMPTS, _START_WAIT_INTERVAL = 60, 0.5class GatewayUnreachable(Exception):@@ -139,20 +142,40 @@ def _signed_out_summary(result: dict) -> str:def _sign_out(target: Path) -> int:from gateway.webapp_listener import browser_session_token- try:- response = _control(target, "webapp-sign-out")- except GatewayUnreachable:- # No gateway is running: replace the stored credential so no browser can use the old one- # when one starts. Behind the sign-in gate, logins bound to it end too.- browser_session_token(target, rotate=True)- print("No gateway is running for this profile. Replaced the stored Webapp credential: every browser "- "must sign in again when the gateway next serves the Webapp.")- return 0- if not response.get("ok"):- print(f"Nobody was signed out: {_refusal(response)}")- return 1- print(_signed_out_summary(response.get("result") or {}))- return 0+ for attempt in range(_START_WAIT_ATTEMPTS + 1):+ try:+ response = _control(target, "webapp-sign-out")+ except GatewayUnreachable:+ response = None+ if response is not None and response.get("ok"):+ print(_signed_out_summary(response.get("result") or {}))+ return 0+ state = _gateway_state(target)+ if response is None and state == "absent":+ # No gateway is running: replace the stored credential so no browser can use the old one+ # when one starts. Behind the sign-in gate, logins bound to it end too.+ browser_session_token(target, rotate=True)+ print("No gateway is running for this profile. Replaced the stored Webapp credential: every browser "+ "must sign in again when the gateway next serves the Webapp.")+ return 0+ if state != "starting":+ reason = _refusal(response) if response is not None else f"the gateway did not answer (state: {state})"+ print(f"Nobody was signed out: {reason}")+ return 1+ # A starting gateway may already hold the stored credential in memory, where rewriting the file+ # never reaches it: wait until it answers the sign-out itself.+ if attempt < _START_WAIT_ATTEMPTS:+ time.sleep(_START_WAIT_INTERVAL)+ print(f"The gateway is still starting, so nobody was signed out. Run hermes webapp --sign-out again once "+ f"it is up ({RESTART_COMMAND} if it never comes up).")+ return 1+++def _gateway_state(home: Path) -> str:+ """What *home*'s gateway lock and control socket say: ``absent`` (none running), ``starting``,+ ``ready``, or why it cannot be reached."""+ from hermes_cli.gateway_runtime import discover_gateway_endpoint+ return discover_gateway_endpoint(home).statedef _explain_refused_launch(target: Path, response: dict) -> int:diff --git a/tests/hermes_cli/test_webapp_launcher.py b/tests/hermes_cli/test_webapp_launcher.pyindex 5855cda7e4f..d5c31ea2031 100644--- a/tests/hermes_cli/test_webapp_launcher.py+++ b/tests/hermes_cli/test_webapp_launcher.py@@ -2,7 +2,9 @@It builds the Webapp bundle when stale, starts the gateway that serves the current profile (the defaultgateway for a profile it serves, else the profile's own), asks that gateway for a one-use launch link-over the control socket and opens it. It never serves anything itself.+over the control socket and opens it. It never serves anything itself. ``--sign-out`` reports what+the gateway did, waits for a gateway that is still starting, and replaces the stored credential+itself only when no gateway runs."""from argparse import Namespacefrom pathlib import Path@@ -44,6 +46,8 @@ def world(monkeypatch, tmp_path):calls["control"].append((Path(home), verb))calls.setdefault("params", []).append(params or {})answer = answers[verb]+ if isinstance(answer, list): # one answer per call, in order+ answer = answer.pop(0) if len(answer) > 1 else answer[0]if isinstance(answer, Exception):raise answerreturn answer@@ -52,9 +56,14 @@ def world(monkeypatch, tmp_path):monkeypatch.setattr(launcher, "_ensure", lambda home: calls["ensure"].append(Path(home)))monkeypatch.setattr(launcher, "_control", control)monkeypatch.setattr(launcher, "_open", lambda url: calls["opened"].append(url) or True)+ states = ["absent"] # what the gateway's lock and control socket say when it does not answer+ monkeypatch.setattr(launcher, "_gateway_state", lambda home: states.pop(0) if len(states) > 1 else states[0],+ raising=False)+ monkeypatch.setattr("time.sleep", lambda seconds: calls.setdefault("slept", []).append(seconds))root = _home(tmp_path / "root", "webapp:\n enabled: true\n")monkeypatch.setenv("HERMES_HOME", str(root))- return {"calls": calls, "answers": answers, "root": root, "tmp": tmp_path, "monkeypatch": monkeypatch}+ return {"calls": calls, "answers": answers, "root": root, "tmp": tmp_path, "monkeypatch": monkeypatch,+ "states": states}def _use_home(world, home):@@ -243,6 +252,54 @@ def test_signing_out_with_no_gateway_running_still_replaces_the_stored_credentiaassert "No gateway is running" in out and "sign in again" in out+STARTING = {"ok": False, "error": "unknown verb: 'webapp-sign-out'"} # its verbs register once it is up+SIGNED_OUT = {"ok": True, "result": {"signed_out": True, "serving": True, "sign_in_gate": False,+ "connections_closed": 1}}++[email protected]("first", [STARTING, launcher.GatewayUnreachable("control socket not up yet")])+def test_sign_out_waits_for_a_starting_gateway_and_signs_out_there(world, capsys, first):+ """A starting gateway may already hold the stored credential in memory, so rewriting the file+ would sign nobody out: the command waits for the gateway to answer instead."""+ from gateway.webapp_listener import TOKEN_PATH, browser_session_token+ before = browser_session_token(world["root"])+ world["answers"]["webapp-sign-out"] = [first, first, SIGNED_OUT]+ world["states"][:] = ["starting"]+ assert launcher.cmd_webapp(_args(sign_out=True)) == 0+ out = capsys.readouterr().out+ assert "Signed out of every Webapp tab: closed 1 browser connection." in out+ assert [verb for _, verb in world["calls"]["control"]] == ["webapp-sign-out"] * 3+ assert (world["root"] / TOKEN_PATH).read_text().strip() == before+++def test_sign_out_on_a_gateway_that_stays_starting_says_nobody_was_signed_out(world, capsys):+ from gateway.webapp_listener import TOKEN_PATH, browser_session_token+ before = browser_session_token(world["root"])+ world["answers"]["webapp-sign-out"] = [STARTING]+ world["states"][:] = ["starting"]+ assert launcher.cmd_webapp(_args(sign_out=True)) == 1+ out = capsys.readouterr().out+ assert "still starting" in out and "nobody was signed out" in out.lower() and "Signed out" not in out+ assert (world["root"] / TOKEN_PATH).read_text().strip() == before+ assert sum(world["calls"]["slept"]) >= 20 # it waited before giving up+++def test_sign_out_on_a_gateway_that_does_not_answer_signs_nobody_out(world, capsys):+ from gateway.webapp_listener import TOKEN_PATH, browser_session_token+ before = browser_session_token(world["root"])+ world["answers"]["webapp-sign-out"] = launcher.GatewayUnreachable("timed out")+ world["states"][:] = ["inaccessible"]+ assert launcher.cmd_webapp(_args(sign_out=True)) == 1+ out = capsys.readouterr().out+ assert "nobody was signed out" in out.lower() and "Signed out" not in out+ assert (world["root"] / TOKEN_PATH).read_text().strip() == before+++def test_a_home_whose_gateway_never_ran_reads_as_having_none(tmp_path):+ # Read from the home's real gateway lock and control socket, as --sign-out does.+ assert launcher._gateway_state(_home(tmp_path / "idle")) == "absent"++def test_the_webapp_command_takes_one_action_at_a_time():import argparsefrom hermes_cli.subcommands.webapp import build_webapp_parser