The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(dashboard): bracket IPv6 URL authorities everywhere hosts compose URLs
Austin Picketta39c2610e504
diff --git a/hermes_cli/gateway_migrate.py b/hermes_cli/gateway_migrate.pyindex 4a3d1631b99..27264f43e85 100644--- a/hermes_cli/gateway_migrate.py+++ b/hermes_cli/gateway_migrate.py@@ -576,7 +576,9 @@ def _listener_url(default_cfg, platform_value: str, profile: str) -> str:host = extra.get("host") or hostport = extra.get("port") or porttail = {"api_server": "/v1/...", "webhook": "/webhooks/<route>"}.get(platform_value, "/...")- return f"http://{host}:{port}/p/{profile}{tail}"+ from hermes_cli.url_utils import format_url_host++ return f"http://{format_url_host(host)}:{port}/p/{profile}{tail}"def _check_secondary_port_binders(plan: MigrationPlan, configs: dict[str, object]) -> None:diff --git a/hermes_cli/main_dashboard.py b/hermes_cli/main_dashboard.pyindex 0b884efd905..2fedc9ec199 100644--- a/hermes_cli/main_dashboard.py+++ b/hermes_cli/main_dashboard.py@@ -927,7 +927,9 @@ def _attach_to_host_backend(args, headless_backend: bool) -> None:except Exception:profile = "default"wanted = getattr(args, "open_profile", "") or profile- url = f"http://{hr.dial_host(record)}:{record.port}/?profile={wanted}"+ from hermes_cli.url_utils import format_url_host++ url = f"http://{format_url_host(hr.dial_host(record))}:{record.port}/?profile={wanted}"kind = "backend" if headless_backend else "dashboard"print(f"Hermes {kind} already running on this host: PID {record.pid}, port {record.port}.")diff --git a/hermes_cli/plugins_activation.py b/hermes_cli/plugins_activation.pyindex 7939d70a62a..30d31c28f2e 100644--- a/hermes_cli/plugins_activation.py+++ b/hermes_cli/plugins_activation.py@@ -190,12 +190,14 @@ def notify_serve_backend(name: str, home: Path) -> Optional[Dict[str, Any]]:import jsonimport urllib.requestfrom gateway import host_rendezvous as hr+ from hermes_cli.url_utils import format_url_hostrecord = _serve_backend_record()if record is None:return Nonetoken = hr.read_token(record.role)request = urllib.request.Request(- f"http://{hr.dial_host(record)}:{record.port}/api/dashboard/agent-plugins/activate",+ f"http://{format_url_host(hr.dial_host(record))}:{record.port}"+ "/api/dashboard/agent-plugins/activate",data=json.dumps({"name": name, "home": str(home)}).encode("utf-8"), method="POST",headers={"Content-Type": "application/json", "X-Hermes-Session-Token": token})with urllib.request.urlopen(request, timeout=60) as response: # noqa: S310 — loopback httpdiff --git a/hermes_cli/proxy/cli.py b/hermes_cli/proxy/cli.pyindex 0f510049dee..4c9ab4ab9ba 100644--- a/hermes_cli/proxy/cli.py+++ b/hermes_cli/proxy/cli.py@@ -34,11 +34,13 @@ def cmd_proxy_start(args: Any) -> int:auth_hint = getattr(adapter, "auth_hint", f"hermes auth add {adapter.name}")_err(f"Not logged into {adapter.display_name}. Run `{auth_hint}` first.")return 2+ from hermes_cli.url_utils import format_url_host+host = getattr(args, "host", None) or DEFAULT_HOSTport = getattr(args, "port", None) or DEFAULT_PORT_err(f"Starting Hermes proxy for {adapter.display_name}\n"- f" Listening on: http://{host}:{port}/v1\n"+ f" Listening on: http://{format_url_host(host)}:{port}/v1\n"f" Forwarding to: (resolved per-request from your subscription)\n"f" Use any bearer token in the client — the proxy attaches your real credential.\n"f"\n"diff --git a/hermes_cli/url_utils.py b/hermes_cli/url_utils.pynew file mode 100644index 00000000000..1e65eefe3b1--- /dev/null+++ b/hermes_cli/url_utils.py@@ -0,0 +1,18 @@+"""Small helpers for composing URLs from configured network hosts."""+++def format_url_host(host: str) -> str:+ """Return *host* in HTTP URL-authority form.++ IPv6 literals require brackets when followed by a port. Already-bracketed+ values are preserved so callers can safely pass either representation.+ """+ host = host.strip()+ if host.startswith("[") and host.endswith("]"):+ inner_host = host[1:-1]+ if ":" in inner_host:+ return f"[{inner_host.replace('%', '%25')}]"+ return host+ if ":" in host:+ return f"[{host.replace('%', '%25')}]"+ return hostdiff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.pyindex 94cbc1546f9..55640470736 100644--- a/hermes_cli/web_server.py+++ b/hermes_cli/web_server.py@@ -1482,7 +1482,9 @@ def _on_server_started(# a piped stdout otherwise surfaces this minutes after the sentinel.print(f" Hermes backend listening on {host}:{actual_port}", flush=True)else:- print(f" Hermes Web UI → http://{host}:{actual_port}")+ from hermes_cli.url_utils import format_url_host++ print(f" Hermes Web UI → http://{format_url_host(host)}:{actual_port}")_maybe_open_browser(host, actual_port, open_browser, initial_profile)if start_mcp_discovery_after_bind:diff --git a/hermes_cli/web_server_lifecycle.py b/hermes_cli/web_server_lifecycle.pyindex 535fc636a80..8de136550ca 100644--- a/hermes_cli/web_server_lifecycle.py+++ b/hermes_cli/web_server_lifecycle.py@@ -236,8 +236,10 @@ def _maybe_open_browser(host: str, actual_port: int, open_browser: bool, initial)return+ from hermes_cli.url_utils import format_url_host+_display_host = host if host not in ("0.0.0.0", "::") else "127.0.0.1"- _open_url = f"http://{_display_host}:{actual_port}"+ _open_url = f"http://{format_url_host(_display_host)}:{actual_port}"if initial_profile:from urllib.parse import quote_open_url += f"/?profile={quote(initial_profile)}"diff --git a/tests/hermes_cli/test_ipv6_url_authorities.py b/tests/hermes_cli/test_ipv6_url_authorities.pynew file mode 100644index 00000000000..17f21dc6c9e--- /dev/null+++ b/tests/hermes_cli/test_ipv6_url_authorities.py@@ -0,0 +1,158 @@+"""IPv6 binds must render as bracketed URL authorities everywhere a URL is built.++An IPv6 literal followed by ``:port`` is only a valid URL authority inside+brackets (``http://[::1]:9119``); unbracketed ``http://::1:9119`` is not a URL a+browser or ``urllib`` can parse. Covers the dashboard attach URL, the+browser auto-open URL, the startup banner, and the shared host formatter+(#67367).+"""+import contextlib+import types++import pytest+import uvicorn++from hermes_cli import main_dashboard, web_server, web_server_lifecycle+++def _stub_uvicorn(monkeypatch):+ """Replace uvicorn.Config/Server with no-op fakes so start_server returns."""+ captured: dict = {}++ class _FakeConfig:+ loaded = True+ host = "127.0.0.1"+ port = 8000+ _loop_factory = None++ def __init__(self, *args, **kwargs):+ captured.update(kwargs)++ def load(self):+ pass++ def get_loop_factory(self):+ return self._loop_factory++ class lifespan_class:+ should_exit = False+ state: dict = {}++ def __init__(self, *a, **kw):+ pass++ async def startup(self):+ pass++ async def shutdown(self):+ pass++ class _FakeServer:+ should_exit = False+ started = True+ servers: list = []+ lifespan = None++ @staticmethod+ def capture_signals():+ return contextlib.nullcontext()++ async def startup(self, sockets=None):+ pass++ async def main_loop(self):+ pass++ async def shutdown(self, sockets=None):+ pass++ monkeypatch.setattr(uvicorn, "Config", _FakeConfig)+ monkeypatch.setattr(uvicorn, "Server", lambda config: _FakeServer())+ return captured+++class TestFormatUrlHost:++ def test_brackets_ipv6_literal_with_port_following(self):+ from hermes_cli.url_utils import format_url_host++ assert format_url_host("::1") == "[::1]"+ assert format_url_host("fe80::1") == "[fe80::1]"++ def test_preserves_ipv4_and_names(self):+ from hermes_cli.url_utils import format_url_host++ assert format_url_host("127.0.0.1") == "127.0.0.1"+ assert format_url_host("localhost") == "localhost"++ def test_already_bracketed_stays_bracketed(self):+ from hermes_cli.url_utils import format_url_host++ assert format_url_host("[::1]") == "[::1]"++ def test_escapes_ipv6_zone_identifier(self):+ from hermes_cli.url_utils import format_url_host++ assert format_url_host("fe80::1%eth0") == "[fe80::1%25eth0]"+ assert format_url_host("[fe80::1%eth0]") == "[fe80::1%25eth0]"+++class TestBrowserOpenUrl:++ def test_maybe_open_browser_brackets_ipv6_loopback(self, monkeypatch):+ """The browser auto-open URL needs brackets around an IPv6 authority."""+ import webbrowser++ opened = []++ class _ImmediateThread:+ def __init__(self, *, target, daemon):+ self._target = target++ def start(self):+ self._target()++ monkeypatch.setattr(web_server_lifecycle.threading, "Thread", _ImmediateThread)+ monkeypatch.setattr(web_server_lifecycle.time, "sleep", lambda _s: None)+ monkeypatch.setattr(webbrowser, "open", lambda url: opened.append(url))+ monkeypatch.setenv("DISPLAY", ":0")++ web_server_lifecycle._maybe_open_browser("::1", 9119, True, "worker_x")++ assert opened == ["http://[::1]:9119/?profile=worker_x"]++ def test_start_server_banner_prints_bracketed_ipv6_url(self, monkeypatch, capsys):+ """The no-browser startup banner must show a valid IPv6 URL."""+ _stub_uvicorn(monkeypatch)++ web_server.start_server(host="::1", port=9119, open_browser=False)++ assert "Hermes Web UI → http://[::1]:9119" in capsys.readouterr().err+++class TestAttachUrl:++ def test_attach_brackets_ipv6_host_in_browser_url(self, monkeypatch):+ """Named-profile attach to a running IPv6 dashboard must open a valid URL."""+ import webbrowser+ from gateway import host_rendezvous as hr++ opened = []+ monkeypatch.setattr(webbrowser, "open", lambda url: opened.append(url))+ record = types.SimpleNamespace(host="::1", port=9119, pid=4242, role="dashboard")+ monkeypatch.setattr(main_dashboard, "_host_backend_attachment", lambda: record)+ monkeypatch.setattr(main_dashboard, "_is_desktop_owned_backend", lambda: False)+ monkeypatch.setattr(main_dashboard, "_explicit_endpoint_flags", lambda: set())+ monkeypatch.setattr(hr, "probe_owner", lambda _r: {"servesSpa": True, "pid": 4242})+ monkeypatch.setattr(+ "hermes_cli.profiles.get_active_profile_name", lambda: "worker_x"+ )++ args = types.SimpleNamespace(+ host="::1", port=9119, no_open=False, isolated=False, open_profile=""+ )+ with pytest.raises(SystemExit) as exc:+ main_dashboard._attach_to_host_backend(args, headless_backend=False)++ assert exc.value.code == 0+ assert opened == ["http://[::1]:9119/?profile=worker_x"]