4 Commits
Author SHA1 Message Date
johannes 6048a037ac Merge branch 'worktree-fix-abort-tools'
build / version (push) Successful in 31s
build / build (aarch64-apple-darwin) (push) Successful in 4m45s
build / build (x86_64-unknown-linux-musl) (push) Successful in 4m56s
build / release (push) Successful in 36s
2026-11-21 18:59:04 +01:00
johannesandClaude Sonnet 5.5 8f0de9465d fix: abort stops running tool calls and kills bash process group
Race the tool round against abort, check abort before starting tools,
answer pending calls with an aborted result, deny permission prompts on
abort, and kill the bash process group on drop.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-21 18:58:42 +01:00
johannesandClaude Sonnet 5.5 2166ef535b feat: card-style status side panel (model, models run, LSP, MCP, tests, session log)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-21 18:58:37 +01:00
gitea-actions 951b69837a ci: bin.json v0.2.5 2026-11-21 12:53:38 +00:00
7 changed files with 948 additions and 156 deletions

No files matched your search

+3 -3
View File
@@ -1,7 +1,7 @@
{ {
"version": "0.2.4", "version": "0.2.5",
"sha256": { "sha256": {
"aarch64-apple-darwin": "41ac25d2a2503b6f14ef0a499f914687a515284f06a31830609ef2d8973583fb", "aarch64-apple-darwin": "22ae7c596d72dac575c6d1e5c002da6ac0d3aff491ab00e8950b9a48f9505560",
"x86_64-unknown-linux-musl": "fcffc0f959fdbf50e99c09501166c661e695dff5c1feed0f39afc6145821f615" "x86_64-unknown-linux-musl": "9ad1e5222d557842b0dca7311d3b3f519dc8dbfec0cc9cdbc59839f1bf3a5622"
} }
} }
+21 -4
View File
@@ -1155,11 +1155,28 @@ async fn main() -> Result<()> {
open_sessions, open_sessions,
yolo: cli.yolo || cfg.permissions.as_deref() == Some("yolo"), yolo: cli.yolo || cfg.permissions.as_deref() == Some("yolo"),
auto: cli.auto || cfg.permissions.as_deref() == Some("auto"), auto: cli.auto || cfg.permissions.as_deref() == Some("auto"),
mcp: mcp mcp: {
.servers let mcp = mcp.clone();
Box::new(move || {
mcp.servers
.iter() .iter()
.map(|(n, s)| (n.clone(), s.st().error.is_none())) .map(|(n, s)| {
.collect(), let st = s.st();
hx_tui::side::McpRow {
name: n.clone(),
state: match (&st.error, st.pending) {
(Some(_), _) => hx_tui::side::McpState::Failed,
(None, true) => hx_tui::side::McpState::Pending,
(None, false) => hx_tui::side::McpState::Ok,
},
tools: st.tools.len(),
prompts: st.prompts.len(),
error: st.error.clone(),
}
})
.collect()
})
},
mouse: cfg.mouse.unwrap_or(true) mouse: cfg.mouse.unwrap_or(true)
&& std::env::var_os("HX_MOUSE").is_none_or(|v| v != "0"), && std::env::var_os("HX_MOUSE").is_none_or(|v| v != "0"),
commands: { commands: {
+84 -1
View File
@@ -421,6 +421,25 @@ impl Agent {
*self.abort.borrow() *self.abort.borrow()
} }
fn abort_calls(
&mut self,
calls: &[(String, String, serde_json::Value)],
) -> Result<Message, Error> {
let content = calls
.iter()
.map(|(id, ..)| ContentBlock::ToolResult {
tool_use_id: id.clone(),
content: "aborted by user".into(),
is_error: true,
})
.collect();
self.push(Message {
role: Role::User,
content,
})?;
Err(Error::Aborted)
}
pub async fn run(&mut self, prompt: impl Into<String>) -> Result<Message, Error> { pub async fn run(&mut self, prompt: impl Into<String>) -> Result<Message, Error> {
let r = self.run_inner(prompt.into()).await; let r = self.run_inner(prompt.into()).await;
self.emit(Event::RunEnd { self.emit(Event::RunEnd {
@@ -529,6 +548,9 @@ impl Agent {
continue; continue;
} }
if self.aborted() {
return self.abort_calls(&calls);
}
let mut results: Vec<Option<ContentBlock>> = vec![None; calls.len()]; let mut results: Vec<Option<ContentBlock>> = vec![None; calls.len()];
let mut runnable = vec![]; let mut runnable = vec![];
for (i, (id, name, args)) in calls.iter().enumerate() { for (i, (id, name, args)) in calls.iter().enumerate() {
@@ -577,10 +599,12 @@ impl Agent {
&self.cx, &self.cx,
); );
tokio::pin!(round); tokio::pin!(round);
let mut ab = self.abort.clone();
loop { loop {
tokio::select! { tokio::select! {
outs = &mut round => break outs, outs = &mut round => break Some(outs),
Some(line) = nrx.recv() => { self.emit(Event::Info(line)).await; } Some(line) = nrx.recv() => { self.emit(Event::Info(line)).await; }
_ = async { ab.wait_for(|a| *a).await.is_ok() } => break None,
} }
} }
}; };
@@ -590,6 +614,9 @@ impl Agent {
.lock() .lock()
.unwrap_or_else(|e| e.into_inner()) .unwrap_or_else(|e| e.into_inner())
.take(); .take();
let Some(outs) = outs else {
return self.abort_calls(&calls);
};
while let Ok(line) = nrx.try_recv() { while let Ok(line) = nrx.try_recv() {
self.emit(Event::Info(line)).await; self.emit(Event::Info(line)).await;
} }
@@ -1093,6 +1120,62 @@ mod tests {
assert!(matches!(a.run("again").await, Err(Error::Aborted))); assert!(matches!(a.run("again").await, Err(Error::Aborted)));
} }
struct Slow;
#[async_trait]
impl Tool for Slow {
fn spec(&self) -> ToolSpec {
ToolSpec {
name: "slow".into(),
description: "sleeps".into(),
input_schema: json!({"type":"object","properties":{}}),
}
}
async fn call(&self, _: Value, _: &crate::tool::ToolCtx) -> ToolResult {
tokio::time::sleep(std::time::Duration::from_secs(30)).await;
ToolResult::ok("done")
}
}
#[tokio::test]
async fn abort_during_tool_round_stops_it_and_answers_the_calls() {
let p = Arc::new(Script(
Mutex::new(vec![
asst(vec![tu("1", "slow"), tu("2", "slow")]),
asst(vec![ContentBlock::Text { text: "ok".into() }]),
]),
Mutex::new(vec![]),
));
let dir = tempfile::tempdir().unwrap();
let mut tools = Registry::default();
tools.add(Slow);
let cx = ToolCtx {
cwd: dir.path().into(),
state: Default::default(),
};
let (mut a, h) = Agent::new(
p.clone(),
tools,
Session::open(dir.path().join("s.jsonl")).unwrap(),
cx,
);
tokio::spawn(async move {
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
h.abort();
});
let t = std::time::Instant::now();
assert!(matches!(a.run("go").await, Err(Error::Aborted)));
assert!(t.elapsed() < std::time::Duration::from_secs(5));
assert!(a.run("again").await.is_ok());
let reqs = p.1.lock().unwrap();
let last = &reqs[1].messages;
let results = last
.iter()
.flat_map(|m| &m.content)
.filter(|b| matches!(b, ContentBlock::ToolResult { is_error: true, .. }))
.count();
assert_eq!(results, 2);
}
#[tokio::test] #[tokio::test]
async fn mask_boundary_waits_for_big_context_and_is_recorded() { async fn mask_boundary_waits_for_big_context_and_is_recorded() {
let big = "z".repeat(8000); let big = "z".repeat(8000);
+8 -1
View File
@@ -135,7 +135,14 @@ pub async fn gate_why(cx: &ToolCtx, req: crate::permit::Request) -> Result<(), S
} }
} }
let rule = req.rule.clone(); let rule = req.rule.clone();
match ask(req).await { let decision = match cx.state.abort.get().cloned() {
Some(mut rx) => tokio::select! {
d = ask(req) => d,
_ = async { rx.wait_for(|a| *a).await.is_ok() } => Decision::Deny,
},
None => ask(req).await,
};
match decision {
Decision::Once => {} Decision::Once => {}
Decision::Always => allow().add(&rule), Decision::Always => allow().add(&rule),
Decision::Edits => allow().allow_edits(), Decision::Edits => allow().allow_edits(),
+28 -7
View File
@@ -366,6 +366,19 @@ impl Tool for ExitPlan {
const LIVE_TAIL: usize = 2048; const LIVE_TAIL: usize = 2048;
#[cfg(unix)]
struct KillGroup(Option<u32>);
#[cfg(unix)]
impl Drop for KillGroup {
fn drop(&mut self) {
if let Some(pid) = self.0 {
let _ = std::process::Command::new("kill")
.args(["-KILL", &format!("-{pid}")])
.status();
}
}
}
pub struct Bash; pub struct Bash;
#[async_trait] #[async_trait]
impl Tool for Bash { impl Tool for Bash {
@@ -396,6 +409,8 @@ impl Tool for Bash {
Err(e) => return ToolResult::err(format!("spawn: {e}")), Err(e) => return ToolResult::err(format!("spawn: {e}")),
}; };
let pid = child.id(); let pid = child.id();
#[cfg(unix)]
let mut group = KillGroup(pid);
let mut so = child.stdout.take().expect("piped"); let mut so = child.stdout.take().expect("piped");
let live = &cx.state.live; let live = &cx.state.live;
let run = async { let run = async {
@@ -420,15 +435,21 @@ impl Tool for Bash {
let res = tokio::time::timeout(Duration::from_secs(secs), run).await; let res = tokio::time::timeout(Duration::from_secs(secs), run).await;
live.lock().unwrap_or_else(|e| e.into_inner()).remove(cmd); live.lock().unwrap_or_else(|e| e.into_inner()).remove(cmd);
let (out, code) = match res { let (out, code) = match res {
Ok(Ok((o, st))) => (o, st.code()), Ok(Ok((o, st))) => {
Ok(Err(e)) => return ToolResult::err(format!("wait: {e}")),
Err(_) => {
#[cfg(unix)] #[cfg(unix)]
if let Some(pid) = pid { {
let _ = std::process::Command::new("kill") group.0 = None;
.args(["-KILL", &format!("-{pid}")])
.status();
} }
(o, st.code())
}
Ok(Err(e)) => {
#[cfg(unix)]
{
group.0 = None;
}
return ToolResult::err(format!("wait: {e}"));
}
Err(_) => {
return ToolResult::err(format!("timed out after {secs}s")); return ToolResult::err(format!("timed out after {secs}s"));
} }
}; };
+132 -140
View File
@@ -11,6 +11,7 @@ pub mod review;
pub mod scroll; pub mod scroll;
pub mod select; pub mod select;
pub mod sessions; pub mod sessions;
pub mod side;
pub mod stats_view; pub mod stats_view;
pub mod status; pub mod status;
pub mod theme; pub mod theme;
@@ -51,7 +52,7 @@ pub struct Setup {
pub mouse: bool, pub mouse: bool,
pub yolo: bool, pub yolo: bool,
pub auto: bool, pub auto: bool,
pub mcp: Vec<(String, bool)>, pub mcp: side::McpStatus,
} }
#[derive(Default, Clone, Copy)] #[derive(Default, Clone, Copy)]
@@ -154,7 +155,11 @@ struct App {
snap: Option<tokio::sync::watch::Receiver<Arc<hx_core::agent::Snap>>>, snap: Option<tokio::sync::watch::Receiver<Arc<hx_core::agent::Snap>>>,
side: bool, side: bool,
lens_lines: Vec<String>, lens_lines: Vec<String>,
mcp: Vec<(String, bool)>, mcp: Vec<side::McpRow>,
log: side::LogRing,
consult: Option<side::Consult>,
seen_subs: std::collections::HashMap<usize, String>,
mode: &'static str,
choose: Option<( choose: Option<(
choose::Choose, choose::Choose,
tokio::sync::oneshot::Sender<Option<Vec<String>>>, tokio::sync::oneshot::Sender<Option<Vec<String>>>,
@@ -179,6 +184,58 @@ impl App {
if sw.provider_changed { if sw.provider_changed {
self.st.quota = None; self.st.quota = None;
} }
self.log.push("main", format!("model {}", self.st.model));
}
fn sync_log(&mut self) {
for s in self.state.subs.list() {
let st = match s.sh.status() {
hx_core::subagent::Status::Running => "started".to_string(),
hx_core::subagent::Status::Done => {
format!("done {}s", s.sh.elapsed().as_secs())
}
hx_core::subagent::Status::Failed(e) => format!("failed {e}"),
hx_core::subagent::Status::Aborted => "aborted".into(),
};
let key = format!("{} {}", s.sh.model, st);
if self.seen_subs.get(&s.sh.id) != Some(&key) {
self.log.push(
format!("{} {}", s.sh.kind, s.sh.model),
st,
);
self.seen_subs.insert(s.sh.id, key);
}
}
}
fn sync_lens_log(&mut self, new: &[String]) {
let state = |x: &str| {
x.split_once(" @ ")
.map(|(n, r)| (n.to_string(), r.rsplit_once(": ").map_or("", |p| p.1).to_string()))
.unwrap_or_else(|| (x.to_string(), String::new()))
};
for x in new {
let (n, s) = state(x);
let old = self.lens_lines.iter().map(|o| state(o)).find(|o| o.0 == n);
if old.as_ref().map(|o| &o.1) != Some(&s) && !s.is_empty() {
self.log.push("lsp", format!("{n} {s}"));
}
}
}
fn sync_mcp(&mut self, new: Vec<side::McpRow>) {
for m in &new {
let old = self.mcp.iter().find(|o| o.name == m.name).map(|o| o.state);
if old != Some(m.state) && m.state != side::McpState::Pending {
let what = match (&m.state, &m.error) {
(side::McpState::Failed, Some(e)) => format!("{} failed: {e}", m.name),
(side::McpState::Failed, None) => format!("{} failed", m.name),
_ => format!("{} up {} tools", m.name, m.tools),
};
self.log.push("mcp", what);
}
}
self.mcp = new;
} }
fn ctx_max_from(&mut self, a: &Agent) { fn ctx_max_from(&mut self, a: &Agent) {
@@ -233,7 +290,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
mouse, mouse,
yolo, yolo,
auto, auto,
mcp, mcp: mcp_status,
} = setup; } = setup;
let kbd = crossterm::terminal::supports_keyboard_enhancement().unwrap_or(false); let kbd = crossterm::terminal::supports_keyboard_enhancement().unwrap_or(false);
let (tx, mut rx) = mpsc::unbounded_channel(); let (tx, mut rx) = mpsc::unbounded_channel();
@@ -350,12 +407,25 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
snap: Some(agent.snap()), snap: Some(agent.snap()),
side: true, side: true,
lens_lines: vec![], lens_lines: vec![],
mcp, mcp: vec![],
log: Default::default(),
consult: None,
seen_subs: Default::default(),
mode: if yolo {
"yolo"
} else if auto {
"auto"
} else {
"ask"
},
state: agent.cx.state.clone(), state: agent.cx.state.clone(),
sub_t: Default::default(), sub_t: Default::default(),
agents: None, agents: None,
}; };
sessions::history(&mut app.t, &agent.session().messages()); sessions::history(&mut app.t, &agent.session().messages());
let first = mcp_status();
app.sync_mcp(first);
app.log.push("main", format!("model {}", app.st.model));
if open_sessions { if open_sessions {
open_sessions_picker(&mut app); open_sessions_picker(&mut app);
} }
@@ -601,15 +671,23 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
} }
t.apply(&ev); t.apply(&ev);
} }
_ = tick.tick(), if app.busy || subs_running(&app) => dirty = true, _ = tick.tick(), if app.busy || subs_running(&app) => {
app.sync_log();
dirty = true;
}
_ = lens_tick.tick() => { _ = lens_tick.tick() => {
let to = std::time::Duration::from_millis(200); let to = std::time::Duration::from_millis(200);
if let Ok(v) = tokio::time::timeout(to, lsp_status()).await { if let Ok(v) = tokio::time::timeout(to, lsp_status()).await {
let s = status::lens_summary(&v); let s = status::lens_summary(&v);
app.sync_lens_log(&v);
app.lens_lines = v; app.lens_lines = v;
dirty |= s != app.lens; dirty |= s != app.lens;
app.lens = s; app.lens = s;
} }
let m = mcp_status();
dirty |= m != app.mcp;
app.sync_mcp(m);
app.sync_log();
} }
} }
} }
@@ -1806,14 +1884,32 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
f.render_widget(block, side); f.render_widget(block, side);
let mut ls = vec![ let mut ls = vec![
spread_line( spread_line(
Span::styled("/lsp", th.accent().add_modifier(Modifier::BOLD)), Span::styled("/status", th.accent().add_modifier(Modifier::BOLD)),
Span::styled("ctrl-l ×", th.dim()), Span::styled("ctrl-l ×", th.dim()),
body.width, body.width,
), ),
Line::default(), Line::default(),
]; ];
ls.extend(side_lines(app, body.width as usize)); let lens = app
f.render_widget(Paragraph::new(ls).wrap(Wrap { trim: false }), body); .state
.lens
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone();
let subs = app.state.subs.list();
ls.extend(side::lines(&side::View {
st: &app.st,
mode: app.mode,
lens_lines: &app.lens_lines,
lens: &lens,
mcp: &app.mcp,
subs: &subs,
consult: app.consult.as_ref(),
log: &app.log,
w: body.width as usize,
h: (body.height as usize).saturating_sub(2),
}));
f.render_widget(Paragraph::new(ls), body);
app.areas.panel = Rect::default(); app.areas.panel = Rect::default();
m m
} }
@@ -1953,128 +2049,6 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
} }
} }
const SIDE_DIAGS: usize = 8;
const SIDE_TESTS: usize = 6;
fn side_lines(app: &App, w: usize) -> Vec<Line<'static>> {
let th = theme::t();
let sec = |label: String| {
Line::styled(
th.rule(&label, w)
.replacen(th.sym.rule, "", 1)
.trim_start()
.to_string(),
th.dim(),
)
};
let mut l = vec![];
if app.lens_lines.is_empty() {
l.push(Line::styled("no servers started", th.dim()));
}
for x in &app.lens_lines {
let (name, state) = match x.split_once(" @ ") {
Some((n, r)) => (n.to_string(), r.rsplit_once(": ").map_or("", |p| p.1)),
None => (x.clone(), ""),
};
let (mark, st, word) = if state.starts_with("running") {
(th.sym.done, th.ok(), "ready")
} else if state.is_empty() {
(th.sym.info, th.dim(), "")
} else if state == "stopped" {
(th.sym.off, th.dim(), "stopped")
} else {
(th.sym.err, th.err(), state)
};
l.push(Line::from(vec![
Span::styled(format!("{mark} "), st),
Span::styled(
format!("{name:<16}"),
if word.is_empty() {
th.sec()
} else {
th.plain()
},
),
Span::styled(format!(" {word}"), th.sec()),
]));
}
let view = app
.state
.lens
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone();
if !view.diags.is_empty() {
l.push(Line::default());
l.push(sec(format!("diagnostics {}", view.diags.len())));
let mut ds = view.diags.clone();
ds.sort_by_key(|d| (!d.error, d.file.clone(), d.line));
for d in ds.iter().take(SIDE_DIAGS) {
let (mark, st) = if d.error {
(th.sym.err, th.err())
} else {
(th.sym.warn, th.warn())
};
let file = d.file.rsplit('/').next().unwrap_or(&d.file);
l.push(Line::from(vec![
Span::styled(format!("{mark} "), st),
Span::styled(format!("{file}:{}:{}", d.line, d.col), th.plain()),
]));
l.push(Line::styled(format!(" {}", d.message), th.sec()));
}
if ds.len() > SIDE_DIAGS {
l.push(Line::styled(
format!(" {} {} more", th.sym.ellipsis, ds.len() - SIDE_DIAGS),
th.dim(),
));
}
}
if let Some(ts) = &view.tests {
let mut ts = ts.clone();
ts.sort_by_key(|t| t.1);
l.push(Line::default());
l.push(sec(format!("affected tests {}", ts.len())));
for (n, ok) in ts.iter().take(SIDE_TESTS) {
l.push(Line::from(vec![
Span::styled(
format!("{} ", if *ok { th.sym.ok } else { th.sym.err }),
if *ok { th.ok() } else { th.err() },
),
Span::styled(n.clone(), th.plain()),
]));
}
if ts.len() > SIDE_TESTS {
l.push(Line::styled(
format!(" {} {} more", th.sym.ellipsis, ts.len() - SIDE_TESTS),
th.dim(),
));
}
}
let u = &app.st.usage;
let tot = u.input_tokens + u.cache_read_tokens + u.cache_write_tokens;
l.push(Line::default());
l.push(sec("context".into()));
let mut ctx = format!("{}k / {}k", app.st.ctx_tokens / 1000, app.st.ctx_max / 1000);
if let Some(p) = (100 * u.cache_read_tokens).checked_div(tot) {
ctx += &format!(" {} cache {p}%", th.sym.info);
}
l.push(Line::styled(ctx, th.sec()));
if !app.mcp.is_empty() {
l.push(Line::default());
l.push(sec("mcp".into()));
l.extend(app.mcp.iter().map(|(n, ok)| {
Line::from(vec![
Span::styled(
format!("{} ", if *ok { th.sym.done } else { th.sym.err }),
if *ok { th.ok() } else { th.err() },
),
Span::styled(n.clone(), th.plain()),
])
}));
}
l
}
fn skills_list(specs: &[CmdSpec], dirs: &[std::path::PathBuf]) -> String { fn skills_list(specs: &[CmdSpec], dirs: &[std::path::PathBuf]) -> String {
let sk: Vec<String> = specs let sk: Vec<String> = specs
.iter() .iter()
@@ -2322,7 +2296,23 @@ mod tests {
#[test] #[test]
fn side_panel_only_on_wide_terminals() { fn side_panel_only_on_wide_terminals() {
let mut app = test_app(); let mut app = test_app();
app.mcp = vec![("git".into(), true), ("db".into(), false)]; app.mcp = vec![
side::McpRow {
name: "git".into(),
state: side::McpState::Ok,
tools: 3,
prompts: 0,
error: None,
},
side::McpRow {
name: "db".into(),
state: side::McpState::Failed,
tools: 0,
prompts: 0,
error: Some("refused".into()),
},
];
app.log.push("lsp", "rust-analyzer running");
app.lens_lines = vec!["rust-analyzer @ /p: running".into()]; app.lens_lines = vec!["rust-analyzer @ /p: running".into()];
*app.state.lens.lock().unwrap() = hx_core::LensView { *app.state.lens.lock().unwrap() = hx_core::LensView {
diags: vec![hx_core::Diag { diags: vec![hx_core::Diag {
@@ -2336,23 +2326,21 @@ mod tests {
}; };
let s = screen(&mut app, 160, 50); let s = screen(&mut app, 160, 50);
assert!( assert!(
s.contains("diagnostics 1 ┈") && s.contains("⚠ codemode.rs:88:13"), s.contains("LSP") && s.contains("⚠ codemode.rs:88 unused variable"),
"{s}"
);
assert!(
s.contains("affected tests 2 ┈") && s.contains("✗ a::bad"),
"{s}" "{s}"
); );
assert!(s.contains("TESTS") && s.contains("✗ a::bad"), "{s}");
let bad = s.find("✗ a::bad").unwrap(); let bad = s.find("✗ a::bad").unwrap();
assert!(bad < s.find("✓ a::ok").unwrap(), "failures first"); assert!(bad < s.find("✓ a::ok").unwrap(), "failures first");
assert!( assert!(
s.contains("/lsp") && s.contains("● rust-analyzer ready"), s.contains("/status") && s.contains("● rust-analyzer") && s.contains("ready"),
"{s}" "{s}"
); );
assert!(s.contains("mcp ┈") && s.contains("✗ db"), "{s}"); assert!(s.contains("MCP") && s.contains("✗ db"), "{s}");
assert!(!screen(&mut app, 80, 24).contains("/lsp")); assert!(s.contains("MODEL") && s.contains("SESSION LOG"), "{s}");
assert!(!screen(&mut app, 80, 24).contains("/status"));
app.side = false; app.side = false;
assert!(!screen(&mut app, 160, 50).contains("/lsp")); assert!(!screen(&mut app, 160, 50).contains("/status"));
} }
#[test] #[test]
@@ -2647,6 +2635,10 @@ mod tests {
side: true, side: true,
lens_lines: vec![], lens_lines: vec![],
mcp: vec![], mcp: vec![],
log: Default::default(),
consult: None,
seen_subs: Default::default(),
mode: "ask",
state: Default::default(), state: Default::default(),
sub_t: Default::default(), sub_t: Default::default(),
agents: None, agents: None,
+672
View File
@@ -0,0 +1,672 @@
use crate::status::Status;
use crate::theme;
use hx_core::LensView;
use hx_core::subagent::{Status as SubStatus, Sub};
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use std::collections::VecDeque;
use std::sync::Arc;
use std::time::{Duration, Instant};
const DIAGS: usize = 6;
const TESTS: usize = 5;
const LOG_ROWS: usize = 8;
const LOG_CAP: usize = 50;
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum McpState {
Pending,
Ok,
Failed,
}
#[derive(Clone, PartialEq, Debug)]
pub struct McpRow {
pub name: String,
pub state: McpState,
pub tools: usize,
pub prompts: usize,
pub error: Option<String>,
}
pub type McpStatus = Box<dyn Fn() -> Vec<McpRow> + Send>;
#[derive(Clone, PartialEq, Debug)]
pub struct Consult {
pub model: String,
pub advising: bool,
pub consults: u32,
pub last: Option<(Duration, Duration)>,
pub triggers: Vec<(String, bool)>,
}
pub struct LogRing {
start: Instant,
items: VecDeque<(Duration, String, String)>,
}
impl Default for LogRing {
fn default() -> Self {
LogRing {
start: Instant::now(),
items: VecDeque::new(),
}
}
}
impl LogRing {
pub fn push(&mut self, src: impl Into<String>, text: impl Into<String>) {
let (src, text) = (src.into(), text.into());
if self.items.back().is_some_and(|l| l.1 == src && l.2 == text) {
return;
}
if self.items.len() == LOG_CAP {
self.items.pop_front();
}
self.items.push_back((self.start.elapsed(), src, text));
}
pub fn len(&self) -> usize {
self.items.len()
}
pub fn is_empty(&self) -> bool {
self.items.is_empty()
}
}
pub struct View<'a> {
pub st: &'a Status,
pub mode: &'a str,
pub lens_lines: &'a [String],
pub lens: &'a LensView,
pub mcp: &'a [McpRow],
pub subs: &'a [Arc<Sub>],
pub consult: Option<&'a Consult>,
pub log: &'a LogRing,
pub w: usize,
pub h: usize,
}
fn short(model: &str) -> &str {
model.strip_prefix("claude-").unwrap_or(model)
}
fn clock(d: Duration) -> String {
let s = d.as_secs();
format!("{}:{:02}", s / 60, s % 60)
}
fn tokens(n: u64) -> String {
match n {
n if n >= 1_000_000 => format!("{:.1}M", n as f64 / 1e6),
n if n >= 1000 => format!("{}k", n / 1000),
n => n.to_string(),
}
}
fn clip(s: &str, w: usize) -> String {
let th = theme::t();
if Span::raw(s).width() <= w {
return s.to_string();
}
let keep = w.saturating_sub(Span::raw(th.sym.ellipsis).width());
let mut out = String::new();
for c in s.chars() {
if Span::raw(format!("{out}{c}")).width() > keep {
break;
}
out.push(c);
}
out + th.sym.ellipsis
}
fn fit(l: Line<'static>, w: usize) -> Line<'static> {
if l.width() <= w {
return l;
}
let mut left = w;
let mut out = vec![];
for s in l.spans {
let sw = s.width();
if sw <= left {
left -= sw;
out.push(s);
continue;
}
out.push(Span::styled(clip(&s.content, left), s.style));
break;
}
Line::from(out)
}
fn bar(frac: f64, n: usize, st: Style) -> Vec<Span<'static>> {
let th = theme::t();
let full = ((frac.clamp(0.0, 1.0) * n as f64).round() as usize).min(n);
vec![
Span::styled(th.sym.bar_full.repeat(full), st),
Span::styled(th.sym.bar_empty.repeat(n - full), th.dim()),
]
}
fn load_style(frac: f64) -> Style {
let th = theme::t();
match frac {
f if f >= 0.9 => th.err(),
f if f >= 0.7 => th.warn(),
_ => th.accent(),
}
}
pub fn card(
title: &str,
right: &str,
border: Style,
body: Vec<Line<'static>>,
w: usize,
) -> Vec<Line<'static>> {
let th = theme::t();
let [h, v, tl, _, tr, _, _, _, bl, _, br] = th.sym.tbl;
let inner = w.saturating_sub(2);
let head = format!(" {title} ");
let tail = if right.is_empty() {
String::new()
} else {
format!(" {} ", clip(right, inner.saturating_sub(head.len() + 3)))
};
let fill = inner.saturating_sub(Span::raw(&head).width() + Span::raw(&tail).width() + 1);
let mut out = vec![Line::from(vec![
Span::styled(format!("{tl}{h}"), border),
Span::styled(head, border.add_modifier(Modifier::BOLD)),
Span::styled(h.repeat(fill), border),
Span::styled(tail, th.sec()),
Span::styled(tr, border),
])];
let cw = inner.saturating_sub(2);
for l in body {
let l = fit(l, cw);
let pad = cw.saturating_sub(l.width());
let mut spans = vec![Span::styled(format!("{v} "), border)];
spans.extend(l.spans);
spans.push(Span::raw(" ".repeat(pad)));
spans.push(Span::styled(format!(" {v}"), border));
out.push(Line::from(spans));
}
out.push(Line::styled(format!("{bl}{}{br}", h.repeat(inner)), border));
out
}
fn model_card(c: &View) -> Vec<Line<'static>> {
let th = theme::t();
let st = c.st;
let mut b = vec![Line::from(vec![
Span::styled(short(&st.model).to_string(), th.plain()),
Span::styled(
format!(
" {} think {} {} {}",
th.sym.info,
st.effort.name(),
th.sym.info,
c.mode
),
th.sec(),
),
])];
let frac = st.ctx_tokens as f64 / st.ctx_max.max(1) as f64;
let mut ctx = vec![Span::styled("ctx ", th.sec())];
ctx.extend(bar(frac, 10, load_style(frac)));
ctx.push(Span::styled(
format!(
" {:.0}% {}/{}",
frac * 100.0,
tokens(st.ctx_tokens as u64),
tokens(st.ctx_max as u64)
),
th.sec(),
));
b.push(Line::from(ctx));
let u = &st.usage;
let tot = u.input_tokens + u.cache_read_tokens + u.cache_write_tokens;
let mut extra = vec![];
if let Some(p) = (100 * u.cache_read_tokens).checked_div(tot) {
extra.push(format!("cache {p}%"));
}
if let Some(p) = (st.pricing)(&st.model) {
extra.push(format!("${:.2}", u.cost(&p)));
}
if !extra.is_empty() {
b.push(Line::styled(
extra.join(&format!(" {} ", th.sym.info)),
th.sec(),
));
}
if let Some(q) = &st.quota {
for w in &q.windows {
let f = w.used_pct / 100.0;
let mut l = vec![Span::styled(format!("{:<4}", w.label), th.sec())];
l.extend(bar(f, 10, load_style(f)));
l.push(Span::styled(format!(" {:.0}%", w.used_pct), th.sec()));
b.push(Line::from(l));
}
}
card("MODEL", "", th.accent(), b, c.w)
}
fn consult_card(c: &View) -> Option<Vec<Line<'static>>> {
let k = c.consult?;
let th = theme::t();
let mut b = vec![Line::styled(short(&k.model).to_string(), th.plain())];
if let Some((ago, took)) = k.last {
b.push(Line::styled(
format!(
"last {} ago {} took {}",
clock(ago),
th.sym.info,
clock(took)
),
th.sec(),
));
}
if !k.triggers.is_empty() {
let mut spans = vec![];
for (n, on) in &k.triggers {
if !spans.is_empty() {
spans.push(Span::raw(" "));
}
let (m, st) = if *on {
(th.sym.done, th.accent().add_modifier(Modifier::BOLD))
} else {
(th.sym.off, th.dim())
};
spans.push(Span::styled(format!("{m} {n}"), st));
}
b.push(Line::from(spans));
}
let (state, border) = if k.advising {
("advising", th.accent())
} else {
("on call", th.dim())
};
Some(card(
"CONSULTANT",
&format!("{state} {} {}", th.sym.info, k.consults),
border,
b,
c.w,
))
}
fn runs_card(c: &View) -> Vec<Line<'static>> {
let th = theme::t();
let u = &c.st.usage;
let mut b = vec![Line::from(vec![
Span::styled(format!("{} ", th.sym.done), th.accent()),
Span::styled(format!("{:<8}", "main"), th.sec()),
Span::styled(short(&c.st.model).to_string(), th.plain()),
Span::styled(
format!(
" {}",
tokens(u.input_tokens + u.cache_read_tokens + u.output_tokens)
),
th.dim(),
),
])];
let mut running = 0;
for s in c.subs.iter().rev().take(4).rev() {
let (mark, st) = match s.sh.status() {
SubStatus::Running => {
running += 1;
(th.sym.pending, th.accent())
}
SubStatus::Done => (th.sym.done, th.ok()),
_ => (th.sym.err, th.err()),
};
b.push(Line::from(vec![
Span::styled(format!("{mark} "), st),
Span::styled(format!("{:<8}", s.sh.kind), th.sec()),
Span::styled(short(&s.sh.model).to_string(), th.plain()),
Span::styled(format!(" {}", clock(s.sh.elapsed())), th.dim()),
]));
}
let right = if c.subs.is_empty() {
String::new()
} else {
format!("{running} running {} {} total", th.sym.info, c.subs.len())
};
card("MODELS RUN", &right, th.dim(), b, c.w)
}
fn lsp_card(c: &View) -> Vec<Line<'static>> {
let th = theme::t();
let mut b = vec![];
let (mut up, mut bad) = (0, false);
for x in c.lens_lines {
let (name, state) = match x.split_once(" @ ") {
Some((n, r)) => (n.to_string(), r.rsplit_once(": ").map_or("", |p| p.1)),
None => (x.clone(), ""),
};
let (mark, st, word) = if state.starts_with("running") {
up += 1;
(th.sym.done, th.ok(), "ready")
} else if state.is_empty() {
(th.sym.info, th.dim(), "")
} else if state == "stopped" {
(th.sym.off, th.dim(), "stopped")
} else {
bad = true;
(th.sym.err, th.err(), state)
};
b.push(Line::from(vec![
Span::styled(format!("{mark} "), st),
Span::styled(format!("{name:<16}"), th.plain()),
Span::styled(format!(" {word}"), th.sec()),
]));
}
if b.is_empty() {
b.push(Line::styled("no servers started", th.dim()));
}
let (errs, warns) = c.lens.diags.iter().fold((0, 0), |(e, w), d| {
if d.error { (e + 1, w) } else { (e, w + 1) }
});
if errs + warns > 0 {
let mut ds = c.lens.diags.clone();
ds.sort_by_key(|d| (!d.error, d.file.clone(), d.line));
for d in ds.iter().take(DIAGS) {
let (mark, st) = if d.error {
(th.sym.err, th.err())
} else {
(th.sym.warn, th.warn())
};
let file = d.file.rsplit('/').next().unwrap_or(&d.file);
b.push(Line::from(vec![
Span::styled(format!("{mark} "), st),
Span::styled(format!("{file}:{} ", d.line), th.plain()),
Span::styled(d.message.lines().next().unwrap_or("").to_string(), th.sec()),
]));
}
if ds.len() > DIAGS {
b.push(Line::styled(
format!("{} {} more", th.sym.ellipsis, ds.len() - DIAGS),
th.dim(),
));
}
}
let mut right = format!("{up}/{} ready", c.lens_lines.len());
if errs + warns > 0 {
right += &format!(" {} {}{errs} {}{warns}", th.sym.info, th.sym.err, th.sym.warn);
}
let border = if bad || errs > 0 {
th.err()
} else if up > 0 {
th.ok()
} else {
th.dim()
};
card("LSP", &right, border, b, c.w)
}
fn mcp_card(c: &View) -> Option<Vec<Line<'static>>> {
if c.mcp.is_empty() {
return None;
}
let th = theme::t();
let mut b = vec![];
for m in c.mcp {
let (mark, st) = match m.state {
McpState::Ok => (th.sym.done, th.ok()),
McpState::Pending => (th.sym.pending, th.dim()),
McpState::Failed => (th.sym.err, th.err()),
};
let note = match m.state {
McpState::Ok => format!("{} tools", m.tools),
McpState::Pending => "connecting".into(),
McpState::Failed => "failed".into(),
};
b.push(Line::from(vec![
Span::styled(format!("{mark} "), st),
Span::styled(format!("{:<14}", m.name), th.plain()),
Span::styled(format!(" {note}"), th.sec()),
]));
if let Some(e) = &m.error {
b.push(Line::styled(
format!(" {}", e.lines().next().unwrap_or("")),
th.err(),
));
}
}
let up = c.mcp.iter().filter(|m| m.state == McpState::Ok).count();
let border = if c.mcp.iter().any(|m| m.state == McpState::Failed) {
th.err()
} else if up == c.mcp.len() {
th.ok()
} else {
th.dim()
};
Some(card(
"MCP",
&format!("{up}/{} up", c.mcp.len()),
border,
b,
c.w,
))
}
fn tests_card(c: &View) -> Option<Vec<Line<'static>>> {
let ts = c.lens.tests.as_ref()?;
let th = theme::t();
let mut ts = ts.clone();
ts.sort_by_key(|t| t.1);
let failed = ts.iter().filter(|t| !t.1).count();
let mut b: Vec<Line<'static>> = ts
.iter()
.take(TESTS)
.map(|(n, ok)| {
Line::from(vec![
Span::styled(
format!("{} ", if *ok { th.sym.ok } else { th.sym.err }),
if *ok { th.ok() } else { th.err() },
),
Span::styled(n.clone(), th.plain()),
])
})
.collect();
if ts.len() > TESTS {
b.push(Line::styled(
format!("{} {} more", th.sym.ellipsis, ts.len() - TESTS),
th.dim(),
));
}
let border = if failed > 0 { th.err() } else { th.ok() };
Some(card(
"TESTS",
&format!("{} ok {} {failed} failed", ts.len() - failed, th.sym.info),
border,
b,
c.w,
))
}
fn log_card(c: &View) -> Option<Vec<Line<'static>>> {
if c.log.is_empty() {
return None;
}
let th = theme::t();
let skip = c.log.items.len().saturating_sub(LOG_ROWS);
let b = c
.log
.items
.iter()
.skip(skip)
.map(|(t, src, text)| {
Line::from(vec![
Span::styled(format!("{:>5} ", clock(*t)), th.dim()),
Span::styled(format!("{src} "), th.accent()),
Span::styled(text.clone(), th.sec()),
])
})
.collect();
Some(card(
"SESSION LOG",
&format!("{}", c.log.len()),
th.dim(),
b,
c.w,
))
}
pub fn lines(c: &View) -> Vec<Line<'static>> {
let cards = [
Some(model_card(c)),
consult_card(c),
Some(runs_card(c)),
Some(lsp_card(c)),
mcp_card(c),
tests_card(c),
log_card(c),
];
let mut out: Vec<Line<'static>> = vec![];
for card in cards.into_iter().flatten() {
let need = card.len() + usize::from(!out.is_empty());
if !out.is_empty() && out.len() + need > c.h {
break;
}
if !out.is_empty() {
out.push(Line::default());
}
out.extend(card);
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn text(ls: &[Line]) -> String {
ls.iter()
.map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect::<String>())
.collect::<Vec<_>>()
.join("\n")
}
fn status() -> Status {
Status {
auto: false,
kind: hx_ai::auth::Kind::Claude,
model: "claude-opus-5-5".into(),
effort: hx_ai::Effort::Off,
usage: Default::default(),
ctx_tokens: 500_000,
ctx_max: 1_000_000,
quota: None,
pricing: |_| None,
}
}
fn view<'a>(
st: &'a Status,
lens: &'a LensView,
mcp: &'a [McpRow],
log: &'a LogRing,
h: usize,
) -> View<'a> {
View {
st,
mode: "auto",
lens_lines: &[],
lens,
mcp,
subs: &[],
consult: None,
log,
w: 37,
h,
}
}
#[test]
fn cards_never_exceed_width() {
let l = card(
"LSP",
"a very long right label that will not fit",
Style::default(),
vec![Line::raw("x".repeat(100))],
37,
);
assert!(l.iter().all(|l| l.width() == 37), "{}", text(&l));
}
#[test]
fn mcp_rows_show_state_and_error() {
let (st, lens, log) = (status(), LensView::default(), LogRing::default());
let mcp = vec![
McpRow {
name: "git".into(),
state: McpState::Ok,
tools: 12,
prompts: 0,
error: None,
},
McpRow {
name: "db".into(),
state: McpState::Failed,
tools: 0,
prompts: 0,
error: Some("connection refused".into()),
},
McpRow {
name: "web".into(),
state: McpState::Pending,
tools: 0,
prompts: 0,
error: None,
},
];
let s = text(&lines(&view(&st, &lens, &mcp, &log, 80)));
assert!(s.contains("MCP") && s.contains("1/3 up"), "{s}");
assert!(s.contains("git") && s.contains("12 tools"), "{s}");
assert!(s.contains("connection refused") && s.contains("connecting"), "{s}");
}
#[test]
fn log_ring_caps_and_skips_repeats() {
let mut r = LogRing::default();
r.push("lsp", "up");
r.push("lsp", "up");
assert_eq!(r.len(), 1);
for i in 0..80 {
r.push("x", format!("{i}"));
}
assert_eq!(r.len(), LOG_CAP);
assert_eq!(r.items.back().unwrap().2, "79");
}
#[test]
fn consultant_hidden_without_data_and_marks_active_trigger() {
let (st, lens, log) = (status(), LensView::default(), LogRing::default());
let mut v = view(&st, &lens, &[], &log, 80);
assert!(!text(&lines(&v)).contains("CONSULTANT"));
let k = Consult {
model: "claude-fable-5-2".into(),
advising: true,
consults: 2,
last: Some((Duration::from_secs(7), Duration::from_secs(27))),
triggers: vec![("before a plan".into(), false), ("before done".into(), true)],
};
v.consult = Some(&k);
let s = text(&lines(&v));
assert!(s.contains("CONSULTANT") && s.contains("advising"), "{s}");
assert!(s.contains("● before done") && s.contains("○ before a plan"), "{s}");
}
#[test]
fn short_panels_drop_lowest_cards_first() {
let (st, lens) = (status(), LensView::default());
let mut log = LogRing::default();
log.push("lsp", "up");
let tall = text(&lines(&view(&st, &lens, &[], &log, 80)));
assert!(tall.contains("SESSION LOG"), "{tall}");
let short = text(&lines(&view(&st, &lens, &[], &log, 12)));
assert!(short.contains("MODEL") && !short.contains("SESSION LOG"), "{short}");
}
}