The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(dashboard): one gateway liveness ladder for status + channels
teknium16179da549638
diff --git a/gateway/status.py b/gateway/status.pyindex 365518e26e9..224dbf6d071 100644--- a/gateway/status.py+++ b/gateway/status.py@@ -22,9 +22,10 @@ import sysimport threadingimport timefrom datetime import datetime, timezone+from dataclasses import dataclassfrom pathlib import Pathfrom hermes_constants import get_hermes_home, _get_platform_default_hermes_home-from typing import Any, NamedTuple, Optional+from typing import Any, Callable, NamedTuple, Optionalfrom utils import atomic_json_writeif sys.platform == "win32":@@ -1138,6 +1139,147 @@ def derive_gateway_drainable(*, gateway_running: bool, gateway_state: Any) -> boreturn bool(gateway_running) and gateway_state in _DRAINABLE_GATEWAY_STATES+@dataclass(frozen=True)+class GatewayLiveness:+ """Resolved gateway liveness for one dashboard surface.++ ``source`` records which rung of the ladder answered, purely for logging+ and tests — never branch product behavior on it.++ ``probe_error`` is True when a rung raised instead of answering. Callers+ that must distinguish "the gateway is down" from "we could not tell"+ need it: the dashboard renders a down badge either way, but the kanban+ dispatcher warning deliberately fails OPEN on an unreadable probe so it+ never cries wolf at a user whose gateway is fine.+ """++ running: bool+ pid: Optional[int]+ source: str+ health_body: Optional[dict[str, Any]] = None+ probe_error: bool = False+++def resolve_gateway_liveness(+ *,+ profile_dir: Optional[Path] = None,+ runtime: Any = _UNSET,+ health_probe: Optional[Callable[[], tuple[bool, Optional[dict[str, Any]]]]] = None,+ use_cache: bool = True,+ pid_probe: Optional[Callable[..., Optional[int]]] = None,+ runtime_reader: Optional[Callable[..., Optional[dict[str, Any]]]] = None,+ runtime_pid_probe: Optional[Callable[..., Optional[int]]] = None,+) -> GatewayLiveness:+ """Single source of truth for "is the gateway up?" across dashboard surfaces.++ Before this existed, ``/api/status`` and ``/api/messaging/platforms``+ each open-coded their own ladder and disagreed on the same page load —+ the sidebar read "running" while the Channels page rendered "The gateway+ is not running." Three deployments hit it: a cross-container gateway+ (only ``/api/status`` ran the HTTP health probe), a profile-scoped+ dashboard (only ``/api/status`` passed the profile's paths, so messaging+ borrowed another profile's runtime state — issue #71211), and a+ launch-service-managed gateway with no PID file (only some callers used+ the runtime-status fallback).++ The ladder, most to least authoritative:++ 1. **PID file + runtime lock** — scoped to ``profile_dir`` when given.+ Cached by default (``use_cache``); high-frequency polling must not+ churn file descriptors re-flocking ``gateway.lock`` on every request.+ 2. **HTTP health probe** — supplied by the caller (the dashboard owns the+ deprecated ``GATEWAY_HEALTH_URL`` config). Covers the gateway running+ in another container where no local PID is visible.+ 3. **Runtime status PID** — validated against the live process table with+ ``expected_home`` so a recycled PID belonging to a *different*+ profile's gateway is never reported as this one's.++ Rung 3 only ever runs against a LOCAL state record: the probe body's PID+ belongs to another host, and ``os.kill``-ing a remote PID is both wrong+ and trips the test live-system guard. Pass ``runtime`` when the caller+ has already read the state file so it isn't read twice per request.++ ``pid_probe`` / ``runtime_reader`` / ``runtime_pid_probe`` let a caller+ inject its own module-level references to these helpers. The dashboard+ passes its ``hermes_cli.web_server`` bindings so the long-standing+ monkeypatch seam in the test-suite keeps working; production callers+ leave them ``None`` and get this module's implementations.+ """+ _pid_probe = pid_probe or (+ get_running_pid_cached if use_cache else get_running_pid+ )+ _runtime_reader = runtime_reader or read_runtime_status+ _runtime_pid_probe = runtime_pid_probe or get_runtime_status_running_pid++ pid_path = (profile_dir / "gateway.pid") if profile_dir is not None else None+ probe_error = False+ try:+ # Plain zero-arg call when unscoped: several callers monkeypatch these+ # probes with zero-arg lambdas, and /api/status's cache signature is+ # keyed on the exact call shape.+ pid = _pid_probe(pid_path) if pid_path is not None else _pid_probe()+ except Exception:+ # A probe failure (permissions, exotic /proc, Windows quirks) must+ # degrade to the next rung, never 500 a status endpoint. Recorded in+ # probe_error so fail-open callers can tell "down" from "unknown".+ pid = None+ probe_error = True+ if pid is not None:+ return GatewayLiveness(running=True, pid=pid, source="pid")++ health_body: Optional[dict[str, Any]] = None+ if health_probe is not None:+ try:+ alive, health_body = health_probe()+ except Exception:+ alive, health_body = False, None+ probe_error = True+ if alive:+ # Display-only PID: it belongs to the remote container.+ remote_pid = health_body.get("pid") if health_body else None+ return GatewayLiveness(+ running=True,+ pid=remote_pid,+ source="health",+ health_body=health_body,+ )++ if runtime is _UNSET:+ try:+ runtime = (+ _runtime_reader(path=profile_dir / "gateway_state.json")+ if profile_dir is not None+ else _runtime_reader()+ )+ except Exception:+ runtime = None+ probe_error = True+ try:+ runtime_pid = (+ _runtime_pid_probe(runtime, expected_home=profile_dir)+ if profile_dir is not None+ else _runtime_pid_probe(runtime)+ )+ except Exception:+ runtime_pid = None+ probe_error = True+ if runtime_pid is not None:+ return GatewayLiveness(+ running=True,+ pid=runtime_pid,+ source="runtime_status",+ health_body=health_body,+ )++ return GatewayLiveness(+ running=False,+ pid=None,+ source="none",+ health_body=health_body,+ probe_error=probe_error,+ )++def get_runtime_status_running_pid(runtime: Optional[dict[str, Any]] = None,*,diff --git a/hermes_cli/kanban.py b/hermes_cli/kanban.pyindex 6bcc7651b43..d43ffba2e92 100644--- a/hermes_cli/kanban.py+++ b/hermes_cli/kanban.py@@ -134,7 +134,9 @@ def _parse_branch_flag(value: Optional[str]) -> Optional[str]:return branch-def _check_dispatcher_presence() -> tuple[bool, str]:+def _check_dispatcher_presence(+ hermes_home: Optional[Path] = None,+) -> tuple[bool, str]:"""Return ``(running, message)``.- ``running=True``: a gateway is alive for this HERMES_HOME and its@@ -149,15 +151,35 @@ def _check_dispatcher_presence() -> tuple[bool, str]:Defensive against import failures and config-read errors — if theprobe itself errors, we return ``(True, "")`` so we don't spamfalse warnings (better to miss a warning than to cry wolf).++ ``hermes_home`` scopes the probe to a named profile's directory. The+ dashboard plugin API passes it because the dashboard backend process can+ be running under a different HERMES_HOME than the profile the request+ targets, which otherwise produced a "no gateway is running" warning+ against a perfectly healthy profile gateway (#71211). CLI callers leave+ it ``None`` and keep the existing process-level behavior."""try:- from gateway.status import get_running_pid # type: ignore+ from gateway.status import resolve_gateway_liveness # type: ignoreexcept Exception:return (True, "") # can't probe — silenttry:- pid = get_running_pid()+ # Same shared ladder the dashboard status endpoints use, so a+ # PID-file-less (launch-service-managed) or cross-container gateway+ # is not misreported as absent. use_cache=False: this is a one-shot+ # CLI/create-time probe, not a polling loop, and it must observe the+ # gateway's state right now rather than a cached snapshot.+ liveness = resolve_gateway_liveness(+ profile_dir=hermes_home, use_cache=False+ )except Exception:return (True, "") # probe errored — silent+ if liveness.probe_error:+ # The resolver swallows per-rung failures so status endpoints never+ # 500. This caller must still fail OPEN: an unreadable probe means+ # "can't tell", not "no gateway", and warning on it cries wolf.+ return (True, "")+ pid = liveness.pid# Even if the gateway is up, dispatch_in_gateway may be off.try:diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.pyindex 7b73e13eaff..64136ce1a6c 100644--- a/hermes_cli/web_server.py+++ b/hermes_cli/web_server.py@@ -96,6 +96,7 @@ from gateway.status import (normalize_updated_at,parse_active_agents,read_runtime_status,+ resolve_gateway_liveness,)from utils import env_var_enabled@@ -3070,41 +3071,60 @@ async def get_status(profile: Optional[str] = None):try:current_ver, latest_ver = check_config_version()# --- Gateway liveness detection ---- # Try local PID check first (same-host). If that fails and a remote- # GATEWAY_HEALTH_URL is configured, probe the gateway over HTTP so the- # dashboard works when the gateway runs in a separate container.+ # Delegated to the single shared ladder in gateway.status so this+ # endpoint and /api/messaging/platforms can never disagree about+ # whether the gateway is up (they used to: sidebar "running" while+ # the Channels page rendered "The gateway is not running").## When ?profile=<name> was given, scope PID and state reads to that# profile's directory — gateway identity files (PID, lock, runtime# status) are written to the per-profile home, not the process-level# HERMES_HOME (see issue #69143). Plain /api/status keeps the exact# zero-arg call so its behavior (and cache signature) is unchanged.- gateway_pid = (- get_running_pid_cached(pid_path=profile_dir / "gateway.pid")+ #+ # The module-level probe references are handed to the resolver so the+ # long-standing `monkeypatch.setattr(web_server, "get_running_pid_cached", ...)`+ # seam used across the test-suite still intercepts them.+ def _bounded_health_probe():+ """Health probe with the route's blocking-call budget preserved.++ The resolver only reaches this rung when the local PID probe came+ up empty, so the timeout is paid at most once per request and only+ in the cross-container case that needs it.+ """+ with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:+ future = pool.submit(_probe_gateway_health)+ try:+ return future.result(timeout=_GATEWAY_HEALTH_ROUTE_TIMEOUT)+ except concurrent.futures.TimeoutError:+ _log.warning(+ "/api/status gateway health probe exceeded %.2fs; "+ "using local status",+ _GATEWAY_HEALTH_ROUTE_TIMEOUT,+ )+ return False, None+ except Exception:+ return False, None++ local_runtime = (+ read_runtime_status(path=profile_dir / "gateway_state.json")if profile_dir- else get_running_pid_cached()+ else read_runtime_status())- gateway_running = gateway_pid is not None- remote_health_body: dict | None = None- if not gateway_running and _GATEWAY_HEALTH_URL:- loop = asyncio.get_running_loop()- try:- alive, remote_health_body = await asyncio.wait_for(- loop.run_in_executor(None, _probe_gateway_health),- timeout=_GATEWAY_HEALTH_ROUTE_TIMEOUT,- )- except TimeoutError:- _log.warning(- "/api/status gateway health probe exceeded %.2fs; using local status",- _GATEWAY_HEALTH_ROUTE_TIMEOUT,- )- alive, remote_health_body = False, None- if alive:- gateway_running = True- # PID from the remote container (display only — not locally valid)- if remote_health_body:- gateway_pid = remote_health_body.get("pid")+ liveness = await run_in_threadpool(+ lambda: resolve_gateway_liveness(+ profile_dir=profile_dir,+ runtime=local_runtime,+ health_probe=_bounded_health_probe if _GATEWAY_HEALTH_URL else None,+ pid_probe=get_running_pid_cached,+ runtime_reader=read_runtime_status,+ runtime_pid_probe=get_runtime_status_running_pid,+ )+ )+ gateway_running = liveness.running+ gateway_pid = liveness.pid+ remote_health_body: dict | None = liveness.health_bodygateway_state = Nonegateway_platforms: dict = {}@@ -3123,39 +3143,9 @@ async def get_status(profile: Optional[str] = None):# Prefer the detailed health endpoint response (has full state) when the# local runtime status file is absent or stale (cross-container).- #- # When ?profile=<name> was given, read from the profile's directory so- # the state file resolves to the per-profile gateway_state.json, not- # the fixed process-level HERMES_HOME (see issue #69143). Plain- # /api/status keeps the exact zero-arg call so existing behavior- # (and monkeypatched call shapes) are unchanged.- local_runtime = (- read_runtime_status(path=profile_dir / "gateway_state.json")- if profile_dir- else read_runtime_status()- )runtime = local_runtimeif runtime is None and remote_health_body and remote_health_body.get("gateway_state"):runtime = remote_health_body- # The runtime-status PID fallback validates liveness with a local- # os.kill() probe, so it must only run against the LOCAL status file —- # never the remote health body, whose PID belongs to another host and- # is display-only. (Running os.kill on a remote PID is both wrong and- # trips the test live-system guard.)- if not gateway_running and local_runtime is not None:- # expected_home scopes the OS-identity check to the requested- # profile so a recycled PID belonging to a different profile's- # live gateway is not reported running for this one.- runtime_pid = (- get_runtime_status_running_pid(- local_runtime, expected_home=profile_dir- )- if profile_dir- else get_runtime_status_running_pid(local_runtime)- )- if runtime_pid is not None:- gateway_running = True- gateway_pid = runtime_pidif runtime:gateway_state = runtime.get("gateway_state")@@ -8592,6 +8582,7 @@ def _messaging_platform_payload(env_on_disk: dict[str, str],runtime: dict | None,scoped: bool = False,+ profile_home: Optional[Path] = None,) -> dict[str, Any]:platform_id = entry["id"]runtime_platforms = runtime.get("platforms") if runtime else {}@@ -8600,10 +8591,29 @@ def _messaging_platform_payload(if isinstance(runtime_platforms, dict)else {})- gateway_running = (- get_running_pid() is not None- or get_runtime_status_running_pid(runtime) is not None+ # Same shared ladder /api/status uses. Before this was unified, the two+ # endpoints disagreed on the same page load — the sidebar strip read+ # "running" (it probed GATEWAY_HEALTH_URL and scoped to the requested+ # profile) while the Channels page rendered "The gateway is not running"+ # (it did neither). Cross-container, profile-scoped, and+ # launch-service-managed deployments each hit that split.+ #+ # profile_home is passed when the request was scoped to a named profile:+ # gateway/status readers resolve process-level paths and do NOT follow the+ # HERMES_HOME contextvar override (#56986 / #69143), so the profile's+ # directory has to be handed over explicitly or messaging silently reports+ # another profile's gateway (#71211).+ liveness = resolve_gateway_liveness(+ profile_dir=profile_home,+ runtime=runtime,+ health_probe=(+ _probe_gateway_health if _GATEWAY_HEALTH_URL else None+ ),+ pid_probe=get_running_pid_cached,+ runtime_reader=read_runtime_status,+ runtime_pid_probe=get_runtime_status_running_pid,)+ gateway_running = liveness.runningenv_vars = []for key in entry["env_vars"]:@@ -9605,17 +9615,26 @@ async def cancel_telegram_onboarding(pairing_id: str):async def get_messaging_platforms(profile: Optional[str] = None):# Profile-scoped so the dashboard's global profile switcher shows the# TARGET profile's channel credentials/state, not the root install's.- # Inside _profile_scope, load_env()/read_runtime_status()/get_running_pid()- # all resolve against the requested profile's HERMES_HOME.+ # load_env() honors the HERMES_HOME contextvar override; the gateway+ # status readers do NOT (they resolve process-level paths), so the+ # profile directory is passed explicitly for those (#71211).with _profile_scope(profile) as scoped_dir:env_on_disk = load_env()- runtime = read_runtime_status()+ runtime = (+ read_runtime_status(path=scoped_dir / "gateway_state.json")+ if scoped_dir is not None+ else read_runtime_status()+ )return {"env_path": str(get_env_path()),"gateway_start_command": _gateway_display_command(profile, "start"),"platforms": [_messaging_platform_payload(- entry, env_on_disk, runtime, scoped=scoped_dir is not None+ entry,+ env_on_disk,+ runtime,+ scoped=scoped_dir is not None,+ profile_home=scoped_dir,)for entry in _messaging_platform_catalog()]@@ -9750,8 +9769,17 @@ async def test_messaging_platform(platform_id: str, profile: Optional[str] = Nonwith _profile_scope(profile) as scoped_dir:env_on_disk = load_env()+ runtime = (+ read_runtime_status(path=scoped_dir / "gateway_state.json")+ if scoped_dir is not None+ else read_runtime_status()+ )payload = _messaging_platform_payload(- entry, env_on_disk, read_runtime_status(), scoped=scoped_dir is not None+ entry,+ env_on_disk,+ runtime,+ scoped=scoped_dir is not None,+ profile_home=scoped_dir,)if not payload["enabled"]:message = f"{entry['name']} is disabled. Enable it, then restart the gateway."diff --git a/plugins/kanban/dashboard/plugin_api.py b/plugins/kanban/dashboard/plugin_api.pyindex fa3edd135d7..51feb4f1c3c 100644--- a/plugins/kanban/dashboard/plugin_api.py+++ b/plugins/kanban/dashboard/plugin_api.py@@ -647,7 +647,15 @@ def create_task(payload: CreateTaskBody, board: Optional[str] = Query(None)):if task and task.status == "ready" and task.assignee:try:from hermes_cli.kanban import _check_dispatcher_presence- running, message = _check_dispatcher_presence()+ from hermes_constants import get_hermes_home++ # Scope the probe to the request's active home. The dashboard+ # backend can run under a different HERMES_HOME than the+ # profile this board belongs to, which otherwise warned "no+ # gateway is running" against a live profile gateway (#71211).+ running, message = _check_dispatcher_presence(+ hermes_home=get_hermes_home()+ )if not running and message:body["warning"] = messageexcept Exception:diff --git a/tests/gateway/test_status.py b/tests/gateway/test_status.pyindex 2866379041e..633e9be0279 100644--- a/tests/gateway/test_status.py+++ b/tests/gateway/test_status.py@@ -2203,3 +2203,174 @@ class TestRuntimeStatusUpdatedAtContract:assert parsed.tzinfo is not None# And it survives the normalization funnel unchanged (canonical form).assert status.normalize_updated_at(updated_at) == updated_at+++class TestResolveGatewayLiveness:+ """The single liveness ladder both dashboard status surfaces share.++ Before this existed, /api/status and /api/messaging/platforms each+ open-coded their own ladder and disagreed on the same page load — the+ sidebar read "running" while the Channels page rendered "The gateway is+ not running." These pin the ladder's ordering and its fail-open signal.+ """++ def test_pid_rung_wins_and_skips_later_rungs(self):+ calls = {"health": 0, "runtime_pid": 0}++ def _health():+ calls["health"] += 1+ return True, {"pid": 999}++ def _runtime_pid(runtime, **kw):+ calls["runtime_pid"] += 1+ return 888++ result = status.resolve_gateway_liveness(+ runtime=None,+ health_probe=_health,+ pid_probe=lambda *a, **k: 4242,+ runtime_pid_probe=_runtime_pid,+ )++ assert result.running is True+ assert result.pid == 4242+ assert result.source == "pid"+ # The authoritative rung answered: no lower rung should have run.+ assert calls == {"health": 0, "runtime_pid": 0}++ def test_health_probe_answers_when_no_local_pid(self):+ """Cross-container gateway: no local PID, but the remote is alive.++ This is the rung /api/messaging/platforms was missing entirely, which+ is what made it contradict the sidebar in Docker Compose deployments.+ """+ result = status.resolve_gateway_liveness(+ runtime=None,+ health_probe=lambda: (True, {"pid": 4321, "gateway_state": "running"}),+ pid_probe=lambda *a, **k: None,+ runtime_pid_probe=lambda *a, **k: None,+ )++ assert result.running is True+ assert result.source == "health"+ # Display-only PID from the remote container.+ assert result.pid == 4321+ assert result.health_body == {"pid": 4321, "gateway_state": "running"}++ def test_runtime_status_rung_answers_when_pid_file_absent(self):+ """Launch-service-managed gateway: live process, no gateway.pid."""+ result = status.resolve_gateway_liveness(+ runtime={"gateway_state": "running", "pid": 777},+ health_probe=None,+ pid_probe=lambda *a, **k: None,+ runtime_pid_probe=lambda *a, **k: 777,+ )++ assert result.running is True+ assert result.pid == 777+ assert result.source == "runtime_status"++ def test_reports_down_when_every_rung_declines(self):+ result = status.resolve_gateway_liveness(+ runtime=None,+ health_probe=lambda: (False, None),+ pid_probe=lambda *a, **k: None,+ runtime_pid_probe=lambda *a, **k: None,+ )++ assert result.running is False+ assert result.pid is None+ assert result.source == "none"+ # Nothing raised, so this is a confident "down", not "unknown".+ assert result.probe_error is False++ def test_probe_exception_degrades_instead_of_raising(self):+ """A raising rung must fall through, never propagate.++ Status endpoints poll this constantly; an exotic /proc or a+ permissions error must not turn into a 500.+ """+ def _boom(*a, **k):+ raise RuntimeError("probe exploded")++ result = status.resolve_gateway_liveness(+ runtime=None,+ health_probe=None,+ pid_probe=_boom,+ runtime_pid_probe=lambda *a, **k: None,+ )++ assert result.running is False+ # probe_error distinguishes "down" from "couldn't tell" for callers+ # that must fail OPEN (the kanban dispatcher warning).+ assert result.probe_error is True++ def test_probe_exception_still_lets_a_lower_rung_win(self):+ def _boom(*a, **k):+ raise RuntimeError("pid probe exploded")++ result = status.resolve_gateway_liveness(+ runtime={"gateway_state": "running", "pid": 555},+ health_probe=None,+ pid_probe=_boom,+ runtime_pid_probe=lambda *a, **k: 555,+ )++ assert result.running is True+ assert result.source == "runtime_status"++ def test_profile_dir_scopes_every_read_to_that_profile(self, tmp_path):+ """Gateway identity files live in the per-profile home.++ The status readers resolve process-level paths and deliberately+ ignore the HERMES_HOME contextvar override (#56986), so the profile+ directory must be threaded through explicitly or a scoped request+ silently reports a DIFFERENT profile's gateway (#71211).+ """+ profile_dir = tmp_path / "profiles" / "worker"+ profile_dir.mkdir(parents=True)+ seen = {}++ def _pid(pid_path=None, **kw):+ seen["pid_path"] = pid_path+ return None++ def _reader(path=None):+ seen["status_path"] = path+ return None++ def _runtime_pid(runtime, *, expected_home=None):+ seen["expected_home"] = expected_home+ return None++ status.resolve_gateway_liveness(+ profile_dir=profile_dir,+ health_probe=None,+ pid_probe=_pid,+ runtime_reader=_reader,+ runtime_pid_probe=_runtime_pid,+ )++ assert seen["pid_path"] == profile_dir / "gateway.pid"+ assert seen["status_path"] == profile_dir / "gateway_state.json"+ # expected_home is what stops a recycled PID belonging to another+ # profile's live gateway from being reported as this profile's.+ assert seen["expected_home"] == profile_dir++ def test_supplied_runtime_is_not_re_read(self):+ """Callers that already read the state file must not pay for it twice."""+ reads = {"count": 0}++ def _reader(path=None):+ reads["count"] += 1+ return None++ status.resolve_gateway_liveness(+ runtime={"gateway_state": "running", "pid": 1},+ health_probe=None,+ pid_probe=lambda *a, **k: None,+ runtime_reader=_reader,+ runtime_pid_probe=lambda *a, **k: None,+ )++ assert reads["count"] == 0diff --git a/tests/hermes_cli/test_web_server.py b/tests/hermes_cli/test_web_server.pyindex 277cb56b5cf..e76c24a5fd6 100644--- a/tests/hermes_cli/test_web_server.py+++ b/tests/hermes_cli/test_web_server.py@@ -397,6 +397,115 @@ class TestWebServerEndpoints:assert data["gateway_pid"] == 4321assert data["gateway_state"] == "running"+ def test_get_status_and_messaging_agree_on_cross_container_gateway(+ self, monkeypatch+ ):+ """The two surfaces must never contradict each other about liveness.++ Reported symptom: the dashboard sidebar read "Gateway running" while+ the Channels page on the same load rendered "The gateway is not+ running." Cause: /api/status probed GATEWAY_HEALTH_URL and+ /api/messaging/platforms did not, so a gateway in another container+ (no local PID file) was live to one endpoint and dead to the other.++ This asserts the RELATIONSHIP — both endpoints resolve liveness the+ same way — not either endpoint's literal value.+ """+ import hermes_cli.web_server as web_server++ # No local PID and no local runtime state: only the health probe can+ # see the gateway, which is exactly the cross-container deployment.+ monkeypatch.setattr(web_server, "get_running_pid_cached", lambda *a, **k: None)+ monkeypatch.setattr(web_server, "get_running_pid", lambda *a, **k: None)+ monkeypatch.setattr(web_server, "read_runtime_status", lambda *a, **k: None)+ monkeypatch.setattr(+ web_server, "get_runtime_status_running_pid", lambda *a, **k: None+ )+ monkeypatch.setattr(web_server, "_GATEWAY_HEALTH_URL", "http://gw:8642")+ monkeypatch.setattr(+ web_server,+ "_probe_gateway_health",+ lambda: (True, {"pid": 4321, "gateway_state": "running", "platforms": {}}),+ )++ status_running = self.client.get("/api/status").json()["gateway_running"]+ platforms = self.client.get("/api/messaging/platforms").json()["platforms"]++ assert status_running is True, "health probe should report the gateway up"+ assert platforms, "catalog must not be empty or the assertion is vacuous"+ for platform in platforms:+ assert platform["gateway_running"] == status_running, (+ f"{platform['id']}: Channels page says "+ f"gateway_running={platform['gateway_running']} while the "+ f"sidebar says {status_running}"+ )++ def test_get_status_and_messaging_agree_when_gateway_is_down(self, monkeypatch):+ """Agreement must hold in the negative direction too.++ Guards against "fix" it by hardcoding True somewhere: with every rung+ declining, both surfaces must report the gateway down.+ """+ import hermes_cli.web_server as web_server++ monkeypatch.setattr(web_server, "get_running_pid_cached", lambda *a, **k: None)+ monkeypatch.setattr(web_server, "get_running_pid", lambda *a, **k: None)+ monkeypatch.setattr(web_server, "read_runtime_status", lambda *a, **k: None)+ monkeypatch.setattr(+ web_server, "get_runtime_status_running_pid", lambda *a, **k: None+ )+ monkeypatch.setattr(web_server, "_GATEWAY_HEALTH_URL", None)++ status_running = self.client.get("/api/status").json()["gateway_running"]+ platforms = self.client.get("/api/messaging/platforms").json()["platforms"]++ assert status_running is False+ assert platforms+ for platform in platforms:+ assert platform["gateway_running"] == status_running++ def test_messaging_platforms_profile_scopes_gateway_reads(self, monkeypatch):+ """?profile=<name> must resolve liveness from the profile's own home.++ The gateway status readers resolve process-level paths and ignore the+ HERMES_HOME contextvar override (#56986), so /api/messaging/platforms+ has to pass the profile directory explicitly — otherwise it reports a+ DIFFERENT profile's gateway as this profile's, which hides a real+ outage behind a false "connected" (issue #71211).+ """+ import hermes_cli.web_server as web_server+ from hermes_cli import profiles as profiles_mod++ worker_home = profiles_mod.get_profile_dir("worker")+ worker_home.mkdir(parents=True)++ seen = {}++ def _pid(pid_path=None, **kw):+ seen["pid_path"] = pid_path+ return None++ def _runtime(path=None):+ seen["status_path"] = path+ return None++ def _runtime_pid(runtime=None, *, expected_home=None):+ seen["expected_home"] = expected_home+ return None++ monkeypatch.setattr(web_server, "get_running_pid_cached", _pid)+ monkeypatch.setattr(web_server, "get_running_pid", _pid)+ monkeypatch.setattr(web_server, "read_runtime_status", _runtime)+ monkeypatch.setattr(web_server, "get_runtime_status_running_pid", _runtime_pid)+ monkeypatch.setattr(web_server, "_GATEWAY_HEALTH_URL", None)++ resp = self.client.get("/api/messaging/platforms?profile=worker")++ assert resp.status_code == 200+ assert seen["pid_path"] == worker_home / "gateway.pid"+ assert seen["status_path"] == worker_home / "gateway_state.json"+ assert seen["expected_home"] == worker_home+def test_get_status_unknown_profile_404s(self):resp = self.client.get("/api/status?profile=no-such-profile")assert resp.status_code == 404diff --git a/tests/hermes_cli/test_web_server_messaging_profiles.py b/tests/hermes_cli/test_web_server_messaging_profiles.pyindex 54420838057..80803b878d5 100644--- a/tests/hermes_cli/test_web_server_messaging_profiles.py+++ b/tests/hermes_cli/test_web_server_messaging_profiles.py@@ -108,11 +108,17 @@ class TestProfileScopedMessagingReads:yaml.safe_dump({"platforms": {"telegram": {"enabled": True}}}),encoding="utf-8",)- monkeypatch.setattr(web_server, "get_running_pid", lambda: None)+ monkeypatch.setattr(web_server, "get_running_pid", lambda *a, **k: None)+ monkeypatch.setattr(+ web_server, "get_running_pid_cached", lambda *a, **k: None+ )monkeypatch.setattr(web_server,"read_runtime_status",- lambda: {+ # Accepts path= : the profile-scoped read now passes the+ # profile's own gateway_state.json explicitly rather than+ # relying on process-level HERMES_HOME resolution (#71211).+ lambda *a, **k: {"gateway_state": "startup_failed","exit_reason": "all configured messaging platforms failed to connect","platforms": {},diff --git a/tests/plugins/test_kanban_dashboard_plugin.py b/tests/plugins/test_kanban_dashboard_plugin.pyindex 717bf660ee9..fee0591a1c7 100644--- a/tests/plugins/test_kanban_dashboard_plugin.py+++ b/tests/plugins/test_kanban_dashboard_plugin.py@@ -1576,7 +1576,7 @@ def test_create_task_includes_warning_when_no_dispatcher(client, monkeypatch):# Force the dispatcher probe to report "not running".monkeypatch.setattr("hermes_cli.kanban._check_dispatcher_presence",- lambda: (False, "No gateway is running — start `hermes gateway start`."),+ lambda **kw: (False, "No gateway is running — start `hermes gateway start`."),)r = client.post("/api/plugins/kanban/tasks",@@ -1592,7 +1592,7 @@ def test_create_task_no_warning_when_dispatcher_up(client, monkeypatch):"""Dispatcher running -> no `warning` field in the response."""monkeypatch.setattr("hermes_cli.kanban._check_dispatcher_presence",- lambda: (True, ""),+ lambda **kw: (True, ""),)r = client.post("/api/plugins/kanban/tasks",@@ -1607,7 +1607,7 @@ def test_create_task_no_warning_on_triage(client, monkeypatch):anyway until promoted)."""monkeypatch.setattr("hermes_cli.kanban._check_dispatcher_presence",- lambda: (False, "oh no"),+ lambda **kw: (False, "oh no"),)r = client.post("/api/plugins/kanban/tasks",@@ -1700,7 +1700,7 @@ def test_single_task_endpoint_survives_task_age_exception(client, monkeypatch):def test_create_task_probe_error_does_not_break_create(client, monkeypatch):"""Probe failure must never break task creation."""- def _raise():+ def _raise(**kw):raise RuntimeError("probe crashed")monkeypatch.setattr("hermes_cli.kanban._check_dispatcher_presence", _raise,