diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.py index 232f8dac804b1..acdd4415539db 100644 --- a/hermes_cli/gateway.py +++ b/hermes_cli/gateway.py @@ -1881,8 +1881,6 @@ def generate_systemd_unit(system: bool = False, run_as_user: str | None = None) Environment="HERMES_HOME={hermes_home}" Restart=always RestartSec=60 -RestartMaxDelaySec=300 -RestartSteps=5 RestartForceExitStatus={GATEWAY_SERVICE_RESTART_EXIT_CODE} KillMode=mixed KillSignal=SIGTERM @@ -1916,8 +1914,6 @@ def generate_systemd_unit(system: bool = False, run_as_user: str | None = None) Environment="HERMES_HOME={hermes_home}" Restart=always RestartSec=60 -RestartMaxDelaySec=300 -RestartSteps=5 RestartForceExitStatus={GATEWAY_SERVICE_RESTART_EXIT_CODE} KillMode=mixed KillSignal=SIGTERM diff --git a/hermes_cli/main.py b/hermes_cli/main.py index 26d957f819569..649846df2b4bf 100644 --- a/hermes_cli/main.py +++ b/hermes_cli/main.py @@ -971,7 +971,13 @@ def _tui_build_needed(tui_dir: Path) -> bool: def _hermes_ink_bundle_stale(tui_dir: Path) -> bool: ink_root = tui_dir / "packages" / "hermes-ink" - bundle = ink_root / "dist" / "ink-bundle.js" + # The @hermes/ink package build emits dist/entry-exports.js (see + # ui-tui/packages/hermes-ink/package.json). Older code checked for the + # pre-rename ink-bundle.js sentinel, which made every embedded dashboard + # chat connection run `npm run build` before accepting /api/pty. Behind + # Nginx that delayed the WebSocket handshake long enough to show + # "[session ended]" / 502 on restored sessions. + bundle = ink_root / "dist" / "entry-exports.js" if not bundle.exists(): return True bm = bundle.stat().st_mtime diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.py index 754dd8344323c..ce30b0e1b6061 100644 --- a/hermes_cli/web_server.py +++ b/hermes_cli/web_server.py @@ -595,7 +595,7 @@ async def get_status(): from hermes_state import SessionDB db = SessionDB() try: - sessions = db.list_sessions_rich(limit=50) + sessions = db.list_sessions_rich(limit=50, order_by_last_active=True) now = time.time() active_sessions = sum( 1 for s in sessions @@ -764,7 +764,7 @@ async def get_sessions(limit: int = 20, offset: int = 0): from hermes_state import SessionDB db = SessionDB() try: - sessions = db.list_sessions_rich(limit=limit, offset=offset) + sessions = db.list_sessions_rich(limit=limit, offset=offset, order_by_last_active=True) total = db.session_count() now = time.time() for s in sessions: @@ -2902,13 +2902,24 @@ def _is_public_bind() -> bool: def _ws_client_is_allowed(ws: "WebSocket") -> bool: - """Check if the WebSocket client IP is acceptable. - - Allows loopback always; allows any IP when bound to all-interfaces - (--insecure mode, guarded by session token auth). + """Check if the WebSocket client is acceptable. + + Allows loopback clients always; allows any IP when bound to all-interfaces + (--insecure mode, guarded by session token auth). For the documented + loopback-behind-reverse-proxy deployment, Uvicorn may replace ws.client + with the X-Forwarded-For address. In that case we still allow the request + when the upstream Host header targets the dashboard's bound host (Nginx + sets Host to 127.0.0.1:9119), preserving the DNS-rebinding guard for WS + routes. """ if _is_public_bind(): return True + + bound_host = getattr(app.state, "bound_host", "") + host_header = ws.headers.get("host", "") + if bound_host and _is_accepted_host(host_header, bound_host): + return True + client_host = ws.client.host if ws.client else "" if not client_host: return True @@ -4050,6 +4061,13 @@ def start_server( app.state.bound_host = host app.state.bound_port = port + # Uvicorn's WebSocket scope uses the socket peer address for ws.client. + # When the loopback-only dashboard is intentionally exposed through a + # same-host reverse proxy, the socket peer is already 127.0.0.1, but + # enabling proxy headers keeps HTTP URL/client metadata consistent with + # the deployment docs while only trusting local proxies. + forwarded_allow_ips = "127.0.0.1,::1" + if open_browser: import webbrowser @@ -4060,4 +4078,11 @@ def _open(): threading.Thread(target=_open, daemon=True).start() print(f" Hermes Web UI → http://{host}:{port}") - uvicorn.run(app, host=host, port=port, log_level="warning") + uvicorn.run( + app, + host=host, + port=port, + log_level="warning", + proxy_headers=True, + forwarded_allow_ips=forwarded_allow_ips, + ) diff --git a/hermes_state.py b/hermes_state.py index 444af167729fd..ae020584b51b3 100644 --- a/hermes_state.py +++ b/hermes_state.py @@ -1028,13 +1028,21 @@ def list_sessions_rich( params = [] if not include_children: - # Show root sessions and branch sessions (whose parent ended with - # end_reason='branched' before the child was created), while still - # hiding sub-agent runs and compression continuations (which also - # carry a parent_session_id but were spawned while the parent was - # still live — i.e., started_at < parent.ended_at). + # Show root sessions, compression chain anchors, and branch sessions + # (whose parent ended with end_reason='branched' before the child + # was created), while still hiding sub-agent runs and live + # compression continuations. A compression root can itself have a + # parent after repeated context compaction; include every + # ``end_reason='compression'`` anchor so projection below can walk + # to the latest live tip rather than leaving later continuations + # invisible. where_clauses.append( "(s.parent_session_id IS NULL" + " OR (s.end_reason = 'compression'" + " AND NOT EXISTS (SELECT 1 FROM sessions p" + " WHERE p.id = s.parent_session_id" + " AND p.end_reason = 'compression'" + " AND s.started_at >= p.ended_at))" " OR EXISTS (SELECT 1 FROM sessions p" " WHERE p.id = s.parent_session_id" " AND p.end_reason = 'branched'" diff --git a/tests/hermes_cli/test_tui_npm_install.py b/tests/hermes_cli/test_tui_npm_install.py index 1dec6257165f9..1104b19ee9b9f 100644 --- a/tests/hermes_cli/test_tui_npm_install.py +++ b/tests/hermes_cli/test_tui_npm_install.py @@ -26,7 +26,7 @@ def _touch_tui_entry(root: Path) -> None: def _touch_ink_bundle(root: Path) -> None: - bundle = root / "packages" / "hermes-ink" / "dist" / "ink-bundle.js" + bundle = root / "packages" / "hermes-ink" / "dist" / "entry-exports.js" bundle.parent.mkdir(parents=True, exist_ok=True) bundle.write_text("export {}") diff --git a/tests/hermes_cli/test_web_server_host_header.py b/tests/hermes_cli/test_web_server_host_header.py index 966127b05ce65..3deb955803974 100644 --- a/tests/hermes_cli/test_web_server_host_header.py +++ b/tests/hermes_cli/test_web_server_host_header.py @@ -84,6 +84,40 @@ def test_case_insensitive_comparison(self): assert _is_accepted_host("LocalHost:9119", "127.0.0.1") +class TestWebSocketClientAllowlist: + """WebSocket allowlist tests for loopback reverse proxy deployments.""" + + def test_loopback_reverse_proxy_host_header_is_allowed(self, monkeypatch): + from starlette.datastructures import Headers + + import hermes_cli.web_server as ws + + class DummyClient: + host = "203.0.113.10" + + class DummyWebSocket: + client = DummyClient() + headers = Headers({"host": "127.0.0.1:9119"}) + + monkeypatch.setattr(ws.app.state, "bound_host", "127.0.0.1", raising=False) + assert ws._ws_client_is_allowed(DummyWebSocket()) + + def test_attacker_host_header_is_rejected_for_non_loopback_client(self, monkeypatch): + from starlette.datastructures import Headers + + import hermes_cli.web_server as ws + + class DummyClient: + host = "203.0.113.10" + + class DummyWebSocket: + client = DummyClient() + headers = Headers({"host": "evil.example"}) + + monkeypatch.setattr(ws.app.state, "bound_host", "127.0.0.1", raising=False) + assert not ws._ws_client_is_allowed(DummyWebSocket()) + + class TestHostHeaderMiddleware: """End-to-end test via the FastAPI app — verify the middleware rejects bad Host headers with 400.""" diff --git a/tests/test_hermes_state.py b/tests/test_hermes_state.py index 55249406683bd..8f662c5e6a923 100644 --- a/tests/test_hermes_state.py +++ b/tests/test_hermes_state.py @@ -2186,7 +2186,7 @@ def test_subagent_session_still_hidden(self, db): assert "root" in ids def test_compression_child_still_hidden(self, db): - """Compression continuation sessions remain hidden (parent ended with 'compression').""" + """Live compression continuation sessions stay hidden behind their root entry.""" import time as _time t0 = _time.time() db.create_session("root", "cli") @@ -2204,7 +2204,39 @@ def test_compression_child_still_hidden(self, db): sessions = db.list_sessions_rich(project_compression_tips=False) ids = [s["id"] for s in sessions] - assert "continuation" not in ids, "Compression continuation should stay hidden" + assert "continuation" not in ids, "Live compression continuation should stay hidden" + + def test_repeated_compression_chain_surfaces_latest_tip(self, db): + """Repeated compression creates compression anchors with parents. + + Those intermediate anchors must remain visible to the projection query; + otherwise the latest live continuation is hidden from /sessions. + """ + t0 = 1709500000.0 + db.create_session("root", "cli") + db.create_session("mid", "cli", parent_session_id="root") + db.create_session("tip", "cli", parent_session_id="mid") + with db._lock: + db._conn.execute( + "UPDATE sessions SET started_at=?, ended_at=?, end_reason='compression' WHERE id=?", + (t0, t0 + 10, "root"), + ) + db._conn.execute( + "UPDATE sessions SET started_at=?, ended_at=?, end_reason='compression' WHERE id=?", + (t0 + 11, t0 + 20, "mid"), + ) + db._conn.execute( + "UPDATE sessions SET started_at=? WHERE id=?", + (t0 + 21, "tip"), + ) + db._conn.commit() + db.append_message("tip", "user", "latest visible conversation") + + sessions = db.list_sessions_rich(order_by_last_active=True) + ids = [s["id"] for s in sessions] + assert "tip" in ids + assert "mid" not in ids + assert "root" not in ids class TestCompressionChainProjection: