The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(webapp): say what is wrong with a webapp block instead of asking to enable it
emozillaa5acfe45f61e
diff --git a/gateway/run_runtime.py b/gateway/run_runtime.pyindex 753928f7a03..45cbb49aa09 100644--- a/gateway/run_runtime.py+++ b/gateway/run_runtime.py@@ -499,8 +499,10 @@ async def start_gateway_runtime_api(runner):from gateway.webapp_listener import browser_session_token, dial_origin, listener_plan, register_control_verbsfrom hermes_constants import get_hermes_homehome = get_hermes_home()- host, port, webapp = listener_plan(home)- runner.webapp_status = {"state": "off", "url": None, "reason": None}+ 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})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)diff --git a/gateway/webapp_listener.py b/gateway/webapp_listener.pyindex f343ee93923..0fd94df5e3e 100644--- a/gateway/webapp_listener.py+++ b/gateway/webapp_listener.py@@ -39,6 +39,8 @@ class WebappSettings:port: int = DEFAULT_PORT#: ``webapp.public_url``: the address a reverse proxy or tunnel serves the Webapp at, or "" for none.public_url: str = ""+ #: Why a ``webapp:`` block that asks for the Webapp keeps it off (it cannot be used), else None.+ reason: str | None = None@propertydef bind(self) -> tuple[str, int]:@@ -71,39 +73,38 @@ def _config_document(home: Path) -> dict:def webapp_settings(home) -> WebappSettings:"""``webapp:`` from *home*'s config. A missing, unreadable or malformed block reads as off, so a- typo never exposes the listener."""+ typo never exposes the listener; a block that cannot be used carries the reason in ``reason``."""path = Path(home) / "config.yaml"from ruamel.yaml.error import YAMLError++ def off(reason: str) -> WebappSettings:+ logger.warning("Webapp stays off: %s", reason)+ return WebappSettings(reason=reason)+try:document = _config_document(Path(home))except (OSError, ValueError, YAMLError) as exc: # the gateway's own config load reports it- logger.warning("Webapp stays off: %s could not be read (%s)", path, exc)- return WebappSettings()+ return off(f"{path} could not be read ({exc})")block = document.get("webapp") if isinstance(document, dict) else Noneif block is None:return WebappSettings()if not isinstance(block, dict):- logger.warning("Webapp stays off: webapp in %s must be a mapping", path)- return WebappSettings()+ return off(f"webapp in {path} must be a mapping")enabled = block.get("enabled", False)if enabled is False:return WebappSettings()if enabled is not True:- logger.warning("Webapp stays off: webapp.enabled must be true or false in %s", path)- return WebappSettings()+ return off(f"webapp.enabled must be true or false in {path}")host = block.get("host", DEFAULT_HOST)port = block.get("port", DEFAULT_PORT)if not isinstance(host, str) or not (_is_loopback(host.strip()) or _is_wildcard(host.strip())):- logger.warning("Webapp stays off: webapp.host must be a loopback address, 0.0.0.0 or :: in %s", path)- return WebappSettings()+ return off(f"webapp.host must be a loopback address, 0.0.0.0 or :: in {path}")if isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535:- logger.warning("Webapp stays off: webapp.port must be a port number (1-65535) in %s", path)- return WebappSettings()+ return off(f"webapp.port must be a port number (1-65535) in {path}")public_url = _public_url(block.get("public_url"))if public_url is None:- logger.warning("Webapp stays off: webapp.public_url must be an http:// or https:// address with no "- "credentials, query or fragment in %s", path)- return WebappSettings()+ return off(f"webapp.public_url must be an http:// or https:// address with no credentials, "+ f"query or fragment in {path}")return WebappSettings(enabled=True, host=host.strip(), port=port, public_url=public_url)@@ -149,15 +150,16 @@ def dial_origin(bind_host: str, port: int) -> str:return f"http://[{host}]:{port}" if ":" in host else f"http://{host}:{port}"-def listener_plan(home) -> tuple[str, int, WebappMount | None]:- """The gateway listener's ``(host, port, webapp)`` for the gateway serving *home*."""+def listener_plan(home) -> tuple[str, int, WebappMount | None, str | None]:+ """The gateway listener's ``(host, port, webapp, reason)`` for the gateway serving *home*;+ *reason* says why a ``webapp:`` block that asks for the Webapp cannot be used."""settings = webapp_settings(home)if not settings.enabled:- return (*settings.bind, None)+ return (*settings.bind, None, settings.reason)from hermes_cli.config import get_project_rootfrom hermes_cli.webapp import webapp_dist_dirmount = WebappMount(dist=webapp_dist_dir(get_project_root()), home=Path(home), public_url=settings.public_url)- return (*settings.bind, mount)+ return (*settings.bind, mount, None)def browser_session_token(home, *, rotate: bool = False) -> str:diff --git a/hermes_cli/webapp_launcher.py b/hermes_cli/webapp_launcher.pyindex bc77185df0c..7bbd91ea66c 100644--- a/hermes_cli/webapp_launcher.py+++ b/hermes_cli/webapp_launcher.py@@ -15,6 +15,7 @@ from 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}"class GatewayUnreachable(Exception):@@ -81,6 +82,18 @@ def _refusal(response: dict) -> str:return message if kind.endswith("Error") and message else error+def _off_message(target: Path, then: str) -> str:+ """Why *target*'s config keeps the Webapp off and what to do about it, then *then*: the+ ``webapp:`` block's own problem when it asks for the Webapp but cannot be used."""+ from gateway.webapp_listener import webapp_settings+ settings = webapp_settings(target)+ if settings.reason:+ return f"The Webapp is off: {settings.reason}. Fix it, then {then}."+ if settings.enabled:+ return STARTED_BEFORE_ON+ return f"The Webapp is off. Set webapp.enabled: true in {target / 'config.yaml'}, then {then}."++def _status(target: Path) -> int:try:response = _control(target, "webapp-status")@@ -89,7 +102,7 @@ def _status(target: Path) -> int:if webapp_settings(target).enabled:print("The gateway is not running. Run hermes webapp to start it.")else:- print(f"The Webapp is off. Set webapp.enabled: true in {target / 'config.yaml'}, then run hermes webapp.")+ print(_off_message(target, "run hermes webapp"))return 1if not response.get("ok"):print(_refusal(response))@@ -98,7 +111,7 @@ def _status(target: Path) -> int:if status["state"] == "serving":print(f"Serving at {status['url']}")elif status["state"] == "off":- print(f"The Webapp is off. Set webapp.enabled: true in {target / 'config.yaml'}, then run {RESTART_COMMAND}.")+ print(_off_message(target, f"run {RESTART_COMMAND}"))else:print(f"Unavailable: {status['reason']}")from gateway.webapp_listener import NOT_BUILT@@ -127,7 +140,7 @@ def _explain_refused_launch(target: Path, response: dict) -> int:except GatewayUnreachable:state = Noneif state == "off":- print(f"The gateway started before the Webapp was turned on. Restart it to serve the Webapp: {RESTART_COMMAND}")+ print(STARTED_BEFORE_ON)else:print(_refusal(response))if state == "unavailable":@@ -147,7 +160,7 @@ def cmd_webapp(args) -> int:if args.sign_out:return _sign_out(target)if not args.build_only and not webapp_settings(target).enabled:- print(f"The Webapp is off. Set webapp.enabled: true in {target / 'config.yaml'}, then run hermes webapp again.")+ print(_off_message(target, "run hermes webapp again"))return 1try:_build(args)diff --git a/tests/gateway/test_webapp_settings.py b/tests/gateway/test_webapp_settings.pynew file mode 100644index 00000000000..4fd089274c1--- /dev/null+++ b/tests/gateway/test_webapp_settings.py@@ -0,0 +1,81 @@+"""A ``webapp:`` block that asks for the Webapp but cannot be used says why.++A malformed block keeps the Webapp off (the listener stays private), and the reason reaches the user:+``webapp_settings`` returns it, the gateway reports the Webapp unavailable with it, and ``hermes webapp``+prints it instead of telling the user to set ``webapp.enabled: true`` when it is already set.+"""+import asyncio+import json+from types import SimpleNamespace++import pytest++from gateway import webapp_listener as webapp++MALFORMED = [+ ("webapp: yes\n", "webapp in"),+ ("webapp:\n enabled: 'true'\n", "webapp.enabled"),+ ("webapp:\n enabled: true\n host: 192.168.1.20\n", "webapp.host"),+ ("webapp:\n enabled: true\n host: ''\n", "webapp.host"),+ ("webapp:\n enabled: true\n port: 70000\n", "webapp.port"),+ ("webapp:\n enabled: true\n port: http\n", "webapp.port"),+ ("webapp:\n enabled: true\n public_url: hermes.example.net\n", "webapp.public_url"),+]+++def _home(tmp_path, config):+ home = tmp_path / "home"+ home.mkdir(parents=True)+ (home / "config.yaml").write_text(config, encoding="utf-8")+ return home++[email protected](("block", "key"), MALFORMED)+def test_a_malformed_webapp_block_says_why_it_keeps_the_webapp_off(tmp_path, block, key):+ home = _home(tmp_path, block)+ settings = webapp.webapp_settings(home)+ assert (settings.enabled, settings.bind) == (False, ("127.0.0.1", 0))+ assert key in settings.reason and str(home / "config.yaml") in settings.reason++[email protected]("block", ["", "webapp:\n enabled: false\n port: 70000\n", "webapp:\n enabled: true\n"])+def test_a_webapp_block_that_is_off_or_valid_has_no_reason(tmp_path, block):+ assert webapp.webapp_settings(_home(tmp_path, block)).reason is None+++def _gateway(monkeypatch, tmp_path, config):+ """The runtime's listener start for *config*, with the listener itself replaced by a stand-in."""+ from gateway import run_api, run_runtime+ from gateway.control_socket import GatewayControlServer++ home = _home(tmp_path, config)+ monkeypatch.setenv("HERMES_HOME", str(home))++ async def start(runner, *, host="127.0.0.1", port=0, webapp=None):+ return SimpleNamespace(api_origin=f"http://127.0.0.1:{port or 50001}")++ monkeypatch.setattr(run_api, "start_gateway_api", start)+ runner = SimpleNamespace(session_runtime_descriptor={}, session_authorities=[],+ session_control_server=GatewayControlServer(home))+ asyncio.run(run_runtime.start_gateway_runtime_api(runner))+ return runner+++def _ask(runner, verb):+ raw = json.dumps({"protocol": 1, "verb": verb, "id": 1, "params": {}}).encode()+ return json.loads(runner.session_control_server.handle_request_line(raw, "same-user-peer"))+++def test_the_gateway_reports_a_malformed_webapp_block_as_unavailable_with_its_reason(monkeypatch, tmp_path):+ runner = _gateway(monkeypatch, tmp_path, "webapp:\n enabled: true\n port: 70000\n")+ status = _ask(runner, "webapp-status")["result"]+ assert (status["state"], status["url"]) == ("unavailable", None)+ assert "webapp.port" in status["reason"]+ refused = _ask(runner, "webapp-launch")+ assert refused["ok"] is False and "webapp.port" in refused["error"]+ assert "webapp.enabled: true" not in refused["error"]+++def test_a_gateway_without_a_webapp_block_still_reports_it_off(monkeypatch, tmp_path):+ runner = _gateway(monkeypatch, tmp_path, "")+ assert _ask(runner, "webapp-status")["result"] == {"state": "off", "url": None, "reason": None}diff --git a/tests/hermes_cli/test_webapp_launcher_reasons.py b/tests/hermes_cli/test_webapp_launcher_reasons.pynew file mode 100644index 00000000000..a716e5822a5--- /dev/null+++ b/tests/hermes_cli/test_webapp_launcher_reasons.py@@ -0,0 +1,77 @@+"""``hermes webapp`` says why the Webapp is off.++When the ``webapp:`` block asks for the Webapp but is malformed, the command prints the block's own+problem (an invalid host, port, public URL or a non-boolean ``enabled``), never "Set webapp.enabled:+true" when it is already set; that advice is kept for a config that does not turn the Webapp on.+"""+from argparse import Namespace+from pathlib import Path++import pytest++from hermes_cli import webapp_launcher as launcher+++def _args(**overrides) -> Namespace:+ values = {"no_open": False, "status": False, "sign_out": False, "build_only": False,+ "force_build": False, "skip_build": False}+ values.update(overrides)+ return Namespace(**values)+++def home(monkeypatch, tmp_path):+ root = tmp_path / "root"+ root.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(root))+ monkeypatch.setattr(launcher, "_build", lambda args: pytest.fail("built a Webapp that is off"))+ monkeypatch.setattr(launcher, "_ensure", lambda home: pytest.fail("started a gateway for a Webapp that is off"))+ return root+++def _write(home: Path, config: str) -> None:+ (home / "config.yaml").write_text(config, encoding="utf-8")++[email protected](("block", "key"), [+ ("webapp:\n enabled: true\n port: 70000\n", "webapp.port"),+ ("webapp:\n enabled: true\n host: 192.168.1.20\n", "webapp.host"),+ ("webapp:\n enabled: 'yes'\n", "webapp.enabled"),+])+def test_the_launcher_prints_why_a_malformed_webapp_block_keeps_it_off(home, capsys, block, key):+ _write(home, block)+ assert launcher.cmd_webapp(_args()) == 1+ out = capsys.readouterr().out+ assert key in out+ assert "Set webapp.enabled: true" not in out+++def test_the_launcher_still_says_how_to_turn_an_absent_webapp_on(home, capsys):+ _write(home, "")+ assert launcher.cmd_webapp(_args()) == 1+ assert "Set webapp.enabled: true" in capsys.readouterr().out+++def test_status_without_a_gateway_prints_why_the_webapp_is_off(home, monkeypatch, capsys):+ def unreachable(*_args, **_kwargs):+ raise launcher.GatewayUnreachable("no gateway")++ monkeypatch.setattr(launcher, "_control", unreachable)+ _write(home, "webapp:\n enabled: true\n port: 70000\n")+ assert launcher.cmd_webapp(_args(status=True)) == 1+ out = capsys.readouterr().out+ assert "webapp.port" in out and "Set webapp.enabled: true" not in out++[email protected](("block", "expected"), [+ ("webapp:\n enabled: true\n port: 70000\n", "webapp.port"),+ # Valid and on: the gateway predates the change and only needs a restart.+ ("webapp:\n enabled: true\n", launcher.RESTART_COMMAND),+])+def test_status_of_a_gateway_that_serves_no_webapp_reads_the_current_config(home, monkeypatch, capsys, block, expected):+ answer = {"ok": True, "result": {"state": "off", "url": None, "reason": None}}+ monkeypatch.setattr(launcher, "_control", lambda *_args, **_kwargs: answer)+ _write(home, block)+ launcher.cmd_webapp(_args(status=True))+ out = capsys.readouterr().out+ assert expected in out and "Set webapp.enabled: true" not in out