use std::io::{self, Write};
use super::frame::{FOOT, GUTTER, GUTTER_WIDTH, gutter_line, truncate_ellipsis, write_band};
use super::wrap::{MAX_LINE_WIDTH, wrap_line};
use crate::style::*;
const MAX_OUTPUT_LINES: usize = 10;
const MAX_READ_LINES: usize = 3;
const BODY_WIDTH: usize = MAX_LINE_WIDTH - GUTTER_WIDTH;
const MAX_SUBJECT_CHARS: usize = 120;
const SIGNAL_TOOLS: [&str; 4] = ["question", "switch_mode", "invoke_skill", "auto_compact"];
const DENIED_BOILERPLATE: &str = "[Tool denied] The user denied the";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ToolStatus {
Ok,
Error,
Denied,
}
impl ToolStatus {
fn glyph(self) -> &'static str {
match self {
ToolStatus::Ok => "●",
ToolStatus::Error => "✕",
ToolStatus::Denied => "⊘",
}
}
fn color(self) -> &'static str {
match self {
ToolStatus::Ok => FG_OK,
ToolStatus::Error => FG_ERR,
ToolStatus::Denied => FG_WARN,
}
}
fn label(self) -> &'static str {
match self {
ToolStatus::Error => "failed",
ToolStatus::Denied => "denied",
_ => "",
}
}
}
pub fn format_duration(ms: u64) -> String {
if ms < 1000 {
format!("{ms}ms")
} else if ms < 60_000 {
format!("{:.1}s", ms as f64 / 1000.0)
} else {
let mins = ms / 60_000;
let secs = (ms % 60_000) / 1000;
format!("{mins}m {secs}s")
}
}
pub fn write_tool_card<W: Write>(
w: &mut W,
tool: &str,
subject: Option<&str>,
status: ToolStatus,
duration_ms: Option<u64>,
body: &str,
) -> io::Result<()> {
write_card_header(w, tool, subject, status, duration_ms)?;
if body.trim().is_empty() {
return Ok(());
}
write_body_lines(w, &card_lines(tool, body, status))
}
pub fn tool_subject(arguments: &serde_json::Value) -> Option<String> {
let args = arguments.as_object()?;
for key in ["command", "path", "file_path", "query", "url", "pattern"] {
if let Some(value) = args.get(key).and_then(|v| v.as_str())
&& !value.trim().is_empty()
{
return Some(value.lines().next().unwrap_or_default().to_string());
}
}
args.values()
.find_map(|v| v.as_str())
.map(|v| v.lines().next().unwrap_or_default().to_string())
.filter(|v| !v.trim().is_empty())
}
fn write_card_header<W: Write>(
w: &mut W,
tool: &str,
subject: Option<&str>,
status: ToolStatus,
duration_ms: Option<u64>,
) -> io::Result<()> {
let subject_text = subject
.map(str::trim)
.filter(|s| !s.is_empty())
.map(|s| truncate_ellipsis(s.lines().next().unwrap_or_default(), MAX_SUBJECT_CHARS));
let tail = match (status, duration_ms) {
(_, Some(ms)) => Some((format!(" · {}", format_duration(ms)), FG_FAINT)),
(ToolStatus::Error | ToolStatus::Denied, None) => {
Some((format!(" · {}", status.label()), status.color()))
}
(ToolStatus::Ok, None) => None,
};
let mut segments: Vec<(&str, &str)> = vec![(status.glyph(), status.color()), (" ", FG_FAINT)];
segments.push((tool, FG_BAND));
if let Some(subject) = &subject_text {
segments.push((" · ", FG_FAINT));
segments.push((subject.as_str(), FG_ACCENT));
}
if let Some((text, color)) = &tail {
segments.push((text.as_str(), *color));
}
write_band(w, &segments)
}
enum BodyLine {
Text(String, &'static str),
}
fn write_body_lines<W: Write>(w: &mut W, lines: &[BodyLine]) -> io::Result<()> {
let last = lines.len().saturating_sub(1);
for (i, line) in lines.iter().enumerate() {
let glyph = if i == last { FOOT } else { GUTTER };
match line {
BodyLine::Text(text, color) => gutter_line(w, glyph, &format!("{color}{text}{RESET}"))?,
}
}
Ok(())
}
fn push_wrapped(lines: &mut Vec<BodyLine>, text: &str, color: &'static str) {
for segment in text.split('\n') {
for row in wrap_line(segment, BODY_WIDTH, BODY_WIDTH) {
lines.push(BodyLine::Text(row, color));
}
}
}
fn push_more(lines: &mut Vec<BodyLine>, hidden: usize, noun: &'static str) {
if hidden > 0 {
let noun = if hidden == 1 { singular(noun) } else { noun };
lines.push(BodyLine::Text(format!("+{hidden} more {noun}"), FG_FAINT));
}
}
fn singular(noun: &str) -> &'static str {
match noun {
"lines" => "line",
_ => "line",
}
}
fn card_lines(tool: &str, body: &str, status: ToolStatus) -> Vec<BodyLine> {
let mut lines: Vec<BodyLine> = Vec::new();
if status == ToolStatus::Error {
push_wrapped(
&mut lines,
&truncate_ellipsis(body.lines().next().unwrap_or("Error"), BODY_WIDTH),
FG_ERR,
);
return lines;
}
if body.starts_with("[Tool denied]") {
if body.starts_with(DENIED_BOILERPLATE) {
return lines;
}
let msg = body.trim_start_matches("[Tool denied]").trim();
push_wrapped(&mut lines, &truncate_ellipsis(msg, BODY_WIDTH), FG_WARN);
return lines;
}
match tool {
"ls" | "grep" | "glob" => push_wrapped(
&mut lines,
&truncate_ellipsis(&summarize_listing_result(body, tool), BODY_WIDTH),
FG_MUTED,
),
"read" => read_lines(&mut lines, body),
t if SIGNAL_TOOLS.contains(&t) => push_wrapped(
&mut lines,
&truncate_ellipsis(body.lines().next().unwrap_or(body), BODY_WIDTH),
FG_MUTED,
),
_ => capped_lines(&mut lines, body.lines(), MAX_OUTPUT_LINES),
}
lines
}
fn capped_lines<'a>(
out: &mut Vec<BodyLine>,
body_lines: impl Iterator<Item = &'a str>,
max: usize,
) {
let all: Vec<&str> = body_lines.collect();
for line in all.iter().take(max) {
push_wrapped(out, line, FG_MUTED);
}
push_more(out, all.len().saturating_sub(max), "lines");
}
fn read_lines(out: &mut Vec<BodyLine>, body: &str) {
let mut lines = body.lines();
let first = lines.next().unwrap_or("");
let is_meta = first.starts_with('(') && first.contains(" lines") && first.ends_with(')');
let (meta, content): (Option<&str>, Vec<&str>) = if is_meta {
(Some(first), lines.collect())
} else {
(None, std::iter::once(first).chain(lines).collect())
};
if let Some(meta) = meta {
out.push(BodyLine::Text(meta.to_string(), FG_FAINT));
}
for line in content.iter().take(MAX_READ_LINES) {
push_wrapped(out, &truncate_ellipsis(line, BODY_WIDTH), FG_MUTED);
}
push_more(out, content.len().saturating_sub(MAX_READ_LINES), "lines");
}
pub fn summarize_listing_result(result: &str, tool_name: &str) -> String {
if result.starts_with("Error:") || result.starts_with("No ") || result == "Directory is empty" {
return result.to_string();
}
let lines: Vec<&str> = result.lines().collect();
let count = lines.len();
let label = match (tool_name, count == 1) {
("ls", true) => "entry",
("ls", false) => "entries",
("grep", true) => "match",
("grep", false) => "matches",
("glob", true) => "file",
("glob", false) => "files",
(_, true) => "result",
(_, false) => "results",
};
const PREVIEW: usize = 3;
let preview = lines
.iter()
.take(PREVIEW)
.copied()
.collect::<Vec<_>>()
.join(", ");
if count <= PREVIEW {
format!("{count} {label} — {preview}")
} else {
format!("{count} {label} — {preview} ... ({} more)", count - PREVIEW)
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn strip_ansi(s: &str) -> String {
let re = regex::Regex::new(r"\x1b\[[0-9;]*[mK]").unwrap();
re.replace_all(s, "").to_string()
}
fn render(tool: &str, body: &str, is_error: bool, ms: Option<u64>) -> String {
let mut buf = Vec::new();
write_tool_card(
&mut buf,
tool,
None,
if is_error {
ToolStatus::Error
} else {
ToolStatus::Ok
},
ms,
body,
)
.unwrap();
String::from_utf8(buf).unwrap()
}
fn plain(s: &str) -> String {
strip_ansi(s)
}
fn body_rows(out: &str) -> Vec<String> {
plain(out).lines().skip(1).map(str::to_string).collect()
}
#[test]
fn success_header_shows_status_glyph_and_duration() {
let out = render("read", "(1 lines)\nhi", false, Some(42));
assert!(out.contains('●'));
assert!(out.contains("read"));
assert!(out.contains("42ms"));
assert!(!out.contains('✕'));
assert!(out.contains(FG_OK), "status color must be applied");
}
#[test]
fn error_header_shows_cross_and_failure_label() {
let mut buf = Vec::new();
write_tool_card(
&mut buf,
"run",
None,
ToolStatus::Error,
None,
"Error: boom",
)
.unwrap();
let out = String::from_utf8(buf).unwrap();
assert!(out.contains('✕'));
assert!(out.contains(FG_ERR));
assert!(plain(&out).contains("failed"), "no duration ⇒ label");
}
#[test]
fn error_with_duration_omits_the_label() {
let out = render("run", "Error: boom", true, Some(1500));
assert!(out.contains('✕'));
assert!(out.contains("1.5s"));
assert!(!plain(&out).contains("failed"));
}
#[test]
fn denied_header_shows_slash_circle_and_denied_label() {
let mut buf = Vec::new();
write_tool_card(
&mut buf,
"run",
Some("rm -rf /"),
ToolStatus::Denied,
None,
"",
)
.unwrap();
let out = String::from_utf8(buf).unwrap();
assert!(out.contains('⊘'));
assert!(plain(&out).contains("denied"));
assert!(plain(&out).contains("rm -rf /"));
}
#[test]
fn subject_appears_on_the_title_band() {
let mut buf = Vec::new();
write_tool_card(
&mut buf,
"read",
Some("src/main.rs"),
ToolStatus::Ok,
None,
"",
)
.unwrap();
assert!(plain(&String::from_utf8(buf).unwrap()).contains("src/main.rs"));
}
#[test]
fn multiline_subject_collapses_to_its_first_line() {
let mut buf = Vec::new();
write_tool_card(
&mut buf,
"run",
Some("echo one\necho two"),
ToolStatus::Ok,
None,
"",
)
.unwrap();
let out = String::from_utf8(buf).unwrap();
assert_eq!(out.lines().count(), 1, "band must stay a single line");
assert!(plain(&out).contains("echo one"));
assert!(!plain(&out).contains("echo two"));
}
#[test]
fn blank_subject_is_omitted() {
let mut buf = Vec::new();
write_tool_card(&mut buf, "ls", Some(" "), ToolStatus::Ok, None, "").unwrap();
assert_eq!(plain(&String::from_utf8(buf).unwrap()).trim(), "● ls");
}
#[test]
fn history_omits_duration() {
let out = render("ls", "a\nb", false, None);
assert!(!plain(&out).contains('·'), "no separator: {out:?}");
assert!(out.contains("ls"));
}
#[test]
fn empty_body_is_header_only() {
let out = render("run", "", false, Some(5));
assert_eq!(out.lines().count(), 1);
}
#[test]
fn whitespace_only_body_is_header_only() {
let out = render("run", " \n ", false, None);
assert_eq!(out.lines().count(), 1);
}
#[test]
fn body_rows_are_gutter_outlined_and_close_with_an_elbow() {
let out = render("run", "one\ntwo", false, None);
let rows = body_rows(&out);
assert_eq!(rows.len(), 2, "band + 2 body rows");
assert!(rows[0].starts_with(" │ "), "body rows use the gutter");
assert!(rows[1].starts_with(" ╰ "), "last row closes the card");
assert!(rows[0].contains("one"));
assert!(rows[1].contains("two"));
}
#[test]
fn single_row_body_closes_with_the_elbow() {
let out = render("ls", "a\nb\nc", false, None);
let rows = body_rows(&out);
assert_eq!(rows.len(), 1);
assert!(rows[0].starts_with(" ╰ "));
}
#[test]
fn elbow_lands_on_the_final_physical_row_after_wrapping() {
let line = "word ".repeat(80);
let out = render("run", line.trim(), false, None);
let rows = body_rows(&out);
assert!(rows.len() > 2, "long line must wrap onto several rows");
assert!(rows.last().unwrap().starts_with(" ╰ "));
for row in &rows[..rows.len() - 1] {
assert!(row.starts_with(" │ "), "no early elbow: {row:?}");
}
}
#[test]
fn no_body_row_exceeds_the_line_budget() {
let out = render("run", &"word ".repeat(60), false, None);
for row in body_rows(&out) {
assert!(row.chars().count() <= MAX_LINE_WIDTH, "overflow: {row:?}");
}
}
#[test]
fn error_body_is_a_single_red_line_truncated() {
let long = format!("Error: {}", "x".repeat(300));
let out = render("run", &long, true, None);
let rows = body_rows(&out);
assert_eq!(rows.len(), 1, "error collapses to one row: {rows:?}");
assert!(out.contains(FG_ERR));
assert!(plain(&rows[0]).ends_with('…'));
assert!(!plain(&out).contains(&"x".repeat(200)));
}
#[test]
fn error_body_shows_only_the_first_line() {
let out = render("run", "Error: boom\nstack trace\nmore", true, None);
let p = plain(&out);
assert!(p.contains("Error: boom"));
assert!(!p.contains("stack trace"), "trace stays hidden: {p:?}");
}
#[test]
fn canonical_denial_renders_band_only() {
let mut buf = Vec::new();
write_tool_card(
&mut buf,
"run",
Some("rm -rf /"),
ToolStatus::Denied,
None,
"[Tool denied] The user denied the 'run' tool call with arguments: command=\"rm -rf /\"",
)
.unwrap();
let out = String::from_utf8(buf).unwrap();
assert_eq!(out.lines().count(), 1, "no body row: {out:?}");
assert!(out.contains('⊘'));
assert!(out.contains(FG_WARN));
}
#[test]
fn non_boilerplate_denial_shows_the_message_without_the_marker() {
let out = render(
"run",
"[Tool denied] sandbox policy refuses writes outside the workspace",
false,
None,
);
let p = plain(&out);
assert!(out.contains(FG_WARN));
assert!(p.contains("sandbox policy"), "{p:?}");
assert!(!p.contains("[Tool denied]"), "marker is redundant: {p:?}");
}
#[test]
fn listing_summary_line() {
let out = render("ls", "Cargo.toml\nsrc\ntarget\nx\ny", false, None);
let p = plain(&out);
assert!(p.contains("5 entries — Cargo.toml, src, target ... (2 more)"));
assert_eq!(body_rows(&out).len(), 1);
}
#[test]
fn listing_error_passes_through() {
let out = render("grep", "Error: bad pattern", true, None);
assert!(plain(&out).contains("Error: bad pattern"));
}
#[test]
fn read_shows_meta_then_capped_preview() {
let content: Vec<String> = (1..=20).map(|i| format!("line{i}")).collect();
let body = format!("(20 lines)\n{}", content.join("\n"));
let out = render("read", &body, false, None);
let p = plain(&out);
assert!(p.contains("(20 lines)"));
assert!(p.contains("line1"));
assert!(p.contains("line3"));
assert!(!p.contains("line4"));
assert!(p.contains("╰ +17 more lines"));
}
#[test]
fn read_without_meta_line_renders_all_as_content() {
let out = render("read", "just one line", false, None);
let p = plain(&out);
assert!(p.contains("just one line"));
assert!(!p.contains("more lines"));
assert_eq!(body_rows(&out).len(), 1);
}
#[test]
fn run_output_capped_with_footer() {
let content: Vec<String> = (1..=50).map(|i| format!("out{i}")).collect();
let out = render("run", &content.join("\n"), false, Some(2300));
let p = plain(&out);
assert!(p.contains("out1"));
assert!(p.contains("out10"));
assert!(!p.contains("out11"));
assert!(p.contains("╰ +40 more lines"));
assert!(out.contains("2.3s"));
}
#[test]
fn short_output_not_capped() {
let out = render("run", "one\ntwo", false, None);
assert!(!plain(&out).contains("more lines"));
}
#[test]
fn signal_tool_result_is_single_dim_line() {
let out = render(
"question",
"User answered the question 'Deploy?' with: 'yes'.",
false,
None,
);
assert_eq!(body_rows(&out).len(), 1);
assert!(plain(&out).contains("User answered the question"));
}
#[test]
fn subject_prefers_the_command_over_other_arguments() {
assert_eq!(
tool_subject(&json!({"command": "cargo build", "timeout": 30})).as_deref(),
Some("cargo build")
);
}
#[test]
fn subject_prefers_the_path_for_file_tools() {
assert_eq!(
tool_subject(&json!({"path": "src/main.rs", "old_str": "a"})).as_deref(),
Some("src/main.rs")
);
}
#[test]
fn subject_falls_back_to_the_first_string_argument() {
assert_eq!(
tool_subject(&json!({"count": 3, "target": "prod"})).as_deref(),
Some("prod")
);
}
#[test]
fn subject_collapses_multiline_arguments_to_one_line() {
assert_eq!(
tool_subject(&json!({"command": "echo one\necho two"})).as_deref(),
Some("echo one")
);
}
#[test]
fn subject_is_none_without_string_arguments() {
assert_eq!(tool_subject(&json!({})), None);
assert_eq!(tool_subject(&json!({"n": 1})), None);
assert_eq!(tool_subject(&json!([])), None);
}
#[test]
fn duration_formatting() {
assert_eq!(format_duration(42), "42ms");
assert_eq!(format_duration(1200), "1.2s");
assert_eq!(format_duration(83_000), "1m 23s");
}
#[test]
fn summarize_labels_per_tool() {
assert_eq!(
summarize_listing_result("a\nb\nc", "grep"),
"3 matches — a, b, c"
);
assert_eq!(summarize_listing_result("a", "ls"), "1 entry — a");
assert_eq!(summarize_listing_result("a\nb", "glob"), "2 files — a, b");
}
#[test]
fn summarize_is_always_a_single_line() {
let out = summarize_listing_result("a\nb\nc\nd\ne", "ls");
assert!(!out.contains('\n'), "{out:?}");
assert_eq!(out, "5 entries — a, b, c ... (2 more)");
}
#[test]
fn summarize_error_passthrough() {
assert_eq!(summarize_listing_result("Error: nope", "ls"), "Error: nope");
}
}