Skip to content

The agent that grows with you

fix(tui): one launch path for Ink's Python helpers; name a bootstrap that cannot start

Teknium7a0e1e2464ab
diff --git a/nix/checks.nix b/nix/checks.nix
index 7c1c4bc6239..8e15e4f8a72 100644
--- a/nix/checks.nix
+++ b/nix/checks.nix
@@ -1201,6 +1201,14 @@ json.dump(sorted(leaf_paths(DEFAULT_CONFIG)), sys.stdout, indent=2)
test -f ${hermes-agent}/ui-tui/dist/entry.js || (echo "FAIL: compiled entry.js missing"; exit 1)
echo "PASS: compiled entry.js present"
+ # The compiled TUI runs these on HERMES_PYTHON; the Python package lives in another
+ # store path, so they must ship beside entry.js (#139208).
+ for helper in gateway_bootstrap.py clipboard_image.py; do
+ test -f ${hermes-agent}/ui-tui/dist/scripts/$helper || \
+ (echo "FAIL: TUI helper $helper missing"; exit 1)
+ done
+ echo "PASS: TUI Python helpers present"
+
# self-contained bundle; no runtime node_modules expected
grep -q "HERMES_TUI_DIR" ${hermes-agent}/bin/hermes || \
diff --git a/tests/tui_gateway/test_ink_helper_dependencies.py b/tests/tui_gateway/test_ink_helper_dependencies.py
index 22e19f3e51d..17dbdeaac03 100644
--- a/tests/tui_gateway/test_ink_helper_dependencies.py
+++ b/tests/tui_gateway/test_ink_helper_dependencies.py
@@ -41,10 +41,11 @@ def _commit_generation() -> None:
json.dumps({"packages": {"venv": {"environment": str(venv)}}, "schema": 1}), encoding="utf-8")
-def _ink_child(script: str, *args: str, **env: str) -> subprocess.CompletedProcess:
+def _ink_child(script: str, *args: str, scripts: Path = _SCRIPTS, **env: str) -> subprocess.CompletedProcess:
+ """Exactly what gatewayClient.ts runs: PYTHONPATH and HERMES_PYTHON_SRC_ROOT name the Python root."""
child_env = {k: v for k, v in os.environ.items() if k != "VIRTUAL_ENV"}
- child_env.update(PYTHONPATH=str(_ROOT), **env)
- return subprocess.run([sys.executable, "-S", str(_SCRIPTS / script), *args], cwd=_ROOT,
+ child_env.update(PYTHONPATH=str(_ROOT), HERMES_PYTHON_SRC_ROOT=str(_ROOT), **env)
+ return subprocess.run([sys.executable, "-S", str(scripts / script), *args], cwd=_ROOT,
env=child_env, capture_output=True, text=True, timeout=60, check=False)
@@ -61,6 +62,26 @@ def test_gateway_bootstrap_reaches_a_verdict_on_the_store_python():
assert child.stderr.strip().splitlines()[0].startswith("gateway "), child.stderr
+def test_packaged_gateway_bootstrap_boots_the_root_it_is_given_or_names_why_it_cannot(tmp_path):
+ """The TUI product ships the helper in its own dist/scripts/ (a separate Nix store path, #139208),
+ where parents[2] is not the Python root: the helper must boot the generation of the root Ink
+ passes, and an interpreter that still cannot load Hermes is a named, terminal verdict the client
+ stops retrying on, never a bare ImportError retried every 30 s (#138878)."""
+ packaged = tmp_path / "hermes-tui" / "dist" / "scripts"
+ packaged.mkdir(parents=True)
+ shutil.copy2(_SCRIPTS / "gateway_bootstrap.py", packaged / "gateway_bootstrap.py")
+
+ bare = _ink_child("gateway_bootstrap.py", "--start", scripts=packaged)
+ assert bare.returncode == 1
+ assert bare.stderr.splitlines()[0] == "gateway unavailable: bootstrap_dependencies", bare.stderr
+
+ _commit_generation()
+ booted = _ink_child("gateway_bootstrap.py", scripts=packaged)
+ assert booted.returncode == 1
+ assert booted.stderr.strip().splitlines()[0].startswith("gateway "), booted.stderr
+ assert "unavailable" not in booted.stderr
+
+
@pytest.mark.platforms("linux")
def test_clipboard_image_converts_wayland_jpeg_with_the_generations_pillow(tmp_path):
"""A non-PNG Wayland clipboard image is converted with Pillow, a core dependency; ImageMagick
diff --git a/ui-tui/scripts/clipboard_image.py b/ui-tui/scripts/clipboard_image.py
index 1e3cc3837e2..7b92f249362 100644
--- a/ui-tui/scripts/clipboard_image.py
+++ b/ui-tui/scripts/clipboard_image.py
@@ -1,8 +1,14 @@
"""Extract the Ink host clipboard without loading a session runtime."""
import json
+import os
import sys
from pathlib import Path
+# The Python root (gatewayClient.ts/imageAttachments.ts pass it): the TUI product ships this
+# helper in dist/scripts/, where parents[2] is not the root.
+ROOT = Path(os.environ.get("HERMES_PYTHON_SRC_ROOT") or Path(__file__).resolve().parents[2])
+sys.path.insert(0, str(ROOT))
+
from hermes_cli.clipboard import save_clipboard_image
from pm.environments import activate_dependencies
@@ -10,5 +16,5 @@ if __name__ == "__main__":
# Ink runs this on HERMES_PYTHON with PYTHONPATH=<root> only, which on a source install is PM's
# store Python: without the committed generation, Pillow is missing and non-PNG clipboard
# images silently depend on ImageMagick being installed.
- activate_dependencies(Path(__file__).resolve().parents[2])
+ activate_dependencies(ROOT)
print(json.dumps(bool(save_clipboard_image(Path(sys.argv[1])))))
diff --git a/ui-tui/scripts/gateway_bootstrap.py b/ui-tui/scripts/gateway_bootstrap.py
index dee6a166a47..47fa0c36935 100644
--- a/ui-tui/scripts/gateway_bootstrap.py
+++ b/ui-tui/scripts/gateway_bootstrap.py
@@ -12,7 +12,11 @@ import os
from pathlib import Path
import sys
-sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
+# The Python root, not this file's location: the TUI product ships this helper in its own
+# dist/scripts/ (a separate Nix store path), so parents[2] is only right in a source tree.
+# gatewayClient.ts passes the root it put on PYTHONPATH.
+ROOT = Path(os.environ.get("HERMES_PYTHON_SRC_ROOT") or Path(__file__).resolve().parents[2])
+sys.path.insert(0, str(ROOT))
@@ -36,7 +40,10 @@ def bootstrap(start: bool, recover: bool = False) -> dict:
# store Python, which owns no packages, and the no-owner discovery fallback already imports one
# (gateway.status -> utils -> hermes_yaml -> ruamel): boot the committed generation first, as
# hermes_bootstrap does for every other entry point.
- activate_dependencies(Path(__file__).resolve().parents[2])
+ try:
+ activate_dependencies(ROOT)
+ except (RuntimeError, OSError) as exc: # no committed generation / unreadable install state
+ raise ImportError(f"dependency environment unavailable: {exc}") from exc
from hermes_constants import get_hermes_home
from hermes_cli.gateway_runtime import control_home_for, discover_gateway_endpoint, ensure_gateway_runtime
from hermes_cli.gateway_runtime_discovery import connect_private
@@ -92,6 +99,11 @@ if __name__ == "__main__":
# Discovery/ticket failures: missing modules, socket/pipe I/O (incl. timeouts), DiscoveryError and
# bad JSON (ValueError), rejected grants (RuntimeError), malformed reply shapes. Anything else
# still exits 1, with a traceback.
- except (ImportError, OSError, RuntimeError, ValueError, LookupError, AttributeError, TypeError) as exc:
+ except ImportError as exc:
+ # This interpreter cannot load Hermes at all: no reconnect fixes that, so name it
+ # (gatewayClient.ts stops retrying on this verdict).
+ print(f"gateway unavailable: bootstrap_dependencies\n{exc}", file=sys.stderr)
+ raise SystemExit(1)
+ except (OSError, RuntimeError, ValueError, LookupError, AttributeError, TypeError) as exc:
print(str(exc), file=sys.stderr)
raise SystemExit(1)
diff --git a/ui-tui/src/__tests__/gatewayLocalLaunch.test.ts b/ui-tui/src/__tests__/gatewayLocalLaunch.test.ts
index 91039d0bba6..b09d33aed5e 100644
--- a/ui-tui/src/__tests__/gatewayLocalLaunch.test.ts
+++ b/ui-tui/src/__tests__/gatewayLocalLaunch.test.ts
@@ -24,3 +24,23 @@ it('reports failed canonical bootstrap without creating an independent owner or
expect(bootstrap).toHaveBeenCalledTimes(1)
gw.kill()
})
+
+it('reports a bootstrap that cannot load Hermes once and stops retrying (#138878)', async () => {
+ vi.useFakeTimers()
+ vi.stubEnv('HERMES_HOME', home)
+ vi.stubEnv('HERMES_TUI_GATEWAY_URL', '')
+ const bootstrap = vi.fn().mockRejectedValue(new Error(
+ 'Command failed: python3 gateway_bootstrap.py --start\ngateway unavailable: bootstrap_dependencies\nNo module named \'ruamel\''))
+ const gw = new GatewayClient(bootstrap)
+ const events: any[] = []
+ gw.on('event', e => events.push(e))
+
+ try {
+ gw.start()
+ gw.drain()
+ await vi.advanceTimersByTimeAsync(5 * 60_000)
+ expect(bootstrap).toHaveBeenCalledTimes(1)
+ expect(events.filter(e => e.type === 'gateway.start_timeout')).toHaveLength(1)
+ expect(events.some(e => e.type === 'gateway.reconnecting')).toBe(false)
+ } finally { gw.kill(); vi.useRealTimers() }
+})
diff --git a/ui-tui/src/app/userMessages.ts b/ui-tui/src/app/userMessages.ts
index 21bdaa28013..94beaa5afd6 100644
--- a/ui-tui/src/app/userMessages.ts
+++ b/ui-tui/src/app/userMessages.ts
@@ -90,7 +90,7 @@ export const backendSlowStartStatus = (): string => t('userMessages.backend.slow
// ui-tui/scripts/gateway_bootstrap.py failure_message). Dependency `DeprecationWarning` /
// `UserWarning` lines are noise and stay in /logs only.
const STDERR_PROBLEM_RE =
- /Traceback|\b[A-Z][A-Za-z]*(?:Error|Exception)\b:|CRITICAL|\[gateway-turn\]|\[gateway-exit\]|^gateway (?:absent|conflict|draining|inaccessible|incompatible|starting): /
+ /Traceback|\b[A-Z][A-Za-z]*(?:Error|Exception)\b:|CRITICAL|\[gateway-turn\]|\[gateway-exit\]|^gateway (?:absent|conflict|draining|inaccessible|incompatible|starting|unavailable): /
/** Only lines that look like a failure earn an activity row; the rest stay in /logs. */
export const stderrLooksLikeProblem = (line: string): boolean => STDERR_PROBLEM_RE.test(line)
diff --git a/ui-tui/src/gatewayClient.ts b/ui-tui/src/gatewayClient.ts
index 45f65bfca9d..e71c96645db 100644
--- a/ui-tui/src/gatewayClient.ts
+++ b/ui-tui/src/gatewayClient.ts
@@ -130,12 +130,16 @@ export interface LocalGatewayGrant { url: string; protocols: string[]; profile_i
export const OWNER_RECOVERY_LIMIT = 3
export const OWNER_RECOVERY_WINDOW_MS = 60_000
+/** gateway_bootstrap.py's verdict for an interpreter that cannot load Hermes or its dependencies. */
+// execFile's error text is `Command failed: …` followed by the child's stderr, hence the line match.
+export const isTerminalBootstrapFailure = (message: string) => /^gateway unavailable: /m.test(message)
+
const bootstrapLocalGateway = async (start: boolean, recover = false): Promise<LocalGatewayGrant> => {
const root = process.env.HERMES_PYTHON_SRC_ROOT ?? resolve(import.meta.dirname, '../../')
const { stdout } = await promisify(execFile)(resolvePython(),
[pythonHelperPath('gateway_bootstrap.py', root), ...(start ? ['--start'] : recover ? ['--recover'] : [])],
- { cwd: root, env: { ...process.env, PYTHONPATH: root }, timeout: 40_000, maxBuffer: 1024 * 1024 })
+ { cwd: root, env: { ...process.env, PYTHONPATH: root, HERMES_PYTHON_SRC_ROOT: root }, timeout: 40_000, maxBuffer: 1024 * 1024 })
return JSON.parse(stdout) as LocalGatewayGrant
}
@@ -606,6 +610,15 @@ export class GatewayClient extends EventEmitter {
python: 'gateway ensure', cwd: '', stderr_tail: this.bootstrapError.message
} })
this.channel.detach(this.bootstrapError)
+
+ // The helper's interpreter cannot load Hermes (gateway_bootstrap.py `gateway unavailable:`):
+ // no reconnect fixes that, so report it once instead of retrying every 30 s forever (#138878).
+ if (isTerminalBootstrapFailure(this.bootstrapError.message)) {
+ this.lifecycle(`[lifecycle] gateway bootstrap cannot start; not retrying: ${this.bootstrapError.message.match(/^gateway unavailable: .*$/m)?.[0]}`)
+
+ return
+ }
+
this.scheduleReconnect()
})
}
diff --git a/ui-tui/src/lib/imageAttachments.ts b/ui-tui/src/lib/imageAttachments.ts
index 96b375129d4..32bb58dbda8 100644
--- a/ui-tui/src/lib/imageAttachments.ts
+++ b/ui-tui/src/lib/imageAttachments.ts
@@ -79,7 +79,7 @@ async function extractClipboardImage(path: string): Promise<boolean> {
(process.platform === 'win32' ? 'python' : 'python3')
const { stdout } = await promisify(execFile)(python, [pythonHelperPath('clipboard_image.py', root), path],
- { cwd: root, env: { ...process.env, PYTHONPATH: root }, timeout: 15_000, windowsHide: true })
+ { cwd: root, env: { ...process.env, PYTHONPATH: root, HERMES_PYTHON_SRC_ROOT: root }, timeout: 15_000, windowsHide: true })
return stdout.trim() === 'true'
}