Skip to main content

eclipse_web/
calls.rs

1//! One line per tool call: the sentence a reader needs, not the JSON the model wrote.
2//!
3//! The dashboard shows a tool call as a single row and keeps its arguments behind a toggle.
4//! What that row says is a rule, and it lives here rather than in the page because a rule in
5//! JavaScript is a rule no test in this repository can check. The message itself is untouched:
6//! `GET /api/sessions/:id` returns the stored messages exactly as the provider would see them and
7//! adds the statements beside them, so nothing here can reach a request.
8//!
9//! The shape is "name, then what it acted on": `write_file src/x.rs · 44 KB`, `shell cargo test`.
10//! A path or a URL is the statement for the tools that take one — the braces and the key names are
11//! noise at a glance — and anything this does not know is the arguments themselves, cut.
12
13use serde_json::{Map, Value};
14
15/// Where a statement is cut. Wide enough for a path and a command, narrow enough that one call
16/// cannot wrap into a paragraph of its own in a half-width window.
17pub const WIDTH: usize = 72;
18
19/// How a call ended, which is what the row's glyph says — the same four marks the full-screen
20/// interface uses (`⏺`, `✓`, `⊘`, `✗`).
21///
22/// The live run knows this from the tool's own `is_error`; a stored session only has the result
23/// text, because the message that carries it has no such field and must not grow one (that shape
24/// belongs to the model). So the inference lives here, once, next to the statement — a rule in the
25/// page would be a rule no test in this repository can check.
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum Outcome {
28    /// Still running: no result yet, or a session that ended mid-call.
29    Running,
30    Ok,
31    /// Nothing broke; someone said no. The interface gives it its own mark because a refusal is
32    /// not a failure.
33    Refused,
34    Failed,
35}
36
37impl Outcome {
38    /// The mark, exactly as the terminal draws it.
39    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    /// The word the page puts in a class name and the API puts in `state`.
49    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
59/// The verdict on one result. `live` is the tool's own `is_error` when the caller has it; a stored
60/// result has none, and the verdict is read off the text.
61pub 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        // Replay: the two things a result says about itself. A shell call opens with its exit code
67        // (`exit code: 0\nstdout:\n…`), and a refusal opens with "declined".
68        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
77/// A refusal is the tool declining, not the tool breaking. The sentence a denied call produces is
78/// `the user declined to run \`shell\`: …` — the reason is the user's, so the wording lives in
79/// `tools` and the check here is anchored to that opening rather than to the word.
80///
81/// `#392`: it used to be `contains("declined")`, so any result that happened to *use* the word — a
82/// `grep` over this file, a diff, a log line — replayed as ⊘ on a call that succeeded. Live and
83/// replayed rows have to agree on the mark, and a prefix only the denial path writes is a signal
84/// both of them can have.
85const DENIED: &str = "the user declined to run `";
86
87fn refused(result: &str) -> bool {
88    result.starts_with(DENIED)
89}
90
91/// `exit code: 3` on the first line, if there is one.
92fn 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
98/// One line describing a call: the tool's name and the part of its arguments worth reading.
99pub 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        // Arguments that are not an object are not something to guess at; showing them cut is
104        // more honest than inventing a summary of text this does not understand.
105        _ => 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                // A command is often several lines; the first one is the statement.
112                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        // The tools whose arguments are a target rather than a payload: the target is the whole
137        // story. `name` is first for the ones that address something by name and path.
138        _ => {
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        // Nothing recognised: the arguments as written, which is what the toggle shows anyway.
153        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
169/// `512 B`, `4.2 KB`, `44 KB`, `1.4 MB`: one significant unit and no more. A reader deciding
170/// whether to open the toggle needs the order of magnitude, not the byte.
171fn 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
195/// `text` cut to [`WIDTH`] characters, on a character boundary, with an ellipsis saying so.
196fn 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    /// A command is the statement for `shell`. One that runs over several lines says what it
214    /// starts with, because the rest of it is on the row's toggle, not on the row.
215    #[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    /// A write is a path and a size. The content is the wall of text the reader asked to fold,
232    /// so it must not be in the statement.
233    #[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    /// A patch replaced something: the path and the size of the replacement are the act.
248    #[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    /// The tools whose argument *is* a target read as the target: a skill is named, a file is a
258    /// path, a fetch is a URL. No braces, no key names.
259    #[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    /// Anything unrecognised is still one line, cut with an ellipsis, and never more than the
286    /// width. The row is a glance; the toggle holds the truth.
287    #[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        // Arguments that are not even an object are shown as they came.
296        assert_eq!(at("weird", "not json at all"), "weird not json at all");
297    }
298
299    /// Cutting happens on characters, not bytes: half a multi-byte character is not a string.
300    #[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    /// `execute_code` carries a program, not an argument: its length is the honest summary.
311    #[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    /// A replayed row has no `is_error` to lean on — the stored result is text and nothing else —
324    /// so the verdict is read off what the result says: a shell call opens with its exit code.
325    #[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        // No exit code and no refusal: a tool that returned normally. Reading that as a failure
336        // would paint every `read_file` red.
337        assert_eq!(outcome("wrote 46080 bytes", None), Outcome::Ok);
338        assert_eq!(outcome("", None), Outcome::Ok);
339    }
340
341    /// A refusal is not a failure: nothing broke, someone said no. It gets the third mark, and the
342    /// same sentence produces it live and on replay.
343    #[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    /// `#392`: the word is not the refusal. A call that *succeeded* and whose output happens to
355    /// contain "declined" — a grep over this module, a diff, a log line — replayed as ⊘, and a
356    /// refusal that says it some other way would still have to be one. The check is anchored to the
357    /// sentence the denial path writes.
358    #[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        // The anchored sentence, which is the only thing a refusal starts with.
373        assert_eq!(
374            outcome("the user declined to run `shell`: that is a delete", None),
375            Outcome::Refused
376        );
377    }
378
379    /// While a call is running there is no result, and the mark says so. Live, the tool's own flag
380    /// is authoritative even when the text would read differently.
381    #[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    /// The marks are the terminal's, character for character, because the two surfaces are read as
389    /// one product.
390    #[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}