use serde_json::{Map, Value};
pub const WIDTH: usize = 72;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Outcome {
Running,
Ok,
Refused,
Failed,
}
impl Outcome {
pub fn glyph(self) -> &'static str {
match self {
Outcome::Running => "\u{23fa}",
Outcome::Ok => "\u{2713}",
Outcome::Refused => "\u{2298}",
Outcome::Failed => "\u{2717}",
}
}
pub fn as_str(self) -> &'static str {
match self {
Outcome::Running => "running",
Outcome::Ok => "ok",
Outcome::Refused => "refused",
Outcome::Failed => "failed",
}
}
}
pub fn outcome(result: &str, live: Option<bool>) -> Outcome {
match live {
Some(true) if refused(result) => Outcome::Refused,
Some(true) => Outcome::Failed,
Some(false) => Outcome::Ok,
None if refused(result) => Outcome::Refused,
None => match exit_code(result) {
Some(0) => Outcome::Ok,
Some(_) => Outcome::Failed,
None => Outcome::Ok,
},
}
}
const DENIED: &str = "the user declined to run `";
fn refused(result: &str) -> bool {
result.starts_with(DENIED)
}
fn exit_code(result: &str) -> Option<i32> {
let first = result.lines().next()?.trim();
let rest = first.strip_prefix("exit code:")?.trim();
rest.parse().ok()
}
pub fn statement(name: &str, arguments: &str) -> String {
let parsed = serde_json::from_str::<Value>(arguments);
let args = match parsed {
Ok(Value::Object(map)) => map,
_ => return cut(&format!("{name} {}", arguments.trim())),
};
let mut parts: Vec<String> = Vec::new();
match name {
"shell" => {
if let Some(command) = text(&args, "command") {
parts.push(first_line(command).to_string());
}
}
"write_file" => {
if let Some(path) = text(&args, "path") {
parts.push(path.to_string());
}
if let Some(size) = byte_size(&args, "content") {
parts.push(format!("· {size}"));
}
}
"patch" => {
if let Some(path) = text(&args, "path") {
parts.push(path.to_string());
}
if let Some(size) = byte_size(&args, "new_string") {
parts.push(format!("· {size}"));
}
}
"execute_code" => {
if let Some(code) = text(&args, "code") {
parts.push(format!("· {}", lines(code)));
}
}
_ => {
for key in ["name", "path", "url"] {
if let Some(value) = text(&args, key) {
parts.push(value.to_string());
}
}
if parts.is_empty() {
if let Some(query) = text(&args, "query") {
parts.push(query.to_string());
}
}
}
}
if parts.is_empty() {
return cut(&format!("{name} {}", arguments.trim()));
}
cut(&format!("{name} {}", parts.join(" ")))
}
fn text<'a>(args: &'a Map<String, Value>, key: &str) -> Option<&'a str> {
args.get(key)
.and_then(Value::as_str)
.map(str::trim)
.filter(|s| !s.is_empty())
}
fn byte_size(args: &Map<String, Value>, key: &str) -> Option<String> {
args.get(key).and_then(Value::as_str).map(|s| size(s.len()))
}
fn size(bytes: usize) -> String {
const KB: f64 = 1024.0;
const MB: f64 = KB * 1024.0;
let b = bytes as f64;
if b < KB {
format!("{bytes} B")
} else if b < 10.0 * KB {
format!("{:.1} KB", b / KB)
} else if b < MB {
format!("{:.0} KB", b / KB)
} else {
format!("{:.1} MB", b / MB)
}
}
fn lines(code: &str) -> String {
let n = code.lines().count().max(1);
format!("{n} line{}", if n == 1 { "" } else { "s" })
}
fn first_line(command: &str) -> &str {
command.lines().next().unwrap_or("").trim()
}
fn cut(text: &str) -> String {
if text.chars().count() <= WIDTH {
return text.to_string();
}
let mut out: String = text.chars().take(WIDTH - 1).collect();
out.push('…');
out
}
#[cfg(test)]
mod tests {
use super::*;
fn at(name: &str, arguments: &str) -> String {
statement(name, arguments)
}
#[test]
fn a_shell_call_shows_the_command_and_not_the_json_around_it() {
assert_eq!(
at("shell", r#"{"command":"cargo test -q --locked"}"#),
"shell cargo test -q --locked"
);
assert_eq!(
at(
"shell",
r#"{"command":"cargo fmt\ncargo clippy --all-targets","cwd":"/x"}"#
),
"shell cargo fmt",
"the first line is the sentence; the rest is the script"
);
}
#[test]
fn a_write_shows_its_path_and_the_size_of_what_it_wrote() {
let content = "x".repeat(45_000);
let line = at(
"write_file",
&serde_json::json!({"path": "crates/x/src/session.rs", "content": content}).to_string(),
);
assert_eq!(line, "write_file crates/x/src/session.rs · 44 KB");
assert!(!line.contains("xxxx"), "{line}");
let small = at("write_file", r#"{"path":"notes.txt","content":"hello"}"#);
assert_eq!(small, "write_file notes.txt · 5 B");
}
#[test]
fn a_patch_shows_its_path_and_the_size_of_the_replacement() {
let line = at(
"patch",
&serde_json::json!({"path": "docs/USER.md", "old_string": "a", "new_string": "b".repeat(2048)}).to_string(),
);
assert_eq!(line, "patch docs/USER.md · 2.0 KB");
}
#[test]
fn a_tool_that_addresses_something_shows_what_it_addresses() {
assert_eq!(
at("read_file", r#"{"path":"src/main.rs"}"#),
"read_file src/main.rs"
);
assert_eq!(
at(
"fetch",
r#"{"url":"https://example.invalid/page","raw":true}"#
),
"fetch https://example.invalid/page"
);
assert_eq!(
at(
"skill_view",
r#"{"name":"eclipse-dev-lab","path":"references/api.md"}"#
),
"skill_view eclipse-dev-lab references/api.md"
);
assert_eq!(
at("session_search", r#"{"query":"gateway restart"}"#),
"session_search gateway restart"
);
}
#[test]
fn an_unknown_tool_is_cut_to_one_line() {
let long = serde_json::json!({"weird": "y".repeat(400)}).to_string();
let line = at("unknown_tool", &long);
assert_eq!(line.chars().count(), WIDTH, "{line}");
assert!(line.ends_with('…'), "{line}");
assert!(line.starts_with("unknown_tool "), "{line}");
assert_eq!(at("weird", "not json at all"), "weird not json at all");
}
#[test]
fn a_cut_never_splits_a_character() {
let line = at("x", &"é".repeat(200));
assert_eq!(line.chars().count(), WIDTH, "{line}");
assert!(line.ends_with('…'));
assert!(line
.chars()
.all(|c| c == 'é' || c == 'x' || c == ' ' || c == '…'));
}
#[test]
fn a_code_block_is_described_by_how_much_of_it_there_is() {
assert_eq!(
at("execute_code", "{\"code\":\"a\\nb\\nc\"}"),
"execute_code · 3 lines"
);
assert_eq!(
at("execute_code", "{\"code\":\"a\"}"),
"execute_code · 1 line"
);
}
#[test]
fn a_stored_result_says_how_the_call_went() {
assert_eq!(
outcome("exit code: 0\nstdout:\nMon Nov 30\n\nstderr:\n", None),
Outcome::Ok
);
assert_eq!(
outcome("exit code: 2\nstdout:\n\nstderr:\nno such file\n", None),
Outcome::Failed
);
assert_eq!(outcome("wrote 46080 bytes", None), Outcome::Ok);
assert_eq!(outcome("", None), Outcome::Ok);
}
#[test]
fn a_declined_call_is_its_own_mark() {
let text = "the user declined to run `shell`: that would delete the tree";
assert_eq!(outcome(text, Some(true)), Outcome::Refused);
assert_eq!(
outcome(text, None),
Outcome::Refused,
"a reload has to agree with the turn it is replaying"
);
}
#[test]
fn the_word_declined_is_not_a_refusal() {
let output =
"crates/eclipse-web/src/calls.rs:78: // the user declined to run it, so nothing";
assert_eq!(
outcome(output, None),
Outcome::Ok,
"a replay of a call that succeeded"
);
assert_eq!(
outcome(output, Some(false)),
Outcome::Ok,
"and the live flag agrees with the text"
);
assert_eq!(
outcome("the user declined to run `shell`: that is a delete", None),
Outcome::Refused
);
}
#[test]
fn the_live_flag_wins_over_the_text() {
assert_eq!(outcome("exit code: 1", Some(false)), Outcome::Ok);
assert_eq!(outcome("all good", Some(true)), Outcome::Failed);
assert_eq!(Outcome::Running.as_str(), "running");
}
#[test]
fn the_marks_are_the_terminals_own() {
assert_eq!(Outcome::Running.glyph(), "⏺");
assert_eq!(Outcome::Ok.glyph(), "✓");
assert_eq!(Outcome::Refused.glyph(), "⊘");
assert_eq!(Outcome::Failed.glyph(), "✗");
assert_eq!(Outcome::Ok.as_str(), "ok");
assert_eq!(Outcome::Refused.as_str(), "refused");
assert_eq!(Outcome::Failed.as_str(), "failed");
}
}