The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): serve a profile created after a single-profile gateway boot (#141623)
Tekniumae601a763282
diff --git a/gateway/run_bootstrap.py b/gateway/run_bootstrap.pyindex af6b92fce6d..92bb2a34906 100644--- a/gateway/run_bootstrap.py+++ b/gateway/run_bootstrap.py@@ -323,17 +323,18 @@ 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."""- if not getattr(runner.config, "multiplex_profiles", False):- return {"multiplex": False, "served_profiles": runner.served_profile_names()}+ 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))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": True, **future.result(timeout=5.0)}+ return {"multiplex": multiplex, **future.result(timeout=5.0)}except concurrent.futures.TimeoutError:- return {"multiplex": True, "pending": True, "served_profiles": runner.served_profile_names()}+ return {"multiplex": multiplex, "pending": True, "served_profiles": runner.served_profile_names()}_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.pyindex af9c3a79c29..638e7711eb0 100644--- a/gateway/run_profile_reconcile.py+++ b/gateway/run_profile_reconcile.py@@ -68,6 +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# ── state helpers ─────────────────────────────────────────────────────────────────────────────@@ -95,7 +96,8 @@ 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)."""+ socket for an immediate rescan), or check whether a single-profile standalone gateway now+ has a second profile to serve."""while self._running:await asyncio.sleep(interval)if not self._running:@@ -104,6 +106,8 @@ class GatewayProfileReconcileMixin: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()except asyncio.CancelledError:raiseexcept Exception:@@ -157,6 +161,7 @@ class GatewayProfileReconcileMixin:from hermes_cli.profiles import profiles_to_serveresult: dict[str, Any] = {"added": [], "removed": [], "rescanned": [], "parked": [], "reason": reason}if not self._multiplex_on():+ await self._restart_to_serve_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.@@ -314,6 +319,29 @@ class GatewayProfileReconcileMixin:from gateway.run_runtime import parked_profile_mapreturn 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."""+ from hermes_cli.gateway_multiplex_mode import (+ SINGLE_PROFILE_REASON, implicit_multiplex_blocker, recorded_standalone_reason)+ from hermes_cli.profiles import profiles_to_serve+ 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:+ return False+ self._standalone_preflight_names = names+ if await self._run_housekeeping_in_executor(implicit_multiplex_blocker) is not None:+ 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)+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-secondarysteps). Returns the park reason — reservation released — when another gateway owns the homediff --git a/tests/gateway/test_single_profile_host_serves_new_profile.py b/tests/gateway/test_single_profile_host_serves_new_profile.pynew file mode 100644index 00000000000..b4fcb25ed1d--- /dev/null+++ b/tests/gateway/test_single_profile_host_serves_new_profile.py@@ -0,0 +1,99 @@+"""A host gateway that booted with ONE profile comes up standalone (``SINGLE_PROFILE_REASON``), and+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).+"""+import asyncio+import os++import pytest++import hermes_constants+from gateway.config import GatewayConfig+from gateway.run import GatewayRunner+from gateway.status import flush_runtime_status, write_runtime_status+from hermes_cli import gateway_migrate as gm+from hermes_cli.gateway_multiplex_mode import SINGLE_PROFILE_REASON+++def standalone_host(tmp_path, monkeypatch):+ home = tmp_path / ".hermes"+ (home / "profiles").mkdir(parents=True)+ (home / "config.yaml").write_text("model: {default: m}\n", encoding="utf-8")+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.delenv("GATEWAY_MULTIPLEX_PROFILES", raising=False)+ monkeypatch.setattr(hermes_constants, "_default_hermes_root_memo", None)+ # The migration preflight's service-manager probes: nothing else on this host runs a gateway.+ 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._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=[])+ flush_runtime_status()+++def _mkprofile(home, name):+ d = home / "profiles" / name+ d.mkdir()+ (d / "config.yaml").write_text("model: {default: m}\n", encoding="utf-8")+ return d++[email protected]("linux")+async def test_profile_created_after_a_single_profile_boot_restarts_the_host_into_the_multiplexer(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 == []++ _mkprofile(home, "daily-news-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+ finally:+ await server.stop()+++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."""+ 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 == []++ # 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 == []