Merge pull request 'M9: theme, turn layout, footer, input, activity line' (#84) from m9-tui into main
ci / check (push) Canceled after 0s
ci / check (push) Canceled after 0s
This commit was merged in pull request #84.
This commit is contained in:
commit
b3960a09ed
4 files changed
+667
-186
No files matched your search
+171
-79
@@ -1,6 +1,7 @@
|
||||
//! Interactive terminal UI.
|
||||
|
||||
pub mod editor;
|
||||
pub mod theme;
|
||||
pub mod transcript;
|
||||
|
||||
use crossterm::event::{
|
||||
@@ -14,12 +15,13 @@ use hx_core::agent::{AbortHandle, Agent};
|
||||
use hx_core::command::{self as cmd, CmdSpec, Completion, Source};
|
||||
use hx_core::hook::{Event, Hook, HookAction};
|
||||
use ratatui::layout::{Constraint, Layout, Rect};
|
||||
use ratatui::style::{Color, Style};
|
||||
use ratatui::style::Modifier;
|
||||
use ratatui::text::Line;
|
||||
use ratatui::text::Span;
|
||||
use ratatui::widgets::{Block, Borders, Clear, Paragraph, Wrap};
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
use tokio::sync::{Mutex, mpsc};
|
||||
use transcript::{Item, Transcript};
|
||||
|
||||
@@ -91,6 +93,11 @@ struct App {
|
||||
model: String,
|
||||
usage: Usage,
|
||||
ctx_tokens: usize,
|
||||
/// auto-compact threshold: the context bar's 100%
|
||||
ctx_max: usize,
|
||||
pricing: fn(&str) -> Option<hx_ai::Pricing>,
|
||||
/// when the current run started (activity line)
|
||||
since: Instant,
|
||||
quit: bool,
|
||||
hint: String,
|
||||
specs: Vec<CmdSpec>,
|
||||
@@ -100,8 +107,9 @@ struct App {
|
||||
ask: Option<(String, tokio::sync::oneshot::Sender<bool>)>,
|
||||
}
|
||||
|
||||
const KEYS: &str = "enter send · alt-enter/ctrl-j newline · esc/ctrl-c abort · ctrl-o expand tools · pgup/pgdn scroll · \
|
||||
tab complete @file / command · /help commands";
|
||||
const KEYS: &str = "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 · /help keys";
|
||||
|
||||
pub fn project_files(root: &std::path::Path) -> Vec<String> {
|
||||
ignore::WalkBuilder::new(root)
|
||||
@@ -172,6 +180,9 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
||||
model: agent.model.clone(),
|
||||
usage: Usage::default(),
|
||||
ctx_tokens: hx_core::agent::estimate_tokens(&agent.session.messages()),
|
||||
ctx_max: agent.compact_at,
|
||||
pricing,
|
||||
since: Instant::now(),
|
||||
quit: false,
|
||||
hint: String::new(),
|
||||
specs,
|
||||
@@ -192,10 +203,8 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
||||
}
|
||||
}
|
||||
}
|
||||
app.t.push(Item::Info(format!(
|
||||
"hx · {:?} · {} · {KEYS}",
|
||||
app.kind, app.model
|
||||
)));
|
||||
app.t
|
||||
.push(Item::Info(format!("hx · {:?} · {}", app.kind, app.model)));
|
||||
let agent = Arc::new(Mutex::new(agent));
|
||||
|
||||
let ctx = Ctx {
|
||||
@@ -495,6 +504,7 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
|
||||
},
|
||||
"compact" => {
|
||||
app.busy = true;
|
||||
app.since = Instant::now();
|
||||
app.t.push(Item::Info("compacting…".into()));
|
||||
let (agent, tx) = (agent.clone(), tx.clone());
|
||||
tokio::spawn(async move {
|
||||
@@ -552,6 +562,7 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
|
||||
line.clone()
|
||||
}));
|
||||
app.busy = true;
|
||||
app.since = Instant::now();
|
||||
let prompt = expand_mentions(&line, cwd);
|
||||
let (agent, tx) = (agent.clone(), tx.clone());
|
||||
tokio::spawn(async move {
|
||||
@@ -567,72 +578,128 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
|
||||
}
|
||||
|
||||
fn draw(f: &mut ratatui::Frame, app: &mut App) {
|
||||
let th = theme::t();
|
||||
let input_h = (app.ed.buf.lines().count().max(1) + usize::from(app.ed.buf.ends_with('\n')))
|
||||
.min(10) as u16
|
||||
+ 2;
|
||||
let [main, status, input] = Layout::vertical([
|
||||
let act_h = u16::from(app.busy);
|
||||
let [main, act, input, status] = Layout::vertical([
|
||||
Constraint::Min(3),
|
||||
Constraint::Length(1),
|
||||
Constraint::Length(act_h),
|
||||
Constraint::Length(input_h),
|
||||
Constraint::Length(1),
|
||||
])
|
||||
.areas(f.area());
|
||||
|
||||
let para = Paragraph::new(app.t.lines(app.expanded)).wrap(Wrap { trim: false });
|
||||
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 max_up = total.saturating_sub(main.height);
|
||||
app.scroll = app.scroll.min(max_up);
|
||||
f.render_widget(para.scroll((max_up - app.scroll, 0)), main);
|
||||
|
||||
let spin = if app.busy {
|
||||
["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"][(std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_millis()
|
||||
/ 80
|
||||
% 10) as usize]
|
||||
} else {
|
||||
" "
|
||||
};
|
||||
let q = if app.queue.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(" · {} queued", app.queue.len())
|
||||
};
|
||||
let up = if app.scroll > 0 {
|
||||
format!(" · ↑{}", app.scroll)
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
let st = if let Some((q, _)) = &app.ask {
|
||||
format!("[y/n] {q}")
|
||||
} else if app.hint.is_empty() {
|
||||
format!(
|
||||
"{spin} {:?} · {} · ctx {}k · {}↑ {}↓{q}{up}",
|
||||
app.kind,
|
||||
app.model,
|
||||
app.ctx_tokens / 1000,
|
||||
app.usage.input_tokens + app.usage.cache_read_tokens,
|
||||
app.usage.output_tokens
|
||||
)
|
||||
} else {
|
||||
app.hint.clone()
|
||||
};
|
||||
f.render_widget(
|
||||
Line::styled(st, Style::default().fg(Color::DarkGray)),
|
||||
status,
|
||||
);
|
||||
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;
|
||||
f.render_widget(transcript::activity_line(&what, t0.elapsed(), frame), act);
|
||||
}
|
||||
|
||||
let block = Block::default()
|
||||
.borders(Borders::TOP | Borders::BOTTOM)
|
||||
.border_style(Style::default().fg(Color::DarkGray));
|
||||
.border_style(th.dim());
|
||||
let inner = block.inner(input);
|
||||
f.render_widget(Paragraph::new(app.ed.buf.as_str()).block(block), input);
|
||||
if let Some((c, sel)) = &app.popup {
|
||||
draw_popup(f, c, *sel, input);
|
||||
}
|
||||
f.render_widget(block, input);
|
||||
let [gut, text] = Layout::horizontal([Constraint::Length(2), Constraint::Min(1)]).areas(inner);
|
||||
f.render_widget(
|
||||
Span::styled(
|
||||
format!("{} ", th.sym.user),
|
||||
th.accent().add_modifier(Modifier::BOLD),
|
||||
),
|
||||
gut,
|
||||
);
|
||||
let (r, c) = app.ed.cursor_rc();
|
||||
let skip = (r as u16).saturating_sub(inner.height.saturating_sub(1));
|
||||
f.set_cursor_position((inner.x + c as u16, inner.y + r as u16 - skip));
|
||||
let skip = (r as u16).saturating_sub(text.height.saturating_sub(1));
|
||||
if app.ed.buf.is_empty() {
|
||||
f.render_widget(Span::styled(PLACEHOLDER, th.dim()), text);
|
||||
} else {
|
||||
f.render_widget(Paragraph::new(app.ed.buf.as_str()).scroll((skip, 0)), text);
|
||||
}
|
||||
f.render_widget(footer(app, status.width), status);
|
||||
if let Some((comp, sel)) = &app.popup {
|
||||
let col = Span::raw(
|
||||
&app.ed.buf[app.ed.buf[..comp.start].rfind('\n').map_or(0, |i| i + 1)..comp.start],
|
||||
)
|
||||
.width() as u16;
|
||||
draw_popup(f, comp, *sel, text.x + col, input.y);
|
||||
}
|
||||
f.set_cursor_position((text.x + c as u16, text.y + r as u16 - skip));
|
||||
}
|
||||
|
||||
/// `ctx ▰▰▰▱▱▱▱▱▱▱ 41k/150k · 12.3k↑ 2.1k↓ ~$0.08` left, `Claude · model · 1 queued` right.
|
||||
/// Hints replace the right side; a pending y/n question takes the whole line.
|
||||
fn footer(app: &App, width: u16) -> Line<'static> {
|
||||
let th = theme::t();
|
||||
if let Some((q, _)) = &app.ask {
|
||||
return Line::styled(format!("[y/n] {q}"), th.warn().add_modifier(Modifier::BOLD));
|
||||
}
|
||||
let k = |n: u64| {
|
||||
if n >= 1000 {
|
||||
format!("{:.1}k", n as f64 / 1000.0)
|
||||
} else {
|
||||
n.to_string()
|
||||
}
|
||||
};
|
||||
let frac = app.ctx_tokens as f64 / app.ctx_max.max(1) as f64;
|
||||
let full = ((frac * 10.0).round() as usize).min(10);
|
||||
let bar_st = match frac {
|
||||
f if f >= 0.9 => th.err(),
|
||||
f if f >= 0.7 => th.warn(),
|
||||
_ => th.accent(),
|
||||
};
|
||||
let cost = (app.pricing)(&app.model)
|
||||
.map(|p| format!(" ~${:.2}", app.usage.cost(&p)))
|
||||
.unwrap_or_default();
|
||||
let mut left = vec![
|
||||
Span::styled("ctx ", th.dim()),
|
||||
Span::styled(th.sym.bar_full.repeat(full), bar_st),
|
||||
Span::styled(th.sym.bar_empty.repeat(10 - full), th.dim()),
|
||||
Span::styled(
|
||||
format!(" {}k/{}k", app.ctx_tokens / 1000, app.ctx_max / 1000),
|
||||
th.dim(),
|
||||
),
|
||||
Span::styled(
|
||||
format!(
|
||||
" · {}↑ {}↓{cost}",
|
||||
k(app.usage.input_tokens + app.usage.cache_read_tokens),
|
||||
k(app.usage.output_tokens)
|
||||
),
|
||||
th.dim(),
|
||||
),
|
||||
];
|
||||
let right = if app.hint.is_empty() {
|
||||
let mut v = vec![format!("{:?}", app.kind), app.model.clone()];
|
||||
if !app.queue.is_empty() {
|
||||
v.push(format!("{} queued", app.queue.len()));
|
||||
}
|
||||
if app.scroll > 0 {
|
||||
v.push(format!("↑{}", app.scroll));
|
||||
}
|
||||
Span::styled(v.join(" · "), th.dim())
|
||||
} else {
|
||||
Span::styled(app.hint.clone(), th.accent())
|
||||
};
|
||||
let w = width as usize;
|
||||
let lw = |l: &[Span]| l.iter().map(Span::width).sum::<usize>();
|
||||
// narrow terminals: drop token counts, then the whole left side
|
||||
if lw(&left) + right.width() + 1 > w {
|
||||
left.pop();
|
||||
}
|
||||
if lw(&left) + right.width() + 1 > w {
|
||||
return Line::from(right);
|
||||
}
|
||||
let pad = w - lw(&left) - right.width();
|
||||
left.push(Span::raw(" ".repeat(pad.max(1))));
|
||||
left.push(right);
|
||||
Line::from(left)
|
||||
}
|
||||
|
||||
/// `/skills`: each skill with its file, then the searched dirs (so a missing skill is easy to debug).
|
||||
@@ -662,35 +729,40 @@ fn skills_list(specs: &[CmdSpec], dirs: &[std::path::PathBuf]) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// Candidates stacked just above the input box.
|
||||
fn draw_popup(f: &mut ratatui::Frame, c: &Completion, sel: usize, input: Rect) {
|
||||
let h = (c.items.len() as u16).min(input.y);
|
||||
let w = c
|
||||
/// Bordered candidate list ending just above row `bottom`, starting at column `x` (the token).
|
||||
fn draw_popup(f: &mut ratatui::Frame, c: &Completion, sel: usize, x: u16, bottom: u16) {
|
||||
let th = theme::t();
|
||||
let lw = c
|
||||
.items
|
||||
.iter()
|
||||
.map(|i| i.label.chars().count() + i.detail.chars().count() + 3)
|
||||
.map(|i| i.label.chars().count())
|
||||
.max()
|
||||
.unwrap_or(0)
|
||||
.min(f.area().width as usize) as u16;
|
||||
let area = Rect::new(input.x, input.y - h, w, h);
|
||||
.unwrap_or(0);
|
||||
let lines: Vec<Line> = c
|
||||
.items
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(n, i)| {
|
||||
let base = if n == sel {
|
||||
Style::default().bg(Color::DarkGray).fg(Color::White)
|
||||
} else {
|
||||
Style::default()
|
||||
};
|
||||
let base = if n == sel { th.sel() } else { th.plain() };
|
||||
Line::from(vec![
|
||||
Span::styled(format!(" {} ", i.label), base),
|
||||
Span::styled(format!("{} ", i.detail), base.fg(Color::Gray)),
|
||||
Span::styled(format!(" {:<lw$} ", i.label), base),
|
||||
Span::styled(
|
||||
format!("{} ", i.detail),
|
||||
if n == sel { base } else { th.dim() },
|
||||
),
|
||||
])
|
||||
})
|
||||
.collect();
|
||||
f.render_widget(Clear, area);
|
||||
f.render_widget(Paragraph::new(lines), area);
|
||||
let area = f.area();
|
||||
let w = (lines.iter().map(Line::width).max().unwrap_or(0) as u16 + 2).min(area.width);
|
||||
let h = (lines.len() as u16 + 2).min(bottom);
|
||||
let x = x.saturating_sub(1).min(area.width - w);
|
||||
let r = Rect::new(x, bottom - h, w, h);
|
||||
f.render_widget(Clear, r);
|
||||
f.render_widget(
|
||||
Paragraph::new(lines).block(Block::bordered().border_style(th.dim())),
|
||||
r,
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -722,6 +794,9 @@ mod tests {
|
||||
model: "m1".into(),
|
||||
usage: Usage::default(),
|
||||
ctx_tokens: 12_000,
|
||||
ctx_max: 150_000,
|
||||
pricing: |_| None,
|
||||
since: Instant::now(),
|
||||
quit: false,
|
||||
hint: String::new(),
|
||||
specs: vec![],
|
||||
@@ -738,10 +813,11 @@ mod tests {
|
||||
.map(|y| (0..40).map(|x| buf[(x, y)].symbol().to_string()).collect())
|
||||
.collect();
|
||||
let all = rows.join("\n");
|
||||
assert!(all.contains("> hello"), "{all}");
|
||||
assert!(all.contains("hi there"), "{all}");
|
||||
assert!(all.contains("Claude · m1 · ctx 12k"), "{all}");
|
||||
assert!(rows[8].starts_with("typing"), "{all}");
|
||||
assert!(all.contains("❯ hello"), "{all}");
|
||||
assert!(all.contains("◆ hi there"), "{all}");
|
||||
assert!(rows[7].starts_with("❯ typing"), "{all}");
|
||||
assert!(rows[9].starts_with("ctx ▰▱▱▱▱▱▱▱▱▱ 12k/150k "), "{all}");
|
||||
assert!(rows[9].ends_with("Claude · m1"), "{all}");
|
||||
}
|
||||
|
||||
fn key(app: &mut App, code: KeyCode) -> Option<String> {
|
||||
@@ -765,6 +841,9 @@ mod tests {
|
||||
model: "m1".into(),
|
||||
usage: Usage::default(),
|
||||
ctx_tokens: 0,
|
||||
ctx_max: 150_000,
|
||||
pricing: |_| None,
|
||||
since: Instant::now(),
|
||||
quit: false,
|
||||
hint: String::new(),
|
||||
specs: cmd::builtins(&["sonnet", "opus"]),
|
||||
@@ -814,11 +893,24 @@ mod tests {
|
||||
let rows: Vec<String> = (0..10)
|
||||
.map(|y| (0..40).map(|x| buf[(x, y)].symbol().to_string()).collect())
|
||||
.collect();
|
||||
assert!(
|
||||
rows[5].starts_with(" /clear start an empty session"),
|
||||
assert_eq!(
|
||||
rows[3], " │ /clear start an empty session │ ",
|
||||
"{rows:#?}"
|
||||
);
|
||||
assert!(rows[6].starts_with(" /compact summarize"), "{rows:#?}");
|
||||
assert!(rows[4].starts_with(" │ /compact summarize"), "{rows:#?}");
|
||||
assert!(rows[9].ends_with("Claude · m1"), "{rows:#?}");
|
||||
|
||||
// footer at 100 cols, and a hint replacing only the right side
|
||||
app.hint = "no match".into();
|
||||
let mut term = ratatui::Terminal::new(TestBackend::new(100, 10)).unwrap();
|
||||
term.draw(|f| draw(f, &mut app)).unwrap();
|
||||
let buf = term.backend().buffer().clone();
|
||||
let last: String = (0..100).map(|x| buf[(x, 9)].symbol().to_string()).collect();
|
||||
assert!(
|
||||
last.starts_with("ctx ▱▱▱▱▱▱▱▱▱▱ 0k/150k · 0↑ 0↓") && last.ends_with("no match"),
|
||||
"{last}"
|
||||
);
|
||||
app.hint.clear();
|
||||
key(&mut app, KeyCode::Down);
|
||||
key(&mut app, KeyCode::Up);
|
||||
key(&mut app, KeyCode::Up);
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
//! Styles and symbols. `NO_COLOR` drops colours (modifiers stay); `HX_ASCII=1` swaps in ASCII symbols.
|
||||
|
||||
use ratatui::style::{Color, Modifier, Style};
|
||||
use std::sync::OnceLock;
|
||||
|
||||
pub struct Sym {
|
||||
pub user: &'static str,
|
||||
pub asst: &'static str,
|
||||
pub ok: &'static str,
|
||||
pub err: &'static str,
|
||||
pub pending: &'static str,
|
||||
pub more: &'static str,
|
||||
pub gutter: &'static str,
|
||||
pub bar_full: &'static str,
|
||||
pub bar_empty: &'static str,
|
||||
pub info: &'static str,
|
||||
pub ellipsis: &'static str,
|
||||
pub minus: &'static str,
|
||||
}
|
||||
|
||||
const UNICODE: Sym = Sym {
|
||||
user: "❯",
|
||||
asst: "◆",
|
||||
ok: "✓",
|
||||
err: "✗",
|
||||
pending: "○",
|
||||
more: "▸",
|
||||
gutter: "│",
|
||||
bar_full: "▰",
|
||||
bar_empty: "▱",
|
||||
info: "·",
|
||||
ellipsis: "…",
|
||||
minus: "−",
|
||||
};
|
||||
|
||||
const ASCII: Sym = Sym {
|
||||
user: ">",
|
||||
asst: "*",
|
||||
ok: "+",
|
||||
err: "x",
|
||||
pending: "o",
|
||||
more: ">",
|
||||
gutter: "|",
|
||||
bar_full: "#",
|
||||
bar_empty: "-",
|
||||
info: "-",
|
||||
ellipsis: "...",
|
||||
minus: "-",
|
||||
};
|
||||
|
||||
pub struct Theme {
|
||||
color: bool,
|
||||
pub sym: &'static Sym,
|
||||
}
|
||||
|
||||
impl Theme {
|
||||
pub fn new(color: bool, ascii: bool) -> Self {
|
||||
Self {
|
||||
color,
|
||||
sym: if ascii { &ASCII } else { &UNICODE },
|
||||
}
|
||||
}
|
||||
|
||||
fn fg(&self, c: Color) -> Style {
|
||||
if self.color {
|
||||
Style::default().fg(c)
|
||||
} else {
|
||||
Style::default()
|
||||
}
|
||||
}
|
||||
pub fn plain(&self) -> Style {
|
||||
Style::default()
|
||||
}
|
||||
pub fn accent(&self) -> Style {
|
||||
self.fg(Color::Cyan)
|
||||
}
|
||||
pub fn dim(&self) -> Style {
|
||||
if self.color {
|
||||
self.fg(Color::DarkGray)
|
||||
} else {
|
||||
Style::default().add_modifier(Modifier::DIM)
|
||||
}
|
||||
}
|
||||
pub fn ok(&self) -> Style {
|
||||
self.fg(Color::Green)
|
||||
}
|
||||
pub fn warn(&self) -> Style {
|
||||
self.fg(Color::Yellow)
|
||||
}
|
||||
pub fn err(&self) -> Style {
|
||||
self.fg(Color::Red)
|
||||
}
|
||||
pub fn add(&self) -> Style {
|
||||
self.fg(Color::Green)
|
||||
}
|
||||
pub fn del(&self) -> Style {
|
||||
self.fg(Color::Red)
|
||||
}
|
||||
pub fn hunk(&self) -> Style {
|
||||
self.fg(Color::Cyan)
|
||||
}
|
||||
pub fn code(&self) -> Style {
|
||||
self.fg(Color::Yellow)
|
||||
}
|
||||
pub fn block_code(&self) -> Style {
|
||||
self.fg(Color::Cyan)
|
||||
}
|
||||
/// Selected row in lists.
|
||||
pub fn sel(&self) -> Style {
|
||||
if self.color {
|
||||
Style::default().bg(Color::DarkGray).fg(Color::White)
|
||||
} else {
|
||||
Style::default().add_modifier(Modifier::REVERSED)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The process-wide theme, read from the environment once.
|
||||
pub fn t() -> &'static Theme {
|
||||
static T: OnceLock<Theme> = OnceLock::new();
|
||||
T.get_or_init(|| {
|
||||
let set = |k| std::env::var_os(k).is_some_and(|v| !v.is_empty() && v != "0");
|
||||
Theme::new(!set("NO_COLOR"), set("HX_ASCII"))
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn fallbacks() {
|
||||
let c = Theme::new(true, false);
|
||||
assert_eq!(c.err().fg, Some(Color::Red));
|
||||
assert_eq!(c.sym.ok, "✓");
|
||||
let n = Theme::new(false, true);
|
||||
assert_eq!(n.err().fg, None);
|
||||
assert!(n.dim().add_modifier.contains(Modifier::DIM));
|
||||
assert!(n.sel().add_modifier.contains(Modifier::REVERSED));
|
||||
assert_eq!((n.sym.ok, n.sym.user), ("+", ">"));
|
||||
}
|
||||
}
|
||||
+352
-106
@@ -1,10 +1,12 @@
|
||||
//! Transcript model and rendering (markdown-ish text, tool calls, diffs).
|
||||
|
||||
use crate::theme;
|
||||
use hx_ai::StreamEvent;
|
||||
use hx_core::hook::Event;
|
||||
use ratatui::style::{Color, Modifier, Style};
|
||||
use ratatui::style::{Modifier, Style};
|
||||
use ratatui::text::{Line, Span};
|
||||
use serde_json::Value;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Item {
|
||||
@@ -16,6 +18,8 @@ pub enum Item {
|
||||
name: String,
|
||||
args: Value,
|
||||
result: Option<(String, bool)>,
|
||||
started: Instant,
|
||||
took: Option<Duration>,
|
||||
},
|
||||
Info(String),
|
||||
Error(String),
|
||||
@@ -56,6 +60,8 @@ impl Transcript {
|
||||
name: name.clone(),
|
||||
args: args.clone(),
|
||||
result: None,
|
||||
started: Instant::now(),
|
||||
took: None,
|
||||
}),
|
||||
Event::ToolResult {
|
||||
id,
|
||||
@@ -63,13 +69,19 @@ impl Transcript {
|
||||
is_error,
|
||||
..
|
||||
} => {
|
||||
if let Some(Item::Tool { result, .. }) = self
|
||||
if let Some(Item::Tool {
|
||||
result,
|
||||
started,
|
||||
took,
|
||||
..
|
||||
}) = self
|
||||
.items
|
||||
.iter_mut()
|
||||
.rev()
|
||||
.find(|i| matches!(i, Item::Tool { id: x, .. } if x == id))
|
||||
{
|
||||
*result = Some((content.clone(), *is_error));
|
||||
*took = Some(started.elapsed());
|
||||
}
|
||||
}
|
||||
Event::Info(s) => self.push(Item::Info(s.clone())),
|
||||
@@ -77,125 +89,283 @@ impl Transcript {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn lines(&self, expanded: bool) -> Vec<Line<'static>> {
|
||||
/// Rendered lines for a transcript `width` columns wide (tool headers right-align to it).
|
||||
pub fn lines(&self, expanded: bool, width: u16) -> Vec<Line<'static>> {
|
||||
let mut out = vec![];
|
||||
for it in &self.items {
|
||||
render(it, expanded, &mut out);
|
||||
out.push(Line::default());
|
||||
for (n, it) in self.items.iter().enumerate() {
|
||||
render(it, expanded, 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))) {
|
||||
out.push(Line::default());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The tool running right now, for the activity line.
|
||||
pub fn running(&self) -> Option<(String, Instant)> {
|
||||
self.items.iter().rev().find_map(|i| match i {
|
||||
Item::Tool {
|
||||
name,
|
||||
result: None,
|
||||
started,
|
||||
..
|
||||
} => Some((name.clone(), *started)),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn dim() -> Style {
|
||||
Style::default().fg(Color::DarkGray)
|
||||
/// `⠹ bash 12s` — `frame` picks the spinner glyph, `elapsed` is shown in whole seconds.
|
||||
pub fn activity_line(what: &str, elapsed: Duration, frame: usize) -> Line<'static> {
|
||||
const SPIN: [&str; 10] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
|
||||
let th = theme::t();
|
||||
let g = if th.sym.ok == "+" {
|
||||
["-", "\\", "|", "/"][frame % 4]
|
||||
} else {
|
||||
SPIN[frame % 10]
|
||||
};
|
||||
Line::from(vec![
|
||||
Span::styled(format!(" {g} "), th.accent()),
|
||||
Span::styled(format!("{what} {}s", elapsed.as_secs()), th.dim()),
|
||||
])
|
||||
}
|
||||
|
||||
fn summary(name: &str, args: &Value) -> String {
|
||||
fn target(args: &Value) -> String {
|
||||
let s = ["path", "command", "pattern", "query"]
|
||||
.iter()
|
||||
.find_map(|k| args[*k].as_str());
|
||||
let s = s.map_or_else(|| args.to_string(), str::to_string);
|
||||
let first = s.lines().next().unwrap_or_default();
|
||||
let mut t: String = first.chars().take(120).collect();
|
||||
if t.len() < s.len() {
|
||||
t.push('…');
|
||||
}
|
||||
format!("{name} {t}")
|
||||
.find_map(|k| args[*k].as_str())
|
||||
.map_or_else(|| args.to_string(), str::to_string);
|
||||
s.lines().next().unwrap_or_default().to_string()
|
||||
}
|
||||
|
||||
fn render(it: &Item, expanded: bool, out: &mut Vec<Line<'static>>) {
|
||||
/// Right-aligned outcome on the tool header: `+3 −1`, `12 lines`, `ok`, `exit 2`.
|
||||
fn outcome(name: &str, content: &str, err: bool) -> String {
|
||||
let m = theme::t().sym.minus;
|
||||
if err {
|
||||
return content
|
||||
.rsplit_once("[exit ")
|
||||
.and_then(|(_, r)| r.split_once(']'))
|
||||
.map_or("error".into(), |(n, _)| format!("exit {n}"));
|
||||
}
|
||||
match name {
|
||||
"edit" => {
|
||||
let n = |c: u8, skip: &str| {
|
||||
content
|
||||
.lines()
|
||||
.filter(|l| l.as_bytes().first() == Some(&c) && !l.starts_with(skip))
|
||||
.count()
|
||||
};
|
||||
format!("+{} {m}{}", n(b'+', "+++"), n(b'-', "---"))
|
||||
}
|
||||
"write" => content
|
||||
.rsplit_once('(')
|
||||
.map_or("ok".into(), |(_, r)| r.trim_end_matches(')').to_string()),
|
||||
"read" => format!("{} lines", content.lines().count()),
|
||||
_ => "ok".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn fmt_dur(d: Duration) -> String {
|
||||
if d.as_secs() >= 60 {
|
||||
format!("{}m{:02}s", d.as_secs() / 60, d.as_secs() % 60)
|
||||
} else {
|
||||
format!("{:.1}s", d.as_secs_f32())
|
||||
}
|
||||
}
|
||||
|
||||
/// Truncate to `w` display columns, adding an ellipsis when cut.
|
||||
fn fit(s: &str, w: usize) -> String {
|
||||
if Span::raw(s).width() <= w {
|
||||
return s.to_string();
|
||||
}
|
||||
let ell = theme::t().sym.ellipsis;
|
||||
let mut out = String::new();
|
||||
for c in s.chars() {
|
||||
if Span::raw(format!("{out}{c}{ell}")).width() > w {
|
||||
break;
|
||||
}
|
||||
out.push(c);
|
||||
}
|
||||
out + ell
|
||||
}
|
||||
|
||||
/// ` ✓ edit src/a.rs ············ +3 −1 0.2s ▸`
|
||||
fn tool_header(
|
||||
name: &str,
|
||||
args: &Value,
|
||||
result: &Option<(String, bool)>,
|
||||
took: Option<Duration>,
|
||||
folded: bool,
|
||||
width: usize,
|
||||
) -> Line<'static> {
|
||||
let th = theme::t();
|
||||
let (mark, st) = match result {
|
||||
None => (th.sym.pending, th.warn()),
|
||||
Some((_, false)) => (th.sym.ok, th.ok()),
|
||||
Some((_, true)) => (th.sym.err, th.err()),
|
||||
};
|
||||
let mut right = match result {
|
||||
Some((c, e)) => outcome(name, c, *e),
|
||||
None => String::new(),
|
||||
};
|
||||
if let Some(d) = took {
|
||||
right = format!("{right} {}", fmt_dur(d));
|
||||
}
|
||||
if folded {
|
||||
right = format!("{right} {}", th.sym.more);
|
||||
}
|
||||
let left = format!(" {mark} {name:<5} ");
|
||||
let lw = Span::raw(left.as_str()).width();
|
||||
let rw = Span::raw(right.as_str()).width();
|
||||
let room = width.saturating_sub(lw + rw + 1).max(8);
|
||||
let tgt = fit(&target(args), room);
|
||||
let pad = width.saturating_sub(lw + Span::raw(tgt.as_str()).width() + rw);
|
||||
Line::from(vec![
|
||||
Span::styled(format!(" {mark} "), st),
|
||||
Span::styled(
|
||||
format!("{name:<5} "),
|
||||
th.plain().add_modifier(Modifier::BOLD),
|
||||
),
|
||||
Span::raw(tgt),
|
||||
Span::raw(" ".repeat(pad.max(1))),
|
||||
Span::styled(
|
||||
right,
|
||||
if matches!(result, Some((_, true))) {
|
||||
th.err()
|
||||
} else {
|
||||
th.dim()
|
||||
},
|
||||
),
|
||||
])
|
||||
}
|
||||
|
||||
/// Prefix the first line with `mark` (styled) and indent the rest by two columns.
|
||||
fn lead(lines: Vec<Line<'static>>, mark: &str, st: Style, out: &mut Vec<Line<'static>>) {
|
||||
for (i, mut l) in lines.into_iter().enumerate() {
|
||||
let p = if i == 0 {
|
||||
Span::styled(format!("{mark} "), st)
|
||||
} else {
|
||||
Span::raw(" ")
|
||||
};
|
||||
l.spans.insert(0, p);
|
||||
out.push(l);
|
||||
}
|
||||
}
|
||||
|
||||
fn render(it: &Item, expanded: bool, width: usize, out: &mut Vec<Line<'static>>) {
|
||||
let th = theme::t();
|
||||
match it {
|
||||
Item::User(s) => {
|
||||
for (i, l) in s.lines().enumerate() {
|
||||
let p = if i == 0 { "> " } else { " " };
|
||||
out.push(Line::from(vec![
|
||||
Span::styled(
|
||||
p,
|
||||
Style::default()
|
||||
.fg(Color::Cyan)
|
||||
.add_modifier(Modifier::BOLD),
|
||||
),
|
||||
Span::styled(l.to_string(), Style::default().add_modifier(Modifier::BOLD)),
|
||||
]));
|
||||
}
|
||||
let b = th.plain().add_modifier(Modifier::BOLD);
|
||||
let ls = s.lines().map(|l| Line::styled(l.to_string(), b)).collect();
|
||||
lead(
|
||||
ls,
|
||||
th.sym.user,
|
||||
th.accent().add_modifier(Modifier::BOLD),
|
||||
out,
|
||||
);
|
||||
}
|
||||
Item::Assistant(s) => markdown(s, out),
|
||||
Item::Thinking(s) => {
|
||||
for l in s.lines() {
|
||||
out.push(Line::styled(
|
||||
l.to_string(),
|
||||
dim().add_modifier(Modifier::ITALIC),
|
||||
));
|
||||
}
|
||||
Item::Assistant(s) => {
|
||||
let mut md = vec![];
|
||||
markdown(s, &mut md);
|
||||
lead(md, th.sym.asst, th.accent(), out);
|
||||
}
|
||||
Item::Info(s) => out.push(Line::styled(format!("· {s}"), dim())),
|
||||
Item::Error(s) => out.push(Line::styled(
|
||||
format!("error: {s}"),
|
||||
Style::default().fg(Color::Red),
|
||||
Item::Thinking(s) if expanded => {
|
||||
let st = th.dim().add_modifier(Modifier::ITALIC);
|
||||
let ls = s.lines().map(|l| Line::styled(l.to_string(), st)).collect();
|
||||
lead(ls, " ", st, out);
|
||||
}
|
||||
Item::Thinking(s) => out.push(Line::styled(
|
||||
format!(
|
||||
" thought · {} words {}",
|
||||
s.split_whitespace().count(),
|
||||
th.sym.more
|
||||
),
|
||||
th.dim().add_modifier(Modifier::ITALIC),
|
||||
)),
|
||||
Item::Info(s) => out.push(Line::styled(format!("{} {s}", th.sym.info), th.dim())),
|
||||
Item::Error(s) => out.push(Line::styled(format!("{} {s}", th.sym.err), th.err())),
|
||||
Item::Tool {
|
||||
name, args, result, ..
|
||||
name,
|
||||
args,
|
||||
result,
|
||||
took,
|
||||
..
|
||||
} => {
|
||||
let (mark, color) = match result {
|
||||
None => ("○", Color::Yellow),
|
||||
Some((_, false)) => ("●", Color::Green),
|
||||
Some((_, true)) => ("●", Color::Red),
|
||||
let mut body = vec![];
|
||||
let folded = match result {
|
||||
Some((content, err)) => tool_body(name, content, *err, expanded, &mut body),
|
||||
None => false,
|
||||
};
|
||||
out.push(Line::from(vec![
|
||||
Span::styled(format!("{mark} "), Style::default().fg(color)),
|
||||
Span::styled(
|
||||
summary(name, args),
|
||||
Style::default().add_modifier(Modifier::BOLD),
|
||||
),
|
||||
]));
|
||||
if let Some((content, err)) = result {
|
||||
tool_body(name, content, *err, expanded, out);
|
||||
}
|
||||
out.push(tool_header(name, args, result, *took, folded, width));
|
||||
out.extend(body);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Collapsed: diffs in full (edits are what you want to review), bash tail, others 1 line.
|
||||
fn tool_body(name: &str, content: &str, err: bool, expanded: bool, out: &mut Vec<Line<'static>>) {
|
||||
let lines: Vec<&str> = content.lines().collect();
|
||||
const DIFF_PREVIEW: usize = 6;
|
||||
const ERR_TAIL: usize = 5;
|
||||
|
||||
/// Body lines behind a gutter. Collapsed: edit diff preview, error tail, nothing otherwise.
|
||||
/// Returns true when output was hidden (header shows the fold marker).
|
||||
fn tool_body(
|
||||
name: &str,
|
||||
content: &str,
|
||||
err: bool,
|
||||
expanded: bool,
|
||||
out: &mut Vec<Line<'static>>,
|
||||
) -> bool {
|
||||
let th = theme::t();
|
||||
let is_diff = name == "edit" && !err;
|
||||
let (show, skipped_front): (Vec<&str>, usize) = if expanded || is_diff {
|
||||
(lines.clone(), 0)
|
||||
} else if name == "bash" || err {
|
||||
let n = lines.len().saturating_sub(5);
|
||||
(lines[n..].to_vec(), n)
|
||||
// the edit tool's first line ("edited x") repeats the header
|
||||
let lines: Vec<&str> = content.lines().skip(usize::from(is_diff)).collect();
|
||||
let (show, before, after) = if expanded {
|
||||
(&lines[..], 0, 0)
|
||||
} else if is_diff {
|
||||
let n = lines.len().min(DIFF_PREVIEW);
|
||||
(&lines[..n], 0, lines.len() - n)
|
||||
} else if err {
|
||||
let n = lines.len().saturating_sub(ERR_TAIL);
|
||||
(&lines[n..], n, 0)
|
||||
} else {
|
||||
(lines.iter().take(1).copied().collect(), 0)
|
||||
(&lines[..0], 0, lines.len())
|
||||
};
|
||||
let hidden = lines.len() - show.len();
|
||||
if skipped_front > 0 {
|
||||
out.push(Line::styled(
|
||||
format!(" ⋮ {skipped_front} earlier lines (ctrl-o)"),
|
||||
dim(),
|
||||
));
|
||||
let g = |st: Style| Span::styled(format!(" {} ", th.sym.gutter), st);
|
||||
let note = |s: String| Line::from(vec![g(th.dim()), Span::styled(s, th.dim())]);
|
||||
if before > 0 {
|
||||
out.push(note(format!(
|
||||
"{} {before} earlier lines (ctrl-o)",
|
||||
th.sym.ellipsis
|
||||
)));
|
||||
}
|
||||
for l in &show {
|
||||
let style = if is_diff {
|
||||
for l in show {
|
||||
let st = if is_diff {
|
||||
match l.as_bytes().first() {
|
||||
Some(b'+') if !l.starts_with("+++") => Style::default().fg(Color::Green),
|
||||
Some(b'-') if !l.starts_with("---") => Style::default().fg(Color::Red),
|
||||
Some(b'@') => Style::default().fg(Color::Cyan),
|
||||
_ => dim(),
|
||||
Some(b'+') if !l.starts_with("+++") => th.add(),
|
||||
Some(b'-') if !l.starts_with("---") => th.del(),
|
||||
Some(b'@') => th.hunk(),
|
||||
_ => th.dim(),
|
||||
}
|
||||
} else if err {
|
||||
Style::default().fg(Color::Red)
|
||||
th.err()
|
||||
} else {
|
||||
dim()
|
||||
th.dim()
|
||||
};
|
||||
out.push(Line::styled(format!(" {l}"), style));
|
||||
out.push(Line::from(vec![
|
||||
g(th.dim()),
|
||||
Span::styled(l.to_string(), st),
|
||||
]));
|
||||
}
|
||||
if hidden > 0 && skipped_front == 0 {
|
||||
out.push(Line::styled(
|
||||
format!(" … {hidden} more lines (ctrl-o)"),
|
||||
dim(),
|
||||
));
|
||||
if after > 0 && is_diff {
|
||||
out.push(note(format!(
|
||||
"{} {after} more lines (ctrl-o)",
|
||||
th.sym.ellipsis
|
||||
)));
|
||||
}
|
||||
// write output is just the header's "N lines"
|
||||
!expanded && after > 0 && !is_diff && name != "write"
|
||||
}
|
||||
|
||||
/// Minimal markdown: fenced code, headings, bullets, inline `code` and **bold**.
|
||||
@@ -204,18 +374,17 @@ fn markdown(s: &str, out: &mut Vec<Line<'static>>) {
|
||||
for l in s.lines() {
|
||||
if l.trim_start().starts_with("```") {
|
||||
code = !code;
|
||||
out.push(Line::styled(l.to_string(), dim()));
|
||||
out.push(Line::styled(l.to_string(), theme::t().dim()));
|
||||
continue;
|
||||
}
|
||||
if code {
|
||||
out.push(Line::styled(
|
||||
l.to_string(),
|
||||
Style::default().fg(Color::Cyan),
|
||||
));
|
||||
out.push(Line::styled(l.to_string(), theme::t().block_code()));
|
||||
} else if l.starts_with('#') {
|
||||
out.push(Line::styled(
|
||||
l.trim_start_matches('#').trim().to_string(),
|
||||
Style::default().add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
|
||||
theme::t()
|
||||
.plain()
|
||||
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
|
||||
));
|
||||
} else {
|
||||
out.push(inline(l));
|
||||
@@ -228,8 +397,8 @@ fn inline(l: &str) -> Line<'static> {
|
||||
let mut rest = l;
|
||||
while !rest.is_empty() {
|
||||
let next = [
|
||||
("`", Style::default().fg(Color::Yellow)),
|
||||
("**", Style::default().add_modifier(Modifier::BOLD)),
|
||||
("`", theme::t().code()),
|
||||
("**", theme::t().plain().add_modifier(Modifier::BOLD)),
|
||||
]
|
||||
.into_iter()
|
||||
.filter_map(|(d, st)| {
|
||||
@@ -259,6 +428,7 @@ fn inline(l: &str) -> Line<'static> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ratatui::style::Color;
|
||||
use serde_json::json;
|
||||
|
||||
fn text(ls: &[Line]) -> Vec<String> {
|
||||
@@ -267,10 +437,21 @@ mod tests {
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn tool(name: &str, args: Value, out: &str, err: bool) -> Item {
|
||||
Item::Tool {
|
||||
id: "1".into(),
|
||||
name: name.into(),
|
||||
args,
|
||||
result: Some((out.into(), err)),
|
||||
started: Instant::now(),
|
||||
took: Some(Duration::from_millis(1234)),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stream_and_tools() {
|
||||
let mut t = Transcript::default();
|
||||
t.push(Item::User("hi".into()));
|
||||
t.push(Item::User("hi\nthere".into()));
|
||||
for d in ["Hel", "lo"] {
|
||||
t.apply(&Event::Stream(StreamEvent::TextDelta { text: d.into() }));
|
||||
}
|
||||
@@ -279,6 +460,7 @@ mod tests {
|
||||
name: "edit".into(),
|
||||
args: json!({"path": "a.rs"}),
|
||||
});
|
||||
assert_eq!(t.running().unwrap().0, "edit");
|
||||
t.apply(&Event::ToolResult {
|
||||
id: "1".into(),
|
||||
name: "edit".into(),
|
||||
@@ -286,35 +468,99 @@ mod tests {
|
||||
content: "edited a.rs\n@@ -1 +1 @@\n-old\n+new".into(),
|
||||
is_error: false,
|
||||
});
|
||||
assert!(t.running().is_none());
|
||||
t.apply(&Event::Stream(StreamEvent::TextDelta {
|
||||
text: "After".into(),
|
||||
}));
|
||||
assert_eq!(t.items[1], Item::Assistant("Hello".into()));
|
||||
assert_eq!(t.items[3], Item::Assistant("After".into()));
|
||||
let ls = t.lines(false);
|
||||
let ls = t.lines(false, 40);
|
||||
let s = text(&ls);
|
||||
assert!(s.contains(&"● edit a.rs".to_string()));
|
||||
assert_eq!(s[..2], ["❯ hi", " there"]);
|
||||
assert_eq!(s[3], "◆ Hello");
|
||||
assert!(
|
||||
s[5].starts_with(" ✓ edit a.rs ") && s[5].contains("+1 −1 0.0s"),
|
||||
"{s:?}"
|
||||
);
|
||||
assert_eq!(s[5].chars().count(), 40, "header fills the width");
|
||||
let minus = ls
|
||||
.iter()
|
||||
.find(|l| text(std::slice::from_ref(l))[0] == " -old")
|
||||
.find(|l| text(std::slice::from_ref(l))[0] == " │ -old")
|
||||
.unwrap();
|
||||
assert_eq!(minus.style.fg, Some(Color::Red));
|
||||
assert_eq!(minus.spans[1].style.fg, Some(Color::Red));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collapse_bash_tail() {
|
||||
fn headers_at_two_widths() {
|
||||
let b = tool(
|
||||
"bash",
|
||||
json!({"command": "cargo test -p hx-lens rust_analyzer"}),
|
||||
"x\n[exit 101]",
|
||||
true,
|
||||
);
|
||||
for w in [40, 80] {
|
||||
let mut out = vec![];
|
||||
render(&b, false, w, &mut out);
|
||||
let s = text(&out);
|
||||
assert_eq!(s[0].chars().count(), w, "{s:?}");
|
||||
assert!(
|
||||
s[0].starts_with(" ✗ bash cargo") && s[0].ends_with("exit 101 1.2s"),
|
||||
"{s:?}"
|
||||
);
|
||||
}
|
||||
let mut out = vec![];
|
||||
render(&b, false, 40, &mut out);
|
||||
assert!(text(&out)[0].contains("…"), "target truncated at 40 cols");
|
||||
let w = tool(
|
||||
"write",
|
||||
json!({"path": "h.txt"}),
|
||||
"wrote h.txt (3 lines)",
|
||||
false,
|
||||
);
|
||||
let mut out = vec![];
|
||||
render(&w, false, 50, &mut out);
|
||||
assert!(
|
||||
text(&out)[0].ends_with(" 3 lines 1.2s"),
|
||||
"{:?}",
|
||||
text(&out)
|
||||
);
|
||||
let r = tool("read", json!({"path": "a"}), "1\n2", false);
|
||||
let mut out = vec![];
|
||||
render(&r, false, 50, &mut out);
|
||||
assert_eq!(out.len(), 1);
|
||||
assert!(text(&out)[0].ends_with("2 lines 1.2s ▸"), "folded marker");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collapse_rules() {
|
||||
let body: String = (1..=20).map(|i| format!("l{i}\n")).collect();
|
||||
tool_body("bash", &body, false, false, &mut out);
|
||||
let mut out = vec![];
|
||||
assert!(!tool_body("bash", &body, true, false, &mut out));
|
||||
let s = text(&out);
|
||||
assert_eq!(s[0], " ⋮ 15 earlier lines (ctrl-o)");
|
||||
assert_eq!(s.last().unwrap(), " l20");
|
||||
assert_eq!(s[0], " │ … 15 earlier lines (ctrl-o)");
|
||||
assert_eq!(s.last().unwrap(), " │ l20");
|
||||
out.clear();
|
||||
tool_body("bash", &body, false, true, &mut out);
|
||||
assert!(tool_body("bash", &body, false, false, &mut out) && out.is_empty());
|
||||
assert!(!tool_body("bash", &body, false, true, &mut out));
|
||||
assert_eq!(out.len(), 20);
|
||||
out.clear();
|
||||
tool_body("read", &body, false, false, &mut out);
|
||||
assert_eq!(text(&out), [" l1", " … 19 more lines (ctrl-o)"]);
|
||||
let diff: String =
|
||||
"edited a\n".to_string() + &(1..=10).map(|i| format!("+l{i}\n")).collect::<String>();
|
||||
tool_body("edit", &diff, false, false, &mut out);
|
||||
assert_eq!(out.len(), DIFF_PREVIEW + 1);
|
||||
assert_eq!(text(&out).last().unwrap(), " │ … 4 more lines (ctrl-o)");
|
||||
let mut out = vec![];
|
||||
render(&Item::Thinking("a b c".into()), false, 40, &mut out);
|
||||
assert_eq!(text(&out), [" thought · 3 words ▸"]);
|
||||
let mut out = vec![];
|
||||
render(&Item::Thinking("a b c".into()), true, 40, &mut out);
|
||||
assert_eq!(text(&out), [" a b c"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn activity() {
|
||||
let l = activity_line("bash", Duration::from_millis(12_900), 2);
|
||||
assert_eq!(text(&[l]), [" ⠹ bash 12s"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+2
-1
@@ -56,7 +56,8 @@ send(b"@not"); send(b"\t")
|
||||
check("tab completion", "es.md")
|
||||
send(b"\x15") # ctrl-u
|
||||
send(b"make hello.txt"); send(b"\r", 3)
|
||||
check("tool call shown", "write hello.txt")
|
||||
check("tool call shown", "hello.txt")
|
||||
check("tool outcome", "1 lines")
|
||||
check("final answer", "Done: file says hi from hx.")
|
||||
check("file written", "") if os.path.exists(f"{tmp}/repo/hello.txt") else (print("FAIL file"), None)
|
||||
send(b"/model claude-opus-4-1\r")
|
||||
|
||||
Reference in new issue
Block a user