Skip to content

The agent that grows with you

fix(gateway): serve a profile created after a single-profile boot in place, without a restart (#141623)

Teknium291959504057
diff --git a/gateway/run_bootstrap.py b/gateway/run_bootstrap.py
index 92bb2a34906..b415b10799f 100644
--- a/gateway/run_bootstrap.py
+++ b/gateway/run_bootstrap.py
@@ -323,18 +323,17 @@ async def _start_gateway_start_control_socket(runner):
def _rescan_profiles_handler() -> dict:
"""``hermes profile create/delete`` asks the multiplexer to reconcile ``profiles/`` now
(the watcher also rescans periodically). Runs on the socket executor: marshal onto the loop
- and wait briefly so the caller learns whether the profile is served. A standalone gateway
- answers ``multiplex: False``, restarting into the multiplexer when it was standalone only
- because the host had a single profile."""
- multiplex = bool(getattr(runner.config, "multiplex_profiles", False))
+ and wait briefly so the caller learns whether the profile is served. A gateway standalone
+ only because the host had one profile starts multiplexing in place on this rescan."""
future = asyncio.run_coroutine_threadsafe(
runner.reconcile_served_profiles(reason="control-socket"), _main_loop)
try:
# Bounded: a token-less create reconciles in milliseconds; a credential-add whose adapter
# connect outlasts this keeps running and the caller sees ``pending`` (not an error).
- return {"multiplex": multiplex, **future.result(timeout=5.0)}
+ result = future.result(timeout=5.0)
except concurrent.futures.TimeoutError:
- return {"multiplex": multiplex, "pending": True, "served_profiles": runner.served_profile_names()}
+ result = {"pending": True, "served_profiles": runner.served_profile_names()}
+ return {"multiplex": bool(getattr(runner.config, "multiplex_profiles", False)), **result}
_control_server = GatewayControlServer(
verb_handlers={"pause-for-update": _pause_for_update_handler, "identify": _identify_runtime,
diff --git a/gateway/run_profile_reconcile.py b/gateway/run_profile_reconcile.py
index 638e7711eb0..dc11e952b2e 100644
--- a/gateway/run_profile_reconcile.py
+++ b/gateway/run_profile_reconcile.py
@@ -68,7 +68,7 @@ class GatewayProfileReconcileMixin:
_profile_own_gateway_warned: Optional[set[str]] = None
_profile_probe_timeout_warned: Optional[set[str]] = None
_hook_consent_signatures: Optional[dict[str, Optional[tuple]]] = None
- _standalone_preflight_names: Optional[tuple] = None
+ _single_profile_blocker_logged: Optional[str] = None
# ── state helpers ─────────────────────────────────────────────────────────────────────────────
@@ -96,18 +96,15 @@ class GatewayProfileReconcileMixin:
async def _profile_reconcile_watcher(self, interval: float = _PROFILE_RESCAN_INTERVAL_SECS) -> None:
"""Supervised safety net, every ``interval`` seconds: re-sync shell hooks whose consent changed
(every gateway), then rescan ``profiles/`` when multiplexing (creators signal the control
- socket for an immediate rescan), or check whether a single-profile standalone gateway now
- has a second profile to serve."""
+ socket for an immediate rescan); a gateway standalone only because the host had one profile
+ starts multiplexing here once a second one exists."""
while self._running:
await asyncio.sleep(interval)
if not self._running:
return
try:
await self._sync_hooks_on_consent_change()
- if self._multiplex_on():
- await self.reconcile_served_profiles(reason="watcher")
- else:
- await self._restart_to_serve_added_profile()
+ await self.reconcile_served_profiles(reason="watcher")
except asyncio.CancelledError:
raise
except Exception:
@@ -160,8 +157,7 @@ class GatewayProfileReconcileMixin:
from gateway.run import MultiplexConfigError
from hermes_cli.profiles import profiles_to_serve
result: dict[str, Any] = {"added": [], "removed": [], "rescanned": [], "parked": [], "reason": reason}
- if not self._multiplex_on():
- await self._restart_to_serve_added_profile()
+ if not self._multiplex_on() and not await self._multiplex_for_added_profile():
return {**result, "multiplex": False, "served_profiles": self.served_profile_names()}
if not self._running or self._served_profile_homes is None:
# Startup enumerates profiles/ itself; a rescan before it finishes has nothing to diff against.
@@ -319,28 +315,52 @@ class GatewayProfileReconcileMixin:
from gateway.run_runtime import parked_profile_map
return list(parked_profile_map(self))
- async def _restart_to_serve_added_profile(self) -> bool:
- """A gateway that booted standalone only because the host had ONE profile cannot serve one
- created since: multiplexing (and the fail-closed secret scope it arms) is settled once per
- boot, so every ticket, session and delete for the new profile was refused (#141623). When the
- host would multiplex now (boot's own preflight, nothing blocking), restart into the
- multiplexer the way ``/restart`` does, after-turn wait included. Any other standalone verdict
- stays: a restart would only repeat it. Each profile set is judged once. True when requested."""
+ async def _multiplex_for_added_profile(self) -> bool:
+ """Start multiplexing in place when this gateway booted standalone ONLY because the host had
+ one profile and a second now exists (#141623). Boot settles the mode once, so without this a
+ profile created afterwards (Desktop's New Agent, ``hermes profile create``) was never served:
+ every ticket, session and delete for it was refused until a manual restart.
+
+ No restart and no drain: the launch env is frozen and unscoped secret reads fail closed
+ (``activate_multi_profile_hosting``, the hosted-room precedent), the launch home becomes the
+ first entry of the reservation, and the caller's ordinary hot-serve reconcile serves the new
+ profile. Turns already running keep their bound scope; the launch profile's later work binds
+ its own scope through ``_standalone_launch_scope`` and the re-wired primary handlers. Any
+ other standalone verdict, or a preflight blocker now, leaves the gateway as it is; nothing is
+ latched, so the next rescan or watcher tick retries once the blocker clears. True when armed."""
from hermes_cli.gateway_multiplex_mode import (
- SINGLE_PROFILE_REASON, implicit_multiplex_blocker, recorded_standalone_reason)
+ SINGLE_PROFILE_REASON, MultiplexDecision, implicit_multiplex_blocker, log_multiplex_decision,
+ recorded_standalone_reason)
from hermes_cli.profiles import profiles_to_serve
+ from hermes_constants import get_default_hermes_root, get_process_hermes_home
if recorded_standalone_reason() != SINGLE_PROFILE_REASON:
return False
- names = tuple(sorted(name for name, _home in profiles_to_serve(multiplex=True, include_parked=True)))
- if len(names) < 2 or names == self._standalone_preflight_names:
+ launch = get_process_hermes_home().resolve()
+ if launch != get_default_hermes_root().resolve():
+ return False # only the default home runs the multiplexer (``_launch_home_may_multiplex``)
+ if len(profiles_to_serve(multiplex=True, include_parked=True)) < 2:
return False
- self._standalone_preflight_names = names
- if await self._run_housekeeping_in_executor(implicit_multiplex_blocker) is not None:
+ blocker = await self._run_housekeeping_in_executor(implicit_multiplex_blocker)
+ if blocker is not None:
+ if blocker != self._single_profile_blocker_logged:
+ logger.warning("[MULTIPLEX] A new profile exists but this gateway stays standalone: %s", blocker)
+ self._single_profile_blocker_logged = blocker
return False
- from gateway.restart import is_container_restart_context, is_gateway_supervisor_process
- via_service = is_gateway_supervisor_process() or is_container_restart_context()
- logger.info("[MULTIPLEX] Profiles %s exist now; restarting to serve every profile", ", ".join(names))
- return self.request_restart(detached=not via_service, via_service=via_service)
+ from tui_gateway.launch_profile_policy import activate_multi_profile_hosting
+ activate_multi_profile_hosting()
+ self.config.multiplex_profiles = True
+ self.config._runtime_profile_homes = (("default", launch),)
+ registry = getattr(self, "session_authorities", None)
+ if registry is not None:
+ registry.multiplexed = True
+ for adapter in list(self.adapters.values()):
+ adapter.set_message_handler(self._primary_message_handler())
+ adapter.set_busy_session_handler(self._primary_busy_session_handler())
+ adapter.set_platform_event_handler(self._primary_platform_event_handler())
+ self._record_served_profiles("default", [("default", launch)])
+ log_multiplex_decision(MultiplexDecision(True, "default", "a second profile was created"))
+ logger.info("[MULTIPLEX] A second profile exists; serving every profile from this process (no restart)")
+ return True
async def _serve_profile_runtime(self, name: str, home: Path) -> Optional[str]:
"""Grow the reservation by *home* and build its session authority (boot's per-secondary
diff --git a/tests/gateway/test_single_profile_host_serves_new_profile.py b/tests/gateway/test_single_profile_host_serves_new_profile.py
index b4fcb25ed1d..96188f16c54 100644
--- a/tests/gateway/test_single_profile_host_serves_new_profile.py
+++ b/tests/gateway/test_single_profile_host_serves_new_profile.py
@@ -2,15 +2,17 @@
multiplexing is settled once per boot. A profile created afterwards (Desktop's New Agent, ``hermes
profile create``) was then never served: every ticket the Desktop minted for it through the host's
control socket was refused, so its sessions, chat and Delete all failed with "Invalid gateway ticket
-response" (#141623). The creator's ``rescan-profiles`` signal (and the 30 s watcher) must restart such
-a gateway into the multiplexer; any other standalone verdict must not restart (it would repeat).
+response" (#141623). The creator's ``rescan-profiles`` signal (and the 30 s watcher) must start serving
+it from the SAME process: no restart, no drain, and unscoped secret reads fail closed from then on.
"""
import asyncio
import os
+import shutil
import pytest
import hermes_constants
+from agent.secret_scope import is_multiplex_active
from gateway.config import GatewayConfig
from gateway.run import GatewayRunner
from gateway.status import flush_runtime_status, write_runtime_status
@@ -30,20 +32,19 @@ def standalone_host(tmp_path, monkeypatch):
monkeypatch.setattr(gm, "_installed_services", lambda _home: [])
monkeypatch.setattr(gm, "_live_gateway_pid", lambda _home: None)
monkeypatch.setattr(gm, "_host_supports_migration", lambda: None)
- runner = object.__new__(GatewayRunner)
- runner.config = GatewayConfig(multiplex_profiles=False)
+ runner = GatewayRunner(GatewayConfig(multiplex_profiles=False))
runner._running = True
- runner._primary_profile_name = "default"
runner.session_runtime_descriptor = {"state": "ready", "served_profiles": [], "capabilities": []}
runner.session_ticket_store = None
restarts = []
runner.request_restart = lambda **kw: restarts.append(kw) or True
- return runner, home, restarts
-
-
-def _boot_verdict(reason):
- write_runtime_status(gateway_state="running", multiplex_standalone_reason=reason, served_profiles=[])
+ write_runtime_status(gateway_state="running", multiplex_standalone_reason=SINGLE_PROFILE_REASON,
+ served_profiles=[])
flush_runtime_status()
+ yield runner, home, restarts
+ from gateway.runtime_ownership import process_ownership
+ for profile in (home / "profiles").iterdir():
+ process_ownership.release(profile.resolve())
def _mkprofile(home, name):
@@ -55,45 +56,48 @@ def _mkprofile(home, name):
@pytest.mark.platforms("linux")
@pytest.mark.asyncio
-async def test_profile_created_after_a_single_profile_boot_restarts_the_host_into_the_multiplexer(standalone_host):
+async def test_profile_created_after_a_single_profile_boot_is_served_without_a_restart(standalone_host):
"""End to end through the creator's real signal: the control socket's ``rescan-profiles`` verb."""
from gateway import control_socket
from gateway.run_bootstrap import _start_gateway_start_control_socket
runner, home, restarts = standalone_host
- _boot_verdict(SINGLE_PROFILE_REASON)
server = await _start_gateway_start_control_socket(runner)
assert server is not None
try:
- # Nothing new yet: a rescan of the one-profile host changes nothing.
answer = await asyncio.to_thread(control_socket.rescan_gateway_profiles, home)
- assert answer["multiplex"] is False and restarts == []
+ assert answer["multiplex"] is False and not is_multiplex_active()
+
+ bot = _mkprofile(home, "daily-news-bot")
+ answer = await asyncio.to_thread(control_socket.rescan_gateway_profiles, home)
+ assert answer["multiplex"] is True
+ assert answer["added"] == ["daily-news-bot"]
+ assert answer["served_profiles"] == ["default", "daily-news-bot"]
+ assert restarts == [] and not runner._draining
+ # The new profile's credentials can never borrow the launch profile's process env.
+ assert is_multiplex_active()
- _mkprofile(home, "daily-news-bot")
+ # Deleting it again unserves it in place; the host keeps running.
+ shutil.rmtree(bot)
answer = await asyncio.to_thread(control_socket.rescan_gateway_profiles, home)
- assert answer["multiplex"] is False # this process still serves only default until it restarts
- assert len(restarts) == 1
- # One restart per profile set: the watcher's next tick must not queue another.
- await runner.reconcile_served_profiles(reason="watcher")
- assert len(restarts) == 1
+ assert answer["removed"] == ["daily-news-bot"] and answer["served_profiles"] == ["default"]
+ assert restarts == []
finally:
await server.stop()
@pytest.mark.asyncio
-async def test_a_standalone_gateway_kept_by_a_real_blocker_never_restarts(standalone_host, monkeypatch):
- """A guard that a restart would repeat (a secondary still runs its own gateway) keeps the host as
- it is: restarting would only drop every live turn to land on the same verdict."""
+async def test_a_blocked_new_profile_is_served_once_the_blocker_clears(standalone_host, monkeypatch):
+ """A preflight blocker (the new profile still runs its own gateway) keeps the host standalone. It
+ is not latched: the next rescan after the blocker clears serves the profile."""
runner, home, restarts = standalone_host
_mkprofile(home, "coder")
- monkeypatch.setattr(gm, "_live_gateway_pid",
- lambda h: os.getpid() if hermes_constants.profile_name_for_home(h) == "coder" else None)
- _boot_verdict("profile(s) 'coder' (pid 1) still run their own gateway; fold them with `x`")
- await runner.reconcile_served_profiles(reason="watcher")
- assert restarts == []
+ own = {"coder": True}
+ monkeypatch.setattr(gm, "_live_gateway_pid", lambda h: os.getpid() if own.get(
+ hermes_constants.profile_name_for_home(h)) else None)
+ result = await runner.reconcile_served_profiles(reason="watcher")
+ assert result["multiplex"] is False and not is_multiplex_active()
- # Booted single-profile, but by the time a second profile appears that profile runs its own
- # gateway: the preflight blocks, so no restart either.
- _boot_verdict(SINGLE_PROFILE_REASON)
- await runner.reconcile_served_profiles(reason="watcher")
- assert restarts == []
+ own["coder"] = False
+ result = await runner.reconcile_served_profiles(reason="watcher")
+ assert result["added"] == ["coder"] and restarts == []