Skip to content

The agent that grows with you

fix(gateway): named profiles attach through the host multiplexer

teknium1f0638e4487df
diff --git a/gateway/session_local.py b/gateway/session_local.py
index e0fe53a06a2..5d9aeac78bd 100644
--- a/gateway/session_local.py
+++ b/gateway/session_local.py
@@ -172,11 +172,14 @@ def publish_local_policy(authority, session_id):
def local_session_info(authority, ref):
live = authority.sessions[ref.session_id]
agent = authority.agent(ref)
+ from gateway.session_authorities import served_profile_name
from gateway.session_policy import policy_for_source
policy = policy_for_source(authority.runner, live.source)
info = {'source': policy.source if policy else live.source.platform.value,
'model': getattr(agent, 'model', policy.model if policy else None), 'lazy': agent is None,
'profile_id': authority.profile_id, 'desktop_protocol': CANONICAL_GATEWAY_PROTOCOL,
+ # Main's TUI labels a named profile's composer (``alpha ❯``) from this field.
+ 'profile_name': served_profile_name(authority.profile_id),
**({'cwd': policy.cwd} if policy else {})}
if policy:
# The creation request the route was frozen with (secrets already extracted), so a
diff --git a/hermes_cli/gateway_runtime.py b/hermes_cli/gateway_runtime.py
index 50a08caf507..35bdeebf360 100644
--- a/hermes_cli/gateway_runtime.py
+++ b/hermes_cli/gateway_runtime.py
@@ -219,9 +219,14 @@ def ensure_gateway_runtime(profile_home: str | Path, *, timeout: float = DEFAULT
# A named profile the default multiplexer serves has no daemon of its own: start
# (or await) the MULTIPLEXER. A per-profile spawn here would become a second owner
# that blocks the multiplexer's next all-or-nothing reserve.
- from hermes_cli.gateway_runtime_multiplex import multiplexer_serves_home
+ from hermes_cli.gateway_runtime_multiplex import implied_host_root, multiplexer_serves_home
target = multiplexer_serves_home(home) or home
service = discover_existing_gateway_service(target, deadline=deadline)
+ if service is None and target == home and (host := implied_host_root(home)) is not None:
+ # Main's guard refuses a named profile a gateway of its own unless it is standalone
+ # or already installed; with no multiplexer evidence yet, the host is still its owner.
+ target = host
+ service = discover_existing_gateway_service(target, deadline=deadline)
# Runtime locks settle races remaining after this second probe.
observed = discover_gateway_endpoint(home, timeout=remaining(deadline))
if observed.state != "absent":
diff --git a/hermes_cli/gateway_runtime_multiplex.py b/hermes_cli/gateway_runtime_multiplex.py
index 229ed0185ac..2a0d67d31ca 100644
--- a/hermes_cli/gateway_runtime_multiplex.py
+++ b/hermes_cli/gateway_runtime_multiplex.py
@@ -23,6 +23,23 @@ def multiplexer_root_for(home: Path) -> Path | None:
return root if root != home else None
+def implied_host_root(home: Path) -> Path | None:
+ """The root whose gateway must serve named profile *home* when nothing records a verdict.
+
+ ``hermes gateway run`` refuses a ``profiles/<name>`` home a gateway of its own unless it authored
+ ``gateway.standalone: true`` (or passes ``--force``); only an explicit multiplex ``false`` on the
+ root leaves the profile to its own daemon.
+ """
+ root = multiplexer_root_for(home)
+ if root is None:
+ return None
+ from hermes_cli.gateway_multiplex_mode import explicit_multiplex_flag
+ from hermes_cli.profiles import profile_is_standalone
+ if explicit_multiplex_flag(root) is False or profile_is_standalone(home):
+ return None
+ return root
+
+
def multiplexer_serves_home(home: Path) -> Path | None:
"""The root whose (possibly stopped) multiplexer serves *home*, else None.
diff --git a/tests/e2e/core/dashboard/_helpers.py b/tests/e2e/core/dashboard/_helpers.py
index aa92d0ce3c4..df8bd49ed9e 100644
--- a/tests/e2e/core/dashboard/_helpers.py
+++ b/tests/e2e/core/dashboard/_helpers.py
@@ -11,6 +11,7 @@ it as ``X-Hermes-Session-Token`` on REST and ``?token=`` on WebSocket upgrades,
from __future__ import annotations
+import contextlib
import json
import os
import re
@@ -155,6 +156,7 @@ class Sandbox:
for p in self.profiles.values():
if p.srv is not None:
p.srv.stop()
+ self._stop_gateways()
leaks = _reaper.reap(_reaper.with_home(self.home), *also)
finally:
if not self._released:
@@ -165,6 +167,17 @@ class Sandbox:
f"{_reaper.REAP_TIMEOUT:.0f}s and were killed:\n " + "\n ".join(leaks))
+ def _stop_gateways(self) -> None:
+ """Under the attach model a TUI starts the gateway daemon (setsid, outside the dashboard's
+ process group), which outlives its viewer by design: stop it the way a user would."""
+ for home in (self.hermes_home, *sorted((self.hermes_home / "profiles").glob("*"))):
+ if (home / "gateway.pid").exists():
+ with contextlib.suppress(Exception):
+ subprocess.run([sys.executable, "-m", "hermes_cli.main", "gateway", "stop"],
+ env=self.env({"HERMES_HOME": str(home)}), cwd=str(self.home),
+ capture_output=True, timeout=60)
+
+
class SandboxLeak(AssertionError):
"""A process spawned inside the sandbox was still running after teardown's deadline."""
diff --git a/tests/hermes_cli/test_gateway_runtime_ensure.py b/tests/hermes_cli/test_gateway_runtime_ensure.py
index 85fb82b75e7..7928d27a9d5 100644
--- a/tests/hermes_cli/test_gateway_runtime_ensure.py
+++ b/tests/hermes_cli/test_gateway_runtime_ensure.py
@@ -311,3 +311,24 @@ def test_unmanaged_root_home_child_ignores_sticky_active_profile(tmp_path, monke
resolved = json.loads(witness.read_text())
assert resolved["home"] == str(root), resolved
assert resolved["argv"] == ["hermes", "gateway", "run", "--quiet"], resolved
+
+
[email protected]("standalone", [False, True])
+def test_named_profile_without_multiplex_evidence_starts_the_host_gateway(tmp_path, monkeypatch, standalone):
+ """`gateway run` refuses a profiles/<name> home a gateway of its own, so ensure must start the host."""
+ from hermes_cli import gateway_runtime as runtime, gateway_runtime_service as service, gateway_runtime_start as start
+
+ root = tmp_path / ".hermes"
+ home = root / "profiles" / "alpha"
+ home.mkdir(parents=True, mode=0o700)
+ if standalone:
+ (home / "config.yaml").write_text("gateway:\n standalone: true\n", encoding="utf-8")
+ spawned = []
+ monkeypatch.setattr(runtime, "discover_gateway_endpoint", lambda *a, **k: runtime.GatewayDiscovery("absent"))
+ monkeypatch.setattr(service, "discover_existing_gateway_service", lambda *a, **k: None)
+ monkeypatch.setattr(start, "spawn_unmanaged_gateway", lambda target, **k: spawned.append(Path(target)))
+
+ runtime.ensure_gateway_runtime(home, timeout=0.3)
+
+ assert spawned == [(home if standalone else root).resolve()]
+
diff --git a/ui-tui/scripts/gateway_bootstrap.py b/ui-tui/scripts/gateway_bootstrap.py
index 8379608a25a..a54fe1c6bb7 100644
--- a/ui-tui/scripts/gateway_bootstrap.py
+++ b/ui-tui/scripts/gateway_bootstrap.py
@@ -11,7 +11,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
def bootstrap(start: bool) -> dict:
from hermes_constants import get_hermes_home
- from hermes_cli.gateway_runtime import discover_gateway_endpoint, ensure_gateway_runtime
+ from hermes_cli.gateway_runtime import control_home_for, discover_gateway_endpoint, ensure_gateway_runtime
from hermes_cli.gateway_runtime_discovery import _socket_path
home = get_hermes_home().resolve()
@@ -25,16 +25,18 @@ def bootstrap(start: bool) -> dict:
if receipt.state != "ready" or receipt.endpoint is None:
raise RuntimeError(f"gateway {receipt.state}: {receipt.reason_code or 'not ready'}")
endpoint = receipt.endpoint
+ # A profile served by the default multiplexer has no socket of its own; the host mints its ticket.
+ control = control_home_for(home, endpoint)
request = json.dumps({"protocol": 1, "id": 1, "verb": "session-ticket", "params": {
"profile_id": endpoint.profile_id, "instance_id": endpoint.instance_id,
"purpose": "interactive"}}).encode() + b"\n"
if os.name == "nt":
from gateway.runtime_bootstrap_windows import query_runtime_control
- raw = query_runtime_control(home, request, 5)
+ raw = query_runtime_control(control, request, 5)
else:
with socket.socket(socket.AF_UNIX) as peer:
peer.settimeout(5)
- peer.connect(str(_socket_path(home)))
+ peer.connect(str(_socket_path(control)))
peer.sendall(request)
with peer.makefile("rb") as stream:
raw = stream.readline(65537)
diff --git a/ui-tui/src/components/branding.tsx b/ui-tui/src/components/branding.tsx
index 8590af9cdbf..42e48f78ca7 100644
--- a/ui-tui/src/components/branding.tsx
+++ b/ui-tui/src/components/branding.tsx
@@ -252,7 +252,8 @@ export function SessionPanel({ info, maxWidth, sid, t }: SessionPanelProps) {
// The canonical authority intentionally returns a narrow metadata snapshot.
// Do not invent tool/skill inventories or crash while rendering that session.
if (!info.skills || !info.tools) {
- return <Box flexDirection="column"><Text color={t.color.muted}>Gateway session {sid}</Text>
+ return <Box flexDirection="column">
+ <Text><Text color={t.color.sessionLabel}>Session: </Text><Text color={t.color.sessionBorder}>{sid}</Text></Text>
<Text color={t.color.muted}>Tool and skill inventory is not exposed by this runtime.</Text></Box>
}