1use serde_json::{Map, Value};
14
15pub const WIDTH: usize = 72;
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum Outcome {
28 Running,
30 Ok,
31 Refused,
34 Failed,
35}
36
37impl Outcome {
38 pub fn glyph(self) -> &'static str {
40 match self {
41 Outcome::Running => "\u{23fa}",
42 Outcome::Ok => "\u{2713}",
43 Outcome::Refused => "\u{2298}",
44 Outcome::Failed => "\u{2717}",
45 }
46 }
47
48 pub fn as_str(self) -> &'static str {
50 match self {
51 Outcome::Running => "running",
52 Outcome::Ok => "ok",
53 Outcome::Refused => "refused",
54 Outcome::Failed => "failed",
55 }
56 }
57}
58
59pub fn outcome(result: &str, live: Option<bool>) -> Outcome {
62 match live {
63 Some(true) if refused(result) => Outcome::Refused,
64 Some(true) => Outcome::Failed,
65 Some(false) => Outcome::Ok,
66 None if refused(result) => Outcome::Refused,
69 None => match exit_code(result) {
70 Some(0) => Outcome::Ok,
71 Some(_) => Outcome::Failed,
72 None => Outcome::Ok,
73 },
74 }
75}
76
77const DENIED: &str = "the user declined to run `";
86
87fn refused(result: &str) -> bool {
88 result.starts_with(DENIED)
89}
90
91fn exit_code(result: &str) -> Option<i32> {
93 let first = result.lines().next()?.trim();
94 let rest = first.strip_prefix("exit code:")?.trim();
95 rest.parse().ok()
96}
97
98pub fn statement(name: &str, arguments: &str) -> String {
100 let parsed = serde_json::from_str::<Value>(arguments);
101 let args = match parsed {
102 Ok(Value::Object(map)) => map,
103 _ => return cut(&format!("{name} {}", arguments.trim())),
106 };
107 let mut parts: Vec<String> = Vec::new();
108 match name {
109 "shell" => {
110 if let Some(command) = text(&args, "command") {
111 parts.push(first_line(command).to_string());
113 }
114 }
115 "write_file" => {
116 if let Some(path) = text(&args, "path") {
117 parts.push(path.to_string());
118 }
119 if let Some(size) = byte_size(&args, "content") {
120 parts.push(format!("· {size}"));
121 }
122 }
123 "patch" => {
124 if let Some(path) = text(&args, "path") {
125 parts.push(path.to_string());
126 }
127 if let Some(size) = byte_size(&args, "new_string") {
128 parts.push(format!("· {size}"));
129 }
130 }
131 "execute_code" => {
132 if let Some(code) = text(&args, "code") {
133 parts.push(format!("· {}", lines(code)));
134 }
135 }
136 _ => {
139 for key in ["name", "path", "url"] {
140 if let Some(value) = text(&args, key) {
141 parts.push(value.to_string());
142 }
143 }
144 if parts.is_empty() {
145 if let Some(query) = text(&args, "query") {
146 parts.push(query.to_string());
147 }
148 }
149 }
150 }
151 if parts.is_empty() {
152 return cut(&format!("{name} {}", arguments.trim()));
154 }
155 cut(&format!("{name} {}", parts.join(" ")))
156}
157
158fn text<'a>(args: &'a Map<String, Value>, key: &str) -> Option<&'a str> {
159 args.get(key)
160 .and_then(Value::as_str)
161 .map(str::trim)
162 .filter(|s| !s.is_empty())
163}
164
165fn byte_size(args: &Map<String, Value>, key: &str) -> Option<String> {
166 args.get(key).and_then(Value::as_str).map(|s| size(s.len()))
167}
168
169fn size(bytes: usize) -> String {
172 const KB: f64 = 1024.0;
173 const MB: f64 = KB * 1024.0;
174 let b = bytes as f64;
175 if b < KB {
176 format!("{bytes} B")
177 } else if b < 10.0 * KB {
178 format!("{:.1} KB", b / KB)
179 } else if b < MB {
180 format!("{:.0} KB", b / KB)
181 } else {
182 format!("{:.1} MB", b / MB)
183 }
184}
185
186fn lines(code: &str) -> String {
187 let n = code.lines().count().max(1);
188 format!("{n} line{}", if n == 1 { "" } else { "s" })
189}
190
191fn first_line(command: &str) -> &str {
192 command.lines().next().unwrap_or("").trim()
193}
194
195fn cut(text: &str) -> String {
197 if text.chars().count() <= WIDTH {
198 return text.to_string();
199 }
200 let mut out: String = text.chars().take(WIDTH - 1).collect();
201 out.push('…');
202 out
203}
204
205#[cfg(test)]
206mod tests {
207 use super::*;
208
209 fn at(name: &str, arguments: &str) -> String {
210 statement(name, arguments)
211 }
212
213 #[test]
216 fn a_shell_call_shows_the_command_and_not_the_json_around_it() {
217 assert_eq!(
218 at("shell", r#"{"command":"cargo test -q --locked"}"#),
219 "shell cargo test -q --locked"
220 );
221 assert_eq!(
222 at(
223 "shell",
224 r#"{"command":"cargo fmt\ncargo clippy --all-targets","cwd":"/x"}"#
225 ),
226 "shell cargo fmt",
227 "the first line is the sentence; the rest is the script"
228 );
229 }
230
231 #[test]
234 fn a_write_shows_its_path_and_the_size_of_what_it_wrote() {
235 let content = "x".repeat(45_000);
236 let line = at(
237 "write_file",
238 &serde_json::json!({"path": "crates/x/src/session.rs", "content": content}).to_string(),
239 );
240 assert_eq!(line, "write_file crates/x/src/session.rs · 44 KB");
241 assert!(!line.contains("xxxx"), "{line}");
242
243 let small = at("write_file", r#"{"path":"notes.txt","content":"hello"}"#);
244 assert_eq!(small, "write_file notes.txt · 5 B");
245 }
246
247 #[test]
249 fn a_patch_shows_its_path_and_the_size_of_the_replacement() {
250 let line = at(
251 "patch",
252 &serde_json::json!({"path": "docs/USER.md", "old_string": "a", "new_string": "b".repeat(2048)}).to_string(),
253 );
254 assert_eq!(line, "patch docs/USER.md · 2.0 KB");
255 }
256
257 #[test]
260 fn a_tool_that_addresses_something_shows_what_it_addresses() {
261 assert_eq!(
262 at("read_file", r#"{"path":"src/main.rs"}"#),
263 "read_file src/main.rs"
264 );
265 assert_eq!(
266 at(
267 "fetch",
268 r#"{"url":"https://example.invalid/page","raw":true}"#
269 ),
270 "fetch https://example.invalid/page"
271 );
272 assert_eq!(
273 at(
274 "skill_view",
275 r#"{"name":"eclipse-dev-lab","path":"references/api.md"}"#
276 ),
277 "skill_view eclipse-dev-lab references/api.md"
278 );
279 assert_eq!(
280 at("session_search", r#"{"query":"gateway restart"}"#),
281 "session_search gateway restart"
282 );
283 }
284
285 #[test]
288 fn an_unknown_tool_is_cut_to_one_line() {
289 let long = serde_json::json!({"weird": "y".repeat(400)}).to_string();
290 let line = at("unknown_tool", &long);
291 assert_eq!(line.chars().count(), WIDTH, "{line}");
292 assert!(line.ends_with('…'), "{line}");
293 assert!(line.starts_with("unknown_tool "), "{line}");
294
295 assert_eq!(at("weird", "not json at all"), "weird not json at all");
297 }
298
299 #[test]
301 fn a_cut_never_splits_a_character() {
302 let line = at("x", &"é".repeat(200));
303 assert_eq!(line.chars().count(), WIDTH, "{line}");
304 assert!(line.ends_with('…'));
305 assert!(line
306 .chars()
307 .all(|c| c == 'é' || c == 'x' || c == ' ' || c == '…'));
308 }
309
310 #[test]
312 fn a_code_block_is_described_by_how_much_of_it_there_is() {
313 assert_eq!(
314 at("execute_code", "{\"code\":\"a\\nb\\nc\"}"),
315 "execute_code · 3 lines"
316 );
317 assert_eq!(
318 at("execute_code", "{\"code\":\"a\"}"),
319 "execute_code · 1 line"
320 );
321 }
322
323 #[test]
326 fn a_stored_result_says_how_the_call_went() {
327 assert_eq!(
328 outcome("exit code: 0\nstdout:\nMon Nov 30\n\nstderr:\n", None),
329 Outcome::Ok
330 );
331 assert_eq!(
332 outcome("exit code: 2\nstdout:\n\nstderr:\nno such file\n", None),
333 Outcome::Failed
334 );
335 assert_eq!(outcome("wrote 46080 bytes", None), Outcome::Ok);
338 assert_eq!(outcome("", None), Outcome::Ok);
339 }
340
341 #[test]
344 fn a_declined_call_is_its_own_mark() {
345 let text = "the user declined to run `shell`: that would delete the tree";
346 assert_eq!(outcome(text, Some(true)), Outcome::Refused);
347 assert_eq!(
348 outcome(text, None),
349 Outcome::Refused,
350 "a reload has to agree with the turn it is replaying"
351 );
352 }
353
354 #[test]
359 fn the_word_declined_is_not_a_refusal() {
360 let output =
361 "crates/eclipse-web/src/calls.rs:78: // the user declined to run it, so nothing";
362 assert_eq!(
363 outcome(output, None),
364 Outcome::Ok,
365 "a replay of a call that succeeded"
366 );
367 assert_eq!(
368 outcome(output, Some(false)),
369 Outcome::Ok,
370 "and the live flag agrees with the text"
371 );
372 assert_eq!(
374 outcome("the user declined to run `shell`: that is a delete", None),
375 Outcome::Refused
376 );
377 }
378
379 #[test]
382 fn the_live_flag_wins_over_the_text() {
383 assert_eq!(outcome("exit code: 1", Some(false)), Outcome::Ok);
384 assert_eq!(outcome("all good", Some(true)), Outcome::Failed);
385 assert_eq!(Outcome::Running.as_str(), "running");
386 }
387
388 #[test]
391 fn the_marks_are_the_terminals_own() {
392 assert_eq!(Outcome::Running.glyph(), "⏺");
393 assert_eq!(Outcome::Ok.glyph(), "✓");
394 assert_eq!(Outcome::Refused.glyph(), "⊘");
395 assert_eq!(Outcome::Failed.glyph(), "✗");
396 assert_eq!(Outcome::Ok.as_str(), "ok");
397 assert_eq!(Outcome::Refused.as_str(), "refused");
398 assert_eq!(Outcome::Failed.as_str(), "failed");
399 }
400}