opentui(phase3): launcher integration — HERMES_TUI_ENGINE dual-engine

hermes --tui launches the native OpenTUI engine (Bun) when
HERMES_TUI_ENGINE=opentui (env) or display.tui_engine=opentui (config);
Ink stays the default and the shipping path is untouched.

- _resolve_tui_engine() (env > config > ink); refuses opentui on
  Windows/Termux (no Bun) -> falls back to ink with a notice.
- _make_opentui_argv() -> [bun, src/entry.real.tsx] (no build step).
- _bun_bin() with HERMES_BUN override.
- Branch at top of _make_tui_argv BEFORE _ensure_tui_node (Bun-only host
  must not bootstrap Node).
- Gate _launch_tui NODE_OPTIONS/--max-old-space-size on engine==ink (Bun
  is JSC; the V8 flag errors/ignores).

Verified end-to-end via tmux: real hermes --tui -> Bun -> OpenTUI ->
real Python gateway streamed a real reply. No-flag default still ink.
This commit is contained in:
alt-glitch
2026-06-08 11:11:54 +00:00
parent 24f74eb888
commit 2bd9c9b881
741 changed files with 17733 additions and 79889 deletions
+4 -253
View File
@@ -289,105 +289,6 @@ class TestSystemdServiceRefresh:
"daemon-reload" in str(c) for c in ran
), "daemon-reload must not run when write was refused"
def test_refresh_refuses_to_bake_any_tempdir_home_into_real_user_unit(
self, tmp_path, monkeypatch
):
"""Structural guard: a manual E2E HERMES_HOME like
``/tmp/hermes-e2e-41264`` carries none of the pytest markers but
poisons the unit identically (seen live 2026-06-11 — an E2E probe ran
``hermes gateway restart`` with a /tmp HERMES_HOME exported; the
restart's unit refresh baked it into the production unit and the
post-update restart produced a 7-hour zombie gateway). The refresh
must refuse ANY temp-dir HERMES_HOME, not just pytest-shaped ones.
"""
unit_path = tmp_path / "hermes-gateway.service"
unit_path.write_text("old unit\n", encoding="utf-8")
monkeypatch.setattr(
gateway_cli, "get_systemd_unit_path", lambda system=False: unit_path
)
polluted_unit = (
"[Service]\n"
'Environment="HERMES_HOME=/tmp/hermes-e2e-41264"\n'
"WorkingDirectory=/tmp/hermes-e2e-41264\n"
)
monkeypatch.setattr(
gateway_cli,
"generate_systemd_unit",
lambda system=False, run_as_user=None: polluted_unit,
)
ran = []
def fake_run(cmd, check=True, **kwargs):
ran.append(cmd)
return SimpleNamespace(returncode=0, stdout="", stderr="")
monkeypatch.setattr(gateway_cli.subprocess, "run", fake_run)
result = gateway_cli.refresh_systemd_unit_if_needed(system=False)
assert result is False, "refresh should refuse to write a temp-home unit"
assert (
unit_path.read_text(encoding="utf-8") == "old unit\n"
), "installed unit must be left untouched"
assert not any(
"daemon-reload" in str(c) for c in ran
), "daemon-reload must not run when write was refused"
class TestTempHomeServiceDefinitionGuard:
"""_temp_home_in_service_definition() — structural temp-dir detection."""
def test_detects_tmp_home_in_systemd_unit(self):
unit = '[Service]\nEnvironment="HERMES_HOME=/tmp/hermes-e2e-41264"\n'
assert (
gateway_cli._temp_home_in_service_definition(unit)
== "/tmp/hermes-e2e-41264"
)
def test_detects_var_tmp_home(self):
unit = '[Service]\nEnvironment="HERMES_HOME=/var/tmp/hermes-x"\n'
assert gateway_cli._temp_home_in_service_definition(unit) is not None
def test_detects_tempdir_env_home(self, monkeypatch, tmp_path):
import tempfile as _tempfile
monkeypatch.setattr(_tempfile, "gettempdir", lambda: str(tmp_path))
unit = f'[Service]\nEnvironment="HERMES_HOME={tmp_path}/hermes-home"\n'
assert gateway_cli._temp_home_in_service_definition(unit) is not None
def test_detects_tmp_home_in_launchd_plist(self):
plist = (
"<dict>\n <key>HERMES_HOME</key>\n"
" <string>/tmp/hermes-e2e-99999</string>\n</dict>\n"
)
assert (
gateway_cli._temp_home_in_service_definition(plist)
== "/tmp/hermes-e2e-99999"
)
def test_accepts_real_home(self):
unit = '[Service]\nEnvironment="HERMES_HOME=/home/alice/.hermes"\n'
assert gateway_cli._temp_home_in_service_definition(unit) is None
def test_accepts_macos_real_home_plist(self):
plist = (
"<dict>\n <key>HERMES_HOME</key>\n"
" <string>/Users/alice/.hermes</string>\n</dict>\n"
)
assert gateway_cli._temp_home_in_service_definition(plist) is None
def test_accepts_unit_without_hermes_home(self):
unit = "[Service]\nExecStart=/usr/bin/python -m hermes_cli.main gateway run\n"
assert gateway_cli._temp_home_in_service_definition(unit) is None
def test_tmp_prefixed_non_temp_path_is_accepted(self):
# /tmpfs-data is NOT under /tmp — prefix matching must be
# component-wise, not string startswith.
unit = '[Service]\nEnvironment="HERMES_HOME=/tmpfs-data/.hermes"\n'
assert gateway_cli._temp_home_in_service_definition(unit) is None
class TestRequireServiceInstalled:
def test_exits_with_install_hint_when_unit_missing(self, tmp_path, monkeypatch, capsys):
@@ -580,17 +481,6 @@ class TestLaunchdServiceRecovery:
plist_path.write_text("<plist>old content</plist>", encoding="utf-8")
monkeypatch.setattr(gateway_cli, "get_launchd_plist_path", lambda: plist_path)
# Patch the generator with synthetic content carrying a real-looking
# home — the temp-home guard refuses to write plists whose
# HERMES_HOME resolves under the (pytest tmp) test HERMES_HOME.
monkeypatch.setattr(
gateway_cli,
"generate_launchd_plist",
lambda: (
"<plist>--replace\n<key>HERMES_HOME</key>"
"<string>/Users/alice/.hermes</string></plist>"
),
)
calls = []
@@ -605,10 +495,7 @@ class TestLaunchdServiceRecovery:
label = gateway_cli.get_launchd_label()
domain = gateway_cli._launchd_domain()
assert "--replace" in plist_path.read_text(encoding="utf-8")
# The calls list includes launchctl print probes from _launchd_domain()
# before the bootout/bootstrap calls. Filter to only bootout/bootstrap.
service_calls = [c for c in calls if "bootout" in c or "bootstrap" in c]
assert service_calls[:2] == [
assert calls[:2] == [
["launchctl", "bootout", f"{domain}/{label}"],
["launchctl", "bootstrap", domain, str(plist_path)],
]
@@ -792,22 +679,10 @@ class TestLaunchdServiceRecovery:
assert "stale" in output.lower()
assert "not loaded" in output.lower()
def test_launchd_domain_uses_user_domain(self, monkeypatch):
def test_launchd_domain_uses_user_domain(self):
# The user/<uid> domain (not gui/<uid>) is the one reachable from
# non-Aqua/background sessions on macOS 26+ (issue #23387).
# When gui/<uid> fails to probe and user/<uid> succeeds,
# _launchd_domain() must return user/<uid>.
gateway_cli._resolved_launchd_domain = None
monkeypatch.setattr(os, "getuid", lambda: 501)
label = gateway_cli.get_launchd_label()
def fake_run(cmd, check=False, **kwargs):
if "print" in cmd and "gui/" in " ".join(cmd):
raise subprocess.CalledProcessError(1, cmd, stderr="Domain error")
return SimpleNamespace(returncode=0, stdout="", stderr="")
monkeypatch.setattr(gateway_cli.subprocess, "run", fake_run)
assert gateway_cli._launchd_domain() == "user/501"
assert gateway_cli._launchd_domain() == f"user/{os.getuid()}"
def test_launchctl_domain_unsupported_recognizes_macos26_codes(self):
# Codes that persist after a fresh bootstrap → launchd truly unavailable.
@@ -886,17 +761,6 @@ class TestLaunchdServiceRecovery:
"""macOS bootstrap error 5 should spawn a detached gateway, not crash."""
plist_path = tmp_path / "ai.hermes.gateway.plist"
monkeypatch.setattr(gateway_cli, "get_launchd_plist_path", lambda: plist_path)
# Synthetic plist with a non-temp home so the temp-home write guard
# (which would trip on the pytest-tmp test HERMES_HOME) stays out of
# the way — this test exercises the bootstrap-error fallback.
monkeypatch.setattr(
gateway_cli,
"generate_launchd_plist",
lambda: (
"<plist><key>HERMES_HOME</key>"
"<string>/Users/alice/.hermes</string></plist>"
),
)
def fake_run(cmd, check=False, **kwargs):
if cmd[:2] == ["launchctl", "bootstrap"]:
@@ -972,114 +836,6 @@ class TestLaunchdServiceRecovery:
assert "nohup hermes gateway run" in out
class TestLaunchdDomainDetection:
"""Regression tests for _launchd_domain() probing (#40831).
The function must detect which launchd domain actually contains (or can
manage) the service, rather than hardcoding ``user/<uid>`` or ``gui/<uid>``.
"""
def _reset_domain_cache(self):
"""Clear any cached domain result between tests."""
gateway_cli._resolved_launchd_domain = None
def test_prefers_gui_domain_when_service_loaded_there(self, monkeypatch):
"""In an Aqua session where the service is loaded under gui/<uid>,
_launchd_domain() must return ``gui/<uid>`` — not ``user/<uid>``."""
self._reset_domain_cache()
monkeypatch.setattr(os, "getuid", lambda: 501)
label = gateway_cli.get_launchd_label()
run_calls = []
def fake_run(cmd, check=False, **kwargs):
run_calls.append(cmd)
return SimpleNamespace(returncode=0, stdout="", stderr="")
monkeypatch.setattr(gateway_cli.subprocess, "run", fake_run)
domain = gateway_cli._launchd_domain()
assert domain == f"gui/501"
# Should have probed gui first
assert run_calls[0] == ["launchctl", "print", f"gui/501/{label}"]
def test_falls_back_to_user_domain_when_gui_fails(self, monkeypatch):
"""In a Background/SSH session where gui/<uid> fails but user/<uid>
works, _launchd_domain() must return ``user/<uid>``."""
self._reset_domain_cache()
monkeypatch.setattr(os, "getuid", lambda: 501)
label = gateway_cli.get_launchd_label()
run_calls = []
def fake_run(cmd, check=False, **kwargs):
run_calls.append(cmd)
if "print" in cmd and "gui/" in " ".join(cmd):
raise subprocess.CalledProcessError(1, cmd, stderr="Domain error")
return SimpleNamespace(returncode=0, stdout="", stderr="")
monkeypatch.setattr(gateway_cli.subprocess, "run", fake_run)
domain = gateway_cli._launchd_domain()
assert domain == f"user/501"
# Should have tried gui first, then user
assert len(run_calls) >= 2
def test_uses_managername_heuristic_when_both_probe_fail(self, monkeypatch):
"""When neither domain contains a loaded service, use
``launchctl managername`` as a tiebreaker: Aqua -> gui, else -> user."""
self._reset_domain_cache()
monkeypatch.setattr(os, "getuid", lambda: 501)
label = gateway_cli.get_launchd_label()
def fake_run(cmd, check=False, **kwargs):
if "print" in cmd:
raise subprocess.CalledProcessError(1, cmd, stderr="not found")
if "managername" in cmd:
return SimpleNamespace(returncode=0, stdout="Aqua\n", stderr="")
return SimpleNamespace(returncode=0, stdout="", stderr="")
monkeypatch.setattr(gateway_cli.subprocess, "run", fake_run)
domain = gateway_cli._launchd_domain()
assert domain == f"gui/501"
def test_managername_background_selects_user_domain(self, monkeypatch):
"""When managername is Background (non-Aqua), use user/<uid>."""
self._reset_domain_cache()
monkeypatch.setattr(os, "getuid", lambda: 501)
def fake_run(cmd, check=False, **kwargs):
if "print" in cmd:
raise subprocess.CalledProcessError(1, cmd, stderr="not found")
if "managername" in cmd:
return SimpleNamespace(returncode=0, stdout="Background\n", stderr="")
return SimpleNamespace(returncode=0, stdout="", stderr="")
monkeypatch.setattr(gateway_cli.subprocess, "run", fake_run)
domain = gateway_cli._launchd_domain()
assert domain == f"user/501"
def test_caches_result_across_calls(self, monkeypatch):
"""Domain detection should run once and cache the result."""
self._reset_domain_cache()
monkeypatch.setattr(os, "getuid", lambda: 501)
run_count = [0]
def fake_run(cmd, check=False, **kwargs):
run_count[0] += 1
return SimpleNamespace(returncode=0, stdout="", stderr="")
monkeypatch.setattr(gateway_cli.subprocess, "run", fake_run)
d1 = gateway_cli._launchd_domain()
d2 = gateway_cli._launchd_domain()
assert d1 == d2
assert run_count[0] == 1 # Only probed once
class TestGatewayServiceDetection:
def test_supports_systemd_services_requires_systemctl_binary(self, monkeypatch):
monkeypatch.setattr(gateway_cli, "is_linux", lambda: True)
@@ -2016,12 +1772,7 @@ class TestProfileArg:
monkeypatch.setattr(gateway_cli, "get_hermes_home", lambda: profile_dir)
unit = gateway_cli.generate_systemd_unit(system=False)
assert "--profile mybot" in unit
assert "gateway run" in unit
# Under a process supervisor (Restart=always), --replace makes each
# restart kill its predecessor → self-kill loop. The systemd unit must
# NOT use --replace; the supervisor owns the lifecycle. (--replace stays
# on the manual launchd fallback path — see test_launchd_plist_includes_profile.)
assert "--replace" not in unit
assert "gateway run --replace" in unit
def test_launchd_plist_includes_profile(self, tmp_path, monkeypatch):
"""generate_launchd_plist should include --profile in ProgramArguments for named profiles."""