tui: live bash output, token counter, structured lens view for side panel
This commit is contained in:
1 parent
79bd3b8ea7
commit
c57d238f7b
7 files changed
+284
-67
No files matched your search
@@ -728,9 +728,9 @@ async fn main() -> Result<()> {
|
||||
agent.tools.add(hx_lens::LspTool::new(mgr.clone()));
|
||||
let tmode = lcfg.tests.unwrap_or(hx_lens::testrun::TestMode::TurnEnd);
|
||||
if tmode != hx_lens::testrun::TestMode::Off {
|
||||
agent
|
||||
.bus
|
||||
.add(hx_lens::testrun::TestLens::new(cwd.clone(), tmode));
|
||||
let tl = hx_lens::testrun::TestLens::new(cwd.clone(), tmode);
|
||||
let _ = tl.state.set(agent.cx.state.clone());
|
||||
agent.bus.add(tl);
|
||||
}
|
||||
// rust-analyzer & co are slow to index: start servers for languages present at the top level now
|
||||
let probe: Vec<_> = std::fs::read_dir(&cwd)
|
||||
|
||||
@@ -73,6 +73,30 @@ pub struct State {
|
||||
pub sub_usage: Mutex<hx_ai::Usage>,
|
||||
/// Subagents of this session (see [`subagent`]).
|
||||
pub subs: subagent::Subs,
|
||||
/// Last output lines of running `bash` calls, keyed by command (UI live view).
|
||||
/// ponytail: keyed by command text, so two identical commands running at once share a tail;
|
||||
/// key by call id once ToolCtx carries it.
|
||||
pub live: Mutex<HashMap<String, String>>,
|
||||
/// Structured last lens report for side panels.
|
||||
pub lens: Mutex<LensView>,
|
||||
}
|
||||
|
||||
/// Lens results of the last turn, structured (the injected text is for the model).
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
pub struct LensView {
|
||||
pub diags: Vec<Diag>,
|
||||
/// (test name, passed); None = no test run yet
|
||||
pub tests: Option<Vec<(String, bool)>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Diag {
|
||||
/// workspace-relative
|
||||
pub file: String,
|
||||
pub line: u32,
|
||||
pub col: u32,
|
||||
pub error: bool,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
impl State {
|
||||
|
||||
@@ -232,6 +232,7 @@ impl Lens {
|
||||
|
||||
let mut last = self.last.lock().await;
|
||||
let mut sections = vec![];
|
||||
let mut fresh = vec![];
|
||||
for f in &files {
|
||||
let rel = PathBuf::from(self.rel(f));
|
||||
let fseq = self.seq.file(f);
|
||||
@@ -241,6 +242,13 @@ impl Lens {
|
||||
.collect();
|
||||
mine.sort_by_key(|x| (x.severity, x.line, x.col));
|
||||
mine.dedup_by(|a, b| a.line == b.line && a.message == b.message);
|
||||
fresh.extend(mine.iter().map(|x| hx_core::Diag {
|
||||
file: rel.display().to_string(),
|
||||
line: x.line,
|
||||
col: x.col,
|
||||
error: x.severity == 1,
|
||||
message: x.message.clone(),
|
||||
}));
|
||||
let body = format_findings(&mine);
|
||||
// freshness gate: file changed on disk while we were checking -> label, don't trust
|
||||
let stale = self.seq.file(f) > start_seq;
|
||||
@@ -266,6 +274,13 @@ impl Lens {
|
||||
));
|
||||
}
|
||||
drop(last);
|
||||
// UI view: checked files get their current findings, others keep theirs
|
||||
if let Some(st) = self.state.get() {
|
||||
let checked: Vec<String> = files.iter().map(|f| self.rel(f)).collect();
|
||||
let mut v = st.lens.lock().unwrap_or_else(|e| e.into_inner());
|
||||
v.diags.retain(|d| !checked.contains(&d.file));
|
||||
v.diags.extend(fresh);
|
||||
}
|
||||
let mut notes: Vec<String> = errs;
|
||||
notes.extend(
|
||||
self.notes
|
||||
|
||||
@@ -30,6 +30,8 @@ pub struct Failure {
|
||||
#[derive(Debug, Clone, PartialEq, Default)]
|
||||
pub struct Outcome {
|
||||
pub passed: usize,
|
||||
/// names of passing tests, when the framework reports them
|
||||
pub ok_names: Vec<String>,
|
||||
pub failures: Vec<Failure>,
|
||||
}
|
||||
|
||||
@@ -207,7 +209,7 @@ pub fn parse_libtest(s: &str) -> Outcome {
|
||||
for line in s.lines() {
|
||||
if let Some(rest) = line.strip_prefix("test ") {
|
||||
if let Some(name) = rest.strip_suffix(" ... ok") {
|
||||
let _ = name;
|
||||
out.ok_names.push(name.to_string());
|
||||
out.passed += 1;
|
||||
} else if let Some(name) = rest.strip_suffix(" ... FAILED") {
|
||||
out.failures.push(Failure {
|
||||
@@ -307,7 +309,10 @@ pub fn parse_junit(s: &str, root: &Path) -> Outcome {
|
||||
});
|
||||
}
|
||||
None if body.contains("<skipped") => {}
|
||||
None => out.passed += 1,
|
||||
None => {
|
||||
out.ok_names.push(name);
|
||||
out.passed += 1
|
||||
}
|
||||
}
|
||||
rest = &rest[body_end.min(rest.len())..];
|
||||
}
|
||||
@@ -326,7 +331,11 @@ pub fn parse_jest(s: &str) -> Result<Outcome, String> {
|
||||
.unwrap_or_default();
|
||||
for a in &asserts {
|
||||
match a["status"].as_str() {
|
||||
Some("passed") => out.passed += 1,
|
||||
Some("passed") => {
|
||||
out.ok_names
|
||||
.push(a["fullName"].as_str().unwrap_or_default().to_string());
|
||||
out.passed += 1
|
||||
}
|
||||
Some("failed") => out.failures.push(Failure {
|
||||
name: a["fullName"].as_str().unwrap_or_default().to_string(),
|
||||
file: file.clone(),
|
||||
@@ -371,7 +380,10 @@ pub fn parse_go(s: &str) -> Outcome {
|
||||
.entry((pkg, test))
|
||||
.or_default()
|
||||
.push_str(e["Output"].as_str().unwrap_or_default()),
|
||||
Some("pass") if !test.is_empty() => out.passed += 1,
|
||||
Some("pass") if !test.is_empty() => {
|
||||
out.ok_names.push(format!("{pkg}.{test}"));
|
||||
out.passed += 1
|
||||
}
|
||||
Some("fail") => {
|
||||
// package-level fail without tests = build failure; with tests it's just the summary
|
||||
let has_test_fail = out.failures.iter().any(|f| f.name.starts_with(&pkg));
|
||||
@@ -478,6 +490,8 @@ pub struct TestLens {
|
||||
pending: tokio::sync::Mutex<Vec<PathBuf>>,
|
||||
/// last report, so an unchanged failure set isn't repeated every turn
|
||||
last: tokio::sync::Mutex<String>,
|
||||
/// agent state: each run's per-test results go to `state.lens.tests` for the UI
|
||||
pub state: std::sync::OnceLock<std::sync::Arc<hx_core::State>>,
|
||||
}
|
||||
|
||||
impl TestLens {
|
||||
@@ -489,6 +503,7 @@ impl TestLens {
|
||||
cap: 3000,
|
||||
pending: Default::default(),
|
||||
last: Default::default(),
|
||||
state: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -509,6 +524,7 @@ impl TestLens {
|
||||
let mut fails = vec![];
|
||||
let mut notes = vec![];
|
||||
let mut passed = 0;
|
||||
let mut ok_names = vec![];
|
||||
let mut ran = 0;
|
||||
for r in &runs {
|
||||
if !installed(r.adapter, &r.root) {
|
||||
@@ -525,6 +541,7 @@ impl TestLens {
|
||||
match run(r, self.timeout).await {
|
||||
Ok(o) => {
|
||||
passed += o.passed;
|
||||
ok_names.extend(o.ok_names);
|
||||
fails.extend(o.failures);
|
||||
}
|
||||
Err(e) => fails.push(Failure {
|
||||
@@ -534,6 +551,14 @@ impl TestLens {
|
||||
}),
|
||||
}
|
||||
}
|
||||
if ran > 0
|
||||
&& let Some(st) = self.state.get()
|
||||
{
|
||||
let mut v: Vec<(String, bool)> =
|
||||
fails.iter().map(|f| (f.name.clone(), false)).collect();
|
||||
v.extend(ok_names.into_iter().map(|n| (n, true)));
|
||||
st.lens.lock().unwrap_or_else(|e| e.into_inner()).tests = Some(v);
|
||||
}
|
||||
let stale = snap(&changed) != before;
|
||||
let mut last = self.last.lock().await;
|
||||
let body = if fails.is_empty() {
|
||||
@@ -633,6 +658,7 @@ mod t {
|
||||
let s = "running 3 tests\ntest a::ok ... ok\ntest a::bad ... FAILED\ntest b ... ignored\n\nfailures:\n\n---- a::bad stdout ----\n\nthread 'a::bad' panicked at src/lib.rs:9:5:\nassertion `left == right` failed\n left: 5\n right: 4\nnote: run with `RUST_BACKTRACE=1` environment variable to display a backtrace\n\n\nfailures:\n a::bad\n\ntest result: FAILED. 1 passed; 1 failed\n";
|
||||
let o = parse_libtest(s);
|
||||
assert_eq!(o.passed, 1);
|
||||
assert_eq!(o.ok_names, ["a::ok"]);
|
||||
assert_eq!(o.failures.len(), 1);
|
||||
assert_eq!(o.failures[0].name, "a::bad");
|
||||
assert!(
|
||||
|
||||
@@ -312,6 +312,9 @@ impl Tool for AskUser {
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes of running bash output kept for the live view.
|
||||
const LIVE_TAIL: usize = 2048;
|
||||
|
||||
pub struct Bash;
|
||||
#[async_trait]
|
||||
impl Tool for Bash {
|
||||
@@ -338,14 +341,37 @@ impl Tool for Bash {
|
||||
// own process group so timeouts kill children too
|
||||
#[cfg(unix)]
|
||||
c.process_group(0);
|
||||
let child = match c.spawn() {
|
||||
let mut child = match c.spawn() {
|
||||
Ok(c) => c,
|
||||
Err(e) => return ToolResult::err(format!("spawn: {e}")),
|
||||
};
|
||||
let pid = child.id();
|
||||
let res = tokio::time::timeout(Duration::from_secs(secs), child.wait_with_output()).await;
|
||||
// read output as it comes so the UI can show the last lines live (state.live)
|
||||
let mut so = child.stdout.take().expect("piped");
|
||||
let live = &cx.state.live;
|
||||
let run = async {
|
||||
use tokio::io::AsyncReadExt;
|
||||
let mut out = vec![];
|
||||
let mut chunk = [0u8; 8192];
|
||||
loop {
|
||||
match so.read(&mut chunk).await {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(n) => {
|
||||
out.extend_from_slice(&chunk[..n]);
|
||||
let start = out.len().saturating_sub(LIVE_TAIL);
|
||||
live.lock().unwrap_or_else(|e| e.into_inner()).insert(
|
||||
cmd.to_string(),
|
||||
String::from_utf8_lossy(&out[start..]).into(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
child.wait().await.map(|st| (out, st))
|
||||
};
|
||||
let res = tokio::time::timeout(Duration::from_secs(secs), run).await;
|
||||
live.lock().unwrap_or_else(|e| e.into_inner()).remove(cmd);
|
||||
let (out, code) = match res {
|
||||
Ok(Ok(o)) => (o.stdout, o.status.code()),
|
||||
Ok(Ok((o, st))) => (o, st.code()),
|
||||
Ok(Err(e)) => return ToolResult::err(format!("wait: {e}")),
|
||||
Err(_) => {
|
||||
#[cfg(unix)]
|
||||
@@ -449,6 +475,22 @@ mod tests {
|
||||
use super::*;
|
||||
use std::time::Instant;
|
||||
|
||||
#[tokio::test]
|
||||
async fn bash_streams_live_tail() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let c = cx(d.path());
|
||||
let cmd = "echo one; sleep 0.4; echo two";
|
||||
let st = c.state.clone();
|
||||
let peek = tokio::spawn(async move {
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
st.live.lock().unwrap().get(cmd).cloned()
|
||||
});
|
||||
let r = Bash.call(json!({"command": cmd}), &c).await;
|
||||
assert_eq!(peek.await.unwrap().as_deref(), Some("one\n"));
|
||||
assert_eq!(r.content, "one\ntwo\n");
|
||||
assert!(c.state.live.lock().unwrap().is_empty(), "cleared when done");
|
||||
}
|
||||
|
||||
fn cx(d: &Path) -> ToolCtx {
|
||||
ToolCtx {
|
||||
cwd: d.into(),
|
||||
|
||||
+94
-52
@@ -188,6 +188,8 @@ struct App {
|
||||
sub_t: std::collections::HashMap<usize, Transcript>,
|
||||
/// subagent list focused / one agent open
|
||||
agents: Option<agents::View>,
|
||||
/// output tokens of the current run: finished requests + streamed estimate (chars/4)
|
||||
run_tokens: (u64, u64),
|
||||
/// header: `~`-shortened cwd and (branch, dirty), refreshed after each run
|
||||
cwd_label: String,
|
||||
git: Option<(String, bool)>,
|
||||
@@ -333,6 +335,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
||||
expanded: false,
|
||||
busy: false,
|
||||
queue: VecDeque::new(),
|
||||
run_tokens: (0, 0),
|
||||
cwd_label: home_short(&cwd),
|
||||
git: git_head(&cwd),
|
||||
st: status::Status {
|
||||
@@ -500,7 +503,15 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
||||
if let Event::Stream(hx_ai::StreamEvent::Quota(q)) = &e {
|
||||
app.st.quota = Some(q.clone());
|
||||
}
|
||||
if let Event::Stream(
|
||||
hx_ai::StreamEvent::TextDelta { text }
|
||||
| hx_ai::StreamEvent::ThinkingDelta { text },
|
||||
) = &e
|
||||
{
|
||||
app.run_tokens.1 += text.len() as u64;
|
||||
}
|
||||
if let Event::Stream(hx_ai::StreamEvent::Done { usage, .. }) = &e {
|
||||
app.run_tokens = (app.run_tokens.0 + usage.output_tokens, 0);
|
||||
app.st.usage.add(usage);
|
||||
app.st.ctx_tokens = (usage.input_tokens + usage.cache_read_tokens + usage.cache_write_tokens + usage.output_tokens) as usize;
|
||||
}
|
||||
@@ -1395,6 +1406,7 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
|
||||
"compact" => {
|
||||
app.busy = true;
|
||||
app.since = Instant::now();
|
||||
app.run_tokens = (0, 0);
|
||||
app.t.push(Item::Info("compacting…".into()));
|
||||
let (agent, tx) = (agent.clone(), tx.clone());
|
||||
tokio::spawn(async move {
|
||||
@@ -1445,6 +1457,7 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
|
||||
}));
|
||||
app.busy = true;
|
||||
app.since = Instant::now();
|
||||
app.run_tokens = (0, 0);
|
||||
let prompt = expand_mentions(&line, cwd);
|
||||
let (agent, tx) = (agent.clone(), tx.clone());
|
||||
let effort = app.st.effort;
|
||||
@@ -1565,6 +1578,12 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
|
||||
}
|
||||
};
|
||||
app.areas.chat = main;
|
||||
app.t.live = app
|
||||
.state
|
||||
.live
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.clone();
|
||||
let para = Paragraph::new(app.t.lines(app.expanded, main.width)).wrap(Wrap { trim: false });
|
||||
let total = para.line_count(main.width) as u16;
|
||||
let top = app.scroll.resolve(total, main.height);
|
||||
@@ -1603,6 +1622,7 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
|
||||
al.push(transcript::activity_line(
|
||||
&what,
|
||||
app.since.elapsed(),
|
||||
app.run_tokens.0 + app.run_tokens.1 / 4,
|
||||
frame,
|
||||
act.width,
|
||||
));
|
||||
@@ -1686,8 +1706,11 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
|
||||
}
|
||||
}
|
||||
|
||||
const SIDE_DIAGS: usize = 8;
|
||||
const SIDE_TESTS: usize = 6;
|
||||
|
||||
/// Right-hand lens panel on wide terminals: servers, last turn's diagnostics and tests,
|
||||
/// context numbers, MCP servers. Built from `/lsp` status lines and the last lens report.
|
||||
/// context numbers, MCP servers. Servers from `/lsp` status lines, findings from `State::lens`.
|
||||
fn side_lines(app: &App, w: usize) -> Vec<Line<'static>> {
|
||||
let th = theme::t();
|
||||
let sec = |label: String| {
|
||||
@@ -1731,60 +1754,58 @@ fn side_lines(app: &App, w: usize) -> Vec<Line<'static>> {
|
||||
Span::styled(format!(" {word}"), th.sec()),
|
||||
]));
|
||||
}
|
||||
// last lens report in the transcript
|
||||
let last = app.t.items.iter().rev().find_map(|i| match i {
|
||||
Item::Lens(v) => Some(v),
|
||||
_ => None,
|
||||
});
|
||||
let diag = last.and_then(|v| v.iter().find(|t| t.contains("diagnostics")));
|
||||
let tests = last.and_then(|v| v.iter().find(|t| t.contains("test")));
|
||||
if let Some(d) = diag {
|
||||
let mut file = "";
|
||||
let mut items = vec![];
|
||||
for x in d.lines().skip(1) {
|
||||
if let Some(f) = x.strip_suffix(':').filter(|_| !x.starts_with(' ')) {
|
||||
file = f.rsplit('/').next().unwrap_or(f);
|
||||
} else if let Some((pos, rest)) = x.trim().split_once(' ') {
|
||||
let (mark, st) = if rest.starts_with("error") {
|
||||
(th.sym.err, th.err())
|
||||
} else {
|
||||
(th.sym.warn, th.warn())
|
||||
};
|
||||
let msg = rest.split_once(": ").map_or(rest, |p| p.1);
|
||||
// drop the trailing `(server)` tag
|
||||
let msg = msg.rsplit_once(" (").map_or(msg, |p| p.0);
|
||||
items.push(Line::from(vec![
|
||||
Span::styled(format!("{mark} "), st),
|
||||
Span::styled(format!("{file}:{pos}"), th.plain()),
|
||||
]));
|
||||
items.push(Line::styled(format!(" {msg}"), 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(),
|
||||
));
|
||||
}
|
||||
l.push(Line::default());
|
||||
l.push(sec(format!("diagnostics {}", items.len() / 2)));
|
||||
l.extend(items);
|
||||
}
|
||||
if let Some(t) = tests {
|
||||
let first = t.lines().next().unwrap_or_default();
|
||||
let first = first
|
||||
.strip_prefix("[lens] ")
|
||||
.unwrap_or(first)
|
||||
.trim_end_matches(':');
|
||||
let bad = first.contains("failing");
|
||||
if let Some(ts) = &view.tests {
|
||||
let mut ts = ts.clone();
|
||||
// failures first
|
||||
ts.sort_by_key(|t| t.1);
|
||||
l.push(Line::default());
|
||||
l.push(sec("tests".into()));
|
||||
l.push(Line::from(vec![
|
||||
Span::styled(
|
||||
format!("{} ", if bad { th.sym.err } else { th.sym.ok }),
|
||||
if bad { th.err() } else { th.ok() },
|
||||
),
|
||||
Span::styled(first.trim_start_matches("tests: ").to_string(), th.plain()),
|
||||
]));
|
||||
l.extend(
|
||||
t.lines()
|
||||
.skip(1)
|
||||
.map(|x| Line::styled(format!(" {}", x.trim()), th.sec())),
|
||||
);
|
||||
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;
|
||||
@@ -2068,7 +2089,27 @@ mod tests {
|
||||
let mut app = test_app();
|
||||
app.mcp = vec![("git".into(), true), ("db".into(), false)];
|
||||
app.lens_lines = vec!["rust-analyzer @ /p: running".into()];
|
||||
*app.state.lens.lock().unwrap() = hx_core::LensView {
|
||||
diags: vec![hx_core::Diag {
|
||||
file: "crates/a/src/codemode.rs".into(),
|
||||
line: 88,
|
||||
col: 13,
|
||||
error: false,
|
||||
message: "unused variable".into(),
|
||||
}],
|
||||
tests: Some(vec![("a::ok".into(), true), ("a::bad".into(), false)]),
|
||||
};
|
||||
let s = screen(&mut app, 160, 50);
|
||||
assert!(
|
||||
s.contains("diagnostics 1 ┈") && s.contains("⚠ codemode.rs:88:13"),
|
||||
"{s}"
|
||||
);
|
||||
assert!(
|
||||
s.contains("affected tests 2 ┈") && s.contains("✗ a::bad"),
|
||||
"{s}"
|
||||
);
|
||||
let bad = s.find("✗ a::bad").unwrap();
|
||||
assert!(bad < s.find("✓ a::ok").unwrap(), "failures first");
|
||||
assert!(
|
||||
s.contains("/lsp") && s.contains("● rust-analyzer ready"),
|
||||
"{s}"
|
||||
@@ -2331,6 +2372,7 @@ mod tests {
|
||||
|
||||
fn test_app() -> App {
|
||||
App {
|
||||
run_tokens: (0, 0),
|
||||
cwd_label: "~/w".into(),
|
||||
git: None,
|
||||
t: Transcript::default(),
|
||||
|
||||
@@ -30,6 +30,8 @@ pub enum Item {
|
||||
#[derive(Default)]
|
||||
pub struct Transcript {
|
||||
pub items: Vec<Item>,
|
||||
/// live output tails of running bash calls by command (copied from `State::live` per draw)
|
||||
pub live: std::collections::HashMap<String, String>,
|
||||
/// true while the last Assistant/Thinking item is still streaming
|
||||
streaming: bool,
|
||||
}
|
||||
@@ -97,6 +99,17 @@ impl Transcript {
|
||||
let mut out = vec![];
|
||||
for (n, it) in self.items.iter().enumerate() {
|
||||
render(it, expanded, width as usize, &mut out);
|
||||
if let Item::Tool {
|
||||
name,
|
||||
args,
|
||||
result: None,
|
||||
..
|
||||
} = it
|
||||
&& name == "bash"
|
||||
&& let Some(tail) = args["command"].as_str().and_then(|c| self.live.get(c))
|
||||
{
|
||||
live_tail(tail, width as usize, &mut out);
|
||||
}
|
||||
// consecutive tool calls stack without a gap
|
||||
let tool = |i: Option<&Item>| matches!(i, Some(Item::Tool { .. }));
|
||||
if !(tool(Some(it)) && tool(self.items.get(n + 1))) {
|
||||
@@ -120,13 +133,28 @@ impl Transcript {
|
||||
}
|
||||
}
|
||||
|
||||
/// `⠹ working 38s · bash esc to abort` — `frame` picks the spinner glyph.
|
||||
pub fn activity_line(what: &str, elapsed: Duration, frame: usize, width: u16) -> Line<'static> {
|
||||
/// `⠹ working 38s · bash · ↓ 4.1k tokens esc to abort` — `frame` picks the spinner
|
||||
/// glyph, `tokens` = output tokens of this run so far.
|
||||
pub fn activity_line(
|
||||
what: &str,
|
||||
elapsed: Duration,
|
||||
tokens: u64,
|
||||
frame: usize,
|
||||
width: u16,
|
||||
) -> Line<'static> {
|
||||
let th = theme::t();
|
||||
let tk = if tokens >= 1000 {
|
||||
format!("{:.1}k", tokens as f64 / 1000.0)
|
||||
} else {
|
||||
tokens.to_string()
|
||||
};
|
||||
let left = vec![
|
||||
Span::styled(format!("{} ", th.spin(frame)), th.accent()),
|
||||
Span::styled(format!("working {}s", elapsed.as_secs()), th.accent()),
|
||||
Span::styled(format!(" {} {what}", th.sym.info), th.sec()),
|
||||
Span::styled(
|
||||
format!(" {0} {what} {0} {1} {tk} tokens", th.sym.info, th.sym.down),
|
||||
th.sec(),
|
||||
),
|
||||
];
|
||||
let hint = Span::styled("esc to abort", th.dim());
|
||||
let lw: usize = left.iter().map(Span::width).sum();
|
||||
@@ -138,6 +166,25 @@ pub fn activity_line(what: &str, elapsed: Duration, frame: usize, width: u16) ->
|
||||
Line::from(l)
|
||||
}
|
||||
|
||||
/// Last [`LIVE_LINES`] non-empty lines of a running command, dim and indented.
|
||||
fn live_tail(tail: &str, width: usize, out: &mut Vec<Line<'static>>) {
|
||||
let th = theme::t();
|
||||
// carriage returns (progress bars): keep what's after the last one per line
|
||||
let ls: Vec<&str> = tail
|
||||
.lines()
|
||||
.map(|l| l.rsplit('\r').next().unwrap_or(l))
|
||||
.filter(|l| !l.trim().is_empty())
|
||||
.collect();
|
||||
for l in &ls[ls.len().saturating_sub(LIVE_LINES)..] {
|
||||
out.push(Line::styled(
|
||||
format!(" {}", fit(l, width.saturating_sub(4))),
|
||||
th.dim(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
const LIVE_LINES: usize = 2;
|
||||
|
||||
fn target(args: &Value) -> String {
|
||||
let s = ["path", "command", "pattern", "query"]
|
||||
.iter()
|
||||
@@ -727,8 +774,29 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn activity() {
|
||||
let l = activity_line("bash", Duration::from_millis(12_900), 2, 40);
|
||||
assert_eq!(text(&[l]), ["⠹ working 12s · bash esc to abort"]);
|
||||
let l = activity_line("bash", Duration::from_millis(12_900), 4130, 2, 60);
|
||||
assert_eq!(
|
||||
text(&[l]),
|
||||
["⠹ working 12s · bash · ↓ 4.1k tokens esc to abort"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn running_bash_shows_live_tail() {
|
||||
let mut t = Transcript::default();
|
||||
t.apply(&Event::ToolCall {
|
||||
id: "1".into(),
|
||||
name: "bash".into(),
|
||||
args: json!({"command": "cargo test"}),
|
||||
});
|
||||
t.live.insert(
|
||||
"cargo test".into(),
|
||||
" Compiling a\n\n Compiling b\nprogress 10%\rprogress 90%\n".into(),
|
||||
);
|
||||
let s = text(&t.lines(false, 40));
|
||||
assert_eq!(s[1..3], [" Compiling b", " progress 90%"], "{s:?}");
|
||||
t.live.clear();
|
||||
assert_eq!(t.lines(false, 40).len(), 2, "no tail when nothing is live");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Reference in new issue
Block a user