Skip to content

The agent that grows with you

fix(desktop): a stale-gateway restart no longer turns the app's restart call into the gateway

Tekniumf40965b2003e
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index d6433c1c1d4..622f5bfc494 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -11680,13 +11680,13 @@ async function dialPoolBackend(profile, entry, opts: { forceLocal?: boolean; poo
// bounded so a wedged drain cannot hang Restart. The gateway's own drain is unaffected by the kill.
const GATEWAY_RESTART_CLIENT_TIMEOUT_MS = 120_000
-// Supervised restart of the per-host gateway Desktop attaches to (it never owns that process):
-// the same resolver, spawn helper and Windows quoting as `gateway ensure`, against the profile
-// that owns the gateway process. A non-zero exit is logged, not thrown: the re-ensure that
-// follows reports what actually answers.
+// Supervised restart of the per-host gateway Desktop attaches to (it never owns that process): the
+// `gateway ensure` resolver, spawn helper and quoting, against the profile owning the process.
+// `--detach`: without a service the CLI would run the replacement as this bounded client, a child
+// the timeout kills. A non-zero exit is logged, not thrown: the re-ensure reports what answers.
async function restartLocalGatewayOwner(ownerProfile: string): Promise<void> {
const backend = await ensureRuntime(
- await resolveHermesBackend(['--profile', ownerProfile, 'gateway', 'restart']),
+ await resolveHermesBackend(['--profile', ownerProfile, 'gateway', 'restart', '--detach']),
() => undefined
)
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.py
index 05cc9c1938e..8267a61049f 100644
--- a/hermes_cli/gateway.py
+++ b/hermes_cli/gateway.py
@@ -5523,7 +5523,7 @@ def _cmd_restart(args):
from gateway.status import get_running_pid
from hermes_cli.gateway_supervised_restart import (
gateway_declares_external_supervisor, refuse_restart_of_service_managed_gateway,
- restart_externally_supervised_gateway,
+ restart_externally_supervised_gateway, start_restart_replacement,
)
supervised_pid = get_running_pid()
if supervised_pid and gateway_declares_external_supervisor(supervised_pid):
@@ -5537,7 +5537,7 @@ def _cmd_restart(args):
_wait_for_api_server_port_free()
_forget_host_gateway_probe()
print("Starting gateway...")
- run_gateway(verbose=0, force=force)
+ start_restart_replacement(args, force=force)
# ``hermes gateway status`` hints for a manually-run / stopped gateway, keyed by host kind.
diff --git a/hermes_cli/gateway_runtime_start.py b/hermes_cli/gateway_runtime_start.py
index 23680c670fa..80e374e0bc2 100644
--- a/hermes_cli/gateway_runtime_start.py
+++ b/hermes_cli/gateway_runtime_start.py
@@ -80,6 +80,20 @@ def spawn_unmanaged_gateway(profile_home: Path, *, deadline: float, idle_exit: b
raise RuntimeStartError(reason) from exc
+def start_detached_replacement(profile_home: Path) -> int:
+ """``gateway restart --detach`` with no service: start the stopped owner's replacement the way
+ ``gateway ensure`` starts an absent one. In the foreground, the restarting client (Desktop's
+ bounded, piped call) would itself become the long-lived gateway it only meant to restart."""
+ import time
+ try:
+ spawn_unmanaged_gateway(profile_home, deadline=time.monotonic() + 30)
+ except RuntimeStartError as exc:
+ print(f"✗ Could not start the gateway in the background: {exc}", file=sys.stderr)
+ return 1
+ print("✓ Started the gateway in the background")
+ return 0
+
+
def stdio_log_path(profile_home: Path) -> Path:
return profile_home / "logs" / "gateway-stdio.log"
diff --git a/hermes_cli/gateway_supervised_restart.py b/hermes_cli/gateway_supervised_restart.py
index f110aac19eb..598141d67b7 100644
--- a/hermes_cli/gateway_supervised_restart.py
+++ b/hermes_cli/gateway_supervised_restart.py
@@ -135,3 +135,17 @@ def refuse_restart_of_service_managed_gateway(pid: int | None) -> None:
" removes the legacy unit so the canonical one can own the gateway.)",
)
sys.exit(1)
+
+
+def start_restart_replacement(args, *, force: bool) -> None:
+ """Start the manual fallback's replacement once the old owner is gone.
+
+ ``--detach`` (Desktop's bounded, piped client; the updater's recovery call) starts it the way
+ ``gateway ensure`` starts an absent owner. In the foreground that caller became the long-lived
+ gateway it only meant to restart: a child its own timeout killed, holding the app's quit open.
+ """
+ from hermes_cli import gateway as gw
+ if getattr(args, "detach", False):
+ from hermes_cli.gateway_runtime_start import start_detached_replacement
+ sys.exit(start_detached_replacement(gw.get_hermes_home()))
+ gw.run_gateway(verbose=0, force=force)
diff --git a/hermes_cli/subcommands/gateway.py b/hermes_cli/subcommands/gateway.py
index aa3b4caec33..2ecf5016fa4 100644
--- a/hermes_cli/subcommands/gateway.py
+++ b/hermes_cli/subcommands/gateway.py
@@ -149,6 +149,9 @@ def build_gateway_parser(
help="Kill ALL gateway processes across all profiles before restarting")
_flag(gateway_restart, "--force", help=_FORCE_SERVED_PROFILE_HELP)
_flag(gateway_restart, "-y", "--yes", "--interrupt", dest="interrupt", help=_INTERRUPT_HELP.format(verb="restart"))
+ _flag(gateway_restart, "--detach", help=(
+ "Without an installed service, start the replacement in the background (as `gateway ensure` "
+ "does) instead of in this terminal; used by apps that run the restart as a short-lived client"))
_add_compat_platform_flag(gateway_restart)
gateway_status = gateway_subparsers.add_parser("status", help="Show gateway status")
diff --git a/hermes_cli/update_restart_recovery.py b/hermes_cli/update_restart_recovery.py
index 5304ea87ffe..533a383aace 100644
--- a/hermes_cli/update_restart_recovery.py
+++ b/hermes_cli/update_restart_recovery.py
@@ -138,8 +138,9 @@ def _run_profile_restart(profile: str, *, run: Callable[..., Any]) -> bool:
else:
kwargs["start_new_session"] = True
# `--interrupt`: the update owns this restart (drain-first, 31637312899); a live session must not
- # strand the profile on pre-update code the way a refusal would.
- argv = [sys.executable, "-m", "hermes_cli.main", "-p", profile, "gateway", "restart", "--interrupt"]
+ # strand the profile on pre-update code the way a refusal would. `--detach`: this bounded call
+ # must not itself become a service-less profile's gateway (killed at the timeout below).
+ argv = [sys.executable, "-m", "hermes_cli.main", "-p", profile, "gateway", "restart", "--interrupt", "--detach"]
return _succeeded(_run_quiet(run, argv, timeout=_PROFILE_RESTART_TIMEOUT, **kwargs))
diff --git a/tests/hermes_cli/test_gateway_restart_no_unit_linger.py b/tests/hermes_cli/test_gateway_restart_no_unit_linger.py
index e2ae1b9fcec..87324e4d11a 100644
--- a/tests/hermes_cli/test_gateway_restart_no_unit_linger.py
+++ b/tests/hermes_cli/test_gateway_restart_no_unit_linger.py
@@ -29,6 +29,31 @@ def test_restart_without_service_unit_runs_gateway_even_without_linger(monkeypat
assert started, "no unit installed: restart must fall through to run_gateway, linger or not"
+def test_detached_restart_without_service_never_runs_the_gateway_in_the_caller(monkeypatch):
+ """Desktop runs `gateway restart --detach` as a bounded, piped client. In the foreground the
+ client became the gateway: a Desktop child its timeout killed, holding app quit open."""
+ from hermes_cli import gateway as gw
+ from hermes_cli import gateway_runtime_start as start
+
+ monkeypatch.setattr(gw, "_refuse_from_inside_gateway", lambda *a, **k: None)
+ monkeypatch.setattr(gw, "_dispatch_via_service_manager_if_s6", lambda *a, **k: False)
+ monkeypatch.setattr(gw, "_installed_service_kind_for", lambda windows: None)
+ monkeypatch.setattr(gw, "supports_systemd_services", lambda: False)
+ monkeypatch.setattr(gw, "stop_profile_gateway", lambda: True)
+ monkeypatch.setattr(gw, "_wait_for_gateway_exit", lambda **k: None)
+ foreground, detached = [], []
+ monkeypatch.setattr(gw, "run_gateway", lambda **k: foreground.append(k))
+ monkeypatch.setattr(start, "spawn_unmanaged_gateway", lambda home, **k: detached.append(home))
+
+ with pytest.raises(SystemExit) as exited:
+ gw._cmd_restart(SimpleNamespace(system=False, all=False, detach=True))
+
+ assert exited.value.code == 0
+ assert not foreground, "--detach must not turn the restarting client into the gateway"
+ assert detached == [gw.get_hermes_home()]
+
+
@pytest.mark.platforms("linux")
def test_restart_with_systemd_unit_still_reports_missing_linger(monkeypatch):
from hermes_cli import gateway as gw
diff --git a/tests/hermes_cli/test_update_restart_recovery.py b/tests/hermes_cli/test_update_restart_recovery.py
index 4fe4db8e1c7..2a182ba5d84 100644
--- a/tests/hermes_cli/test_update_restart_recovery.py
+++ b/tests/hermes_cli/test_update_restart_recovery.py
@@ -277,8 +277,8 @@ def test_recovery_child_restarts_each_profile_with_a_fresh_main(monkeypatch):
"covered": {},
}
assert [call[0] for call in calls] == [
- [sys.executable, "-m", "hermes_cli.main", "-p", "coder", "gateway", "restart", "--interrupt"],
- [sys.executable, "-m", "hermes_cli.main", "-p", "default", "gateway", "restart", "--interrupt"],
+ [sys.executable, "-m", "hermes_cli.main", "-p", "coder", "gateway", "restart", "--interrupt", "--detach"],
+ [sys.executable, "-m", "hermes_cli.main", "-p", "default", "gateway", "restart", "--interrupt", "--detach"],
]
for _, kwargs in calls:
assert kwargs["stdin"] is subprocess.DEVNULL
@@ -466,4 +466,4 @@ def test_recovery_module_end_to_end_in_a_real_fresh_process(tmp_path):
restarts = [json.loads(line) for line in ledger.read_text().splitlines()]
assert [argv[argv.index("-p") + 1] for argv in restarts] == ["coder", "default"]
for argv in restarts:
- assert argv[-3:] == ["gateway", "restart", "--interrupt"]
+ assert argv[-4:] == ["gateway", "restart", "--interrupt", "--detach"]
diff --git a/website/docs/reference/cli-commands.md b/website/docs/reference/cli-commands.md
index 51258b4bd6d..e6cc93fbc0d 100644
--- a/website/docs/reference/cli-commands.md
+++ b/website/docs/reference/cli-commands.md
@@ -334,6 +334,7 @@ Options:
|--------|-------------|
| `--all` | On `start` / `restart` / `stop`: act on **every profile's** gateway, not just the active `HERMES_HOME`. Useful if you run multiple profiles side-by-side and want to restart them all after `hermes update`. |
| `-y`, `--yes` | On `stop` / `restart`: when the gateway is running chat turns, cron jobs or background delegations, the command lists them and asks `y/N` before interrupting them. `--yes` skips the question. With no terminal to ask on (scripts, cron) it refuses unless `--yes` is passed. `--interrupt` is an alias. |
+| `--detach` | On `restart`: when no gateway service is installed, start the replacement in the background (the way `hermes gateway ensure` starts one) instead of in the current terminal. The desktop app and the updater's recovery restart pass it so their short-lived restart call never becomes the gateway itself. Service, supervisor and Windows-task restarts are unchanged. |
| `--no-supervise` | On `run`: inside the s6-overlay Docker image, opt out of auto-supervision and use pre-s6 foreground semantics — gateway runs as the container's main process with no auto-restart. No-op outside the s6 image. Equivalent to setting `HERMES_GATEWAY_NO_SUPERVISE=1`. |
| `--external-supervisor` | On `run`: declare that a wrapper-provided process manager owns the foreground gateway. Use this when `sudo`, `env -i`, or another wrapper strips launchd/systemd's native environment marker. In-chat restarts and updates exit back to that manager instead of spawning a detached replacement. |