Skip to content

The agent that grows with you

fix(cli): never ask the gateway for a subagent tail from the monitor's render path

kshitijk4pooraec3de66b177
diff --git a/hermes_cli/cli_subagent_monitor.py b/hermes_cli/cli_subagent_monitor.py
index 805b2f7e63d..2d1ecd8b572 100644
--- a/hermes_cli/cli_subagent_monitor.py
+++ b/hermes_cli/cli_subagent_monitor.py
@@ -42,6 +42,7 @@ class SubagentMonitor:
self.app = None
self.opening = False
self.collapsed = False
+ self.detail = False # the monitor's detail view is open (its tick fetches the gateway tail)
@property
def has_rows(self):
@@ -122,12 +123,23 @@ class SubagentMonitor:
if now - self._last_poll < 1:
return
self._last_poll = now
- if self.refresh():
+ changed = self.refresh()
+ if self._poll_tail() or changed:
if self.app is not None:
self.invalidate()
else:
self.cli._invalidate()
+ def _poll_tail(self):
+ """Off the render path (the spinner thread's tick): refresh the gateway tail the open detail
+ view paints from the cache. True when the text changed."""
+ from hermes_cli.gateway_tools import process_view
+ row, view = self.selected, process_view()
+ if not self.detail or view is None or row is None or row.get('kind') == 'process':
+ return False
+ before = view.subagent_tail(row['subagent_id'])
+ return view.subagent_tail(row['subagent_id'], fetch=True) != before
+
def select(self, delta):
roster = self.roster
if roster:
@@ -274,7 +286,8 @@ def read_tail(path):
def subagent_tail(row):
- """The child's transcript tail: the gateway's ``subagent.tail`` when it runs the child, else the
+ """The child's transcript tail: the gateway's ``subagent.tail`` when it runs the child (as cached
+ by the monitor's tick, never fetched here: the detail view calls this every frame), else the
transcript file this process wrote."""
from hermes_cli.gateway_tools import process_view
view = process_view()
@@ -383,7 +396,8 @@ def build_monitor_application(monitor, **kwargs):
@kb.add('enter', filter=listing)
def detail(event):
if monitor.selected:
- state['detail'] = True
+ state['detail'] = monitor.detail = True
+ monitor._last_poll = 0 # the spinner thread's next tick fetches the tail
update_tail()
app.layout.focus(tail)
@@ -422,7 +436,7 @@ def build_monitor_application(monitor, **kwargs):
state['steering'] = state['confirm'] = False
app.layout.focus(tail if state['detail'] else roster)
elif state['detail']:
- state['detail'] = False
+ state['detail'] = monitor.detail = False
app.layout.focus(roster)
else:
app.exit()
@@ -476,7 +490,7 @@ def open_monitor(cli):
await monitor.app.run_async()
finally:
monitor.app = None
- monitor.opening = False
+ monitor.detail = monitor.opening = False
cli._invalidate()
asyncio.get_running_loop().create_task(run())
diff --git a/hermes_cli/gateway_tools.py b/hermes_cli/gateway_tools.py
index e1380136c4a..b882bb24cba 100644
--- a/hermes_cli/gateway_tools.py
+++ b/hermes_cli/gateway_tools.py
@@ -153,20 +153,21 @@ class GatewayProcessView:
self._subagents_lock.release()
return [dict(row) for row in self.subagents]
- def subagent_tail(self, subagent_id):
+ def subagent_tail(self, subagent_id, *, fetch=False):
"""The child's live transcript tail (``subagent.tail``); None when the gateway has none.
- The monitor repaints the detail view every frame, so the answer is reused for a second."""
+ The detail view repaints every frame and reads only the cache; ``fetch`` (the monitor's
+ tick, on the spinner thread) asks the gateway at most once a second, failures included."""
now = time.time()
- cached = self._tail
- if cached and cached[0] == subagent_id and now - cached[1] < _POLL_SECONDS:
- return cached[2]
+ cached = self._tail if self._tail and self._tail[0] == subagent_id else None
+ if not fetch or (cached and now - cached[1] < _POLL_SECONDS):
+ return cached[2] if cached else None
try:
result = self.connection.call("subagent.tail", session_id=self.session_id,
subagent_id=subagent_id, timeout=5) or {}
+ text = result.get("text") if result.get("available") else None
except (GatewayClientError, RuntimeError) as exc:
logger.debug("subagent.tail failed: %s", exc)
- return None
- text = result.get("text") if result.get("available") else None
+ text = None
self._tail = (subagent_id, now, text)
return text
diff --git a/tests/hermes_cli/test_subagent_monitor_gateway.py b/tests/hermes_cli/test_subagent_monitor_gateway.py
index 9d905e07e77..734815724ec 100644
--- a/tests/hermes_cli/test_subagent_monitor_gateway.py
+++ b/tests/hermes_cli/test_subagent_monitor_gateway.py
@@ -26,12 +26,15 @@ class FakeClient:
self.children = [{"subagent_id": "sa-0-1", "goal": "Audit the parser", "status": "running",
"started_at": time.time() - 7, "last_tool": "read_file", "accepting_steer": True}]
self.steered = []
+ self.tail_error = None
async def rpc(self, method, *, _timeout=None, **params):
self.calls.append((method, params))
if method == "subagent.list":
return {"subagents": self.children, "delegations": []}
if method == "subagent.tail":
+ if self.tail_error:
+ raise self.tail_error
return {"subagent_id": params["subagent_id"], "available": True, "text": "step 1\nstep 2\n",
"truncated": False}
if method == "subagent.steer":
@@ -66,12 +69,15 @@ def gateway(monkeypatch):
def test_monitor_lists_tails_and_controls_the_gateway_sessions_children(gateway):
from hermes_cli import cli_subagent_monitor
agent, client = gateway
- monitor = cli_subagent_monitor.SubagentMonitor(SimpleNamespace(agent=agent, _agent_running=True))
+ monitor = cli_subagent_monitor.SubagentMonitor(SimpleNamespace(agent=agent, _agent_running=True,
+ _invalidate=lambda: None))
monitor.refresh()
assert [r["subagent_id"] for r in monitor.entries] == ["sa-0-1"]
assert monitor.entries[0]["last_tool"] == "read_file" and monitor.entries[0]["elapsed"] >= 6
assert ("subagent.list", {"session_id": SID}) in client.calls
+ monitor.detail = True # the open detail view: the spinner thread's tick fetches its tail
+ monitor.tick()
assert cli_subagent_monitor.subagent_tail(monitor.selected) == "step 1\nstep 2\n"
assert "note" in monitor.control("steer", "Focus on the tokenizer")
@@ -89,3 +95,52 @@ def test_idle_session_without_children_does_not_poll_the_roster(gateway):
monitor = SubagentMonitor(SimpleNamespace(agent=agent, _agent_running=False))
monitor.refresh()
assert not any(method == "subagent.list" for method, _ in client.calls)
+
+
+def test_detail_view_paints_the_cached_tail_and_only_the_tick_asks_the_gateway(gateway):
+ """The detail view repaints every frame on the UI loop: it must never block on subagent.tail.
+ The spinner thread's tick fetches the tail; a failing gateway is asked once per poll."""
+ from prompt_toolkit.data_structures import Size
+ from prompt_toolkit.input import create_pipe_input
+ from prompt_toolkit.output import DummyOutput
+
+ from hermes_cli import cli_subagent_monitor
+ from hermes_cli.gateway_client import GatewayRPCError
+ agent, client = gateway
+ monitor = cli_subagent_monitor.SubagentMonitor(SimpleNamespace(agent=agent, _agent_running=True,
+ _invalidate=lambda: None))
+ monitor.refresh()
+ tails = lambda: sum(method == "subagent.tail" for method, _ in client.calls)
+
+ async def run():
+ with create_pipe_input() as pipe:
+ output = DummyOutput()
+ output.get_size = lambda: Size(rows=14, columns=80)
+ monitor.app = app = cli_subagent_monitor.build_monitor_application(monitor, input=pipe, output=output)
+ rendered = asyncio.Event()
+ app.after_render += lambda app: rendered.set()
+ task = asyncio.create_task(app.run_async())
+ await asyncio.wait_for(rendered.wait(), 3)
+ rendered.clear()
+ pipe.send_text("\r") # open the detail view: several frames, none of them asks the gateway
+ await asyncio.wait_for(rendered.wait(), 3)
+ for _ in range(3):
+ rendered.clear()
+ app.invalidate()
+ await asyncio.wait_for(rendered.wait(), 3)
+ assert tails() == 0 and app.current_buffer.text != "step 1\nstep 2\n"
+ rendered.clear()
+ monitor.tick() # the spinner thread's tick fetches the tail and repaints from the cache
+ await asyncio.wait_for(rendered.wait(), 3)
+ assert tails() == 1 and app.current_buffer.text == "step 1\nstep 2\n"
+ pipe.send_text("\x1b")
+ pipe.send_text("q")
+ await asyncio.wait_for(task, 3)
+ asyncio.run(run())
+
+ view = gateway_tools.process_view()
+ client.tail_error = GatewayRPCError("unavailable")
+ view._tail = None
+ assert view.subagent_tail("sa-0-1", fetch=True) is None
+ assert view.subagent_tail("sa-0-1", fetch=True) is None # the failure is cached for the poll interval
+ assert tails() == 2