Skip to content

The agent that grows with you

fix(gateway): the Webapp's control verbs answer "starting" from the control socket's first moment

emozilla49f75ab653c8
diff --git a/apps/desktop/src/api/webapp-access.ts b/apps/desktop/src/api/webapp-access.ts
index a87d35c34a0..50df950f823 100644
--- a/apps/desktop/src/api/webapp-access.ts
+++ b/apps/desktop/src/api/webapp-access.ts
@@ -9,7 +9,7 @@ export interface WebAccessStatus {
/** `webapp.enabled` in the serving gateway's config: what it serves from its next start. */
enabled: boolean
/** What the gateway serves now; `stopped` when none answers. */
- gateway: { reason: null | string; state: 'off' | 'serving' | 'stopped' | 'unavailable'; url: null | string }
+ gateway: { reason: null | string; state: 'off' | 'serving' | 'starting' | 'stopped' | 'unavailable'; url: null | string }
lan_address: null | string
/** Who the configured web app serves; `local` is a loopback bind, reachable from this computer only. */
mode: 'local' | null | WebAccessMode
diff --git a/gateway/run_bootstrap.py b/gateway/run_bootstrap.py
index 0a682990e7f..e0eceaa9a7d 100644
--- a/gateway/run_bootstrap.py
+++ b/gateway/run_bootstrap.py
@@ -364,6 +364,11 @@ async def _start_gateway_start_control_socket(runner):
# live adapters' handlers (#87770); tools/prompt still wait for the next session.
"reload-plugins": reload_plugins_verb(runner, _main_loop)})
_control_server.ticket_store = runner.session_ticket_store
+ # The Webapp's verbs answer from the socket's first moment ("starting" until the listener
+ # settles): a client polling a restarting gateway must never read "unknown verb" as a failure.
+ from gateway.webapp_listener import register_control_verbs
+ from hermes_constants import get_hermes_home
+ register_control_verbs(runner, get_hermes_home(), server=_control_server)
if not await _control_server.start():
_control_server = None
else:
diff --git a/gateway/run_runtime.py b/gateway/run_runtime.py
index 1ef7f38c985..c1a71b60d4d 100644
--- a/gateway/run_runtime.py
+++ b/gateway/run_runtime.py
@@ -497,14 +497,18 @@ async def recover_bot_mailbox(authority):
async def start_gateway_runtime_api(runner):
from gateway import run_api
from gateway.webapp_listener import (
- BrowserCredentialError, browser_session_token, dial_origin, listener_plan, register_control_verbs,
+ STARTING, BrowserCredentialError, browser_session_token, dial_origin, listener_plan, register_control_verbs,
)
from hermes_constants import get_hermes_home
home = get_hermes_home()
+ # The bootstrap registered these before its control socket answered; a runner started without it
+ # (an embedded gateway) gets them here, before the listener's slow start.
+ register_control_verbs(runner, home)
host, port, webapp, unusable = listener_plan(home)
# A webapp: block that asks for the Webapp but cannot be used is reported with its reason.
runner.webapp_status = ({"state": "unavailable", "url": None, "reason": unusable} if unusable
- else {"state": "off", "url": None, "reason": None})
+ else {"state": "off", "url": None, "reason": None} if webapp is None
+ else dict(STARTING))
try:
# Without the Webapp the listener is main's: the same call, a private ephemeral port.
runner.session_api = await (run_api.start_gateway_api(runner, host=host, port=port, webapp=webapp)
@@ -538,7 +542,6 @@ async def start_gateway_runtime_api(runner):
else:
if webapp is not None:
runner.webapp_status = {"state": "serving", "url": dial_origin(host, port), "reason": None}
- register_control_verbs(runner, home)
runner.session_runtime_descriptor['api_origin'] = runner.session_api.api_origin
for authority in _authorities(runner):
await _recover_profile_bot_mailbox(runner, authority)
diff --git a/gateway/webapp_listener.py b/gateway/webapp_listener.py
index acbc9ee1e9e..b09492a187d 100644
--- a/gateway/webapp_listener.py
+++ b/gateway/webapp_listener.py
@@ -320,26 +320,38 @@ def _bundle_missing(web) -> str | None:
return None if dist is None else bundle_missing_reason(dist)
-def register_control_verbs(runner, home) -> None:
- """The private control-socket verbs ``hermes webapp`` uses; only an authenticated same-user peer
- reaches them. ``webapp-launch`` returns a one-use launch link, so the credential crosses neither
- the socket nor a browser's argv; where nothing can check who redeems such a link (macOS, the BSDs,
- WSL) it is marked private, for the user to open by hand. ``webapp-sign-out`` replaces the
- browser credential, which also ends every login bound to it behind the sign-in gate, closes the
- browser sockets those opened, and reports how many it closed."""
- server = getattr(runner, "session_control_server", None)
+#: ``webapp-status`` from the control socket's start until the listener settles on serving, off or
+#: unavailable: Web Access keeps waiting on it, as on a gateway that has not restarted yet.
+STARTING = {"state": "starting", "url": None, "reason": None}
+_STILL_STARTING = "The Webapp is still starting; try again in a moment."
+
+
+def register_control_verbs(runner, home, server=None) -> None:
+ """The private control-socket verbs ``hermes webapp`` uses on *server* (the runner's control
+ server by default); only an authenticated same-user peer reaches them. The gateway registers them
+ before its control socket answers, so they answer from its first moment: :data:`STARTING` until
+ the listener sets ``runner.webapp_status``. ``webapp-launch`` returns a one-use launch link, so
+ the credential crosses neither the socket nor a browser's argv; where nothing can check who
+ redeems such a link (macOS, the BSDs, WSL) it is marked private, for the user to open by hand.
+ ``webapp-sign-out`` replaces the browser credential, which also ends every login bound to it
+ behind the sign-in gate, closes the browser sockets those opened, and reports how many it closed."""
+ server = server if server is not None else getattr(runner, "session_control_server", None)
if server is None:
return
+ if getattr(runner, "webapp_status", None) is None:
+ runner.webapp_status = dict(STARTING)
def serving():
status = runner.webapp_status
if status["state"] == "off":
raise RuntimeError("The Webapp is off. Set webapp.enabled: true in config.yaml and restart the gateway.")
+ if status["state"] == "starting":
+ raise RuntimeError(_STILL_STARTING)
if status["state"] != "serving":
raise RuntimeError(f"The Webapp is unavailable: {status['reason']}")
web = getattr(getattr(getattr(runner, "session_api", None), "app", None), "web", None)
if web is None:
- raise RuntimeError("The Webapp is still starting; try again.")
+ raise RuntimeError(_STILL_STARTING)
return status, web
def webapp_status(_params, _peer):
@@ -387,6 +399,10 @@ def register_control_verbs(runner, home) -> None:
def webapp_sign_out(_params, _peer):
from hermes_cli import browser_credential
+ if runner.webapp_status["state"] == "starting":
+ # The starting listener may already hold the stored credential in memory, where replacing
+ # the file never reaches it: the caller waits for the listener to settle.
+ raise RuntimeError(_STILL_STARTING)
if runner.webapp_status["state"] != "serving":
# No browser reaches this gateway's Webapp and it holds no browser credential: replacing
# the stored one is the whole sign-out, and the next start serves the new one.
diff --git a/hermes_cli/webapp_launcher.py b/hermes_cli/webapp_launcher.py
index 03fa1214df1..076b4ded557 100644
--- a/hermes_cli/webapp_launcher.py
+++ b/hermes_cli/webapp_launcher.py
@@ -128,6 +128,8 @@ def _status(target: Path) -> int:
status = response["result"]
if status["state"] == "serving":
print(f"Serving at {status['url']}")
+ elif status["state"] == "starting":
+ print("The gateway is still starting the Webapp. Run hermes webapp --status again in a moment.")
elif status["state"] == "off":
print(_off_message(target, f"run {RESTART_COMMAND}"))
else:
diff --git a/tests/gateway/test_webapp_listener.py b/tests/gateway/test_webapp_listener.py
index ce815701224..e7ed8468f25 100644
--- a/tests/gateway/test_webapp_listener.py
+++ b/tests/gateway/test_webapp_listener.py
@@ -98,7 +98,9 @@ def test_a_credential_the_browser_would_refuse_is_replaced(tmp_path, stored):
assert re.fullmatch(r"[A-Za-z0-9_-]{43}", token)
-def _start_runtime_api(monkeypatch, tmp_path, config, *, busy=False, refuse=None):
+def _start_runtime_api(monkeypatch, tmp_path, config, *, busy=False, refuse=None, while_starting=None):
+ """Start the runtime's listener for *config* with the listener itself stood in; *while_starting*
+ (a list) records what each Webapp verb answers while the Webapp's listener starts."""
from gateway import run_api, run_runtime
home = _home(tmp_path, config)
monkeypatch.setenv("HERMES_HOME", str(home))
@@ -106,6 +108,8 @@ def _start_runtime_api(monkeypatch, tmp_path, config, *, busy=False, refuse=None
async def start(runner, *, host="127.0.0.1", port=0, webapp=None):
calls.append((host, port, webapp))
+ if while_starting is not None and webapp is not None:
+ while_starting.append({verb: _ask(runner, verb) for verb in WEBAPP_VERBS})
if busy and port:
raise OSError(errno.EADDRINUSE, "Address already in use")
if refuse is not None and webapp is not None:
@@ -120,9 +124,47 @@ def _start_runtime_api(monkeypatch, tmp_path, config, *, busy=False, refuse=None
return runner, calls, home
-def _ask(runner, verb, peer="same-user-peer", params=None):
+WEBAPP_VERBS = ("webapp-status", "webapp-launch", "webapp-sign-out")
+
+
+def _ask(runner, verb, peer="same-user-peer", params=None, server=None):
raw = json.dumps({"protocol": 1, "verb": verb, "id": 1, "params": params or {}}).encode()
- return json.loads(runner.session_control_server.handle_request_line(raw, peer))
+ return json.loads((server or runner.session_control_server).handle_request_line(raw, peer))
+
+
+def test_the_webapp_verbs_answer_while_the_webapps_listener_starts(monkeypatch, tmp_path):
+ """While the Webapp's listener starts (the dashboard import and mount take seconds), its verbs
+ answer: status says ``starting``, which a client polling a restarting gateway keeps waiting on,
+ never an unknown verb it would show as a failure. Launch and sign-out refuse as still starting,
+ and sign-out leaves the stored credential alone (the starting listener may already hold it)."""
+ seen = []
+ runner, _, home = _start_runtime_api(
+ monkeypatch, tmp_path, "webapp:\n enabled: true\n port: 9555\n", while_starting=seen)
+ [answers] = seen
+ assert answers["webapp-status"]["result"] == {"state": "starting", "url": None, "reason": None}
+ for verb in ("webapp-launch", "webapp-sign-out"):
+ assert answers[verb]["ok"] is False and "still starting" in answers[verb]["error"], answers[verb]
+ assert not (home / webapp.TOKEN_PATH).exists() # sign-out wrote no credential
+ assert runner.webapp_status["state"] == "serving"
+
+
+def test_the_gateway_registers_the_webapp_verbs_before_its_control_socket_answers(monkeypatch, tmp_path):
+ """The gateway's control socket answers from the moment it starts; the Webapp's verbs are on it
+ from that moment too (``starting`` until the listener settles), not only once the listener is up."""
+ from gateway import control_socket, run_bootstrap
+ home = _home(tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ seen = {}
+
+ async def start(server):
+ seen["status"] = _ask(None, "webapp-status", server=server)
+ return False # nothing binds in this test
+
+ monkeypatch.setattr(control_socket.GatewayControlServer, "start", start)
+ runner = SimpleNamespace(session_runtime_descriptor={}, session_ticket_store=None)
+ assert asyncio.run(run_bootstrap._start_gateway_start_control_socket(runner)) is None
+ assert seen["status"]["ok"] is True, seen
+ assert seen["status"]["result"]["state"] == "starting"
def test_the_gateway_listens_on_the_webapp_port_when_enabled(monkeypatch, tmp_path):
diff --git a/tests/hermes_cli/test_webapp_launcher.py b/tests/hermes_cli/test_webapp_launcher.py
index ee195df4edd..e78956f64a0 100644
--- a/tests/hermes_cli/test_webapp_launcher.py
+++ b/tests/hermes_cli/test_webapp_launcher.py
@@ -173,6 +173,15 @@ def test_status_reads_the_running_gateway_without_starting_one(world, capsys):
assert "http://127.0.0.1:9120" in capsys.readouterr().out
+def test_status_of_a_gateway_still_starting_the_webapp_says_so(world, capsys):
+ """A gateway answers ``starting`` until its Webapp listener settles: that is neither a failure nor a
+ reason to restart it."""
+ world["answers"]["webapp-status"] = {"ok": True, "result": {"state": "starting", "url": None, "reason": None}}
+ assert launcher.cmd_webapp(_args(status=True)) == 0
+ out = capsys.readouterr().out
+ assert "still starting" in out and "Unavailable" not in out and launcher.RESTART_COMMAND not in out
+
+
def test_status_with_no_gateway_running_says_so(world, capsys):
world["answers"]["webapp-status"] = launcher.GatewayUnreachable("no gateway")
assert launcher.cmd_webapp(_args(status=True)) == 1
@@ -267,7 +276,7 @@ def test_signing_out_with_no_gateway_and_a_credential_that_cannot_be_stored_says
assert "Nobody was signed out" in out and str(world["root"] / TOKEN_PATH) in out
-STARTING = {"ok": False, "error": "unknown verb: 'webapp-sign-out'"} # its verbs register once it is up
+STARTING = {"ok": False, "error": "RuntimeError: The Webapp is still starting; try again in a moment."}
SIGNED_OUT = {"ok": True, "result": {"signed_out": True, "serving": True, "sign_in_gate": False,
"connections_closed": 1}}