Skip to content

The agent that grows with you

fix(cli): retry dashboard action spawns without CREATE_BREAKAWAY_FROM_JOB when a job denies it

Suhasan Kanagala9ef7743975f8
diff --git a/hermes_cli/web_server_gateway.py b/hermes_cli/web_server_gateway.py
index f2b1993bec9..6bc413f19c7 100644
--- a/hermes_cli/web_server_gateway.py
+++ b/hermes_cli/web_server_gateway.py
@@ -13,7 +13,7 @@ import time
import urllib.request
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
-from hermes_cli._subprocess_compat import windows_detach_flags
+from hermes_cli._subprocess_compat import windows_detach_flags, windows_detach_flags_without_breakaway
from hermes_cli.config import get_hermes_home
# Same logger the code used before extraction (record parity).
@@ -516,11 +516,36 @@ def _spawn_hermes_action(
# Named-profile actions get a scrubbed, pinned environment so the child cannot inherit the
# dashboard profile's credentials; see _profile_action_environment (also drops _HERMES_GATEWAY).
action_env = _profile_action_environment(subcommand, env_overrides)
- detach = {"creationflags": windows_detach_flags()} if sys.platform == "win32" else {"start_new_session": True}
- proc = subprocess.Popen(
- cmd, cwd=str(PROJECT_ROOT), stdin=subprocess.DEVNULL, stdout=log_file, stderr=subprocess.STDOUT,
- env=action_env, **detach,
- )
+
+ def _popen(**detach: Any) -> subprocess.Popen:
+ return subprocess.Popen(
+ cmd, cwd=str(PROJECT_ROOT), stdin=subprocess.DEVNULL, stdout=log_file, stderr=subprocess.STDOUT,
+ env=action_env, **detach,
+ )
+
+ try:
+ if sys.platform == "win32":
+ try:
+ proc = _popen(creationflags=windows_detach_flags())
+ except OSError as exc:
+ # CREATE_BREAKAWAY_FROM_JOB is refused ("Access is denied") when the parent's job
+ # object forbids breakaway — an Electron/Tauri-launched dashboard, some Windows
+ # Terminal configs. The flag is best-effort by contract (windows_detach_flags);
+ # retry without it so the action still spawns, and record why for the status route.
+ if getattr(exc, "winerror", None) != 5:
+ raise
+ log_file.write(
+ f"{name}: breakaway spawn refused ({exc}); retrying without CREATE_BREAKAWAY_FROM_JOB\n".encode()
+ )
+ proc = _popen(creationflags=windows_detach_flags_without_breakaway())
+ else:
+ proc = _popen(start_new_session=True)
+ except OSError as exc:
+ # Without this the action log would hold only the started-header for a spawn that never
+ # happened; close the handle the child would have owned and let the endpoint report it.
+ log_file.write(f"{name}: spawn failed: {exc}\n".encode())
+ log_file.close()
+ raise
log_file.close() # child holds its own dup'd fd; keeping ours leaks one per action
_ACTION_RESULTS.pop(name, None)
_ACTION_COMMANDS[name] = tuple(subcommand)
diff --git a/tests/hermes_cli/test_dashboard_admin_endpoints.py b/tests/hermes_cli/test_dashboard_admin_endpoints.py
index d18e6cdc27e..f239b985706 100644
--- a/tests/hermes_cli/test_dashboard_admin_endpoints.py
+++ b/tests/hermes_cli/test_dashboard_admin_endpoints.py
@@ -997,6 +997,69 @@ def test_spawn_hermes_action_scrubs_gateway_loop_guard_env(monkeypatch, tmp_path
assert captured["env"]["OPENAI_API_KEY"] == "default-action-provider-key"
+# ---------------------------------------------------------------------------
+# _spawn_hermes_action breakaway fallback (#139592)
+# ---------------------------------------------------------------------------
+
+def test_spawn_hermes_action_retries_without_breakaway_when_job_denies(monkeypatch, tmp_path):
+ """A parent job object that forbids breakaway (an Electron/Tauri-launched dashboard, some
+ Windows Terminal configs) refuses CREATE_BREAKAWAY_FROM_JOB with access-denied. The action
+ must still spawn — retried without the flag — and the refusal must land in the action log,
+ which otherwise shows a bare started-header and no reason (#139592).
+ """
+ import hermes_cli.web_server as ws
+ from hermes_cli import _subprocess_compat
+
+ monkeypatch.setattr(_web_server_gateway, "_ACTION_LOG_DIR", tmp_path)
+ monkeypatch.setattr(_web_server_gateway, "_ACTION_PROCS", {})
+
+ denied = PermissionError("breakaway denied")
+ denied.winerror = 5
+ flags_seen = []
+
+ class _FakeProc:
+ pid = 4321
+
+ def _fake_popen(cmd, **kwargs):
+ flags_seen.append(kwargs.get("creationflags"))
+ if len(flags_seen) == 1:
+ raise denied
+ return _FakeProc()
+
+ monkeypatch.setattr(ws.subprocess, "Popen", _fake_popen)
+
+ proc = _web_server_gateway._spawn_hermes_action(["gateway", "restart"], "gateway-restart")
+
+ assert proc.pid == 4321
+ assert flags_seen == [
+ _subprocess_compat.windows_detach_flags(),
+ _subprocess_compat.windows_detach_flags_without_breakaway(),
+ ]
+ log = (tmp_path / _web_server_gateway._ACTION_LOG_FILES["gateway-restart"]).read_text()
+ assert "retrying without CREATE_BREAKAWAY_FROM_JOB" in log
+
+
+def test_spawn_hermes_action_records_a_failed_spawn_and_reraises(monkeypatch, tmp_path):
+ """A spawn that never happened leaves the reason in the action log (previously a bare
+ started-header) and still raises to the endpoint (#139592)."""
+ import hermes_cli.web_server as ws
+
+ monkeypatch.setattr(_web_server_gateway, "_ACTION_LOG_DIR", tmp_path)
+ monkeypatch.setattr(_web_server_gateway, "_ACTION_PROCS", {})
+
+ def _fake_popen(cmd, **kwargs):
+ raise FileNotFoundError("runtime command missing")
+
+ monkeypatch.setattr(ws.subprocess, "Popen", _fake_popen)
+
+ with pytest.raises(FileNotFoundError):
+ _web_server_gateway._spawn_hermes_action(["gateway", "restart"], "gateway-restart")
+
+ log = (tmp_path / _web_server_gateway._ACTION_LOG_FILES["gateway-restart"]).read_text()
+ assert "spawn failed" in log
+
+
def test_named_profile_action_isolates_parent_env_and_loads_target_env(monkeypatch, tmp_path):
"""A dashboard action for a named profile must not borrow the dashboard profile's
platform/provider environment, while the target profile's own dotenv still loads in the child."""