fix(multiplex): dashboard and gateway stop see a served profile's gateway as the multiplexer
A profile served by the default multiplexer owns no gateway.pid / gateway_state.json, so every surface that reads per-profile identity files called it stopped while the CLI status surfaces (hermes -p X status / gateway status / cron status) said "running via the default-profile multiplexer": - `/api/status?profile=X` and `/api/messaging/platforms?profile=X` reported gateway_running=false / state=None / "gateway_stopped" in the same body that listed X under gateways[].served_profiles. The shared ladder `resolve_gateway_liveness` gains a fourth rung for a named profile_dir: the live default multiplexer that records X in served_profiles IS X's gateway (pid = multiplexer pid, runtime = its record, X's `<X>:<platform>` entries re-keyed to the standalone shape). - `POST /api/gateway/stop?profile=X` spawned `hermes -p X gateway stop`, which printed "No gateway running for this profile" (exit 0) into the action log while the UI flipped to stopped and the multiplexer kept serving X; `/api/gateway/restart?profile=X` spawned a `-p X gateway restart` that only exits 78. start/stop now answer 409 with the multiplexer explanation (one helper shared with the existing start refusal) and restart targets the multiplexer, the process that actually serves X. A `--force`-started separate gateway for X (own pid file) keeps normal per-profile management. - CLI `hermes -p X gateway stop` refuses with exit 78 like run/start/install/restart when X has no gateway of its own, instead of a contradictory exit-0 "not running". Docs: multi-profile-gateways.md §1 and §5 describe stop + the dashboard behaviour.
This commit is contained in:
+48
-1
@@ -912,6 +912,42 @@ class GatewayLiveness:
|
||||
source: str
|
||||
health_body: Optional[dict[str, Any]] = None
|
||||
probe_error: bool = False
|
||||
# The multiplexer's own ``gateway_state.json`` when the ``multiplexer`` rung answered: a served
|
||||
# profile writes no runtime record of its own, so its platform states live there under
|
||||
# ``<profile>:<platform>`` keys.
|
||||
runtime: Optional[dict[str, Any]] = None
|
||||
|
||||
|
||||
def multiplexer_liveness_for_profile(profile_dir: Path) -> Optional[tuple[int, dict[str, Any]]]:
|
||||
"""``(pid, default gateway_state.json)`` when the live default multiplexer serves the named profile at
|
||||
``profile_dir``; None for the default home itself, an unserved profile, or no live multiplexer.
|
||||
|
||||
A served profile owns no ``gateway.pid``/``gateway_state.json`` (#97120), so every PID-file rung of the
|
||||
dashboard ladder reports it stopped while ``hermes -p X status`` says running — the two must agree.
|
||||
"""
|
||||
name = _profile_name_for_home(Path(profile_dir))
|
||||
if not name:
|
||||
return None
|
||||
from hermes_cli.gateway import named_profile_served_by_running_multiplexer
|
||||
from hermes_cli.gateway_multiplex_served import live_default_gateway_pid
|
||||
from hermes_constants import get_default_hermes_root
|
||||
if not named_profile_served_by_running_multiplexer(name):
|
||||
return None
|
||||
pid = live_default_gateway_pid()
|
||||
if pid is None:
|
||||
return None
|
||||
return pid, read_runtime_status(get_default_hermes_root() / "gateway_state.json") or {}
|
||||
|
||||
|
||||
def profile_platforms_from_multiplexer(runtime: Optional[dict[str, Any]], profile: str) -> dict[str, Any]:
|
||||
"""The ``<profile>:<platform>`` entries of a multiplexer record, re-keyed to bare platform names — the
|
||||
same shape a standalone gateway for ``profile`` writes into its own ``gateway_state.json``."""
|
||||
plats = (runtime or {}).get("platforms")
|
||||
if not isinstance(plats, dict):
|
||||
return {}
|
||||
prefix = f"{profile}:"
|
||||
return {key[len(prefix):]: value for key, value in plats.items()
|
||||
if isinstance(key, str) and key.startswith(prefix) and isinstance(value, dict)}
|
||||
|
||||
|
||||
def resolve_gateway_liveness(
|
||||
@@ -926,7 +962,9 @@ def resolve_gateway_liveness(
|
||||
so polling does not re-flock ``gateway.lock``); (2) caller-supplied HTTP health probe (gateway
|
||||
in another container); (3) LOCAL runtime status PID validated against the live process table
|
||||
with ``expected_home`` (a recycled PID of another profile never counts; pass ``runtime`` if
|
||||
already read). ``*_probe``/``runtime_reader`` are the dashboard's injection/test seam. A rung
|
||||
already read); (4) for a named ``profile_dir`` only, the live default multiplexer that records the
|
||||
profile in ``served_profiles`` (a served profile writes no identity files of its own). ``*_probe``/
|
||||
``runtime_reader`` are the dashboard's injection/test seam. A rung
|
||||
that raises degrades to the next (never 500 a status endpoint) and sets ``probe_error``.
|
||||
|
||||
Before this existed, ``/api/status`` and ``/api/messaging/platforms`` each open-coded their own ladder
|
||||
@@ -973,6 +1011,15 @@ def resolve_gateway_liveness(
|
||||
return GatewayLiveness(
|
||||
running=True, pid=runtime_pid, source="runtime_status", health_body=health_body
|
||||
)
|
||||
# (4) A named profile served by the live default multiplexer: no identity files of its own, but
|
||||
# the multiplexer IS its gateway (mirrors `hermes -p X status` / `gateway list`).
|
||||
if scoped:
|
||||
served = guarded(multiplexer_liveness_for_profile, profile_dir)
|
||||
if served is not None:
|
||||
mux_pid, mux_runtime = served
|
||||
return GatewayLiveness(
|
||||
running=True, pid=mux_pid, source="multiplexer", health_body=health_body, runtime=mux_runtime
|
||||
)
|
||||
return GatewayLiveness(
|
||||
running=False, pid=None, source="none", health_body=health_body, probe_error=probe_error
|
||||
)
|
||||
|
||||
@@ -6105,6 +6105,19 @@ def _cmd_stop(args):
|
||||
_refuse_from_inside_gateway("stop", "restart loops")
|
||||
stop_all = getattr(args, "all", False)
|
||||
system = getattr(args, "system", False)
|
||||
if not stop_all and not find_gateway_pids() and named_profile_served_by_running_multiplexer():
|
||||
# A served profile owns no gateway to stop; "No gateway running for this profile" (exit 0) would
|
||||
# contradict `gateway status` ("running via the default-profile multiplexer") on the same profile.
|
||||
# A `--force`-started separate gateway HAS a pid of its own and is stopped normally.
|
||||
print_error(
|
||||
f"The default gateway is running as a profile multiplexer and serves profile "
|
||||
f"'{_current_profile_name()}' — there is no separate gateway for this profile to stop."
|
||||
)
|
||||
print(" Stop or restart the multiplexer from the default profile instead:")
|
||||
print()
|
||||
print(" hermes gateway stop # takes every served profile offline")
|
||||
print(" hermes gateway restart")
|
||||
sys.exit(GATEWAY_FATAL_CONFIG_EXIT_CODE)
|
||||
# Under s6 a bare pkill is seen as a crash and restarted; go through the supervisor.
|
||||
if stop_all and _dispatch_all_via_service_manager_if_s6("stop"):
|
||||
return
|
||||
|
||||
@@ -21,7 +21,8 @@ from typing import Any, Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
|
||||
from gateway.status import resolve_gateway_liveness
|
||||
from gateway.status import (
|
||||
multiplexer_liveness_for_profile, profile_platforms_from_multiplexer, resolve_gateway_liveness)
|
||||
from hermes_cli._subprocess_compat import windows_hide_flags
|
||||
from hermes_cli.config import OPTIONAL_ENV_VARS, get_env_path, redact_key
|
||||
from hermes_cli.web_deps import LateState, late
|
||||
@@ -274,6 +275,12 @@ def _platform_payloads(scoped_dir: Optional[Path], entries) -> list[dict[str, An
|
||||
HERMES_HOME contextvar; the gateway status readers do not, hence the explicit path)."""
|
||||
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()
|
||||
if scoped_dir is not None and runtime is None:
|
||||
# A profile served by the multiplexer writes no record of its own; its adapters live in the
|
||||
# multiplexer's record under ``<profile>:<platform>``.
|
||||
served = multiplexer_liveness_for_profile(scoped_dir)
|
||||
if served is not None:
|
||||
runtime = {**served[1], "platforms": profile_platforms_from_multiplexer(served[1], scoped_dir.name)}
|
||||
return [_messaging_platform_payload(entry, env_on_disk, runtime, scoped=scoped_dir is not None, profile_home=scoped_dir)
|
||||
for entry in entries]
|
||||
|
||||
|
||||
@@ -250,15 +250,12 @@ async def set_webhook_enabled(name: str, body: WebhookEnabledToggle):
|
||||
|
||||
@router.post("/api/gateway/start")
|
||||
async def start_gateway(profile: Optional[str] = None):
|
||||
from hermes_cli.gateway import named_profile_served_by_running_multiplexer
|
||||
from hermes_cli.web_server_gateway import multiplexed_profile_refusal
|
||||
# The spawned `hermes -p X gateway start` would refuse with exit 78 into an action log nobody reads;
|
||||
# surface the same refusal here so the UI can point at the multiplexer instead of showing "started".
|
||||
if profile and profile != "default" and await asyncio.to_thread(named_profile_served_by_running_multiplexer, profile):
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail=f"The default gateway already serves profile '{profile}' as a multiplexer; "
|
||||
"restart it from the default profile instead of starting a separate gateway.",
|
||||
)
|
||||
refusal = await asyncio.to_thread(multiplexed_profile_refusal, profile, "start")
|
||||
if refusal:
|
||||
raise HTTPException(status_code=409, detail=refusal)
|
||||
with http_failure("Failed to spawn gateway start", 500, "Failed to start gateway"):
|
||||
proc = _spawn_hermes_action(_gateway_subcommand(profile, "start"), "gateway-start")
|
||||
return {"ok": True, "pid": proc.pid, "name": "gateway-start"}
|
||||
@@ -266,6 +263,12 @@ async def start_gateway(profile: Optional[str] = None):
|
||||
|
||||
@router.post("/api/gateway/stop")
|
||||
async def stop_gateway(profile: Optional[str] = None):
|
||||
from hermes_cli.web_server_gateway import multiplexed_profile_refusal
|
||||
# A served profile has no gateway of its own to stop: the child prints "No gateway running for this
|
||||
# profile" (exit 0) while the multiplexer keeps serving it and the UI flips to "stopped".
|
||||
refusal = await asyncio.to_thread(multiplexed_profile_refusal, profile, "stop")
|
||||
if refusal:
|
||||
raise HTTPException(status_code=409, detail=refusal)
|
||||
with http_failure("Failed to spawn gateway stop", 500, "Failed to stop gateway"):
|
||||
proc = _spawn_hermes_action(_gateway_subcommand(profile, "stop"), "gateway-stop")
|
||||
return {"ok": True, "pid": proc.pid, "name": "gateway-stop"}
|
||||
|
||||
@@ -18,7 +18,9 @@ from hermes_cli.web_deps import LateState, late
|
||||
from hermes_cli.web_server_gateway import _display_system_platform
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
from fastapi import HTTPException, Request
|
||||
from gateway.status import derive_gateway_busy, derive_gateway_drainable, normalize_updated_at, parse_active_agents, resolve_gateway_liveness
|
||||
from gateway.status import (
|
||||
derive_gateway_busy, derive_gateway_drainable, normalize_updated_at, parse_active_agents,
|
||||
profile_platforms_from_multiplexer, resolve_gateway_liveness)
|
||||
from hermes_cli import __version__, __release_date__
|
||||
from hermes_cli.config import get_config_path, get_env_path
|
||||
from hermes_cli.web_models import CuratorPause, LearningNodeRef, LearningNodeEdit, DebugShareRequest
|
||||
@@ -250,6 +252,11 @@ async def _resolve_gateway_status(profile_dir: Optional[Path], health_url) -> Di
|
||||
runtime = local_runtime
|
||||
if runtime is None and remote_health_body and remote_health_body.get("gateway_state"):
|
||||
runtime = remote_health_body
|
||||
if liveness.runtime is not None and profile_dir is not None:
|
||||
# Served by the multiplexer: its record is this profile's runtime, with the profile's own
|
||||
# adapters under ``<profile>:<platform>`` re-keyed to the standalone shape.
|
||||
runtime = {**liveness.runtime,
|
||||
"platforms": profile_platforms_from_multiplexer(liveness.runtime, profile_dir.name)}
|
||||
|
||||
gateway_state = None
|
||||
gateway_platforms: dict = {}
|
||||
|
||||
@@ -356,8 +356,36 @@ def _spawn_hermes_action(
|
||||
|
||||
|
||||
def _gateway_subcommand(profile: Optional[str], verb: str) -> List[str]:
|
||||
"""``hermes [-p X] gateway <verb>`` argv for a dashboard lifecycle action. A profile served by the
|
||||
live default multiplexer has no gateway of its own: ``restart`` targets the multiplexer (the process
|
||||
that actually serves X — a ``-p X gateway restart`` child only exits 78 into the action log while the
|
||||
UI reports "restarted"); ``start``/``stop`` are refused by the caller (``multiplexed_profile_refusal``)."""
|
||||
from hermes_cli.web_server_profiles import _profile_cli_args
|
||||
return _profile_cli_args(profile) + ["gateway", verb]
|
||||
args = _profile_cli_args(profile)
|
||||
if args and verb == "restart" and multiplexed_profile_refusal(args[-1], verb) is not None:
|
||||
args = []
|
||||
return args + ["gateway", verb]
|
||||
|
||||
|
||||
def _profile_is_multiplexed(profile: str) -> bool:
|
||||
from hermes_cli.gateway import named_profile_served_by_running_multiplexer
|
||||
return named_profile_served_by_running_multiplexer(profile)
|
||||
|
||||
|
||||
def multiplexed_profile_refusal(profile: Optional[str], verb: str) -> Optional[str]:
|
||||
"""Refusal text for ``gateway start``/``stop`` on a profile the live default multiplexer serves and
|
||||
that has no gateway of its own (a ``--force``-started separate one is managed normally), else None.
|
||||
The spawned ``hermes -p X gateway <verb>`` would only print exit-78 / "no gateway running for this
|
||||
profile" into an action log nobody reads while the UI shows the verb as done."""
|
||||
requested = (profile or "").strip()
|
||||
if not requested or requested.lower() in {"current", "default"} or not _profile_is_multiplexed(requested):
|
||||
return None
|
||||
from hermes_cli.profiles import _check_gateway_running
|
||||
from hermes_cli.web_server_profiles import _resolve_profile_dir
|
||||
if _check_gateway_running(_resolve_profile_dir(requested)):
|
||||
return None
|
||||
return (f"The default gateway already serves profile '{requested}' as a multiplexer; "
|
||||
f"{verb} it from the default profile instead of a separate gateway for this profile.")
|
||||
|
||||
|
||||
def _restart_gateway_after(profile: Optional[str], *, what: str, label: str) -> dict[str, Any]:
|
||||
|
||||
@@ -94,3 +94,46 @@ def test_status_surfaces_agree_for_a_satellite_profile(served_root, monkeypatch)
|
||||
with contextlib.redirect_stdout(buf):
|
||||
cr.cron_status()
|
||||
assert "NOT fire" not in buf.getvalue() and "multiplexer" in buf.getvalue()
|
||||
|
||||
|
||||
def test_dashboard_liveness_ladder_reports_served_profile_running(served_root):
|
||||
"""`/api/status?profile=X` and `/api/messaging/platforms?profile=X` share this ladder: a served
|
||||
profile has no gateway.pid/gateway_state.json, so without the multiplexer rung the dashboard said
|
||||
"stopped" while `hermes -p X status` said running. Alpha's `<X>:<platform>` entries project as its own."""
|
||||
from gateway.status import profile_platforms_from_multiplexer, resolve_gateway_liveness
|
||||
(served_root / "gateway_state.json").write_text(json.dumps({
|
||||
"pid": os.getpid(), "hermes_home": str(served_root), "gateway_state": "running",
|
||||
"served_profiles": ["default", "coder"],
|
||||
"platforms": {"api_server": {"state": "connected"}, "coder:telegram": {"state": "connected"}}}))
|
||||
coder = served_root / "profiles" / "coder"
|
||||
live = resolve_gateway_liveness(profile_dir=coder, health_probe=None, use_cache=False)
|
||||
assert live.running is True and live.pid == os.getpid() and live.source == "multiplexer"
|
||||
assert profile_platforms_from_multiplexer(live.runtime, "coder") == {"telegram": {"state": "connected"}}
|
||||
# An unserved profile keeps the historical "stopped" answer.
|
||||
other = resolve_gateway_liveness(profile_dir=served_root / "profiles" / "other", health_probe=None, use_cache=False)
|
||||
assert other.running is False
|
||||
|
||||
|
||||
def test_dashboard_lifecycle_verbs_target_the_multiplexer(served_root, monkeypatch):
|
||||
"""`gateway restart` for a served profile restarts the multiplexer (a `-p X` child only exits 78 into
|
||||
the action log); `start`/`stop` refuse; a profile with its own gateway is managed normally."""
|
||||
from hermes_cli import profiles as profiles_mod
|
||||
from hermes_cli.web_server_gateway import _gateway_subcommand, multiplexed_profile_refusal
|
||||
monkeypatch.setattr(profiles_mod, "_check_gateway_running", lambda home: False)
|
||||
assert _gateway_subcommand("coder", "restart") == ["gateway", "restart"]
|
||||
assert multiplexed_profile_refusal("coder", "stop") and multiplexed_profile_refusal("coder", "start")
|
||||
assert _gateway_subcommand("other", "restart") == ["-p", "other", "gateway", "restart"]
|
||||
assert multiplexed_profile_refusal("other", "stop") is None
|
||||
# coder started its own gateway with --force: it is that gateway the verbs address.
|
||||
monkeypatch.setattr(profiles_mod, "_check_gateway_running", lambda home: True)
|
||||
assert _gateway_subcommand("coder", "restart") == ["-p", "coder", "gateway", "restart"]
|
||||
assert multiplexed_profile_refusal("coder", "stop") is None
|
||||
|
||||
|
||||
def test_cli_stop_refuses_for_a_served_profile_without_its_own_gateway(served_root, monkeypatch):
|
||||
import hermes_cli.gateway as gw
|
||||
monkeypatch.setattr(gw, "find_gateway_pids", lambda *a, **k: [])
|
||||
monkeypatch.setattr(gw, "_refuse_from_inside_gateway", lambda *a, **k: None)
|
||||
with contextlib.redirect_stdout(io.StringIO()), pytest.raises(SystemExit) as exc:
|
||||
gw._cmd_stop(argparse.Namespace(system=False, all=False))
|
||||
assert exc.value.code == gw.GATEWAY_FATAL_CONFIG_EXIT_CODE
|
||||
|
||||
@@ -126,7 +126,13 @@ profile 'coder'. ...
|
||||
|
||||
The refusal happens in the CLI before any service manager is touched, so a served
|
||||
profile never ends up with a permanently failed systemd unit or a launchd respawn
|
||||
loop. The Desktop app's per-profile "Start gateway" action is refused the same way.
|
||||
loop. `hermes -p coder gateway stop` refuses the same way (exit 78) when coder has no
|
||||
gateway of its own — there is nothing to stop but the multiplexer, which
|
||||
`hermes gateway stop` on the default profile takes down for every served profile.
|
||||
The dashboard and Desktop app follow the CLI: for a served profile the "Start" and
|
||||
"Stop" gateway actions answer `409` with the same explanation, and "Restart"
|
||||
restarts the multiplexer (the process that actually serves the profile) instead of
|
||||
spawning a `-p coder gateway restart` that could only fail.
|
||||
"Served" is read from the running gateway's own record (`served_profiles` in the
|
||||
default home's `gateway_state.json`), so it stays correct when the multiplexer was
|
||||
enabled only through `GATEWAY_MULTIPLEX_PROFILES` in the default profile's
|
||||
@@ -246,7 +252,9 @@ There is a single process-level PID and lock (the multiplexer, under the default
|
||||
home). `hermes status` on the default profile reports the multiplexer and lists
|
||||
the profiles it serves (`Serves: coder, research`); `hermes -p coder status`,
|
||||
`hermes -p coder gateway status` and `hermes -p coder cron status` all report
|
||||
"running via the default-profile multiplexer" instead of "stopped". The single
|
||||
"running via the default-profile multiplexer" instead of "stopped", and the
|
||||
dashboard's `/api/status?profile=coder` / Channels page report the multiplexer as
|
||||
coder's running gateway (with coder's own adapters as its platforms). The single
|
||||
`gateway_state.json` lives under the default home: secondary adapters appear
|
||||
there as `<profile>:<platform>` entries beside `served_profiles`; nothing is
|
||||
written under a secondary profile's home.
|
||||
|
||||
Reference in New Issue
Block a user