fix(gateway): drop HERMES_WEBAPP_ADDRESS_WAIT, skip wait for idle-exit gateways, and pin teardown-stop guards
Address review findings from BearHuddleston on https://github.com/NousResearch/hermes-agent/pull/160232: - Remove the HERMES_WEBAPP_ADDRESS_WAIT environment variable override and its HX002 waiver from gateway/run_runtime_listener.py; pass address_wait / wait_seconds explicitly to start_gateway_runtime_api and _start_gateway_api_waiting_for_address (keeping WEBAPP_ADDRESS_WAIT_SECONDS as the default), pass address_wait in tests/gateway/fixtures/webapp_fallback_peer.py instead of env_overrides, and update website/docs/getting-started/nix-setup.md for the 20s supervised wait. - Skip the 20s address wait in gateway/run_bootstrap.py when idle_exit is True so TUI / chat -q idle-exit gateways (which Ink waits on with a hard 30s budget) fall back immediately, and add a parametrized test covering idle_exit=True vs supervised (idle_exit=False). - Add a parametrized test pinning that a stop beginning while a Webapp listener binds, falls back to the private listener, or is refused publishes no listener after teardown and starts no fallback.
This commit is contained in:
committed by
Mark S.
parent
126911ef00
commit
93dd2a4efb
@@ -754,8 +754,10 @@ async def _start_gateway_listener_and_runner(
|
||||
_resolve_gateway_exit_verdict, _shutdown_gateway_health_export,
|
||||
)
|
||||
from gateway.run_common import abort_startup_if_shutdown_requested, startup_should_abort
|
||||
from gateway.run_runtime_listener import start_gateway_runtime_api
|
||||
await start_gateway_runtime_api(runner)
|
||||
from gateway.run_runtime_listener import WEBAPP_ADDRESS_WAIT_SECONDS, start_gateway_runtime_api
|
||||
# A client's own idle-exit gateway (TUI, chat -q) has that client waiting on a hard start budget
|
||||
# (Ink's is 30 s), and the boot race the address wait covers is a supervised unit's.
|
||||
await start_gateway_runtime_api(runner, address_wait=0.0 if idle_exit else WEBAPP_ADDRESS_WAIT_SECONDS)
|
||||
if startup_should_abort(runner):
|
||||
try:
|
||||
await abort_startup_if_shutdown_requested(runner, check=False)
|
||||
|
||||
@@ -5,8 +5,6 @@ import asyncio
|
||||
from contextlib import suppress
|
||||
import errno
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
import time
|
||||
|
||||
# Log-record parity with gateway/run_runtime.py.
|
||||
@@ -17,29 +15,12 @@ logger = logging.getLogger("gateway.run_runtime")
|
||||
# daemon reports ready, and a DHCP lease lands the same way. The bind then fails with EADDRNOTAVAIL, and
|
||||
# the gateway keeps running with the Webapp off (see below) — nothing crashes, so no Restart= policy
|
||||
# retries it and the address stays dark until someone restarts the gateway by hand. Wait, bounded, for the
|
||||
# address to appear, then bind again. ``HERMES_WEBAPP_ADDRESS_WAIT`` overrides the wait in seconds (0
|
||||
# disables it); only EADDRNOTAVAIL is waited out, so a busy port or a refused bind still reports at once.
|
||||
# address to appear, then bind again. Only EADDRNOTAVAIL is waited out, so a busy port or a refused bind
|
||||
# still reports at once.
|
||||
WEBAPP_ADDRESS_WAIT_SECONDS = 20.0
|
||||
_WEBAPP_ADDRESS_POLL_SECONDS = 0.5
|
||||
|
||||
|
||||
def _webapp_address_wait_seconds() -> float:
|
||||
"""How long to wait for ``webapp.host`` to be assigned to an interface (see above)."""
|
||||
# health: allow HX002 -- process-level boot-timing override for systemd/supervisor startup ordering (shared by the gateway process, not per-profile)
|
||||
raw = os.environ.get("HERMES_WEBAPP_ADDRESS_WAIT")
|
||||
if raw is None or not raw.strip():
|
||||
return WEBAPP_ADDRESS_WAIT_SECONDS
|
||||
try:
|
||||
seconds = float(raw)
|
||||
except ValueError:
|
||||
seconds = float("nan")
|
||||
if not math.isfinite(seconds):
|
||||
logger.warning("HERMES_WEBAPP_ADDRESS_WAIT=%r is not a number of seconds; using %.0fs",
|
||||
raw, WEBAPP_ADDRESS_WAIT_SECONDS)
|
||||
return WEBAPP_ADDRESS_WAIT_SECONDS
|
||||
return max(0.0, seconds)
|
||||
|
||||
|
||||
async def _wait_for_address_retry(runner, delay: float) -> None:
|
||||
"""Sleep up to *delay* seconds for the address to appear, waking at once on shutdown."""
|
||||
shutdown_event = getattr(runner, "_shutdown_event", None)
|
||||
@@ -63,7 +44,7 @@ async def _close_listener_if_stopping(run_api, runner, handle) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
async def _start_gateway_api_waiting_for_address(run_api, runner, *, host, port, webapp):
|
||||
async def _start_gateway_api_waiting_for_address(run_api, runner, *, host, port, webapp, wait_seconds):
|
||||
"""Start the gateway's listener, waiting out a specific ``webapp.host`` an interface has not been given yet.
|
||||
|
||||
A failed start leaves nothing behind (``start_gateway_api`` closes its listener and clears its
|
||||
@@ -76,8 +57,8 @@ async def _start_gateway_api_waiting_for_address(run_api, runner, *, host, port,
|
||||
from gateway.run_common import startup_should_abort
|
||||
from gateway.webapp_listener import loopback_companion
|
||||
|
||||
wait_for_address = webapp is not None and bool(loopback_companion(host))
|
||||
deadline = (time.monotonic() + _webapp_address_wait_seconds()) if wait_for_address else 0.0
|
||||
wait_for_address = wait_seconds > 0 and webapp is not None and bool(loopback_companion(host))
|
||||
deadline = time.monotonic() + wait_seconds
|
||||
warned = False
|
||||
|
||||
async def _start():
|
||||
@@ -130,7 +111,7 @@ def _webapp_unavailable_reason(exc: BaseException, *, host: str, port: int, run_
|
||||
return f"could not listen on {address} ({cause})"
|
||||
|
||||
|
||||
async def start_gateway_runtime_api(runner):
|
||||
async def start_gateway_runtime_api(runner, *, address_wait: float = WEBAPP_ADDRESS_WAIT_SECONDS):
|
||||
from gateway import run_api, run_runtime
|
||||
from gateway.run_common import startup_should_abort
|
||||
from gateway.webapp_listener import (
|
||||
@@ -150,7 +131,7 @@ async def start_gateway_runtime_api(runner):
|
||||
try:
|
||||
# Without the Webapp the listener is main's: the same call, a private ephemeral port.
|
||||
handle = await _start_gateway_api_waiting_for_address(
|
||||
run_api, runner, host=host, port=port, webapp=webapp)
|
||||
run_api, runner, host=host, port=port, webapp=webapp, wait_seconds=address_wait)
|
||||
except (Exception, SystemExit) as exc: # health: allow BLE001 -- Webapp listener bind/credential/auth-gate failures intentionally fall back to the private listener and record the reason in webapp_status
|
||||
if startup_should_abort(runner):
|
||||
runner.session_api = None
|
||||
|
||||
@@ -20,6 +20,7 @@ Run as ``python webapp_fallback_peer.py '<spec json>'`` with an isolated ``HERME
|
||||
- ``probe_bind_host``: also ask ``/api/status`` at the Webapp's own (non-loopback) ``webapp.host`` address;
|
||||
- ``report_listening``: addresses to report, once the gateway started, whether anything accepts a
|
||||
connection on the Webapp's port there;
|
||||
- ``address_wait``: seconds to wait for a ``webapp.host`` no interface holds yet (default: the runtime's);
|
||||
- ``credential``: the stored browser credential this gateway finds: ``"folder-is-a-file"`` (a plain
|
||||
file where the ``webapp/`` folder goes), ``"token-is-a-folder"`` (a folder where
|
||||
``webapp/session-token`` goes), ``"not-utf8"`` (the token saved as UTF-16), or null for a
|
||||
@@ -48,7 +49,7 @@ def free_port() -> int:
|
||||
return probe.getsockname()[1]
|
||||
|
||||
|
||||
def run(tmp_path, spec, *, env_overrides: dict[str, str] | None = None) -> dict:
|
||||
def run(tmp_path, spec) -> dict:
|
||||
"""Run this peer for *spec* in a fresh home under *tmp_path*; returns its receipt."""
|
||||
from tests.gateway.fixtures.local_recovery_probe import child_env
|
||||
|
||||
@@ -59,8 +60,6 @@ def run(tmp_path, spec, *, env_overrides: dict[str, str] | None = None) -> dict:
|
||||
env = child_env()
|
||||
env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),
|
||||
PYTHONUNBUFFERED="1")
|
||||
if env_overrides:
|
||||
env.update(env_overrides)
|
||||
result = subprocess.run([sys.executable, __file__, json.dumps(spec)], cwd=root, env=env,
|
||||
capture_output=True, text=True, timeout=120, check=False)
|
||||
receipt = home / "receipt.json"
|
||||
@@ -221,7 +220,7 @@ async def probe(spec):
|
||||
from gateway.control_socket import GatewayControlServer
|
||||
from gateway.run import GatewayRunner
|
||||
from gateway.run_api import stop_gateway_api
|
||||
from gateway.run_runtime_listener import start_gateway_runtime_api
|
||||
from gateway.run_runtime_listener import WEBAPP_ADDRESS_WAIT_SECONDS, start_gateway_runtime_api
|
||||
from gateway.session_authority import initialize_session_authority
|
||||
import hermes_cli.webapp
|
||||
|
||||
@@ -287,7 +286,7 @@ async def probe(spec):
|
||||
|
||||
report = {"start_error": None}
|
||||
try:
|
||||
await start_gateway_runtime_api(runner)
|
||||
await start_gateway_runtime_api(runner, address_wait=spec.get("address_wait", WEBAPP_ADDRESS_WAIT_SECONDS))
|
||||
except BaseException as exc: # what would take the whole gateway down
|
||||
report["start_error"] = f"{type(exc).__name__}: {exc}"
|
||||
report["start_traceback"] = traceback.format_exc()
|
||||
|
||||
@@ -31,15 +31,14 @@ def _api(failures):
|
||||
ListenerAddressError=run_api.ListenerAddressError), calls
|
||||
|
||||
|
||||
def _start(api, *, webapp="mount", host="100.64.0.5", port=9119):
|
||||
def _start(api, *, webapp="mount", host="100.64.0.5", port=9119, wait_seconds=5.0):
|
||||
return asyncio.run(run_runtime_listener._start_gateway_api_waiting_for_address(
|
||||
api, object(), host=host, port=port, webapp=webapp))
|
||||
api, object(), host=host, port=port, webapp=webapp, wait_seconds=wait_seconds))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fast(monkeypatch):
|
||||
monkeypatch.setattr(run_runtime_listener, "_WEBAPP_ADDRESS_POLL_SECONDS", 0.01)
|
||||
monkeypatch.setenv("HERMES_WEBAPP_ADDRESS_WAIT", "5")
|
||||
return monkeypatch
|
||||
|
||||
|
||||
@@ -98,7 +97,6 @@ def test_ipv6_loopback_eaddrnotavail_falls_back_immediately_without_retrying(mon
|
||||
"webapp:\n enabled: true\n host: '::1'\n port: 9119\n", encoding="utf-8"
|
||||
)
|
||||
monkeypatch.setenv("HERMES_HOME", str(home))
|
||||
monkeypatch.setenv("HERMES_WEBAPP_ADDRESS_WAIT", "5")
|
||||
monkeypatch.setattr(run_runtime_listener, "_WEBAPP_ADDRESS_POLL_SECONDS", 0.01)
|
||||
|
||||
calls = []
|
||||
@@ -115,25 +113,23 @@ def test_ipv6_loopback_eaddrnotavail_falls_back_immediately_without_retrying(mon
|
||||
session_authorities=[],
|
||||
session_control_server=GatewayControlServer(home),
|
||||
)
|
||||
asyncio.run(run_runtime_listener.start_gateway_runtime_api(runner))
|
||||
asyncio.run(run_runtime_listener.start_gateway_runtime_api(runner, address_wait=5.0))
|
||||
assert calls == ["::1", "127.0.0.1"]
|
||||
assert runner.webapp_status["state"] == "unavailable"
|
||||
|
||||
|
||||
def test_the_wait_is_bounded_and_the_last_error_is_raised(fast):
|
||||
fast.setenv("HERMES_WEBAPP_ADDRESS_WAIT", "0.05")
|
||||
api, calls = _api([OSError(errno.EADDRNOTAVAIL, "address not assigned to an interface")] * 100)
|
||||
with pytest.raises(OSError) as caught:
|
||||
_start(api)
|
||||
_start(api, wait_seconds=0.05)
|
||||
assert caught.value.errno == errno.EADDRNOTAVAIL
|
||||
assert len(calls) > 1, "it retried before giving up"
|
||||
|
||||
|
||||
def test_zero_disables_the_wait(fast):
|
||||
fast.setenv("HERMES_WEBAPP_ADDRESS_WAIT", "0")
|
||||
api, calls = _api([OSError(errno.EADDRNOTAVAIL, "address not assigned to an interface")])
|
||||
with pytest.raises(OSError):
|
||||
_start(api)
|
||||
_start(api, wait_seconds=0.0)
|
||||
assert len(calls) == 1, "one attempt, then the usual 'Webapp unavailable' report"
|
||||
|
||||
|
||||
@@ -154,16 +150,6 @@ def test_the_loopback_companion_failure_is_not_waited_for(fast):
|
||||
assert len(calls) == 1
|
||||
|
||||
|
||||
def test_a_garbage_override_falls_back_to_the_default(monkeypatch):
|
||||
monkeypatch.setenv("HERMES_WEBAPP_ADDRESS_WAIT", "soon")
|
||||
assert run_runtime_listener._webapp_address_wait_seconds() == run_runtime_listener.WEBAPP_ADDRESS_WAIT_SECONDS
|
||||
|
||||
|
||||
def test_no_override_uses_the_default(monkeypatch):
|
||||
monkeypatch.delenv("HERMES_WEBAPP_ADDRESS_WAIT", raising=False)
|
||||
assert run_runtime_listener._webapp_address_wait_seconds() == run_runtime_listener.WEBAPP_ADDRESS_WAIT_SECONDS
|
||||
|
||||
|
||||
def test_start_gateway_runtime_api_waits_for_late_webapp_host_and_warns_once(monkeypatch, tmp_path, caplog):
|
||||
home = tmp_path / "home"
|
||||
home.mkdir()
|
||||
@@ -171,7 +157,6 @@ def test_start_gateway_runtime_api_waits_for_late_webapp_host_and_warns_once(mon
|
||||
"webapp:\n enabled: true\n host: 100.64.0.5\n port: 9119\n", encoding="utf-8"
|
||||
)
|
||||
monkeypatch.setenv("HERMES_HOME", str(home))
|
||||
monkeypatch.setenv("HERMES_WEBAPP_ADDRESS_WAIT", "5")
|
||||
monkeypatch.setattr(run_runtime_listener, "_WEBAPP_ADDRESS_POLL_SECONDS", 0.01)
|
||||
|
||||
webapp_calls = []
|
||||
@@ -193,7 +178,7 @@ def test_start_gateway_runtime_api_waits_for_late_webapp_host_and_warns_once(mon
|
||||
)
|
||||
|
||||
with caplog.at_level(logging.WARNING, logger="gateway.run_runtime"):
|
||||
asyncio.run(run_runtime_listener.start_gateway_runtime_api(runner))
|
||||
asyncio.run(run_runtime_listener.start_gateway_runtime_api(runner, address_wait=5.0))
|
||||
|
||||
assert runner.webapp_status == {
|
||||
"state": "serving",
|
||||
@@ -231,7 +216,6 @@ def test_non_eaddrnotavail_oserrors_fail_immediately_without_sleeping(fast, capl
|
||||
|
||||
|
||||
def test_zero_wait_does_not_sleep_or_warn(fast, caplog):
|
||||
fast.setenv("HERMES_WEBAPP_ADDRESS_WAIT", "0")
|
||||
sleeps = []
|
||||
|
||||
async def record_sleep(delay):
|
||||
@@ -241,40 +225,14 @@ def test_zero_wait_does_not_sleep_or_warn(fast, caplog):
|
||||
api, calls = _api([OSError(errno.EADDRNOTAVAIL, "address not assigned to an interface")])
|
||||
with caplog.at_level(logging.WARNING, logger="gateway.run_runtime"):
|
||||
with pytest.raises(OSError) as caught:
|
||||
_start(api)
|
||||
_start(api, wait_seconds=0.0)
|
||||
assert caught.value.errno == errno.EADDRNOTAVAIL
|
||||
assert len(calls) == 1
|
||||
assert sleeps == []
|
||||
assert not any("not assigned to any interface yet" in r.getMessage() for r in caplog.records)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw", ["nan", "inf", "-inf"])
|
||||
def test_non_finite_override_falls_back_to_default(monkeypatch, caplog, raw):
|
||||
monkeypatch.setenv("HERMES_WEBAPP_ADDRESS_WAIT", raw)
|
||||
with caplog.at_level(logging.WARNING, logger="gateway.run_runtime"):
|
||||
assert run_runtime_listener._webapp_address_wait_seconds() == run_runtime_listener.WEBAPP_ADDRESS_WAIT_SECONDS
|
||||
assert any("HERMES_WEBAPP_ADDRESS_WAIT" in r.getMessage() for r in caplog.records)
|
||||
|
||||
|
||||
def test_negative_override_clamps_to_zero_without_waiting(fast):
|
||||
fast.setenv("HERMES_WEBAPP_ADDRESS_WAIT", "-5")
|
||||
sleeps = []
|
||||
|
||||
async def record_sleep(delay):
|
||||
sleeps.append(delay)
|
||||
|
||||
fast.setattr(run_runtime_listener.asyncio, "sleep", record_sleep)
|
||||
assert run_runtime_listener._webapp_address_wait_seconds() == 0.0
|
||||
api, calls = _api([OSError(errno.EADDRNOTAVAIL, "address not assigned to an interface")])
|
||||
with pytest.raises(OSError) as caught:
|
||||
_start(api)
|
||||
assert caught.value.errno == errno.EADDRNOTAVAIL
|
||||
assert len(calls) == 1
|
||||
assert sleeps == []
|
||||
|
||||
|
||||
def test_cancellation_during_wait_sleep_propagates(monkeypatch):
|
||||
monkeypatch.setenv("HERMES_WEBAPP_ADDRESS_WAIT", "5")
|
||||
monkeypatch.setattr(run_runtime_listener, "_WEBAPP_ADDRESS_POLL_SECONDS", 10.0)
|
||||
real_sleep = asyncio.sleep
|
||||
|
||||
@@ -288,7 +246,7 @@ def test_cancellation_during_wait_sleep_propagates(monkeypatch):
|
||||
monkeypatch.setattr(run_runtime_listener.asyncio, "sleep", tracked_sleep)
|
||||
api, calls = _api([OSError(errno.EADDRNOTAVAIL, "address not assigned to an interface")] * 5)
|
||||
task = asyncio.create_task(run_runtime_listener._start_gateway_api_waiting_for_address(
|
||||
api, object(), host="100.64.0.5", port=9119, webapp="mount"))
|
||||
api, object(), host="100.64.0.5", port=9119, webapp="mount", wait_seconds=5.0))
|
||||
await asyncio.wait_for(entered_sleep.wait(), timeout=2.0)
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
@@ -324,7 +282,6 @@ def test_operator_stop_during_wait_aborts_without_rebinding_or_private_fallback(
|
||||
"webapp:\n enabled: true\n host: 192.0.2.77\n port: 9119\n", encoding="utf-8"
|
||||
)
|
||||
monkeypatch.setenv("HERMES_HOME", str(home))
|
||||
monkeypatch.setenv("HERMES_WEBAPP_ADDRESS_WAIT", "5")
|
||||
monkeypatch.setattr(run_runtime_listener, "_WEBAPP_ADDRESS_POLL_SECONDS", 5.0)
|
||||
monkeypatch.setattr(status, "consume_takeover_marker_for_self", lambda: False)
|
||||
monkeypatch.setattr(shutdown_forensics, "snapshot_shutdown_context", lambda sig: None)
|
||||
@@ -363,7 +320,7 @@ def test_operator_stop_during_wait_aborts_without_rebinding_or_private_fallback(
|
||||
return types.SimpleNamespace(api_origin="http://127.0.0.1:50001")
|
||||
|
||||
monkeypatch.setattr(run_api, "start_gateway_api", start)
|
||||
await asyncio.wait_for(run_runtime_listener.start_gateway_runtime_api(runner), timeout=2.0)
|
||||
await asyncio.wait_for(run_runtime_listener.start_gateway_runtime_api(runner, address_wait=5.0), timeout=2.0)
|
||||
assert completed.is_set(), "operator stop ran while the address wait was active"
|
||||
assert calls == [("192.0.2.77", False)], "no retry and no private fallback after operator stop"
|
||||
assert runner.session_api is None
|
||||
@@ -374,7 +331,6 @@ def test_operator_stop_during_wait_aborts_without_rebinding_or_private_fallback(
|
||||
|
||||
|
||||
def test_restart_requested_during_wait_aborts_without_binding(monkeypatch):
|
||||
monkeypatch.setenv("HERMES_WEBAPP_ADDRESS_WAIT", "5")
|
||||
monkeypatch.setattr(run_runtime_listener, "_WEBAPP_ADDRESS_POLL_SECONDS", 0.01)
|
||||
|
||||
async def run_scenario():
|
||||
@@ -388,7 +344,7 @@ def test_restart_requested_during_wait_aborts_without_binding(monkeypatch):
|
||||
|
||||
api = types.SimpleNamespace(start_gateway_api=start, ListenerAddressError=run_api.ListenerAddressError)
|
||||
result = await run_runtime_listener._start_gateway_api_waiting_for_address(
|
||||
api, runner, host="100.64.0.5", port=9119, webapp="mount"
|
||||
api, runner, host="100.64.0.5", port=9119, webapp="mount", wait_seconds=5.0
|
||||
)
|
||||
assert result is None
|
||||
assert len(calls) == 1
|
||||
@@ -396,6 +352,47 @@ def test_restart_requested_during_wait_aborts_without_binding(monkeypatch):
|
||||
asyncio.run(run_scenario())
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("failure", "binds", "closed"), [
|
||||
(None, 1, 1),
|
||||
(OSError(errno.EADDRINUSE, "Address already in use"), 2, 1),
|
||||
(SystemExit("the sign-in gate refused"), 1, 0),
|
||||
], ids=["webapp-bound", "private-fallback-bound", "webapp-refused"])
|
||||
def test_a_stop_during_a_bind_publishes_no_listener(monkeypatch, tmp_path, failure, binds, closed):
|
||||
"""A stop that begins while a listener binds: nothing is published after teardown, no fallback starts."""
|
||||
home = tmp_path / "home"
|
||||
home.mkdir()
|
||||
(home / "config.yaml").write_text(
|
||||
"webapp:\n enabled: true\n host: 100.64.0.5\n port: 9119\n", encoding="utf-8"
|
||||
)
|
||||
monkeypatch.setenv("HERMES_HOME", str(home))
|
||||
calls, stopped = [], []
|
||||
|
||||
async def start(r, *, host="127.0.0.1", port=0, webapp=None):
|
||||
calls.append(host)
|
||||
if webapp is not None and failure is not None:
|
||||
if isinstance(failure, SystemExit):
|
||||
r._stop_requested_by_signal = True # the stop lands while the gate refuses
|
||||
raise failure
|
||||
r._stop_requested_by_signal = True # the stop lands while this bind succeeds
|
||||
return types.SimpleNamespace(api_origin="http://127.0.0.1:50001")
|
||||
|
||||
async def stop(handle):
|
||||
stopped.append(handle)
|
||||
|
||||
monkeypatch.setattr(run_api, "start_gateway_api", start)
|
||||
monkeypatch.setattr(run_api, "stop_gateway_api", stop)
|
||||
runner = types.SimpleNamespace(
|
||||
session_runtime_descriptor={},
|
||||
session_authorities=[],
|
||||
session_control_server=GatewayControlServer(home),
|
||||
)
|
||||
asyncio.run(run_runtime_listener.start_gateway_runtime_api(runner))
|
||||
assert len(calls) == binds
|
||||
assert len(stopped) == closed
|
||||
assert runner.session_api is None
|
||||
assert "api_origin" not in runner.session_runtime_descriptor
|
||||
|
||||
|
||||
def test_unified_startup_abort_handles_restart_flags_and_minimal_test_doubles():
|
||||
from gateway.run_common import abort_startup_if_shutdown_requested, startup_should_abort
|
||||
|
||||
@@ -452,7 +449,7 @@ def test_bootstrap_listener_and_runner_aborts_before_keepalive_and_runner_start(
|
||||
called_runner = []
|
||||
stop_calls = []
|
||||
|
||||
async def fake_start_api(r):
|
||||
async def fake_start_api(r, **kwargs):
|
||||
r._stop_requested_by_signal = True
|
||||
r.session_api = None
|
||||
|
||||
@@ -488,3 +485,46 @@ def test_bootstrap_listener_and_runner_aborts_before_keepalive_and_runner_start(
|
||||
assert called_runner == []
|
||||
|
||||
asyncio.run(run_scenario())
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("idle_exit", "webapp_binds", "state"), [(True, 1, "unavailable"), (False, 3, "serving")],
|
||||
ids=["client-idle-exit-start", "supervised"])
|
||||
def test_only_a_supervised_gateway_waits_for_the_address(monkeypatch, tmp_path, idle_exit, webapp_binds, state):
|
||||
"""A TUI or ``chat -q`` client waits on its own idle-exit gateway with a hard start budget (Ink: 30 s)."""
|
||||
from gateway import lifecycle_ledger, run_bootstrap
|
||||
from hermes_cli import nous_auth_keepalive
|
||||
|
||||
home = tmp_path / "home"
|
||||
home.mkdir()
|
||||
(home / "config.yaml").write_text(
|
||||
"webapp:\n enabled: true\n host: 100.64.0.5\n port: 9119\n", encoding="utf-8"
|
||||
)
|
||||
monkeypatch.setenv("HERMES_HOME", str(home))
|
||||
monkeypatch.setattr(run_runtime_listener, "_WEBAPP_ADDRESS_POLL_SECONDS", 0.01)
|
||||
monkeypatch.setattr(lifecycle_ledger, "record_startup", lambda: None)
|
||||
monkeypatch.setattr(nous_auth_keepalive, "start_nous_auth_keepalive", lambda: None)
|
||||
monkeypatch.setattr(run_api, "preload_session_socket", lambda: None)
|
||||
monkeypatch.setattr(run_bootstrap, "preload_stop_path_modules", lambda: None)
|
||||
|
||||
async def run_runner(r, sig):
|
||||
return None
|
||||
|
||||
monkeypatch.setattr(run_bootstrap, "_start_gateway_run_runner", run_runner)
|
||||
binds = []
|
||||
|
||||
async def start(r, *, host="127.0.0.1", port=0, webapp=None):
|
||||
if webapp is not None:
|
||||
binds.append(host)
|
||||
if len(binds) < 3: # the address arrives on the third try
|
||||
raise OSError(errno.EADDRNOTAVAIL, "address not assigned to an interface")
|
||||
return types.SimpleNamespace(api_origin="http://127.0.0.1:50001")
|
||||
|
||||
monkeypatch.setattr(run_api, "start_gateway_api", start)
|
||||
runner = types.SimpleNamespace(
|
||||
session_runtime_descriptor={},
|
||||
session_authorities=[],
|
||||
session_control_server=GatewayControlServer(home),
|
||||
)
|
||||
asyncio.run(run_bootstrap._start_gateway_listener_and_runner(runner, [False], idle_exit=idle_exit))
|
||||
assert len(binds) == webapp_binds
|
||||
assert runner.webapp_status["state"] == state
|
||||
|
||||
@@ -96,8 +96,7 @@ def test_a_gateway_bound_to_its_own_address_serves_it_behind_sign_in_and_native_
|
||||
def test_an_address_no_interface_holds_leaves_the_webapp_unavailable_and_native_clients_a_listener(tmp_path):
|
||||
port = free_port()
|
||||
report = run(tmp_path, {"webapp": {"enabled": True, "host": "192.0.2.77", "port": port}, "basic_auth": True,
|
||||
"report_listening": ["127.0.0.1"]},
|
||||
env_overrides={"HERMES_WEBAPP_ADDRESS_WAIT": "0"})
|
||||
"report_listening": ["127.0.0.1"], "address_wait": 0})
|
||||
assert report["start_error"] is None, report.get("start_traceback")
|
||||
assert report["status"]["state"] == "unavailable"
|
||||
assert report["status"]["reason"] == (f"could not listen on 192.0.2.77:{port} "
|
||||
@@ -117,8 +116,8 @@ def test_an_interface_broadcast_is_not_served_as_a_machine_address(tmp_path):
|
||||
if broadcast is None:
|
||||
pytest.skip("no IPv4 interface with a directed broadcast")
|
||||
port = free_port()
|
||||
report = run(tmp_path, {"webapp": {"enabled": True, "host": broadcast, "port": port}, "basic_auth": True},
|
||||
env_overrides={"HERMES_WEBAPP_ADDRESS_WAIT": "0"})
|
||||
report = run(tmp_path, {"webapp": {"enabled": True, "host": broadcast, "port": port}, "basic_auth": True,
|
||||
"address_wait": 0})
|
||||
assert report["status"]["state"] == "unavailable"
|
||||
assert "not assigned to any network interface" in report["status"]["reason"]
|
||||
assert report["native_session_list"] is True
|
||||
|
||||
@@ -756,7 +756,7 @@ Check it with `hermes webapp --status` (a gateway that has just restarted takes
|
||||
- **A public address.** A backend reached through a proxy or tunnel at its own `https://` hostname has that address in `HERMES_DASHBOARD_PUBLIC_URL` or `settings.dashboard.public_url`. The Webapp reads neither: it builds its sign-in callback on `webapp.public_url`. When `settings.webapp.public_url` is unset, set it to the address the backend actually used, the first of these that is an `http://` or `https://` URL (a blank or malformed value is skipped): `HERMES_DASHBOARD_PUBLIC_URL` (from `environment` or `environmentFiles`, which the module writes into the Hermes home's `.env`), then `settings.dashboard.public_url`. `settings.dashboard.trusted_proxies` already applies to the Webapp.
|
||||
|
||||
- **Sign-in.** Keep the sign-in the backend used, in `environmentFiles` (`HERMES_DASHBOARD_BASIC_AUTH_*`, `HERMES_DASHBOARD_OAUTH_CLIENT_ID`, `HERMES_DASHBOARD_OIDC_*`) or in `settings.dashboard`: the Webapp signs in with the same providers, and a non-loopback `host` needs one.
|
||||
- **The address.** `settings.webapp.host` takes `127.0.0.1`, `::1`, `localhost`, `0.0.0.0`, `::` or one IP address of this machine, not a hostname. A backend bound to a name (such as a Tailscale MagicDNS name) moves to that name's IP address. `settings.webapp` has no counterpart to `backend.waitFor` or `backend.interfaceName`, so the address must exist when the gateway starts.
|
||||
- **The address.** `settings.webapp.host` takes `127.0.0.1`, `::1`, `localhost`, `0.0.0.0`, `::` or one IP address of this machine, not a hostname. A backend bound to a name (such as a Tailscale MagicDNS name) moves to that name's IP address. `settings.webapp` has no counterpart to `backend.waitFor` or `backend.interfaceName`: the gateway service waits up to 20 seconds for the address to be assigned to an interface, then keeps running without the Webapp until it restarts.
|
||||
- **Desktop.** With `backend.mode = "none"`, the `programs.hermes-agent.desktop` wrapper no longer points the app at the backend (`HERMES_DESKTOP_REMOTE_URL`), and `backend.sessionTokenFile` has no effect. The app attaches to the gateway on this machine instead.
|
||||
|
||||
See [What clients notice after the move](../user-guide/features/web-dashboard.md#after-the-move).
|
||||
|
||||
Reference in New Issue
Block a user