Skip to content

The agent that grows with you

fix(tui): resolve the helpers' Python root at call time

Tekniuma1a07821567f
diff --git a/tests/tui_gateway/test_tui_gateway_notification_poller.py b/tests/tui_gateway/test_tui_gateway_notification_poller.py
new file mode 100644
index 00000000000..b1cc360b80c
--- /dev/null
+++ b/tests/tui_gateway/test_tui_gateway_notification_poller.py
@@ -0,0 +1,61 @@
+"""One live notification poller per TUI session across agent rebuilds (#138806)."""
+
+import threading
+import time
+import types
+
+from tui_gateway import server
+
+
+def _session():
+ return {"agent": types.SimpleNamespace(), "session_key": "session-key", "history": [],
+ "history_lock": threading.Lock(), "history_version": 0, "running": False,
+ "attached_images": [], "image_counter": 0, "cols": 80, "slash_worker": None,
+ "show_reasoning": False, "tool_progress_mode": "all"}
+
+
+def test_session_rebuild_stops_previous_notification_poller(monkeypatch):
+ """Rebuilding the agent for a live session re-enters _start_session_services; the previous
+ poller's stop event must be set before the record's ``_notif_stop`` is replaced (#138806).
+ Otherwise the orphaned poller keeps draining the process-global completion queue for the
+ session (two live loops per rebuild) until the session itself is finalized — close can only
+ signal the newest event."""
+ monkeypatch.setattr(server, "_notify_session_boundary", lambda *a, **k: None)
+ sess = _session()
+ server._sessions["sid_rebuild"] = sess
+ try:
+ 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
+
+ # Agent rebuild for the SAME session (in-session /model switch, resume, late MCP refresh).
+ server._start_session_services("sid_rebuild", "session-key", sess)
+ second_stop = sess["_notif_stop"]
+ assert second_stop is not first_stop
+ 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)
+ assert not first_thread.is_alive(), "the stopped previous poller never exited"
+ live = [
+ thread
+ for _stop, thread in list(server._notification_pollers)
+ if thread.name == "tui-notif-poller-sid_rebuild" and thread.is_alive()
+ ]
+ assert len(live) == 1, f"expected exactly one live poller, got {len(live)}"
+
+ # Session close can only signal the newest stop event — which now stops the only live poller.
+ second_stop.set()
+ live[0].join(timeout=3.0)
+ assert not live[0].is_alive()
+ finally:
+ server._sessions.pop("sid_rebuild", None)
+ for stop, thread in list(server._notification_pollers):
+ stop.set()
+ thread.join(timeout=1.0)
diff --git a/ui-tui/scripts/clipboard_image.py b/ui-tui/scripts/clipboard_image.py
index 7b92f249362..04f2b96681c 100644
--- a/ui-tui/scripts/clipboard_image.py
+++ b/ui-tui/scripts/clipboard_image.py
@@ -6,8 +6,11 @@ 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))
+def python_root() -> Path:
+ return Path(os.environ.get("HERMES_PYTHON_SRC_ROOT") or Path(__file__).resolve().parents[2])
+
+
+sys.path.insert(0, str(python_root()))
from hermes_cli.clipboard import save_clipboard_image
from pm.environments import activate_dependencies
@@ -16,5 +19,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(ROOT)
+ activate_dependencies(python_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 47fa0c36935..b7936c4eecc 100644
--- a/ui-tui/scripts/gateway_bootstrap.py
+++ b/ui-tui/scripts/gateway_bootstrap.py
@@ -15,8 +15,11 @@ import sys
# 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))
+def python_root() -> Path:
+ return Path(os.environ.get("HERMES_PYTHON_SRC_ROOT") or Path(__file__).resolve().parents[2])
+
+
+sys.path.insert(0, str(python_root()))
@@ -41,7 +44,7 @@ def bootstrap(start: bool, recover: bool = False) -> dict:
# (gateway.status -> utils -> hermes_yaml -> ruamel): boot the committed generation first, as
# hermes_bootstrap does for every other entry point.
try:
- activate_dependencies(ROOT)
+ activate_dependencies(python_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