feat(cli): show live dock and full-screen subagent controls above composer
This commit is contained in:
@@ -92,6 +92,171 @@ class SubagentMonitor:
|
||||
return '\n'.join(lines)
|
||||
|
||||
|
||||
def read_tail(path):
|
||||
if not path:
|
||||
return 'Live transcript not available yet.'
|
||||
try:
|
||||
with open(path, 'rb') as stream:
|
||||
stream.seek(0, 2)
|
||||
stream.seek(max(0, stream.tell() - 32768))
|
||||
text = stream.read(32768).decode('utf-8', errors='replace')
|
||||
return ''.join(c for c in text if c.isprintable() or c in '\n\t')
|
||||
except OSError:
|
||||
return 'Live transcript not available yet.'
|
||||
|
||||
|
||||
def build_monitor_application(monitor, **kwargs):
|
||||
from prompt_toolkit.application import Application
|
||||
from prompt_toolkit.data_structures import Point
|
||||
from prompt_toolkit.filters import Condition
|
||||
from prompt_toolkit.key_binding import KeyBindings
|
||||
from prompt_toolkit.layout import ConditionalContainer, HSplit, Layout, Window
|
||||
from prompt_toolkit.layout.controls import FormattedTextControl
|
||||
from prompt_toolkit.widgets import TextArea
|
||||
|
||||
state = {'detail': False, 'steering': False, 'confirm': False, 'notice': ''}
|
||||
steer = TextArea(height=1, prompt='Steer: ', multiline=False)
|
||||
tail = TextArea(read_only=True, scrollbar=True, wrap_lines=True)
|
||||
|
||||
def roster_text():
|
||||
size = app.output.get_size()
|
||||
rows = []
|
||||
for row in monitor.entries:
|
||||
selected = row['subagent_id'] == monitor.selected_id
|
||||
text = f"{'❯' if selected else ' '} {row['elapsed']}s · {row.get('status') or 'starting'} · {row.get('goal') or row['subagent_id']}"
|
||||
if row.get('last_tool'):
|
||||
text += f" · last: {row['last_tool']}"
|
||||
rows.append(('reverse' if selected else '', _clip(text, size.columns) + '\n'))
|
||||
return rows or [('', 'No live subagents. Results arrive in the conversation.')]
|
||||
|
||||
def cursor():
|
||||
index = next((i for i, row in enumerate(monitor.entries) if row['subagent_id'] == monitor.selected_id), 0)
|
||||
return Point(x=0, y=index)
|
||||
|
||||
roster = Window(FormattedTextControl(roster_text, focusable=True, get_cursor_position=cursor))
|
||||
|
||||
def update_tail():
|
||||
row = monitor.selected
|
||||
text = read_tail(row.get('live_transcript')) if row else 'This subagent is no longer live.'
|
||||
if text != tail.text:
|
||||
following = tail.buffer.cursor_position == len(tail.text)
|
||||
position = tail.buffer.cursor_position
|
||||
tail.text = text
|
||||
tail.buffer.cursor_position = len(text) if following else min(position, len(text))
|
||||
|
||||
def header():
|
||||
row = monitor.selected
|
||||
title = f"Subagents · {len(monitor.entries)} live"
|
||||
if state['detail'] and row:
|
||||
title += f" · {row['subagent_id']} · {row.get('goal') or ''}"
|
||||
return [('bold', _clip(title, app.output.get_size().columns))]
|
||||
|
||||
def footer():
|
||||
if state['confirm']:
|
||||
return 'Stop selected subagent? y confirm · Esc cancel'
|
||||
if state['steering']:
|
||||
return 'Enter queues guidance · Esc cancels (does not interrupt)'
|
||||
return ('Esc roster · PgUp/PgDn tail · s steer · x stop' if state['detail'] else
|
||||
'↑/↓ select · Enter tail · s steer · x stop · q/F6 close')
|
||||
|
||||
kb = KeyBindings()
|
||||
normal = Condition(lambda: not state['steering'] and not state['confirm'])
|
||||
listing = normal & Condition(lambda: not state['detail'])
|
||||
|
||||
@kb.add('up', filter=listing)
|
||||
def up(event):
|
||||
monitor.select(-1)
|
||||
|
||||
@kb.add('down', filter=listing)
|
||||
def down(event):
|
||||
monitor.select(1)
|
||||
|
||||
@kb.add('enter', filter=listing)
|
||||
def detail(event):
|
||||
if monitor.selected:
|
||||
state['detail'] = True
|
||||
update_tail()
|
||||
app.layout.focus(tail)
|
||||
|
||||
@kb.add('s', filter=normal)
|
||||
def start_steer(event):
|
||||
if monitor.selected:
|
||||
state['steering'] = True
|
||||
app.layout.focus(steer)
|
||||
|
||||
@kb.add('enter', filter=Condition(lambda: state['steering']))
|
||||
def send_steer(event):
|
||||
if not steer.text.strip():
|
||||
return
|
||||
result = monitor.control('steer', steer.text)
|
||||
state['notice'] = result.get('error') or result.get('note') or str(result)
|
||||
steer.text = ''
|
||||
state['steering'] = False
|
||||
app.layout.focus(tail if state['detail'] else roster)
|
||||
|
||||
@kb.add('x', filter=normal)
|
||||
def stop(event):
|
||||
if monitor.selected:
|
||||
state['confirm'] = True
|
||||
|
||||
@kb.add('y', filter=Condition(lambda: state['confirm']))
|
||||
def confirm(event):
|
||||
result = monitor.control('stop')
|
||||
state['notice'] = result.get('error') or result.get('note') or str(result)
|
||||
state['confirm'] = False
|
||||
|
||||
@kb.add('escape', eager=True)
|
||||
def back(event):
|
||||
if state['steering'] or state['confirm']:
|
||||
state['steering'] = state['confirm'] = False
|
||||
app.layout.focus(tail if state['detail'] else roster)
|
||||
elif state['detail']:
|
||||
state['detail'] = False
|
||||
app.layout.focus(roster)
|
||||
else:
|
||||
app.exit()
|
||||
|
||||
@kb.add('q', filter=normal)
|
||||
@kb.add('f6', filter=normal)
|
||||
@kb.add('c-c')
|
||||
def close(event):
|
||||
app.exit()
|
||||
|
||||
layout = Layout(HSplit([
|
||||
Window(FormattedTextControl(header), height=1),
|
||||
ConditionalContainer(roster, filter=Condition(lambda: not state['detail'])),
|
||||
ConditionalContainer(tail, filter=Condition(lambda: state['detail'])),
|
||||
ConditionalContainer(steer, filter=Condition(lambda: state['steering'])),
|
||||
Window(FormattedTextControl(lambda: _clip(state['notice'], app.output.get_size().columns)), height=1),
|
||||
Window(FormattedTextControl(footer), height=1),
|
||||
]), focused_element=roster)
|
||||
app = Application(layout=layout, key_bindings=kb, full_screen=True, mouse_support=False,
|
||||
before_render=lambda app: update_tail() if state['detail'] else None, **kwargs)
|
||||
return app
|
||||
|
||||
|
||||
def open_monitor(cli):
|
||||
import asyncio
|
||||
from prompt_toolkit.application import in_terminal
|
||||
monitor = getattr(cli, '_subagent_monitor', None)
|
||||
if monitor is None or monitor.opening:
|
||||
return
|
||||
monitor.opening = True
|
||||
|
||||
async def run():
|
||||
try:
|
||||
async with in_terminal():
|
||||
monitor.refresh()
|
||||
monitor.app = build_monitor_application(monitor)
|
||||
await monitor.app.run_async()
|
||||
finally:
|
||||
monitor.app = None
|
||||
monitor.opening = False
|
||||
cli._invalidate()
|
||||
|
||||
asyncio.get_running_loop().create_task(run())
|
||||
|
||||
|
||||
def install_dock(cli):
|
||||
from prompt_toolkit.application import get_app
|
||||
from prompt_toolkit.layout import ConditionalContainer, Window
|
||||
|
||||
@@ -387,6 +387,7 @@ class CLITuiMixin:
|
||||
*self._get_extra_tui_widgets(),
|
||||
getattr(self, "_pet_widget", None),
|
||||
getattr(self, "_stash_panel_widget", None),
|
||||
getattr(self, "_subagent_dock_widget", None),
|
||||
status_bar,
|
||||
input_rule_top,
|
||||
image_bar,
|
||||
@@ -401,6 +402,9 @@ class CLITuiMixin:
|
||||
if not self._app:
|
||||
time.sleep(0.1)
|
||||
continue
|
||||
monitor = getattr(self, "_subagent_monitor", None)
|
||||
if monitor is not None:
|
||||
monitor.tick()
|
||||
if self._command_running:
|
||||
self._invalidate(min_interval=0.1)
|
||||
time.sleep(0.1)
|
||||
@@ -1853,6 +1857,12 @@ class CLITuiMixin:
|
||||
kb.add(Keys.BracketedPaste, eager=True)(self._tui_handle_paste)
|
||||
kb.add('c-v')(self._tui_handle_ctrl_v)
|
||||
kb.add('escape', 'v')(self._tui_handle_alt_v)
|
||||
from hermes_cli.cli_subagent_monitor import open_monitor
|
||||
kb.add('f6', filter=Condition(lambda: not any(
|
||||
getattr(self, name, None) for name in (
|
||||
'_clarify_state', '_approval_state', '_slash_confirm_state', '_sudo_state',
|
||||
'_secret_state', '_model_picker_state', '_command_palette_state'))))(
|
||||
lambda event: open_monitor(self))
|
||||
return kb
|
||||
|
||||
def _tui_bind_editor_and_stash(self, kb) -> None:
|
||||
@@ -2000,6 +2010,8 @@ class CLITuiMixin:
|
||||
def _tui_build_layout(self, kb):
|
||||
"""Build the TUI widgets, Layout and Style; registers wrapper keybindings on ``kb``."""
|
||||
cli_ref = self
|
||||
from hermes_cli.cli_subagent_monitor import install_dock
|
||||
install_dock(self)
|
||||
input_area = self._tui_build_input_area()
|
||||
spinner_widget = Window(
|
||||
content=FormattedTextControl(self._tui_spinner_text),
|
||||
|
||||
@@ -24,6 +24,13 @@ def test_dock_scopes_children_and_fits_short_narrow_terminal(monkeypatch):
|
||||
assert dock.refresh(now=21)
|
||||
assert dock.dock_text(columns=32, rows=14) == ''
|
||||
assert not dock.refresh(now=22)
|
||||
from hermes_cli.cli_tui_mixin import CLITuiMixin
|
||||
cli = SimpleNamespace(_subagent_dock_widget='dock', _get_extra_tui_widgets=lambda: [])
|
||||
children = CLITuiMixin._build_tui_layout_children(cli, sudo_widget=None, secret_widget=None,
|
||||
approval_widget=None, clarify_widget=None, spacer='spacer', status_bar='status',
|
||||
input_rule_top='top', image_bar=None, input_area='composer', input_rule_bot='bottom',
|
||||
voice_status_bar=None, completions_menu=None)
|
||||
assert children.index('dock') < children.index('status') < children.index('composer')
|
||||
|
||||
|
||||
def test_monitor_controls_recheck_ownership_and_keep_selection(monkeypatch):
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Monitor navigation and controls run without borrowing the chat composer."""
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
|
||||
|
||||
def test_monitor_keys_navigate_steer_and_preserve_chat_draft(monkeypatch):
|
||||
from hermes_cli.cli_subagent_monitor import SubagentMonitor, build_monitor_application
|
||||
from prompt_toolkit.buffer import Buffer
|
||||
from prompt_toolkit.input import create_pipe_input
|
||||
from prompt_toolkit.output import DummyOutput
|
||||
from tools import delegate_tool_registry as registry
|
||||
monkeypatch.setattr(registry, '_active_subagents', {})
|
||||
received = []
|
||||
child = SimpleNamespace(steer=lambda text: received.append(text) or True,
|
||||
interrupt=lambda *a, **kw: received.append('STOP') or True)
|
||||
for sid in ['first', 'second']:
|
||||
registry._register_subagent(dict(subagent_id=sid, goal=sid, owner_agent_session_id='owner',
|
||||
started_at=1, status='running', agent=child))
|
||||
composer = Buffer()
|
||||
composer.text = 'my unfinished draft'
|
||||
dock = SubagentMonitor(SimpleNamespace(agent=SimpleNamespace(session_id='owner')))
|
||||
dock.refresh()
|
||||
|
||||
async def run():
|
||||
with create_pipe_input() as pipe:
|
||||
app = build_monitor_application(dock, input=pipe, output=DummyOutput())
|
||||
task = asyncio.create_task(app.run_async())
|
||||
await asyncio.sleep(0.1)
|
||||
pipe.send_text('\x1b[B\rsFocus on tests\r')
|
||||
await asyncio.sleep(0.2)
|
||||
pipe.send_text('\x1b')
|
||||
await asyncio.sleep(0.6)
|
||||
pipe.send_text('q')
|
||||
await asyncio.wait_for(task, 3)
|
||||
asyncio.run(run())
|
||||
assert dock.selected_id == 'second'
|
||||
assert received == ['Focus on tests']
|
||||
assert composer.text == 'my unfinished draft'
|
||||
|
||||
|
||||
def test_extended_tail_is_bounded_and_literal(tmp_path):
|
||||
from hermes_cli.cli_subagent_monitor import read_tail
|
||||
path = tmp_path / 'child.log'
|
||||
path.write_text('old data\n' * 20000 + '\x1b[2Jlast activity\n', encoding='utf-8')
|
||||
tail = read_tail(str(path))
|
||||
assert 'last activity' in tail and '\x1b' not in tail
|
||||
assert len(tail) <= 32768
|
||||
assert 'not available' in read_tail(str(tmp_path / 'missing.log'))
|
||||
Reference in New Issue
Block a user