Skip to content

The agent that grows with you

refactor(tui): local gateway bootstrap in its own module; poller test without sleeps

Tekniumcb1722523a34
diff --git a/tests/tui_gateway/test_tui_gateway_notification_poller.py b/tests/tui_gateway/test_tui_gateway_notification_poller.py
index b1cc360b80c..d9cc662c72f 100644
--- a/tests/tui_gateway/test_tui_gateway_notification_poller.py
+++ b/tests/tui_gateway/test_tui_gateway_notification_poller.py
@@ -1,7 +1,6 @@
"""One live notification poller per TUI session across agent rebuilds (#138806)."""
import threading
-import time
import types
from tui_gateway import server
@@ -27,6 +26,9 @@ def test_session_rebuild_stops_previous_notification_poller(monkeypatch):
server._start_session_services("sid_rebuild", "session-key", sess)
first_stop = sess["_notif_stop"]
assert not first_stop.is_set() # a fresh session really starts its poller running
+ # Identify the first poller by its stop event now: once it exits, the rebuild may prune it
+ # and only the replacement would carry the shared thread name.
+ first_thread = next(thread for stop, thread in list(server._notification_pollers) if stop is first_stop)
# Agent rebuild for the SAME session (in-session /model switch, resume, late MCP refresh).
server._start_session_services("sid_rebuild", "session-key", sess)
@@ -35,13 +37,7 @@ def test_session_rebuild_stops_previous_notification_poller(monkeypatch):
assert first_stop.is_set() # the previous poller was stopped, not orphaned
# The old loop wakes at most every 0.5s; give it its real deadline to exit.
- first_thread = next(
- thread
- for _stop, thread in list(server._notification_pollers)
- if thread.name == "tui-notif-poller-sid_rebuild")
- deadline = time.time() + 3.0
- while first_thread.is_alive() and time.time() < deadline:
- time.sleep(0.05)
+ first_thread.join(timeout=3.0)
assert not first_thread.is_alive(), "the stopped previous poller never exited"
live = [
thread
diff --git a/ui-tui/src/gatewayClient.ts b/ui-tui/src/gatewayClient.ts
index e71c96645db..b8fee681dc9 100644
--- a/ui-tui/src/gatewayClient.ts
+++ b/ui-tui/src/gatewayClient.ts
@@ -1,7 +1,4 @@
-import { execFile } from 'node:child_process'
import { EventEmitter } from 'node:events'
-import { resolve } from 'node:path'
-import { promisify } from 'node:util'
import type { GatewayEvent } from '@hermes/shared/gateway-events'
import {
@@ -26,7 +23,7 @@ import type { AnyGatewayEvent } from './gatewayTypes.js'
import { t } from './i18n/runtime.js'
import { CircularBuffer } from './lib/circularBuffer.js'
import { recordParentLifecycle } from './lib/parentLog.js'
-import { pythonHelperPath } from './lib/pythonHelpers.js'
+import { bootstrapLocalGateway, isTerminalBootstrapFailure, type LocalGatewayGrant } from './localGatewayBootstrap.js'
const MAX_GATEWAY_LOG_LINES = 200
const MAX_LOG_LINE_BYTES = 4096
@@ -68,26 +65,6 @@ const resolveSidecarUrl = () => {
return raw ? raw : null
}
-const resolvePython = () => {
- // Trust HERMES_PYTHON only. The launcher guarantees it: hermes_cli/main.py
- // validates it and falls back to its own sys.executable, and the Nix
- // wrapper sets it too. So a TUI started the normal way already knows its
- // interpreter, and scanning VIRTUAL_ENV / .venv here can only find a
- // DIFFERENT python than the parent process runs on — with the pm store,
- // a stale venv path is actively dangerous (the interpreter a gateway
- // child gets must match the one that spawned it).
- const configured = process.env.HERMES_PYTHON?.trim()
-
- if (configured) {
- return configured
- }
-
- // The one case with no launcher above it: `npm run dev` / `npm start`
- // straight out of ui-tui/. A developer doing that runs inside their own
- // activated environment, so PATH is the right question there.
- return process.platform === 'win32' ? 'python' : 'python3'
-}
-
// Matches `<scheme>://user:pass@host…` style user-info segments in
// otherwise-malformed URLs that the WHATWG `URL` parser can't accept.
// Used by the `redactUrl` fallback so embedded credentials are
@@ -120,8 +97,6 @@ const redactUrl = (raw: string): string => {
}
}
-export interface LocalGatewayGrant { url: string; protocols: string[]; profile_id: string; instance_id: string }
-
// Reconnects after the first launch are discovery-only, except that a bounded number per window
// re-ensure an owner that is not ready (gateway_bootstrap.py --recover): crashed, idle-exited,
// stopped with `hermes gateway stop` while this TUI is open, or an older Hermes's gateway. Main's
@@ -130,20 +105,6 @@ 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, HERMES_PYTHON_SRC_ROOT: root }, timeout: 40_000, maxBuffer: 1024 * 1024 })
-
- return JSON.parse(stdout) as LocalGatewayGrant
-}
-
export interface AttachHold { sid: string; frames: AnyGatewayEvent[] }
export class GatewayClient extends EventEmitter {
diff --git a/ui-tui/src/localGatewayBootstrap.ts b/ui-tui/src/localGatewayBootstrap.ts
new file mode 100644
index 00000000000..839ada03e40
--- /dev/null
+++ b/ui-tui/src/localGatewayBootstrap.ts
@@ -0,0 +1,44 @@
+/** Local gateway bootstrap for the Ink TUI: run ui-tui's `gateway_bootstrap.py` on the install's
+interpreter and parse its grant (or its named terminal failure). Kept out of the transport class;
+`GatewayClient` takes it as its injected `bootstrap`. */
+import { execFile } from 'node:child_process'
+import { resolve } from 'node:path'
+import { promisify } from 'node:util'
+
+import { pythonHelperPath } from './lib/pythonHelpers.js'
+
+const resolvePython = () => {
+ // Trust HERMES_PYTHON only. The launcher guarantees it: hermes_cli/main.py
+ // validates it and falls back to its own sys.executable, and the Nix
+ // wrapper sets it too. So a TUI started the normal way already knows its
+ // interpreter, and scanning VIRTUAL_ENV / .venv here can only find a
+ // DIFFERENT python than the parent process runs on — with the pm store,
+ // a stale venv path is actively dangerous (the interpreter a gateway
+ // child gets must match the one that spawned it).
+ const configured = process.env.HERMES_PYTHON?.trim()
+
+ if (configured) {
+ return configured
+ }
+
+ // The one case with no launcher above it: `npm run dev` / `npm start`
+ // straight out of ui-tui/. A developer doing that runs inside their own
+ // activated environment, so PATH is the right question there.
+ return process.platform === 'win32' ? 'python' : 'python3'
+}
+
+export interface LocalGatewayGrant { url: string; protocols: string[]; profile_id: string; instance_id: string }
+
+/** 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)
+
+export 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, HERMES_PYTHON_SRC_ROOT: root }, timeout: 40_000, maxBuffer: 1024 * 1024 })
+
+ return JSON.parse(stdout) as LocalGatewayGrant
+}