Skip to content

The agent that grows with you

fix(gateway): keep launchd_stop's bootout quiet too; prove the fd-2 invariant with a fake launchctl

Teknium1a500a43a750
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.py
index 178f91fbc07..abeaef358bb 100644
--- a/hermes_cli/gateway.py
+++ b/hermes_cli/gateway.py
@@ -4071,9 +4071,10 @@ def launchd_stop():
_mark_planned_stop()
# bootout unloads the definition so KeepAlive doesn't respawn; `hermes gateway start` re-bootstraps.
try:
- subprocess.run(["launchctl", "bootout", target], check=True, timeout=90)
+ # Captured: an already-unloaded job (3/113/125) is handled below, so launchctl's own
+ # "Boot-out failed: 3" must not print around the ✓ line; e.stderr stays on the raised error.
+ subprocess.run(["launchctl", "bootout", target], check=True, timeout=90, **_CAPTURE_TEXT)
except subprocess.CalledProcessError as e:
- # Job already unloaded (3/113/125) or domain unmanageable (5/125): fall through to the PID-based kill.
# Job already unloaded (3/113/125), or the domain can't be managed at all (5/125, macOS 26+
# detached-fallback process, issue #23387) — in both cases just fall through to the PID-based kill
# below.
diff --git a/tests/hermes_cli/test_gateway_service.py b/tests/hermes_cli/test_gateway_service.py
index 2b6159699da..52e6b761e39 100644
--- a/tests/hermes_cli/test_gateway_service.py
+++ b/tests/hermes_cli/test_gateway_service.py
@@ -2514,6 +2514,71 @@ class TestLaunchctlBootstrapEioRetry:
assert excinfo.value.returncode == 5
+class TestLaunchdUnloadedJobStderrStaysOffTerminal:
+ """#106273: against an UNLOADED job, ``launchctl bootout`` / ``kickstart -k`` exit 3 and print
+ ``Could not find service ...`` / ``Boot-out failed: 3`` on fd 2. Those exits are the *handled*
+ case, so a real launchctl child (fake binary on PATH, real fd inheritance) must leave the
+ terminal's stderr empty while the CLI's own status lines print. ``capfd`` reads fd 2, so an
+ inherited-stderr regression fires even though ``subprocess.run`` never touches ``sys.stderr``."""
+
+ @pytest.fixture
+ def fake_launchctl(self, tmp_path, monkeypatch):
+ bin_dir = tmp_path / "bin"
+ bin_dir.mkdir()
+ script = bin_dir / "launchctl"
+ # bootout exits $FAKE_BOOTOUT_RC (default 3 = unloaded); `kickstart -k` is the unloaded 3;
+ # bootstrap / plain kickstart / print succeed. Every invocation is logged for the caller.
+ script.write_text(
+ "#!/bin/sh\n"
+ 'echo "$@" >> "$FAKE_LAUNCHCTL_LOG"\n'
+ 'case "$1" in\n'
+ ' bootout) echo "Boot-out failed: ${FAKE_BOOTOUT_RC:-3}: No such process" >&2; exit "${FAKE_BOOTOUT_RC:-3}" ;;\n'
+ ' kickstart) if [ "$2" = "-k" ]; then echo "Could not find service in domain for user gui: 501" >&2; exit 3; fi ;;\n'
+ "esac\n"
+ "exit 0\n",
+ encoding="utf-8",
+ )
+ script.chmod(0o755)
+ log = tmp_path / "calls.log"
+ monkeypatch.setenv("PATH", f"{bin_dir}{os.pathsep}{os.environ['PATH']}")
+ monkeypatch.setenv("FAKE_LAUNCHCTL_LOG", str(log))
+ monkeypatch.setattr(gateway_cli, "get_launchd_label", lambda: "ai.hermes.gateway")
+ monkeypatch.setattr(gateway_cli, "_launchd_domain", lambda: "gui/501")
+ monkeypatch.setattr(gateway_cli, "get_launchd_plist_path", lambda: tmp_path / "ai.hermes.gateway.plist")
+ monkeypatch.setattr(gateway_cli, "_clear_launchd_unsupported_marker", lambda: None)
+ monkeypatch.setattr(gateway_cli, "_mark_planned_stop", lambda *a, **k: None)
+ monkeypatch.setattr(gateway_cli, "_wait_for_gateway_exit", lambda *a, **k: True)
+ monkeypatch.setattr("gateway.status.get_running_pid", lambda *a, **k: None)
+ return log
+
+ def test_restart_of_unloaded_job_reloads_without_launchctl_noise(self, fake_launchctl, capfd):
+ gateway_cli.launchd_restart()
+
+ out, err = capfd.readouterr()
+ assert "↻ launchd job was unloaded; reloading" in out
+ assert "✓ Service restarted" in out
+ assert err == ""
+ verbs = [line.split()[0] for line in fake_launchctl.read_text(encoding="utf-8").splitlines()]
+ assert verbs == ["kickstart", "bootout", "bootstrap", "kickstart"]
+
+ def test_stop_of_unloaded_job_is_quiet_but_a_real_bootout_failure_keeps_stderr(
+ self, fake_launchctl, capfd, monkeypatch
+ ):
+ gateway_cli.launchd_stop()
+ out, err = capfd.readouterr()
+ assert "✓ Service stopped" in out
+ assert err == ""
+
+ # Unexpected exit code: not swallowed, and the captured stderr rides on the exception for
+ # the caller's diagnostic instead of having been printed raw by launchctl.
+ monkeypatch.setenv("FAKE_BOOTOUT_RC", "1")
+ with pytest.raises(subprocess.CalledProcessError) as excinfo:
+ gateway_cli.launchd_stop()
+ assert excinfo.value.returncode == 1
+ assert "Boot-out failed: 1" in excinfo.value.stderr
+ assert capfd.readouterr().err == ""
+
+
class TestRetryLaunchctlBootstrapUntilRegistered:
"""`_retry_launchctl_bootstrap_until_registered` — salvage of #53277.