Skip to content

The agent that grows with you

fix(gateway): --detach keeps --force, covers --all, and older runtimes still restart

Tekniumc1c8543a1339
diff --git a/apps/desktop/electron/local-gateway-restart-detach.test.ts b/apps/desktop/electron/local-gateway-restart-detach.test.ts
new file mode 100644
index 00000000000..a1bf3981271
--- /dev/null
+++ b/apps/desktop/electron/local-gateway-restart-detach.test.ts
@@ -0,0 +1,42 @@
+import fs from 'node:fs/promises'
+import os from 'node:os'
+import path from 'node:path'
+
+import { expect, test } from 'vitest'
+
+import { runGatewayEnsure, runGatewayOwnerRestart } from './local-gateway'
+
+// A real bounded client against a fake `hermes`: `new` knows `--detach`; `old` predates it and
+// rejects it the way argparse does. Each run appends its argv, so the test reads what was executed.
+async function fakeHermes(kind: 'new' | 'old') {
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'gw-detach-'))
+ const calls = path.join(dir, 'calls')
+
+ const reject = kind === 'old'
+ ? 'case " $* " in *" --detach "*) echo "hermes: error: unrecognized arguments: --detach" >&2; exit 2;; esac\n'
+ : ''
+
+ const bin = path.join(dir, 'hermes')
+ await fs.writeFile(bin, `#!/bin/sh\necho "$*" >> "${calls}"\n${reject}echo "✓ restarted"\n`, { mode: 0o755 })
+ const run = (args: string[]) => runGatewayEnsure({ command: bin, args, env: {}, shell: false }, dir, dir, {}, { timeoutMs: 5000, label: 'hermes gateway restart' })
+
+ return { run, calls: async () => (await fs.readFile(calls, 'utf8')).trim().split('\n') }
+}
+
+test.skipIf(process.platform === 'win32')('a stale-owner restart asks for a detached replacement', async () => {
+ const hermes = await fakeHermes('new')
+ const result = await runGatewayOwnerRestart(hermes.run, 'work')
+
+ expect(result.code).toBe(0)
+ expect(await hermes.calls()).toEqual(['--profile work gateway restart --detach'])
+})
+
+// apps/desktop/AGENTS.md "Compatibility": a runtime older than `--detach` still restarts (its old
+// behaviour, which works under a service) instead of failing on the flag and leaving the stale owner.
+test.skipIf(process.platform === 'win32')('a runtime that predates --detach still restarts the owner', async () => {
+ const hermes = await fakeHermes('old')
+ const result = await runGatewayOwnerRestart(hermes.run, 'default')
+
+ expect(result.code).toBe(0)
+ expect(await hermes.calls()).toEqual(['--profile default gateway restart --detach', '--profile default gateway restart'])
+})
diff --git a/apps/desktop/electron/local-gateway.ts b/apps/desktop/electron/local-gateway.ts
index a7c28d5d31c..ba80e09a90f 100644
--- a/apps/desktop/electron/local-gateway.ts
+++ b/apps/desktop/electron/local-gateway.ts
@@ -86,6 +86,20 @@ export function gatewayOwnerProfile(endpoint: GatewayEndpoint): string {
return path.basename(path.dirname(home)) === 'profiles' ? path.basename(home) : 'default'
}
+/** `hermes --profile P gateway restart --detach`: without a service, the CLI would otherwise run the
+ * replacement as this bounded client, a child its timeout kills. A runtime older than `--detach`
+ * names the flag argparse rejects (exit 2); it gets its old restart, which still works wherever a
+ * service owns the gateway, instead of no restart at all. */
+export async function runGatewayOwnerRestart(
+ run: (args: string[]) => Promise<{ code: number; stdout: string; stderr: string }>,
+ ownerProfile: string
+): Promise<{ code: number; stdout: string; stderr: string }> {
+ const args = ['--profile', ownerProfile, 'gateway', 'restart']
+ const result = await run([...args, '--detach'])
+
+ return result.code === 2 && /unrecognized arguments:.*--detach/.test(result.stderr) ? run(args) : result
+}
+
/** One restart per (owner process, stale gateway, client) per Desktop process. An owner a restart cannot move
* (a service unit pinned to another checkout) is then attached as-is instead of being restarted
* on every dial. */
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 622f5bfc494..4212fba482e 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -1,7 +1,7 @@
import { type ChildProcess, execFileSync, spawn } from 'node:child_process'
import type { GatewayEndpoint } from './local-gateway'
-import { configurePythonGatewayTicketClient, createLocalGatewayDials, createStaleGatewayRestarter, ensureLocalGateway, gatewayOwnerProfile, localGatewayDial, nativeGatewayHttpHeaders, redialLocalGateway, runGatewayEnsure } from './local-gateway'
+import { configurePythonGatewayTicketClient, createLocalGatewayDials, createStaleGatewayRestarter, ensureLocalGateway, gatewayOwnerProfile, localGatewayDial, nativeGatewayHttpHeaders, redialLocalGateway, runGatewayEnsure, runGatewayOwnerRestart } from './local-gateway'
import { closeGatewayTicketBridges, createGatewayTicketResolver } from './local-gateway-python'
import { createPluginWsUrlHandler } from './plugin-ws-url'
const localGatewayDials = createLocalGatewayDials()
@@ -11681,22 +11681,21 @@ async function dialPoolBackend(profile, entry, opts: { forceLocal?: boolean; poo
const GATEWAY_RESTART_CLIENT_TIMEOUT_MS = 120_000
// 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.
+// `gateway ensure` resolver, spawn helper and quoting, against the profile owning the process, with
+// `--detach` (runGatewayOwnerRestart). 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', '--detach']),
- () => undefined
- )
+ const result = await runGatewayOwnerRestart(async args => {
+ const backend = await ensureRuntime(await resolveHermesBackend(args), () => undefined)
- const result = await runGatewayEnsure(
- { ...backend, env: desktopBackendSpawnEnv(backend.env || {}) },
- resolveHermesCwd(),
- HERMES_HOME,
- profileBackendParentEnv({ hermesHome: HERMES_HOME, profile: ownerProfile }),
- { timeoutMs: GATEWAY_RESTART_CLIENT_TIMEOUT_MS, label: 'hermes gateway restart' }
- )
+ return runGatewayEnsure(
+ { ...backend, env: desktopBackendSpawnEnv(backend.env || {}) },
+ resolveHermesCwd(),
+ HERMES_HOME,
+ profileBackendParentEnv({ hermesHome: HERMES_HOME, profile: ownerProfile }),
+ { timeoutMs: GATEWAY_RESTART_CLIENT_TIMEOUT_MS, label: 'hermes gateway restart' }
+ )
+ }, ownerProfile)
const reason = `${result.stdout}\n${result.stderr}`.trim().split(/\r?\n/).filter(Boolean).pop()
rememberLog(`[gateway] hermes --profile ${ownerProfile} gateway restart exited ${result.code}${reason ? `: ${reason}` : ''}`)
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.py
index 8267a61049f..cbd3e49f799 100644
--- a/hermes_cli/gateway.py
+++ b/hermes_cli/gateway.py
@@ -5387,7 +5387,7 @@ def _stop_host_multiplexer(owner) -> int:
return 0
-def _restart_all(system: bool) -> None:
+def _restart_all(system: bool, detach: bool = False) -> None:
from hermes_cli.gateway_profile_lifecycle import host_scope_for_all_verb
owner = _host_multiplexer_for_all_verb()
if owner is not None and not _host_multiplexer_is_ours(owner):
@@ -5403,10 +5403,10 @@ def _restart_all(system: bool) -> None:
# No live owner: stop/kill/start as the host root, not as the invoking profile (whose own
# gateway the run-side guard would refuse — the host stayed down after a Desktop update).
with host_scope_for_all_verb(owner):
- _restart_all_as_host(owner, system)
+ _restart_all_as_host(owner, system, detach)
-def _restart_all_as_host(owner, system: bool) -> None:
+def _restart_all_as_host(owner, system: bool, detach: bool = False) -> None:
service_stopped = _stop_installed_service(system)
if owner is not None:
# Stop ONLY the host process: its served set comes back with it, and any per-profile
@@ -5436,11 +5436,11 @@ def _restart_all_as_host(owner, system: bool) -> None:
_service_call(kind, "start", system)
return
from hermes_constants import get_routing_process_hermes_home, named_profile_home
- if named_profile_home(get_routing_process_hermes_home()) is not None:
- # A named profile's CLI never runs the root IN this process: os.environ holds that profile's
- # .env and the root's dotenv load does not clear inherited keys, so the host served the
- # default profile with the named profile's credentials. The detached child starts from the
- # scrubbed host env (the root's own secrets only); `--replace` is part of its argv.
+ if detach or named_profile_home(get_routing_process_hermes_home()) is not None:
+ # Never run the root IN this process for `--detach` (the bounded caller would become the host
+ # gateway its timeout kills) or a named profile's CLI (os.environ holds that profile's .env,
+ # which the root's dotenv load does not clear: the host served default with its credentials).
+ # The detached child starts from the scrubbed host env; `--replace` is part of its argv.
if not _spawn_detached_gateway():
print_error("Failed to start the host gateway as a background process.")
sys.exit(1)
@@ -5471,7 +5471,7 @@ def _cmd_restart(args):
if not restart_all and _dispatch_via_service_manager_if_s6("restart"):
return
if restart_all:
- _restart_all(system)
+ _restart_all(system, getattr(args, "detach", False))
return
# Reap orphans only past the refusal guards above (#125394): the Desktop backend used to reap
diff --git a/hermes_cli/gateway_runtime_start.py b/hermes_cli/gateway_runtime_start.py
index 80e374e0bc2..ac185f2479f 100644
--- a/hermes_cli/gateway_runtime_start.py
+++ b/hermes_cli/gateway_runtime_start.py
@@ -32,13 +32,16 @@ DAEMON_STRIPPED_ENV = (
)
-def spawn_unmanaged_gateway(profile_home: Path, *, deadline: float, idle_exit: bool = False) -> subprocess.Popen:
+def spawn_unmanaged_gateway(profile_home: Path, *, deadline: float, idle_exit: bool = False,
+ force: bool = False) -> subprocess.Popen:
"""Request a daemon, not readiness. Refuse Windows no-breakaway fallback.
No --replace, persistence, login changes, elevation, shell, or inherited stdio.
The gateway runtime's own exclusive ownership fence arbitrates racing starts.
``idle_exit``: the daemon ends itself once idle (a chat/TUI/cron client's own start; never
Desktop's ``gateway ensure``, which keeps its attached gateway for the app's lifetime).
+ ``force``: a ``gateway restart --force --detach`` replacement keeps the ``--force`` its old owner
+ needed (a named profile under a multiplexer), or it exits on the run-side guard.
"""
home = profile_home.resolve()
root = Path(__file__).resolve().parent.parent
@@ -47,7 +50,7 @@ def spawn_unmanaged_gateway(profile_home: Path, *, deadline: float, idle_exit: b
# profile's daemon. A <root>/profiles/<name> home is already trusted as-is.
selector = [] if home.parent.name == "profiles" else ["--profile", "default"]
command = [sys.executable, "-m", "hermes_cli.main", *selector, "gateway", "run", "--quiet",
- *(["--idle-exit"] if idle_exit else [])]
+ *(["--idle-exit"] if idle_exit else []), *(["--force"] if force else [])]
# The target profile's own secrets, never the launching client's: a `hermes -p work` client's
# dotenv would otherwise become the default daemon's frozen launch env (host_gateway_child_env).
from tools.environments.local import served_profile_child_env
@@ -80,13 +83,13 @@ 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:
+def start_detached_replacement(profile_home: Path, *, force: bool = False) -> 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)
+ spawn_unmanaged_gateway(profile_home, deadline=time.monotonic() + 30, force=force)
except RuntimeStartError as exc:
print(f"✗ Could not start the gateway in the background: {exc}", file=sys.stderr)
return 1
diff --git a/hermes_cli/gateway_supervised_restart.py b/hermes_cli/gateway_supervised_restart.py
index 598141d67b7..1f92986208a 100644
--- a/hermes_cli/gateway_supervised_restart.py
+++ b/hermes_cli/gateway_supervised_restart.py
@@ -147,5 +147,5 @@ def start_restart_replacement(args, *, force: bool) -> None:
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()))
+ sys.exit(start_detached_replacement(gw.get_hermes_home(), force=force))
gw.run_gateway(verbose=0, force=force)
diff --git a/tests/hermes_cli/test_gateway_host_verbs.py b/tests/hermes_cli/test_gateway_host_verbs.py
index f4045147e93..97164ace7df 100644
--- a/tests/hermes_cli/test_gateway_host_verbs.py
+++ b/tests/hermes_cli/test_gateway_host_verbs.py
@@ -274,7 +274,7 @@ def test_named_profile_restart_all_reaches_the_all_aware_branch(monkeypatch):
monkeypatch.setattr(gw, "_guard_named_profile_under_multiplexer",
lambda **k: pytest.fail("the generic guard pre-empted the --all branch"))
called: list[bool] = []
- monkeypatch.setattr(gw, "_restart_all", lambda system: called.append(True))
+ monkeypatch.setattr(gw, "_restart_all", lambda system, detach=False: called.append(True))
gw._cmd_restart(SimpleNamespace(system=False, all=True, force=False))
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 87324e4d11a..6ae4ac600bd 100644
--- a/tests/hermes_cli/test_gateway_restart_no_unit_linger.py
+++ b/tests/hermes_cli/test_gateway_restart_no_unit_linger.py
@@ -75,3 +75,60 @@ def test_restart_with_systemd_unit_still_reports_missing_linger(monkeypatch):
gw._cmd_restart(SimpleNamespace(system=False, all=False))
assert not started, "a broken unit must surface the linger hint, not double-start a detached gateway"
+
+
+def test_detached_restart_keeps_force_for_the_replacement(monkeypatch):
+ """`restart --force --detach`: the old owner needed `--force` (a named profile under a
+ multiplexer); a replacement launched without it exits on the run-side guard."""
+ 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)
+ monkeypatch.setattr(gw, "run_gateway", lambda **k: pytest.fail("the caller became the gateway"))
+ launched, real_popen = [], start.subprocess.Popen
+
+ def _popen(cmd, **kwargs): # only the gateway launch is faked; process scans stay real
+ if "hermes_cli.main" not in cmd:
+ return real_popen(cmd, **kwargs)
+ launched.append(cmd)
+ return SimpleNamespace()
+
+ monkeypatch.setattr(start.subprocess, "Popen", _popen)
+
+ with pytest.raises(SystemExit) as exited:
+ gw._cmd_restart(SimpleNamespace(system=False, all=False, force=True, detach=True))
+
+ assert exited.value.code == 0
+ assert len(launched) == 1 and launched[0][-4:] == ["gateway", "run", "--quiet", "--force"]
+
+
+def test_detached_restart_all_never_runs_the_host_gateway_in_the_caller(monkeypatch, tmp_path):
+ """`restart --all --detach` from the root profile with no service took the in-process path."""
+ import hermes_constants
+ from hermes_cli import gateway as gw
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ hermes_constants._default_hermes_root_memo = None
+ monkeypatch.setattr(gw, "_refuse_from_inside_gateway", lambda *a, **k: None)
+ monkeypatch.setattr(gw, "_dispatch_all_via_service_manager_if_s6", lambda verb: False)
+ monkeypatch.setattr(gw, "_host_multiplexer_for_all_verb", lambda: None)
+ monkeypatch.setattr(gw, "_stop_installed_service", lambda system: False)
+ monkeypatch.setattr(gw, "kill_gateway_processes", lambda **k: 1)
+ monkeypatch.setattr(gw, "_wait_for_gateway_exit", lambda **k: None)
+ monkeypatch.setattr(gw, "_wait_for_api_server_port_free", lambda **k: None)
+ monkeypatch.setattr(gw, "_discard_dead_host_record", lambda: False)
+ monkeypatch.setattr(gw, "_installed_service_kind_for", lambda windows: None)
+ monkeypatch.setattr(gw, "run_gateway", lambda **k: pytest.fail("the caller became the host gateway"))
+ detached = []
+ monkeypatch.setattr(gw, "_spawn_detached_gateway", lambda: detached.append(True) or True)
+
+ gw._cmd_restart(SimpleNamespace(system=False, all=True, force=False, detach=True))
+
+ assert detached == [True]