Skip to content

The agent that grows with you

feat(cli): open the gateway's Webapp with hermes webapp

emozilla463af9d5c78b
diff --git a/hermes_cli/gateway_client.py b/hermes_cli/gateway_client.py
index 788837b3e44..cbb02af51f4 100644
--- a/hermes_cli/gateway_client.py
+++ b/hermes_cli/gateway_client.py
@@ -223,9 +223,33 @@ class GatewayClient:
self.pending.pop(rid, None)
+def private_control_query(home: Path, request: bytes, timeout: float = 5) -> bytes:
+ """Send one request line to *home*'s gateway control socket as this OS user; the raw answer.
+
+ The socket authenticates the peer (same user only), which is what lets a private verb answer."""
+ if os.name == "nt":
+ from gateway.runtime_bootstrap_windows import query_runtime_control
+ return query_runtime_control(home, request, timeout)
+ from hermes_cli.gateway_runtime_discovery import connect_private
+ deadline = time.monotonic() + timeout
+ with connect_private(home, timeout) as peer:
+ peer.sendall(request)
+ data = bytearray()
+ while b"\n" not in data:
+ budget = deadline - time.monotonic()
+ if budget <= 0:
+ raise GatewayClientError("Gateway bootstrap timed out")
+ peer.settimeout(budget)
+ chunk = peer.recv(4096)
+ if not chunk or len(data) + len(chunk) > 65536:
+ raise GatewayClientError("Invalid gateway bootstrap response")
+ data.extend(chunk)
+ return bytes(data)
+
+
def _session_ticket(home: Path, endpoint, *, purpose="interactive", scope=None, subject=None) -> str:
from hermes_cli.gateway_runtime import control_home_for
- from hermes_cli.gateway_runtime_discovery import connect_private, _identify_response
+ from hermes_cli.gateway_runtime_discovery import _identify_response
# A served secondary's ticket is minted by the multiplexer's socket, bound to the secondary.
home = control_home_for(home, endpoint)
# ``subject`` names the principal a same-user caller acts for (the standalone dashboard's
@@ -234,24 +258,7 @@ def _session_ticket(home: Path, endpoint, *, purpose="interactive", scope=None,
"profile_id": endpoint.profile_id, "instance_id": endpoint.instance_id, "purpose": purpose,
**({"scope": scope} if scope else {}), **({"subject": subject} if subject else {}),
}}).encode() + b"\n"
- if os.name == "nt":
- from gateway.runtime_bootstrap_windows import query_runtime_control
- data = query_runtime_control(home, request, 5)
- else:
- deadline = time.monotonic() + 5
- with connect_private(home, 5) as peer:
- peer.sendall(request)
- data = bytearray()
- while b"\n" not in data:
- budget = deadline - time.monotonic()
- if budget <= 0:
- raise GatewayClientError("Gateway bootstrap timed out")
- peer.settimeout(budget)
- chunk = peer.recv(4096)
- if not chunk or len(data) + len(chunk) > 65536:
- raise GatewayClientError("Invalid gateway bootstrap response")
- data.extend(chunk)
- grant = _identify_response(bytes(data))
+ grant = _identify_response(private_control_query(home, request))
if any(grant.get(k) != v for k, v in {
"profile_id": endpoint.profile_id, "instance_id": endpoint.instance_id, "runtime_protocol": 1,
}.items()) or not isinstance(grant.get("ticket"), str) or not grant["ticket"]:
@@ -260,11 +267,12 @@ def _session_ticket(home: Path, endpoint, *, purpose="interactive", scope=None,
@asynccontextmanager
-async def connect_gateway(endpoint=None, subject=None):
+async def connect_gateway(endpoint=None, subject=None, *, max_size=8 * 1024 * 1024):
"""Attach to this home's owner. ``endpoint``: an already-discovered ready owner to dial as-is
(maintenance that must never start a gateway); default ensures one, starting it if needed.
``subject``: mint the ticket for this principal (the caller's authenticated dashboard user)
- rather than the socket identity; only a peer the owner already trusts may name one."""
+ rather than the socket identity; only a peer the owner already trusts may name one.
+ ``max_size``: the largest frame accepted; a ``session.resume`` answer carries the whole history."""
from websockets.asyncio.client import connect
from hermes_constants import get_hermes_home
from hermes_cli.gateway_runtime import attachable, ensure_gateway_runtime, gateway_profile_home
@@ -302,7 +310,7 @@ async def connect_gateway(endpoint=None, subject=None):
# The gateway is a loopback (or explicitly named) peer, never something to route through the
# user's HTTP(S) proxy; websockets>=14 reads HTTP_PROXY/HTTPS_PROXY by default and a proxy that
# cannot reach 127.0.0.1 turns every launch into a 10 s open timeout.
- async with connect(url, subprotocols=protocols, open_timeout=10, max_size=8 * 1024 * 1024,
+ async with connect(url, subprotocols=protocols, open_timeout=10, max_size=max_size,
proxy=None) as ws:
if protocols and ws.subprotocol != GATEWAY_WS_PROTOCOL:
raise GatewayClientError("Gateway protocol mismatch; update/restart required")
diff --git a/hermes_cli/main.py b/hermes_cli/main.py
index e5384f28173..28717e732ec 100644
--- a/hermes_cli/main.py
+++ b/hermes_cli/main.py
@@ -375,6 +375,7 @@ from hermes_cli.subcommands.console import build_console_parser
from hermes_cli.subcommands.update import build_update_parser
from hermes_cli.subcommands.uninstall import build_uninstall_parser
from hermes_cli.subcommands.dashboard import build_dashboard_parser, build_serve_parser
+from hermes_cli.subcommands.webapp import build_webapp_parser
from hermes_cli.subcommands.gui import build_gui_parser
from hermes_cli.subcommands.logs import build_logs_parser
from hermes_cli.subcommands.prompt_size import build_prompt_size_parser
@@ -1840,6 +1841,7 @@ cmd_debug = _forward_command("cmd_debug", "hermes_cli.debug", "run_debug", doc='
cmd_skin = _forward_command("cmd_skin", "hermes_cli.skin_cmd", "skin_command", doc='Skin management (list / use / set).')
cmd_import = _forward_command("cmd_import", "hermes_cli.backup", "run_import", forward_return=True, doc='Restore a Hermes backup from a zip file.')
cmd_dashboard_register = _forward_command("cmd_dashboard_register", "hermes_cli.dashboard_register", "cmd_dashboard_register", doc='Register a self-hosted dashboard OAuth client with Nous Portal.')
+cmd_webapp = _forward_command("cmd_webapp", "hermes_cli.webapp_launcher", "cmd_webapp", forward_return=True, doc='Open the browser-hosted Desktop the gateway serves.')
cmd_gateway_enroll = _forward_command("cmd_gateway_enroll", "hermes_cli.gateway_enroll", "cmd_gateway_enroll", doc='Enroll a self-hosted gateway with a relay connector.')
cmd_prompt_size = _forward_command("cmd_prompt_size", "hermes_cli.prompt_size", "cmd_prompt_size", doc='Show a byte/char breakdown of the system prompt + tool schemas.')
cmd_pairing = _forward_command("cmd_pairing", "hermes_cli.pairing", "pairing_command")
@@ -2438,7 +2440,7 @@ def _coalesce_session_name_args(argv: list) -> list:
_SUBCOMMANDS = {
"chat", "model", "gateway", "setup", "whatsapp", "whatsapp-cloud", "login", "logout",
"auth", "status", "cron", "doctor", "config", "pairing", "skills", "tools", "mcp",
- "sessions", "insights", "update", "uninstall", "profile", "dashboard", "serve",
+ "sessions", "insights", "update", "uninstall", "profile", "dashboard", "serve", "webapp",
"desktop", "gui", "honcho", "claw", "plugins", "security", "acp", "webhook", "peer",
"memory", "dump", "debug", "backup", "import", "completion", "logs", "usage",
}
@@ -3383,10 +3385,8 @@ def _build_cli_parser():
build_profile_parser(subparsers, cmd_profile=cmd_profile)
build_completion_parser(subparsers, cmd_completion=cmd_completion, parser=parser)
build_dashboard_parser(
- subparsers,
- cmd_dashboard=cmd_dashboard,
- cmd_dashboard_register=cmd_dashboard_register,
- )
+ subparsers, cmd_dashboard=cmd_dashboard, cmd_dashboard_register=cmd_dashboard_register)
+ build_webapp_parser(subparsers, cmd_webapp=cmd_webapp)
# "desktop" is canonical (Hermes-Setup.exe tells users to run it, so it
# must be the name --help shows); "gui" is a deprecated alias.
build_gui_parser(subparsers, cmd_gui=cmd_gui)
diff --git a/hermes_cli/subcommands/webapp.py b/hermes_cli/subcommands/webapp.py
new file mode 100644
index 00000000000..98631fb29d7
--- /dev/null
+++ b/hermes_cli/subcommands/webapp.py
@@ -0,0 +1,27 @@
+"""``hermes webapp``: open the Desktop workspace in a browser, served by the gateway."""
+
+from __future__ import annotations
+
+from typing import Callable
+
+
+def build_webapp_parser(subparsers, *, cmd_webapp: Callable) -> None:
+ parser = subparsers.add_parser(
+ "webapp",
+ help="Open the Hermes Desktop workspace in a browser",
+ description=(
+ "Open the Hermes Desktop workspace in a browser. The gateway serves it when "
+ "webapp.enabled is true in config.yaml; this command builds the bundle when needed, "
+ "starts the gateway and opens a one-use sign-in link."
+ ),
+ )
+ parser.add_argument("--no-open", action="store_true", help="Print the one-use link instead of opening a browser")
+ parser.add_argument("--force-build", action="store_true",
+ help="Rebuild the Webapp bundle even when its build receipt is current")
+ parser.add_argument("--skip-build", action="store_true", help="Use the existing Webapp bundle as is")
+ action = parser.add_mutually_exclusive_group()
+ action.add_argument("--build-only", action="store_true", help="Build the Webapp bundle and stop")
+ action.add_argument("--status", action="store_true", help="Show whether the gateway is serving the Webapp")
+ action.add_argument("--sign-out", action="store_true",
+ help="Sign out every Webapp tab (each needs a new link from hermes webapp)")
+ parser.set_defaults(func=cmd_webapp)
diff --git a/hermes_cli/web_routers/webapp.py b/hermes_cli/web_routers/webapp.py
index 465dea5c35c..4ee1c0ca512 100644
--- a/hermes_cli/web_routers/webapp.py
+++ b/hermes_cli/web_routers/webapp.py
@@ -216,7 +216,7 @@ history.replaceState(null, '', location.pathname);
const ticket = params.get('ticket') || '';
const fail = () => {
document.getElementById('status').textContent = 'This launch link was already used or has expired. '
- + 'Open the private link printed by hermes webapp, or restart hermes webapp for a new one.';
+ + 'Run hermes webapp again for a new one.';
};
if (!/^[A-Za-z0-9_-]{43}$/.test(ticket)) {
fail();
diff --git a/hermes_cli/webapp_launcher.py b/hermes_cli/webapp_launcher.py
new file mode 100644
index 00000000000..402d52c17a6
--- /dev/null
+++ b/hermes_cli/webapp_launcher.py
@@ -0,0 +1,175 @@
+"""``hermes webapp``: open the browser-hosted Desktop that the gateway serves.
+
+The gateway serves the Webapp on its own listener when its home's config sets ``webapp.enabled``
+(``gateway.webapp_listener``). This command builds the bundle when it is stale, starts the gateway that
+serves the current profile, asks it for a one-use launch link over the control socket (same OS user
+only) and opens that link, so the credential appears in no argv, output or link. On macOS, where a
+one-use link cannot be redeemed, it prints the gateway's private link for the user to open instead.
+``--status`` and ``--sign-out`` talk to a running gateway and never start one.
+"""
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+RESTART_COMMAND = "hermes gateway restart"
+
+
+class GatewayUnreachable(Exception):
+ """The gateway for that home did not start or does not answer on its control socket."""
+
+
+def _gateway_home(home: Path) -> Path:
+ """The home whose gateway serves *home*: the default gateway for a named profile it serves (the
+ route native Desktop takes), else the profile's own."""
+ from hermes_cli.gateway_runtime_multiplex import implied_host_root
+ return implied_host_root(home) or home
+
+
+def _build(args):
+ from hermes_cli.config import get_project_root
+ from hermes_cli.webapp import prepare_webapp_renderer
+ return prepare_webapp_renderer(
+ get_project_root(), force=args.force_build, skip_build=args.skip_build,
+ explicit=args.force_build or args.build_only)
+
+
+def _ensure(home) -> None:
+ from hermes_cli.gateway_runtime import attachable, ensure_gateway_runtime
+ result = ensure_gateway_runtime(home, idle_exit=False)
+ if not attachable(result):
+ cause = ": ".join(part for part in (result.state, result.detail or result.reason_code) if part)
+ raise GatewayUnreachable(f"The gateway did not start ({cause}).")
+
+
+def _control(home, verb: str, params: dict | None = None) -> dict:
+ from hermes_cli.gateway_client import private_control_query
+ request = json.dumps({"protocol": 1, "id": 1, "verb": verb, "params": params or {}}).encode() + b"\n"
+ try:
+ data = private_control_query(Path(home), request)
+ return json.loads(data.split(b"\n", 1)[0])
+ except Exception as exc: # no socket, a refused peer, a timeout or a garbled answer
+ raise GatewayUnreachable(str(exc)) from exc
+
+
+def _open(url: str) -> bool:
+ import webbrowser
+ from hermes_cli.auth_device_flow import _can_open_graphical_browser
+ if not _can_open_graphical_browser():
+ return False
+ try:
+ return bool(webbrowser.open(url))
+ except (webbrowser.Error, OSError):
+ return False
+
+
+def _profile_choice(home: Path, target: Path) -> dict:
+ """``{"profile": name}`` when the gateway serves *home* as one of its named profiles, so the
+ Webapp opens on the profile this command ran for."""
+ from hermes_constants import profile_name_for_home
+ if Path(home).resolve() == Path(target).resolve():
+ return {}
+ name = profile_name_for_home(home)
+ return {"profile": name} if name and name != "default" else {}
+
+
+def _refusal(response: dict) -> str:
+ error = str(response.get("error") or "The gateway refused the request.")
+ kind, _, message = error.partition(": ")
+ return message if kind.endswith("Error") and message else error
+
+
+def _status(target: Path) -> int:
+ try:
+ response = _control(target, "webapp-status")
+ except GatewayUnreachable:
+ from gateway.webapp_listener import webapp_settings
+ 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.")
+ return 1
+ if not response.get("ok"):
+ print(_refusal(response))
+ return 1
+ status = response["result"]
+ 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}.")
+ else:
+ print(f"Unavailable: {status['reason']}")
+ return 0
+
+
+def _sign_out(target: Path) -> int:
+ from gateway.webapp_listener import browser_session_token
+ try:
+ response = _control(target, "webapp-sign-out")
+ except GatewayUnreachable:
+ response = {"ok": False}
+ if not response.get("ok"):
+ # No gateway is serving the Webapp right now: replace the stored credential so no tab can
+ # use the old one when it does.
+ browser_session_token(target, rotate=True)
+ print("Signed out of every Webapp tab.")
+ return 0
+
+
+def _explain_refused_launch(target: Path, response: dict) -> int:
+ try:
+ state = (_control(target, "webapp-status").get("result") or {}).get("state")
+ except GatewayUnreachable:
+ state = None
+ if state == "off":
+ print(f"The gateway started before the Webapp was turned on. Restart it to serve the Webapp: {RESTART_COMMAND}")
+ else:
+ print(_refusal(response))
+ return 1
+
+
+def cmd_webapp(args) -> int:
+ from gateway.webapp_listener import webapp_settings
+ from hermes_cli.webapp import WebappBuildError
+ from hermes_constants import get_hermes_home
+
+ home = get_hermes_home()
+ target = _gateway_home(home)
+ if args.status:
+ return _status(target)
+ 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.")
+ return 1
+ try:
+ _build(args)
+ except WebappBuildError as exc:
+ print(f"✗ {exc}")
+ print(" Build it explicitly:")
+ print(" hermes webapp --build-only")
+ return 1
+ if args.build_only:
+ print("Webapp bundle ready.")
+ return 0
+ try:
+ _ensure(target)
+ response = _control(target, "webapp-launch", _profile_choice(home, target))
+ except GatewayUnreachable as exc:
+ print(str(exc))
+ return 1
+ if not response.get("ok"):
+ return _explain_refused_launch(target, response)
+ link = response["result"]
+ if link.get("private"):
+ # The gateway's own credential (macOS, where a one-use link cannot be redeemed): for the user
+ # to open, never for a browser launcher whose arguments other processes can read.
+ print("Open this link in your browser. It signs the browser in as you, so keep it private:")
+ print(f" {link['url']}")
+ return 0
+ if not args.no_open and _open(link["url"]):
+ print("Opened the Webapp in your browser.")
+ return 0
+ print(f"Open the Webapp with this one-use link (valid for {link['expires_in_seconds']} seconds):")
+ print(f" {link['url']}")
+ return 0
diff --git a/tests/gateway/test_control_socket_peer_security.py b/tests/gateway/test_control_socket_peer_security.py
index fbbc9bf5719..263c089723e 100644
--- a/tests/gateway/test_control_socket_peer_security.py
+++ b/tests/gateway/test_control_socket_peer_security.py
@@ -132,9 +132,14 @@ def test_clients_refuse_a_control_listener_run_by_another_uid(tmp_path, monkeypa
spec = importlib.util.spec_from_file_location("tui_bootstrap", "ui-tui/scripts/gateway_bootstrap.py")
tui_bootstrap = importlib.util.module_from_spec(spec)
spec.loader.exec_module(tui_bootstrap)
- for client in (gateway_client._session_ticket, session_hosted_transport.owner_request, tui_bootstrap.bootstrap):
+ for client in (gateway_client.private_control_query, session_hosted_transport.owner_request, tui_bootstrap.bootstrap):
source = inspect.getsource(client)
assert "connect_private(" in source and "AF_UNIX" not in source, client.__qualname__
+ # The other control-socket clients dial through private_control_query.
+ from hermes_cli import webapp_launcher
+ for caller in (gateway_client._session_ticket, webapp_launcher._control):
+ source = inspect.getsource(caller)
+ assert "private_control_query(" in source and "AF_UNIX" not in source, caller.__qualname__
def test_long_home_survives_a_squatted_shared_fallback_directory(tmp_path, monkeypatch):
diff --git a/tests/hermes_cli/test_webapp_launcher.py b/tests/hermes_cli/test_webapp_launcher.py
new file mode 100644
index 00000000000..2fd3b32a22a
--- /dev/null
+++ b/tests/hermes_cli/test_webapp_launcher.py
@@ -0,0 +1,211 @@
+"""``hermes webapp`` opens the browser-hosted Desktop that the gateway serves.
+
+It builds the Webapp bundle when stale, starts the gateway that serves the current profile (the default
+gateway 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.
+"""
+from argparse import Namespace
+from pathlib import Path
+
+import pytest
+
+from hermes_cli import webapp_launcher as launcher
+
+LINK = "http://127.0.0.1:9120/webapp/launch#ticket=" + "t" * 43
+
+
+def _home(path: Path, config: str = "") -> Path:
+ path.mkdir(parents=True, exist_ok=True)
+ (path / "config.yaml").write_text(config, encoding="utf-8")
+ return path
+
+
+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 world(monkeypatch, tmp_path):
+ """The launcher's side effects, recorded; the control socket answers from ``answers``."""
+ calls = {"build": 0, "ensure": [], "control": [], "opened": []}
+ answers = {"webapp-launch": {"ok": True, "result": {"url": LINK, "private": False, "expires_in_seconds": 60}},
+ "webapp-status": {"ok": True, "result": {"state": "serving", "url": LINK.split("/webapp")[0],
+ "reason": None}},
+ "webapp-sign-out": {"ok": True, "result": {"signed_out": True}}}
+
+ def build(args):
+ calls["build"] += 1
+ return tmp_path / "dist-webapp"
+
+ def control(home, verb, params=None):
+ calls["control"].append((Path(home), verb))
+ calls.setdefault("params", []).append(params or {})
+ answer = answers[verb]
+ if isinstance(answer, Exception):
+ raise answer
+ return answer
+
+ monkeypatch.setattr(launcher, "_build", build)
+ 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)
+ 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}
+
+
+def _use_home(world, home):
+ world["monkeypatch"].setenv("HERMES_HOME", str(home))
+
+
+def test_the_webapp_opens_from_a_one_use_link_its_gateway_mints(world, capsys):
+ assert launcher.cmd_webapp(_args()) == 0
+ calls = world["calls"]
+ assert calls["build"] == 1
+ assert calls["ensure"] == [world["root"]]
+ assert calls["control"] == [(world["root"], "webapp-launch")]
+ assert calls["opened"] == [LINK]
+ out = capsys.readouterr().out
+ assert "Opened the Webapp in your browser" in out
+ assert "ticket=" not in out
+
+
+def test_a_named_profile_opens_the_webapp_of_the_default_gateway_on_that_profile(world):
+ profile = _home(world["root"] / "profiles" / "work")
+ _use_home(world, profile)
+ assert launcher.cmd_webapp(_args()) == 0
+ assert world["calls"]["ensure"] == [world["root"]]
+ assert world["calls"]["control"] == [(world["root"], "webapp-launch")]
+ assert world["calls"]["params"] == [{"profile": "work"}]
+
+
+def test_the_default_profile_opens_without_a_profile_choice(world):
+ assert launcher.cmd_webapp(_args()) == 0
+ assert world["calls"]["params"] == [{}]
+
+
+def test_a_standalone_profile_opens_the_webapp_of_its_own_gateway(world):
+ profile = _home(world["root"] / "profiles" / "solo",
+ "gateway:\n standalone: true\nwebapp:\n enabled: true\n")
+ _use_home(world, profile)
+ assert launcher.cmd_webapp(_args()) == 0
+ assert world["calls"]["ensure"] == [profile]
+
+
+def test_the_launcher_says_how_to_turn_the_webapp_on(world, capsys):
+ (world["root"] / "config.yaml").write_text("", encoding="utf-8")
+ assert launcher.cmd_webapp(_args()) == 1
+ out = capsys.readouterr().out
+ assert "webapp.enabled: true" in out and str(world["root"] / "config.yaml") in out
+ assert (world["calls"]["build"], world["calls"]["ensure"]) == (0, [])
+
+
+def test_a_gateway_started_before_the_webapp_was_turned_on_asks_for_a_restart(world, capsys):
+ world["answers"]["webapp-launch"] = {"ok": False, "error": "RuntimeError: The Webapp is off. Set ..."}
+ world["answers"]["webapp-status"] = {"ok": True, "result": {"state": "off", "url": None, "reason": None}}
+ assert launcher.cmd_webapp(_args()) == 1
+ out = capsys.readouterr().out
+ assert "hermes gateway restart" in out
+ assert world["calls"]["opened"] == []
+
+
+def test_a_webapp_the_gateway_could_not_serve_reports_why(world, capsys):
+ reason = "could not listen on 127.0.0.1:9120 (Address already in use)"
+ world["answers"]["webapp-launch"] = {"ok": False, "error": f"RuntimeError: The Webapp is unavailable: {reason}"}
+ world["answers"]["webapp-status"] = {"ok": True, "result": {"state": "unavailable", "url": None,
+ "reason": reason}}
+ assert launcher.cmd_webapp(_args()) == 1
+ assert reason in capsys.readouterr().out
+
+
+def test_no_open_prints_the_link_instead(world, capsys):
+ assert launcher.cmd_webapp(_args(no_open=True)) == 0
+ assert world["calls"]["opened"] == []
+ out = capsys.readouterr().out
+ assert LINK in out and "60 seconds" in out
+
+
+def test_a_browser_that_will_not_open_leaves_the_link_on_screen(world, capsys):
+ world["monkeypatch"].setattr(launcher, "_open", lambda url: False)
+ assert launcher.cmd_webapp(_args()) == 0
+ assert LINK in capsys.readouterr().out
+
+
+def test_build_only_builds_without_a_gateway(world):
+ assert launcher.cmd_webapp(_args(build_only=True)) == 0
+ assert (world["calls"]["build"], world["calls"]["ensure"], world["calls"]["control"]) == (1, [], [])
+
+
+def test_status_reads_the_running_gateway_without_starting_one(world, capsys):
+ assert launcher.cmd_webapp(_args(status=True)) == 0
+ assert world["calls"]["ensure"] == []
+ assert world["calls"]["control"] == [(world["root"], "webapp-status")]
+ assert "http://127.0.0.1:9120" in capsys.readouterr().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
+ assert "gateway is not running" in capsys.readouterr().out
+
+
+def test_status_with_no_gateway_running_and_the_webapp_off_says_how_to_turn_it_on(world, capsys):
+ (world["root"] / "config.yaml").write_text("", encoding="utf-8")
+ world["answers"]["webapp-status"] = launcher.GatewayUnreachable("no gateway")
+ assert launcher.cmd_webapp(_args(status=True)) == 1
+ out = capsys.readouterr().out
+ assert "webapp.enabled: true" in out and str(world["root"] / "config.yaml") in out
+ assert "Run hermes webapp" not in out
+
+
+def test_sign_out_replaces_the_browser_credential_on_the_running_gateway(world, capsys):
+ assert launcher.cmd_webapp(_args(sign_out=True)) == 0
+ assert world["calls"]["control"] == [(world["root"], "webapp-sign-out")]
+ assert world["calls"]["ensure"] == []
+ assert "Signed out" in capsys.readouterr().out
+
+
+def test_a_gateway_that_will_not_start_is_reported(world, capsys):
+ def refuse(home):
+ raise launcher.GatewayUnreachable("The gateway did not start (inaccessible: lock owned by another user).")
+
+ world["monkeypatch"].setattr(launcher, "_ensure", refuse)
+ assert launcher.cmd_webapp(_args()) == 1
+ assert "lock owned by another user" in capsys.readouterr().out
+ assert world["calls"]["control"] == []
+
+
+def test_signing_out_with_no_gateway_running_still_replaces_the_stored_credential(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("no gateway")
+ assert launcher.cmd_webapp(_args(sign_out=True)) == 0
+ assert (world["root"] / TOKEN_PATH).read_text().strip() != before
+ assert "Signed out" in capsys.readouterr().out
+
+
+def test_the_webapp_command_takes_one_action_at_a_time():
+ import argparse
+ from hermes_cli.subcommands.webapp import build_webapp_parser
+ parser = argparse.ArgumentParser()
+ seen = []
+ build_webapp_parser(parser.add_subparsers(), cmd_webapp=seen.append)
+ args = parser.parse_args(["webapp", "--no-open", "--force-build"])
+ args.func(args)
+ assert vars(seen[0]) | {"func": None} == vars(_args(no_open=True, force_build=True)) | {"func": None}
+ for clash in (["--status", "--sign-out"], ["--status", "--build-only"], ["--sign-out", "--build-only"]):
+ with pytest.raises(SystemExit):
+ parser.parse_args(["webapp", *clash])
+
+
+def test_a_private_link_is_printed_for_the_user_and_never_handed_to_a_browser_launcher(world, capsys):
+ private = "http://127.0.0.1:9120/#hermes-session=" + "s" * 43
+ world["answers"]["webapp-launch"] = {"ok": True, "result": {"url": private, "private": True,
+ "expires_in_seconds": None}}
+ assert launcher.cmd_webapp(_args()) == 0
+ assert world["calls"]["opened"] == []
+ out = capsys.readouterr().out
+ assert private in out and "keep it private" in out