feat(subagent): implement visibility management for completed and running tools in SubAgentWidget
This commit is contained in:
@@ -11,6 +11,10 @@ from .tool_call_widget import ToolCallWidget
|
||||
|
||||
_SPINNER_FRAMES = "\u280b\u2819\u2839\u2838\u283c\u2834\u2826\u2827\u2807\u280f"
|
||||
|
||||
# Keep in sync with display.py MAX_SA_VISIBLE / MAX_SA_RUNNING
|
||||
_MAX_VISIBLE_COMPLETED = 3
|
||||
_MAX_VISIBLE_RUNNING = 2
|
||||
|
||||
|
||||
class SubAgentWidget(Vertical):
|
||||
"""Displays a sub-agent's activity with a bordered frame.
|
||||
@@ -18,6 +22,7 @@ class SubAgentWidget(Vertical):
|
||||
Active state::
|
||||
|
||||
┌ ▶ Cooking with research-agent — Search literature ─┐
|
||||
│ ✓ 8 completed │
|
||||
│ ● tavily_search query="LLM attention" │
|
||||
│ ✓ 3 results │
|
||||
└─────────────────────────────────────────────────────┘
|
||||
@@ -40,6 +45,14 @@ class SubAgentWidget(Vertical):
|
||||
height: auto;
|
||||
padding: 0 0 0 2;
|
||||
}
|
||||
SubAgentWidget .sa-collapse-summary {
|
||||
height: auto;
|
||||
padding: 0 0 0 2;
|
||||
display: none;
|
||||
}
|
||||
SubAgentWidget .sa-collapse-summary.--visible {
|
||||
display: block;
|
||||
}
|
||||
SubAgentWidget .sa-footer {
|
||||
height: auto;
|
||||
color: #22d3ee;
|
||||
@@ -61,6 +74,9 @@ class SubAgentWidget(Vertical):
|
||||
self._tool_count = 0
|
||||
self._timer_handle = None
|
||||
self._tool_widgets: dict[str, ToolCallWidget] = {}
|
||||
# Ordered lists to track completed / running tools for collapsing
|
||||
self._completed_ids: list[str] = []
|
||||
self._running_ids: list[str] = []
|
||||
|
||||
@property
|
||||
def sa_name(self) -> str:
|
||||
@@ -78,6 +94,7 @@ class SubAgentWidget(Vertical):
|
||||
|
||||
def compose(self):
|
||||
yield Static("", classes="sa-header")
|
||||
yield Static("", classes="sa-collapse-summary")
|
||||
yield Vertical(classes="sa-tools")
|
||||
yield Static("", classes="sa-footer")
|
||||
|
||||
@@ -145,8 +162,10 @@ class SubAgentWidget(Vertical):
|
||||
w = ToolCallWidget(tool_name, tool_args, tool_id)
|
||||
tools_container = self.query_one(".sa-tools", Vertical)
|
||||
await tools_container.mount(w)
|
||||
if tool_id:
|
||||
self._tool_widgets[tool_id] = w
|
||||
key = tool_id or f"_anon_{self._tool_count}"
|
||||
self._tool_widgets[key] = w
|
||||
self._running_ids.append(key)
|
||||
self._update_visibility()
|
||||
return w
|
||||
|
||||
def complete_tool(
|
||||
@@ -158,13 +177,16 @@ class SubAgentWidget(Vertical):
|
||||
) -> None:
|
||||
"""Update the matching ToolCallWidget with its result."""
|
||||
widget = None
|
||||
matched_key = ""
|
||||
if tool_id and tool_id in self._tool_widgets:
|
||||
widget = self._tool_widgets[tool_id]
|
||||
matched_key = tool_id
|
||||
else:
|
||||
# Match by name — find first running tool with this name
|
||||
for w in self._tool_widgets.values():
|
||||
for key, w in self._tool_widgets.items():
|
||||
if w.tool_name == tool_name and w._status == "running":
|
||||
widget = w
|
||||
matched_key = key
|
||||
break
|
||||
if widget is None:
|
||||
# Fallback: find any running tool
|
||||
@@ -173,6 +195,11 @@ class SubAgentWidget(Vertical):
|
||||
if isinstance(child, ToolCallWidget) and child._status == "running":
|
||||
if child.tool_name == tool_name:
|
||||
widget = child
|
||||
# Find the key for this widget
|
||||
for key, w in self._tool_widgets.items():
|
||||
if w is widget:
|
||||
matched_key = key
|
||||
break
|
||||
break
|
||||
|
||||
if widget is not None:
|
||||
@@ -180,6 +207,73 @@ class SubAgentWidget(Vertical):
|
||||
widget.set_success(content)
|
||||
else:
|
||||
widget.set_error(content)
|
||||
# Move from running to completed
|
||||
if matched_key and matched_key in self._running_ids:
|
||||
self._running_ids.remove(matched_key)
|
||||
if matched_key:
|
||||
self._completed_ids.append(matched_key)
|
||||
self._update_visibility()
|
||||
|
||||
def _update_visibility(self) -> None:
|
||||
"""Hide older completed tools, keep recent ones visible.
|
||||
|
||||
Mirrors the Rich display.py collapsing logic:
|
||||
- At most ``_MAX_VISIBLE_COMPLETED`` completed tools shown
|
||||
(fewer if running tools take up slots).
|
||||
- At most ``_MAX_VISIBLE_RUNNING`` running tools shown.
|
||||
"""
|
||||
# Determine how many completed slots are available
|
||||
running_visible = self._running_ids[-_MAX_VISIBLE_RUNNING:]
|
||||
completed_slots = max(0, _MAX_VISIBLE_COMPLETED - len(running_visible))
|
||||
completed_visible = self._completed_ids[-completed_slots:] if completed_slots else []
|
||||
completed_hidden = self._completed_ids[:-completed_slots] if completed_slots and len(self._completed_ids) > completed_slots else (self._completed_ids if not completed_slots else [])
|
||||
|
||||
# Running tools to hide
|
||||
running_hidden = self._running_ids[:-_MAX_VISIBLE_RUNNING] if len(self._running_ids) > _MAX_VISIBLE_RUNNING else []
|
||||
|
||||
# Apply visibility
|
||||
visible_keys = set(completed_visible) | set(running_visible)
|
||||
hidden_keys = set(completed_hidden) | set(running_hidden)
|
||||
|
||||
for key in visible_keys:
|
||||
w = self._tool_widgets.get(key)
|
||||
if w is not None:
|
||||
w.display = True
|
||||
|
||||
for key in hidden_keys:
|
||||
w = self._tool_widgets.get(key)
|
||||
if w is not None:
|
||||
w.display = False
|
||||
|
||||
# Update collapse summary
|
||||
total_hidden = len(completed_hidden)
|
||||
hidden_running_count = len(running_hidden)
|
||||
|
||||
summary_w = self.query_one(".sa-collapse-summary", Static)
|
||||
if total_hidden > 0 or hidden_running_count > 0:
|
||||
line = Text()
|
||||
if total_hidden > 0:
|
||||
# Count successes/failures among hidden completed
|
||||
ok = 0
|
||||
fail = 0
|
||||
for key in completed_hidden:
|
||||
w = self._tool_widgets.get(key)
|
||||
if w is not None:
|
||||
if w._status == "error":
|
||||
fail += 1
|
||||
else:
|
||||
ok += 1
|
||||
line.append(f"\u2713 {ok} completed", style="dim green")
|
||||
if fail > 0:
|
||||
line.append(f" | {fail} failed", style="dim red")
|
||||
if hidden_running_count > 0:
|
||||
if total_hidden > 0:
|
||||
line.append(" | ", style="dim")
|
||||
line.append(f"\u25cf {hidden_running_count} more running...", style="dim yellow")
|
||||
summary_w.update(line)
|
||||
summary_w.add_class("--visible")
|
||||
else:
|
||||
summary_w.remove_class("--visible")
|
||||
|
||||
def finalize(self) -> None:
|
||||
"""Mark sub-agent as completed and stop all nested timers."""
|
||||
|
||||
@@ -14,6 +14,7 @@ from rich.console import Console, Group # type: ignore[import-untyped]
|
||||
from rich.live import Live # type: ignore[import-untyped]
|
||||
from rich.markdown import Markdown # type: ignore[import-untyped]
|
||||
from rich.panel import Panel # type: ignore[import-untyped]
|
||||
from rich.spinner import Spinner # type: ignore[import-untyped]
|
||||
from rich.text import Text # type: ignore[import-untyped]
|
||||
|
||||
from ..paths import resolve_virtual_path
|
||||
@@ -221,6 +222,8 @@ def _render_subagent_section(sa: 'SubAgentState', compact: bool = False) -> list
|
||||
return elements
|
||||
|
||||
# --- Full mode: bordered section for Live streaming ---
|
||||
MAX_SA_VISIBLE = 3 # max completed tools shown
|
||||
MAX_SA_RUNNING = 2 # max running tools shown
|
||||
|
||||
# Header
|
||||
header = Text()
|
||||
@@ -231,8 +234,21 @@ def _render_subagent_section(sa: 'SubAgentState', compact: bool = False) -> list
|
||||
header.append(f"\u2713 {display_name}", style="bold green")
|
||||
elements.append(header)
|
||||
|
||||
# Show every tool call with its status
|
||||
for tc, tr in completed:
|
||||
# Completed tools — collapse older ones into a summary
|
||||
slots = max(0, MAX_SA_VISIBLE - len(pending))
|
||||
hidden = completed[:-slots] if slots and len(completed) > slots else (completed if not slots else [])
|
||||
visible = completed[-slots:] if slots else []
|
||||
|
||||
if hidden:
|
||||
ok = sum(1 for _, tr in hidden if tr.get("success", True))
|
||||
fail = len(hidden) - ok
|
||||
summary = Text("\u2502 ", style=BORDER)
|
||||
summary.append(f"\u2713 {ok} completed", style="dim green")
|
||||
if fail > 0:
|
||||
summary.append(f" | {fail} failed", style="dim red")
|
||||
elements.append(summary)
|
||||
|
||||
for tc, tr in visible:
|
||||
tc_line = Text("\u2502 ", style=BORDER)
|
||||
tc_name = format_tool_compact(tc["name"], tc.get("args"))
|
||||
if tr.get("success", True):
|
||||
@@ -249,7 +265,14 @@ def _render_subagent_section(sa: 'SubAgentState', compact: bool = False) -> list
|
||||
continue
|
||||
elements.append(tc_line)
|
||||
|
||||
# Pending/running tools
|
||||
# Pending/running tools — limit visible
|
||||
hidden_running = len(pending) - MAX_SA_RUNNING
|
||||
if hidden_running > 0:
|
||||
run_summary = Text("\u2502 ", style=BORDER)
|
||||
run_summary.append(f"\u25cf {hidden_running} more running...", style="dim yellow")
|
||||
elements.append(run_summary)
|
||||
pending = pending[-MAX_SA_RUNNING:]
|
||||
|
||||
for tc in pending:
|
||||
tc_line = Text("\u2502 ", style=BORDER)
|
||||
tc_name = format_tool_compact(tc["name"], tc.get("args"))
|
||||
@@ -339,7 +362,7 @@ def create_streaming_display(
|
||||
|
||||
# Initial waiting state
|
||||
if is_waiting and not thinking_text and not response_text and not tool_calls:
|
||||
elements.append(Text("Thinking...", style="cyan"))
|
||||
elements.append(Spinner("dots", text=" Thinking...", style="cyan"))
|
||||
return Group(*elements)
|
||||
|
||||
# Thinking panel
|
||||
@@ -420,7 +443,7 @@ def create_streaming_display(
|
||||
|
||||
for tc, tr in running_regular:
|
||||
elements.append(_render_tool_call_line(tc, tr))
|
||||
elements.append(Text(" Running...", style="yellow"))
|
||||
elements.append(Spinner("dots", text=" Running...", style="yellow"))
|
||||
|
||||
# Task tool calls are rendered as part of sub-agent sections below
|
||||
|
||||
@@ -466,7 +489,7 @@ def create_streaming_display(
|
||||
# Check if any sub-agent is active
|
||||
any_active = any(sa.is_active for sa in subagents)
|
||||
if not any_active:
|
||||
elements.append(Text(" Analyzing results...", style="cyan"))
|
||||
elements.append(Spinner("dots", text=" Analyzing results...", style="cyan"))
|
||||
|
||||
# Final response -- render as streaming Markdown whenever all tools are done.
|
||||
# The Live display is transient; display_final_results() re-renders the
|
||||
@@ -635,9 +658,6 @@ def _run_streaming(
|
||||
|
||||
async def _consume() -> None:
|
||||
nonlocal _thinking_sent, _todo_sent
|
||||
# Manual refresh pacing: max 10Hz (every 100ms)
|
||||
refresh_interval = 0.1
|
||||
last_refresh = 0.0
|
||||
async for event in stream_agent_events(agent, message, thread_id, metadata=metadata):
|
||||
event_type = state.handle_event(event)
|
||||
|
||||
@@ -709,10 +729,6 @@ def _run_streaming(
|
||||
**state.get_display_args(),
|
||||
show_thinking=show_thinking,
|
||||
))
|
||||
now = loop.time()
|
||||
if now - last_refresh >= refresh_interval:
|
||||
live.refresh()
|
||||
last_refresh = now
|
||||
|
||||
with Live(console=console, auto_refresh=False, transient=True) as live:
|
||||
live.update(create_streaming_display(is_waiting=True))
|
||||
@@ -721,8 +737,28 @@ def _run_streaming(
|
||||
except RuntimeError:
|
||||
# No current event loop
|
||||
loop = _create_event_loop()
|
||||
loop.run_until_complete(_consume())
|
||||
live.refresh()
|
||||
|
||||
async def _run_with_refresh() -> None:
|
||||
async def _periodic_refresh() -> None:
|
||||
try:
|
||||
while True:
|
||||
await asyncio.sleep(0.1)
|
||||
live.refresh()
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
|
||||
refresh_task = asyncio.ensure_future(_periodic_refresh())
|
||||
try:
|
||||
await _consume()
|
||||
finally:
|
||||
refresh_task.cancel()
|
||||
try:
|
||||
await refresh_task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
live.refresh()
|
||||
|
||||
loop.run_until_complete(_run_with_refresh())
|
||||
|
||||
# Flush any remaining thinking that wasn't sent during streaming
|
||||
if on_thinking and not _thinking_sent and state.thinking_text:
|
||||
|
||||
Reference in New Issue
Block a user