Subagent overview and detail view (ctrl-g) #114

Merged
hermes merged 1 commits from subagent-panel into main 2026-10-02 14:17:07 +00:00
5 changed files with 877 additions and 44 deletions

No files matched your search

+1 -1
View File
@@ -65,7 +65,7 @@ tests = "turn_end" # affected tests: turn_end | agent_end | off
## Subagents
The model can call `task(prompt, kind)` to run a subagent with a fresh context and get back only its final answer (cut at 8 KB), so big searches don't fill the main context. `explore` (default) is read-only (`read`, `lsp`, `bash`) on the provider's cheapest model (`explore_model` in config); `general` has the parent's tools and model, and the lens runs on its edits. Up to 3 run in parallel, none can start another, a parent abort stops them. Their sessions are written to `<session>.sub/`; `hx stats` lists them and the footer token counts include them. A child starts with a cold prompt cache and costs tokens of its own: it saves *main-context* size, not total tokens.
The model can call `task(prompt, kind)` to run a subagent with a fresh context and get back only its final answer (cut at 8 KB), so big searches don't fill the main context. `explore` (default) is read-only (`read`, `lsp`, `bash`) on the provider's cheapest model (`explore_model` in config); `general` has the parent's tools and model, and the lens runs on its edits. Up to 3 run in parallel, none can start another, a parent abort stops them. Their sessions are written to `<session>.sub/`; `hx stats` lists them and the footer token counts include them. **Overview:** while any subagent exists, a list sits above the footer (bottom right: spinner/✓, id, kind, task, time, calls, tokens). `ctrl-g` focuses it (`↑↓`, `enter` opens, `esc` closes); the detail view shows that agent's live transcript. Typing there messages the agent: while it runs the text is delivered at its next turn end (like steering the main agent), after it finished it continues that agent's conversation. `ctrl-c` aborts that agent only; `ctrl-s` sends its last answer to the main chat as `[subagent N] …`. NDJSON/RPC carry no per-agent events yet.\n\nA child starts with a cold prompt cache and costs tokens of its own: it saves *main-context* size, not total tokens.
## Skills
+2
View File
@@ -59,6 +59,8 @@ pub struct State {
pub abort: std::sync::OnceLock<tokio::sync::watch::Receiver<bool>>,
/// Tokens spent by subagents, drained into the agent's usage after each tool round.
pub sub_usage: Mutex<hx_ai::Usage>,
/// Subagents of this session (see [`subagent`]).
pub subs: subagent::Subs,
}
impl State {
+315 -39
View File
@@ -2,19 +2,21 @@
//!
//! `explore` is read-only research on a cheap model, `general` has the parent's tools. Children
//! share the parent's `State` (read-guard, usage counter, abort) and log to `<session>.sub/`.
//! Every child is also kept in [`Subs`] after it ends, so the UI can show it, queue a message
//! for it while it runs, or continue it afterwards.
use crate::agent::Agent;
use crate::hook::Hook;
use crate::agent::{Agent, Error};
use crate::hook::{Event, Hook, HookAction};
use crate::session::Session;
use crate::tool::{Registry, Tool, ToolCtx, ToolResult};
use async_trait::async_trait;
use hx_ai::{ContentBlock, Provider, ToolSpec};
use hx_ai::{Message, Provider, StreamEvent, ToolSpec, Usage};
use serde_json::{Value, json};
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::Instant;
use tokio::sync::Semaphore;
use tokio::sync::{Semaphore, mpsc};
/// Everything needed to start one kind of child.
pub struct Role {
@@ -32,10 +34,194 @@ pub struct Task {
/// hooks (lens) the `general` child runs with
pub hooks: Vec<Arc<dyn Hook>>,
pub max_turns: u32,
sem: Semaphore,
sem: Arc<Semaphore>,
n: AtomicUsize,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Status {
Running,
Done,
Failed(String),
Aborted,
}
/// What the UI reads while a child runs (everything behind std mutexes: readable from draw code).
pub struct Shared {
pub id: usize,
pub kind: &'static str,
pub model: String,
/// the first prompt
pub prompt: String,
pub started: Instant,
pub ended: Mutex<Option<Instant>>,
pub status: Mutex<Status>,
pub calls: AtomicUsize,
pub usage: Mutex<Usage>,
/// messages from the user, delivered at the child's next turn end
inbox: Mutex<Vec<String>>,
/// part of `usage` already added to `State::sub_usage`
rolled: Mutex<Usage>,
}
impl Shared {
pub fn status(&self) -> Status {
self.status
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone()
}
/// Run time so far, or total when finished.
pub fn elapsed(&self) -> std::time::Duration {
let end = *self.ended.lock().unwrap_or_else(|e| e.into_inner());
end.unwrap_or_else(Instant::now) - self.started
}
}
pub struct Sub {
pub sh: Arc<Shared>,
agent: tokio::sync::Mutex<Agent>,
abort: crate::agent::AbortHandle,
state: Arc<crate::State>,
sem: Arc<Semaphore>,
}
/// Every child of this session, oldest first, plus where their events go.
#[derive(Default)]
pub struct Subs {
list: Mutex<Vec<Arc<Sub>>>,
/// (child id, event) for the UI; set by interactive frontends
pub events: OnceLock<mpsc::UnboundedSender<(usize, Event)>>,
}
const KEEP: usize = 20;
impl Subs {
pub fn list(&self) -> Vec<Arc<Sub>> {
self.list.lock().unwrap_or_else(|e| e.into_inner()).clone()
}
pub fn get(&self, id: usize) -> Option<Arc<Sub>> {
self.list().into_iter().find(|s| s.sh.id == id)
}
fn add(&self, s: Arc<Sub>) {
let mut l = self.list.lock().unwrap_or_else(|e| e.into_inner());
l.push(s);
// drop the oldest finished children beyond KEEP (their session files stay)
while l.len() > KEEP {
match l.iter().position(|s| s.sh.status() != Status::Running) {
Some(i) => {
l.remove(i);
}
None => break,
}
}
}
}
fn diff(a: &Usage, b: &Usage) -> Usage {
Usage {
input_tokens: a.input_tokens.saturating_sub(b.input_tokens),
output_tokens: a.output_tokens.saturating_sub(b.output_tokens),
cache_read_tokens: a.cache_read_tokens.saturating_sub(b.cache_read_tokens),
cache_write_tokens: a.cache_write_tokens.saturating_sub(b.cache_write_tokens),
}
}
/// On the child's bus: counts, forwards events to the UI, delivers queued user messages.
struct Live(Arc<Shared>, Option<mpsc::UnboundedSender<(usize, Event)>>);
#[async_trait]
impl Hook for Live {
async fn on(&self, ev: &Event) -> HookAction {
match ev {
Event::ToolCall { .. } => {
self.0.calls.fetch_add(1, Ordering::Relaxed);
}
Event::Stream(StreamEvent::Done { usage, .. }) => {
self.0
.usage
.lock()
.unwrap_or_else(|e| e.into_inner())
.add(usage);
}
_ => {}
}
if let Some(tx) = &self.1 {
let _ = tx.send((self.0.id, ev.clone()));
}
if matches!(ev, Event::TurnEnd | Event::AgentEnd) {
let m = std::mem::take(&mut *self.0.inbox.lock().unwrap_or_else(|e| e.into_inner()));
if !m.is_empty() {
return HookAction::Inject(m.join("\n\n"));
}
}
HookAction::Continue
}
}
impl Sub {
pub fn abort(&self) {
self.abort.abort();
}
/// A message for this child: queued for its next turn end while it runs (like steering the
/// main agent); otherwise it continues the child's conversation in the background.
pub fn prompt(self: &Arc<Self>, text: String) {
{
let mut st = self.sh.status.lock().unwrap_or_else(|e| e.into_inner());
if *st == Status::Running {
self.sh
.inbox
.lock()
.unwrap_or_else(|e| e.into_inner())
.push(text);
return;
}
*st = Status::Running;
*self.sh.ended.lock().unwrap_or_else(|e| e.into_inner()) = None;
}
let me = self.clone();
tokio::spawn(async move {
let _permit = me.sem.acquire().await;
let _ = me.drive(text).await;
});
}
/// Run until done, then once more per message that arrived meanwhile; sets the final status.
async fn drive(&self, mut p: String) -> Result<Message, Error> {
let mut a = self.agent.lock().await;
loop {
let r = a.run(p).await;
let cur = a.usage().clone();
let delta = {
let mut rolled = self.sh.rolled.lock().unwrap_or_else(|e| e.into_inner());
let d = diff(&cur, &rolled);
*rolled = cur;
d
};
self.state
.sub_usage
.lock()
.unwrap_or_else(|e| e.into_inner())
.add(&delta);
let mut st = self.sh.status.lock().unwrap_or_else(|e| e.into_inner());
let pending =
std::mem::take(&mut *self.sh.inbox.lock().unwrap_or_else(|e| e.into_inner()));
if r.is_ok() && !pending.is_empty() {
p = pending.join("\n\n");
continue;
}
*st = match &r {
Ok(_) => Status::Done,
Err(Error::Aborted) => Status::Aborted,
Err(e) => Status::Failed(e.to_string()),
};
*self.sh.ended.lock().unwrap_or_else(|e| e.into_inner()) = Some(Instant::now());
return r;
}
}
}
/// Tools of a read-only child. ponytail: `bash` can still write; the prompt forbids it. Drop
/// `bash` for a search/grep tool if models ignore that.
pub const EXPLORE_TOOLS: &[&str] = &["read", "lsp", "bash"];
@@ -51,7 +237,7 @@ impl Task {
dir: dir.clone(),
hooks: vec![],
max_turns: 40,
sem: Semaphore::new(parallel.max(1)),
sem: Arc::new(Semaphore::new(parallel.max(1))),
// continue numbering when the session is resumed
n: AtomicUsize::new(std::fs::read_dir(&dir).map_or(0, |d| d.count())),
}
@@ -63,11 +249,11 @@ pub fn spec() -> ToolSpec {
ToolSpec {
name: "task".into(),
description: "Run a subagent in a fresh context; you get back only its final answer. kind=explore (default): read-only research on a cheaper model; use it for searching/reading that would fill your context (many files or >10k tokens). kind=general: same tools as you, may edit. The subagent sees nothing of this conversation: make the prompt self-contained. Several task calls in one turn run in parallel. Not for small lookups.".into(),
input_schema: json!({"type":"object","properties":{
"prompt":{"type":"string"},
"kind":{"type":"string","enum":["explore","general"]}},
"required":["prompt"]}),
}
input_schema: json!({"type":"object","properties":{
"prompt":{"type":"string"},
"kind":{"type":"string","enum":["explore","general"]}},
"required":["prompt"]}),
}
}
#[async_trait]
@@ -89,10 +275,8 @@ impl Tool for Task {
let Ok(_permit) = self.sem.acquire().await else {
return ToolResult::err("subagents unavailable");
};
let path = self.dir.join(format!(
"{:03}-{kind}.jsonl",
self.n.fetch_add(1, Ordering::Relaxed) + 1
));
let id = self.n.fetch_add(1, Ordering::Relaxed) + 1;
let path = self.dir.join(format!("{id:03}-{kind}.jsonl"));
let session = match Session::open(&path) {
Ok(s) => s,
Err(e) => return ToolResult::err(format!("subagent session: {e}")),
@@ -109,47 +293,59 @@ impl Tool for Task {
child.set_model(role.model.clone());
child.set_system(role.system.clone());
child.set_max_turns(self.max_turns);
let sh = Arc::new(Shared {
id,
kind,
model: role.model.clone(),
prompt: prompt.to_string(),
started: Instant::now(),
ended: Mutex::new(None),
status: Mutex::new(Status::Running),
calls: AtomicUsize::new(0),
usage: Mutex::default(),
inbox: Mutex::default(),
rolled: Mutex::default(),
});
child
.bus
.add(Live(sh.clone(), cx.state.subs.events.get().cloned()));
if kind == "general" {
for h in &self.hooks {
child.bus.add_arc(h.clone());
}
}
let sub = Arc::new(Sub {
sh: sh.clone(),
agent: tokio::sync::Mutex::new(child),
abort: handle,
state: cx.state.clone(),
sem: self.sem.clone(),
});
cx.state.subs.add(sub.clone());
// parent abort stops the child
let bridge = cx.state.abort.get().cloned().map(|mut rx| {
let s = sub.clone();
tokio::spawn(async move {
if rx.wait_for(|a| *a).await.is_ok() {
handle.abort();
s.abort();
}
})
});
let t0 = Instant::now();
// waiting for a slot may have outlasted an abort
let r = if aborted() {
Err(crate::agent::Error::Aborted)
} else {
child.run(prompt).await
};
if aborted() {
sub.abort();
}
let r = sub.drive(prompt.to_string()).await;
if let Some(b) = bridge {
b.abort();
}
let u = child.usage().clone();
cx.state
.sub_usage
.lock()
.unwrap_or_else(|e| e.into_inner())
.add(&u);
let calls: usize = child
.session()
.messages()
.iter()
.flat_map(|m| &m.content)
.filter(|b| matches!(b, ContentBlock::ToolUse { .. }))
.count();
let u = sh.usage.lock().unwrap_or_else(|e| e.into_inner()).clone();
let tok = u.input_tokens + u.cache_read_tokens + u.cache_write_tokens + u.output_tokens;
let stats = format!(
"[task {kind} · {calls} tool calls · {}k tok · {}s]",
"[task {kind} · {} tool calls · {}k tok · {}s]",
sh.calls.load(Ordering::Relaxed),
tok / 1000,
t0.elapsed().as_secs()
sh.elapsed().as_secs()
);
match r {
Ok(m) => {
@@ -173,7 +369,7 @@ impl Tool for Task {
mod tests {
use super::*;
use futures::{StreamExt, stream::BoxStream};
use hx_ai::{Message, Request, Role as R, StopReason, StreamEvent, Usage};
use hx_ai::{ContentBlock, Request, Role as R, StopReason};
use std::sync::Mutex;
/// Replays scripted assistant messages; records requests.
@@ -344,4 +540,84 @@ mod tests {
let r = t.call(json!({"prompt":"a"}), &cx).await;
assert!(r.is_error && r.content.contains("aborted"), "{r:?}");
}
#[tokio::test]
async fn registry_keeps_child_and_message_during_run_is_delivered_at_turn_end() {
let d = tempfile::tempdir().unwrap();
let p = Arc::new(Script(
Mutex::new(vec![call("read", json!({})), text("a"), text("b")]),
Default::default(),
));
let t = Task::new(
role(&p, "cheap"),
role(&p, "main"),
d.path().join("s.sub"),
3,
);
let cx = ToolCtx {
cwd: d.path().into(),
state: Default::default(),
};
let (tx, mut rx) = mpsc::unbounded_channel();
let _ = cx.state.subs.events.set(tx);
// queue a message while the child runs: the first Done event is a good "while running" point
let st = cx.state.clone();
let q = tokio::spawn(async move {
while let Some((id, ev)) = rx.recv().await {
if matches!(ev, Event::TurnStart) {
st.subs.get(id).unwrap().prompt("also check b".into());
return;
}
}
});
let r = t.call(json!({"prompt":"look"}), &cx).await;
q.await.unwrap();
assert!(!r.is_error, "{r:?}");
let subs = cx.state.subs.list();
assert_eq!(subs.len(), 1);
assert_eq!(subs[0].sh.status(), Status::Done);
assert_eq!(subs[0].sh.calls.load(Ordering::Relaxed), 1);
// the message reached the child's next request (after its tool round)
let reqs = p.1.lock().unwrap();
let last = &reqs.last().unwrap().messages;
assert!(
last.iter().any(|m| m.text().contains("also check b")),
"{last:?}"
);
}
#[tokio::test]
async fn prompting_a_finished_child_continues_it_and_rolls_up_usage() {
let d = tempfile::tempdir().unwrap();
let p = Arc::new(Script(
Mutex::new(vec![text("first"), text("second")]),
Default::default(),
));
let t = Task::new(
role(&p, "cheap"),
role(&p, "main"),
d.path().join("s.sub"),
3,
);
let cx = ToolCtx {
cwd: d.path().into(),
state: Default::default(),
};
t.call(json!({"prompt":"one"}), &cx).await;
let sub = cx.state.subs.get(1).unwrap();
assert_eq!(cx.state.sub_usage.lock().unwrap().input_tokens, 1000);
sub.prompt("two".into());
assert_eq!(sub.sh.status(), Status::Running);
for _ in 0..100 {
if sub.sh.status() == Status::Done {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
}
assert_eq!(sub.sh.status(), Status::Done);
// same conversation: second request carries the first exchange; only the delta was rolled up
let reqs = p.1.lock().unwrap();
assert_eq!(reqs[1].messages.len(), 3);
assert_eq!(cx.state.sub_usage.lock().unwrap().input_tokens, 2000);
}
}
+291
View File
@@ -0,0 +1,291 @@
//! Subagent overview (small list above the footer) and the per-agent detail view.
use crate::editor::Editor;
use crate::theme;
use crate::transcript::Transcript;
use hx_core::subagent::{Status, Sub};
use ratatui::layout::{Constraint, Layout};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Paragraph, Wrap};
use std::time::Duration;
/// What the list needs per agent (plain data, so rendering is testable).
#[derive(Clone, Debug, PartialEq)]
pub struct Row {
pub id: usize,
pub kind: &'static str,
pub prompt: String,
pub status: Status,
pub elapsed: Duration,
pub calls: usize,
pub tokens: u64,
}
pub fn row(s: &Sub) -> Row {
let u = s.sh.usage.lock().unwrap_or_else(|e| e.into_inner()).clone();
Row {
id: s.sh.id,
kind: s.sh.kind,
prompt: s.sh.prompt.lines().next().unwrap_or_default().to_string(),
status: s.sh.status(),
elapsed: s.sh.elapsed(),
calls: s.sh.calls.load(std::sync::atomic::Ordering::Relaxed),
tokens: u.input_tokens + u.cache_read_tokens + u.cache_write_tokens + u.output_tokens,
}
}
pub enum View {
/// list focused, selected index
List(usize),
Detail {
id: usize,
ed: Editor,
scroll: u16,
},
}
pub const MAX_ROWS: usize = 5;
fn dur(d: Duration) -> String {
match d.as_secs() {
s if s >= 60 => format!("{}m{:02}s", s / 60, s % 60),
s => format!("{s}s"),
}
}
fn glyph(s: &Status, frame: usize) -> &'static str {
let th = theme::t();
match s {
Status::Running if th.sym.ok == "+" => ["-", "\\", "|", "/"][frame % 4],
Status::Running => ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"][frame % 10],
Status::Done => th.sym.ok,
_ => th.sym.err,
}
}
/// Rows shown (the last `MAX_ROWS`, scrolled so `sel` is visible): `⠹ 1 explore grep auth 12s 8 calls`.
pub fn lines(rows: &[Row], sel: Option<usize>, frame: usize, width: u16) -> Vec<Line<'static>> {
let th = theme::t();
let w = width as usize;
let first = sel
.map_or(rows.len(), |s| s + 1)
.max(MAX_ROWS)
.min(rows.len())
.saturating_sub(MAX_ROWS);
rows.iter()
.enumerate()
.skip(first)
.take(MAX_ROWS)
.map(|(i, r)| {
let tail = format!(" {} {}c {}k", dur(r.elapsed), r.calls, r.tokens / 1000);
let head = format!("{} {} {:<7} ", glyph(&r.status, frame), r.id, r.kind);
let room = w.saturating_sub(head.chars().count() + tail.chars().count());
let mut p: String = r.prompt.chars().take(room).collect();
if r.prompt.chars().count() > room && room > 0 {
p.pop();
p.push('…');
}
let pad = " ".repeat(room.saturating_sub(p.chars().count()));
let st = if sel == Some(i) {
th.sel()
} else {
match r.status {
Status::Running => th.plain(),
Status::Done => th.dim(),
_ => th.err(),
}
};
Line::from(vec![Span::styled(format!("{head}{p}{pad}{tail}"), st)])
})
.collect()
}
pub fn list_height(n: usize) -> u16 {
n.min(MAX_ROWS) as u16
}
/// Last assistant text of an agent's transcript, for ctrl-s.
pub fn last_answer(t: &Transcript) -> Option<String> {
t.items.iter().rev().find_map(|i| match i {
crate::transcript::Item::Assistant(s) if !s.trim().is_empty() => Some(s.clone()),
_ => None,
})
}
pub fn help(running: bool) -> &'static str {
if running {
"enter queue for next turn · ctrl-s to main chat · ctrl-c abort agent · esc back"
} else {
"enter continue agent · ctrl-s to main chat · esc back"
}
}
/// Full-screen view of one agent: header, its transcript, input, help.
pub struct Detail<'a> {
pub row: &'a Row,
pub model: &'a str,
pub t: &'a Transcript,
pub ed: &'a Editor,
pub expanded: bool,
pub frame: usize,
}
pub fn draw_detail(f: &mut ratatui::Frame, d: &Detail, scroll: &mut u16) {
let Detail {
row: r,
model,
t,
ed,
expanded,
frame,
} = *d;
let th = theme::t();
let input_h = ed.buf.lines().count().clamp(1, 8) as u16 + 2;
let [head, body, input, foot] = Layout::vertical([
Constraint::Length(1),
Constraint::Min(3),
Constraint::Length(input_h),
Constraint::Length(1),
])
.areas(f.area());
f.render_widget(
Line::from(vec![
Span::styled(
format!(
"{} agent {} · {} · {model}",
glyph(&r.status, frame),
r.id,
r.kind
),
th.accent(),
),
Span::styled(
format!(
" · {:?} {} · {} calls · {}k tok",
r.status,
dur(r.elapsed),
r.calls,
r.tokens / 1000
)
.replace("Running", "running")
.replace("Done", "done"),
th.dim(),
),
]),
head,
);
let para = Paragraph::new(t.lines(expanded, body.width)).wrap(Wrap { trim: false });
let total = para.line_count(body.width) as u16;
let max_up = total.saturating_sub(body.height);
*scroll = (*scroll).min(max_up);
f.render_widget(para.scroll((max_up - *scroll, 0)), body);
let block = Block::default()
.borders(Borders::TOP | Borders::BOTTOM)
.border_style(th.dim());
let inner = block.inner(input);
f.render_widget(block, input);
let (row, col) = ed.cursor_rc();
let skip = (row as u16).saturating_sub(inner.height.saturating_sub(1));
if ed.buf.is_empty() {
let hint = if r.status == Status::Running {
"message the agent (delivered at its next turn end)"
} else {
"prompt the agent to continue"
};
f.render_widget(Span::styled(hint, th.dim()), inner);
} else {
f.render_widget(Paragraph::new(ed.buf.as_str()).scroll((skip, 0)), inner);
}
f.set_cursor_position((inner.x + col as u16, inner.y + row as u16 - skip));
f.render_widget(
Span::styled(help(r.status == Status::Running), th.dim()),
foot,
);
}
#[cfg(test)]
mod tests {
use super::*;
fn r(id: usize, st: Status) -> Row {
Row {
id,
kind: "explore",
prompt: "grep the auth middleware for token expiry checks".into(),
status: st,
elapsed: Duration::from_secs(72),
calls: 8,
tokens: 41_000,
}
}
fn text(l: &Line) -> String {
l.spans.iter().map(|s| s.content.to_string()).collect()
}
#[test]
fn rows_fit_width_and_show_status() {
let v = vec![r(1, Status::Running), r(2, Status::Done)];
for w in [40u16, 60, 100] {
for l in lines(&v, None, 0, w) {
assert_eq!(l.width(), w as usize, "{}", text(&l));
}
}
let l = lines(&v, None, 0, 60);
assert!(text(&l[0]).starts_with("⠋ 1 explore ") && text(&l[0]).ends_with(" 1m12s 8c 41k"));
assert!(text(&l[1]).starts_with("✓ 2 explore "), "{}", text(&l[1]));
assert!(text(&l[0]).contains('…'));
}
#[test]
fn only_last_five_and_selection_stays_visible() {
let v: Vec<Row> = (1..=8).map(|i| r(i, Status::Done)).collect();
let ids = |l: Vec<Line>| {
l.iter()
.map(|x| text(x).chars().nth(2).unwrap().to_string())
.collect::<Vec<_>>()
};
assert_eq!(ids(lines(&v, None, 0, 60)), ["4", "5", "6", "7", "8"]);
assert_eq!(ids(lines(&v, Some(0), 0, 60)), ["1", "2", "3", "4", "5"]);
assert_eq!(ids(lines(&v, Some(6), 0, 60)), ["3", "4", "5", "6", "7"]);
}
#[test]
fn detail_renders_header_transcript_and_input() {
use crate::transcript::Item;
let mut t = Transcript::default();
t.push(Item::User("find it".into()));
t.push(Item::Assistant("found in src/a.rs".into()));
let mut ed = Editor::default();
ed.insert("and then?");
let mut sc = 0;
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(80, 12)).unwrap();
let row = r(3, Status::Running);
let d = Detail {
row: &row,
model: "haiku",
t: &t,
ed: &ed,
expanded: false,
frame: 0,
};
term.draw(|f| draw_detail(f, &d, &mut sc)).unwrap();
let b = term.backend().buffer().clone();
let rows: Vec<String> = (0..12)
.map(|y| (0..80).map(|x| b[(x, y)].symbol().to_string()).collect())
.collect();
assert!(
rows[0].contains("agent 3 · explore · haiku") && rows[0].contains("running 1m12s"),
"{}",
rows[0]
);
let all = rows.join("\n");
assert!(
all.contains("find it")
&& all.contains("found in src/a.rs")
&& all.contains("and then?"),
"{all}"
);
assert!(rows[11].contains("queue for next turn"));
assert_eq!(last_answer(&t).as_deref(), Some("found in src/a.rs"));
}
}
+268 -4
View File
@@ -1,5 +1,6 @@
//! Interactive terminal UI.
pub mod agents;
pub mod choose;
pub mod editor;
pub mod picker;
@@ -126,6 +127,12 @@ struct App {
choose::Choose,
tokio::sync::oneshot::Sender<Option<Vec<String>>>,
)>,
/// shared agent state: the subagent registry lives in it
state: Arc<hx_core::State>,
/// transcripts of subagents, fed by their events
sub_t: std::collections::HashMap<usize, Transcript>,
/// subagent list focused / one agent open
agents: Option<agents::View>,
}
impl App {
@@ -144,7 +151,7 @@ impl App {
}
}
const KEYS: &str = "enter send · alt-enter/ctrl-j newline · esc/ctrl-c abort · ctrl-o expand · pgup/pgdn scroll · \
const KEYS: &str = "ctrl-g agents · enter send · alt-enter/ctrl-j newline · esc/ctrl-c abort · ctrl-o expand · pgup/pgdn scroll · \
tab complete @file / command";
const PLACEHOLDER: &str = "/ commands · @ files · ctrl-p picker · /help keys";
/// Columns from which listings go to a side panel.
@@ -212,6 +219,8 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
Box::pin(async move { orx.await.unwrap_or(None) })
}));
}
let (stx, mut srx) = mpsc::unbounded_channel();
let _ = agent.cx.state.subs.events.set(stx);
let abort: AbortHandle = agent.abort_handle();
let cwd = agent.cx.cwd.clone();
let mut app = App {
@@ -246,6 +255,9 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
ask: None,
lens: (String::new(), false),
choose: None,
state: agent.cx.state.clone(),
sub_t: Default::default(),
agents: None,
};
sessions::history(&mut app.t, &agent.session().messages());
if open_sessions {
@@ -357,7 +369,17 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
}
}
}
_ = tick.tick(), if app.busy => dirty = true,
Some((id, ev)) = srx.recv() => {
dirty = true;
let t = app.sub_t.entry(id).or_default();
if t.items.is_empty()
&& let Some(s) = app.state.subs.get(id)
{
t.push(Item::User(s.sh.prompt.clone()));
}
t.apply(&ev);
}
_ = tick.tick(), if app.busy || subs_running(&app) => dirty = true,
_ = lens_tick.tick() => {
// short timeout: the manager lock can be held while a server starts
let to = std::time::Duration::from_millis(200);
@@ -425,6 +447,95 @@ fn switch_session(app: &mut App, a: &mut Agent, sess: hx_core::session::Session)
}
/// Picker keys. Returns a line to submit when an entry runs.
fn subs_running(app: &App) -> bool {
app.state
.subs
.list()
.iter()
.any(|s| s.sh.status() == hx_core::subagent::Status::Running)
}
/// Keys while the agent list or an agent's detail view has focus.
fn agents_key(app: &mut App, k: KeyEvent) -> Option<String> {
let ctrl = k.modifiers.contains(KeyModifiers::CONTROL);
let subs = app.state.subs.list();
match app.agents.as_mut()? {
agents::View::List(sel) => {
*sel = (*sel).min(subs.len().saturating_sub(1));
match k.code {
KeyCode::Up | KeyCode::Char('k') => *sel = sel.saturating_sub(1),
KeyCode::Down | KeyCode::Char('j') => {
*sel = (*sel + 1).min(subs.len().saturating_sub(1));
}
KeyCode::Enter => {
if let Some(s) = subs.get(*sel) {
app.agents = Some(agents::View::Detail {
id: s.sh.id,
ed: Editor::default(),
scroll: 0,
});
}
}
KeyCode::Esc | KeyCode::Char('q') => app.agents = None,
_ => {}
}
}
agents::View::Detail { id, ed, scroll } => {
let sub = subs.iter().find(|s| s.sh.id == *id);
match k.code {
KeyCode::Esc => app.agents = None,
KeyCode::Char('c') if ctrl => {
if let Some(s) = sub {
s.abort();
}
}
KeyCode::Char('s') if ctrl => {
if let Some(a) = app.sub_t.get(id).and_then(agents::last_answer) {
let line = format!("[subagent {id}] {a}");
app.agents = None;
return Some(line);
}
app.hint = "agent has no answer yet".into();
}
KeyCode::Char('o') if ctrl => app.expanded = !app.expanded,
KeyCode::Char('j') if ctrl => ed.insert("\n"),
KeyCode::Enter
if k.modifiers
.intersects(KeyModifiers::ALT | KeyModifiers::SHIFT) =>
{
ed.insert("\n");
}
KeyCode::Enter => {
if let Action::Submit(text) = ed.submit()
&& let Some(s) = sub
{
app.sub_t
.entry(*id)
.or_default()
.push(Item::User(text.clone()));
s.prompt(text);
}
}
KeyCode::Char('u') if ctrl => ed.kill_line(),
KeyCode::Char('w') if ctrl => ed.kill_word(),
KeyCode::Char(c) if !ctrl => ed.insert(c.encode_utf8(&mut [0; 4])),
KeyCode::Backspace => ed.backspace(),
KeyCode::Delete => ed.delete(),
KeyCode::Left => ed.left(),
KeyCode::Right => ed.right(),
KeyCode::Home => ed.home(),
KeyCode::End => ed.end(),
KeyCode::Up => ed.up(),
KeyCode::Down => ed.down(),
KeyCode::PageUp => *scroll = scroll.saturating_add(10),
KeyCode::PageDown => *scroll = scroll.saturating_sub(10),
_ => {}
}
}
}
None
}
fn picker_key(app: &mut App, k: KeyEvent) -> Option<String> {
match app.picker.as_mut()?.key(k) {
picker::Act::None => None,
@@ -464,6 +575,21 @@ fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option<String> {
if app.sessions.is_some() {
return sessions_key(app, k);
}
if ctrl && k.code == KeyCode::Char('g') {
app.popup = None;
app.agents = match (app.agents.take(), app.state.subs.list().len()) {
(_, 0) => {
app.hint = "no subagents yet".into();
None
}
(None, n) => Some(agents::View::List(n - 1)),
(Some(_), _) => None,
};
return None;
}
if app.agents.is_some() {
return agents_key(app, k);
}
if app.picker.is_some() {
return picker_key(app, k);
}
@@ -561,6 +687,14 @@ fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option<String> {
None
}
/// Footer hint while the agent list has focus, else the transient hint.
fn agents_hint(app: &App) -> &str {
match app.agents {
Some(agents::View::List(_)) => "↑↓ select · enter open · esc close",
_ => &app.hint,
}
}
fn completion(app: &App) -> Completion {
cmd::complete(&app.ed.buf, app.ed.cur, &app.specs, &app.files)
}
@@ -766,9 +900,35 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
+ 2;
let act_h = u16::from(app.busy);
app.wide = f.area().width >= WIDE;
if let Some(agents::View::Detail { id, ed, scroll }) = &mut app.agents {
let subs = app.state.subs.list();
if let Some(s) = subs.iter().find(|s| s.sh.id == *id) {
let t = app.sub_t.entry(*id).or_default();
let row = agents::row(s);
let d = agents::Detail {
row: &row,
model: &s.sh.model,
t,
ed,
expanded: app.expanded,
frame: (app.since.elapsed().as_millis() / 80) as usize,
};
agents::draw_detail(f, &d, scroll);
return;
}
app.agents = None;
}
let sub_rows: Vec<agents::Row> = app
.state
.subs
.list()
.iter()
.map(|s| agents::row(s))
.collect();
let foot_h = status::rows_for(f.area().width, app.ask.is_some());
let [main, act, input, status_row] = Layout::vertical([
let [main, subs_area, act, input, status_row] = Layout::vertical([
Constraint::Min(3),
Constraint::Length(agents::list_height(sub_rows.len())),
Constraint::Length(act_h),
Constraint::Length(input_h),
Constraint::Length(foot_h),
@@ -800,6 +960,21 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
app.scroll = app.scroll.min(max_up);
f.render_widget(para.scroll((max_up - app.scroll, 0)), main);
if !sub_rows.is_empty() {
let w = subs_area.width.min(56);
let sel = match &app.agents {
Some(agents::View::List(s)) => Some((*s).min(sub_rows.len() - 1)),
_ => None,
};
let frame = (app.since.elapsed().as_millis() / 80) as usize;
let r = Rect::new(
subs_area.x + subs_area.width - w,
subs_area.y,
w,
subs_area.height,
);
f.render_widget(Paragraph::new(agents::lines(&sub_rows, sel, frame, w)), r);
}
if app.busy {
let (what, t0) = app.t.running().unwrap_or(("thinking…".into(), app.since));
let frame = (app.since.elapsed().as_millis() / 80) as usize;
@@ -828,7 +1003,10 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
}
let chrome = status::Chrome {
ask: app.ask.as_ref().map(|(q, _)| q.as_str()),
hint: app.choose.as_ref().map_or(&app.hint, |(c, _)| c.help()),
hint: app
.choose
.as_ref()
.map_or_else(|| agents_hint(app), |(c, _)| c.help()),
queued: app.queue.len(),
scroll: app.scroll,
title: app.title.as_deref(),
@@ -966,6 +1144,89 @@ mod tests {
assert!(rows[9].ends_with("Claude · m1"), "{all}");
}
#[tokio::test]
async fn ctrl_g_opens_agents_list_detail_and_back() {
use hx_core::tool::{Tool, ToolCtx};
let mut app = test_app();
let ctrl_g = || KeyEvent::new(KeyCode::Char('g'), KeyModifiers::CONTROL);
let ab = AbortHandle::detached();
on_key(&mut app, ctrl_g(), &ab);
assert_eq!(
(app.hint.as_str(), app.agents.is_none()),
("no subagents yet", true)
);
// register one finished child through the real tool
struct P;
#[async_trait::async_trait]
impl Provider for P {
async fn stream(
&self,
_: hx_ai::Request,
) -> hx_ai::Result<futures::stream::BoxStream<'static, hx_ai::Result<hx_ai::StreamEvent>>>
{
use futures::StreamExt;
let m = hx_ai::Message {
role: hx_ai::Role::Assistant,
content: vec![hx_ai::ContentBlock::Text {
text: "answer".into(),
}],
};
Ok(futures::stream::iter(vec![Ok(hx_ai::StreamEvent::Done {
message: m,
stop: hx_ai::StopReason::EndTurn,
usage: Usage::default(),
})])
.boxed())
}
}
let d = tempfile::tempdir().unwrap();
let role = || hx_core::subagent::Role {
provider: Arc::new(P),
model: "m".into(),
tools: Default::default(),
system: String::new(),
};
let task = hx_core::subagent::Task::new(role(), role(), d.path().join("s.sub"), 1);
let cx = ToolCtx {
cwd: d.path().into(),
state: app.state.clone(),
};
task.call(serde_json::json!({"prompt": "find x"}), &cx)
.await;
on_key(&mut app, ctrl_g(), &ab);
assert!(matches!(app.agents, Some(agents::View::List(0))));
key(&mut app, KeyCode::Enter);
assert!(matches!(
app.agents,
Some(agents::View::Detail { id: 1, .. })
));
// typing goes to the agent's editor, not the main one
key(&mut app, KeyCode::Char('h'));
assert!(app.ed.buf.is_empty());
key(&mut app, KeyCode::Esc);
assert!(app.agents.is_none());
// ctrl-g in the list closes it again
on_key(&mut app, ctrl_g(), &ab);
on_key(&mut app, ctrl_g(), &ab);
assert!(app.agents.is_none());
// the overview row is drawn bottom right
let mut term = ratatui::Terminal::new(TestBackend::new(100, 12)).unwrap();
term.draw(|f| draw(f, &mut app)).unwrap();
let b = term.backend().buffer().clone();
let all: String = (0..12)
.map(|y| {
(0..100)
.map(|x| b[(x, y)].symbol().to_string())
.collect::<String>()
+ "\n"
})
.collect();
assert!(
all.contains("✓ 1 explore") && all.contains("find x"),
"{all}"
);
}
fn key(app: &mut App, code: KeyCode) -> Option<String> {
on_key(
app,
@@ -1012,6 +1273,9 @@ mod tests {
ask: None,
lens: (String::new(), false),
choose: None,
state: Default::default(),
sub_t: Default::default(),
agents: None,
}
}