eclipse-web 0.13.4

Local web dashboard for eclipse
Documentation
//! One line per tool call: the sentence a reader needs, not the JSON the model wrote.
//!
//! The dashboard shows a tool call as a single row and keeps its arguments behind a toggle.
//! What that row says is a rule, and it lives here rather than in the page because a rule in
//! JavaScript is a rule no test in this repository can check. The message itself is untouched:
//! `GET /api/sessions/:id` returns the stored messages exactly as the provider would see them and
//! adds the statements beside them, so nothing here can reach a request.
//!
//! The shape is "name, then what it acted on": `write_file src/x.rs · 44 KB`, `shell cargo test`.
//! A path or a URL is the statement for the tools that take one — the braces and the key names are
//! noise at a glance — and anything this does not know is the arguments themselves, cut.

use serde_json::{Map, Value};

/// Where a statement is cut. Wide enough for a path and a command, narrow enough that one call
/// cannot wrap into a paragraph of its own in a half-width window.
pub const WIDTH: usize = 72;

/// How a call ended, which is what the row's glyph says — the same four marks the full-screen
/// interface uses (`⏺`, `✓`, `⊘`, `✗`).
///
/// The live run knows this from the tool's own `is_error`; a stored session only has the result
/// text, because the message that carries it has no such field and must not grow one (that shape
/// belongs to the model). So the inference lives here, once, next to the statement — a rule in the
/// page would be a rule no test in this repository can check.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Outcome {
    /// Still running: no result yet, or a session that ended mid-call.
    Running,
    Ok,
    /// Nothing broke; someone said no. The interface gives it its own mark because a refusal is
    /// not a failure.
    Refused,
    Failed,
}

impl Outcome {
    /// The mark, exactly as the terminal draws it.
    pub fn glyph(self) -> &'static str {
        match self {
            Outcome::Running => "\u{23fa}",
            Outcome::Ok => "\u{2713}",
            Outcome::Refused => "\u{2298}",
            Outcome::Failed => "\u{2717}",
        }
    }

    /// The word the page puts in a class name and the API puts in `state`.
    pub fn as_str(self) -> &'static str {
        match self {
            Outcome::Running => "running",
            Outcome::Ok => "ok",
            Outcome::Refused => "refused",
            Outcome::Failed => "failed",
        }
    }
}

/// The verdict on one result. `live` is the tool's own `is_error` when the caller has it; a stored
/// result has none, and the verdict is read off the text.
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,
        // Replay: the two things a result says about itself. A shell call opens with its exit code
        // (`exit code: 0\nstdout:\n…`), and a refusal opens with "declined".
        None if refused(result) => Outcome::Refused,
        None => match exit_code(result) {
            Some(0) => Outcome::Ok,
            Some(_) => Outcome::Failed,
            None => Outcome::Ok,
        },
    }
}

/// A refusal is the tool declining, not the tool breaking. The sentence a denied call produces is
/// `the user declined to run \`shell\`: …` — the reason is the user's, so the wording lives in
/// `tools` and the check here is anchored to that opening rather than to the word.
///
/// `#392`: it used to be `contains("declined")`, so any result that happened to *use* the word — a
/// `grep` over this file, a diff, a log line — replayed as ⊘ on a call that succeeded. Live and
/// replayed rows have to agree on the mark, and a prefix only the denial path writes is a signal
/// both of them can have.
const DENIED: &str = "the user declined to run `";

fn refused(result: &str) -> bool {
    result.starts_with(DENIED)
}

/// `exit code: 3` on the first line, if there is one.
fn exit_code(result: &str) -> Option<i32> {
    let first = result.lines().next()?.trim();
    let rest = first.strip_prefix("exit code:")?.trim();
    rest.parse().ok()
}

/// One line describing a call: the tool's name and the part of its arguments worth reading.
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,
        // Arguments that are not an object are not something to guess at; showing them cut is
        // more honest than inventing a summary of text this does not understand.
        _ => return cut(&format!("{name} {}", arguments.trim())),
    };
    let mut parts: Vec<String> = Vec::new();
    match name {
        "shell" => {
            if let Some(command) = text(&args, "command") {
                // A command is often several lines; the first one is the statement.
                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)));
            }
        }
        // The tools whose arguments are a target rather than a payload: the target is the whole
        // story. `name` is first for the ones that address something by name and path.
        _ => {
            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() {
        // Nothing recognised: the arguments as written, which is what the toggle shows anyway.
        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()))
}

/// `512 B`, `4.2 KB`, `44 KB`, `1.4 MB`: one significant unit and no more. A reader deciding
/// whether to open the toggle needs the order of magnitude, not the byte.
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()
}

/// `text` cut to [`WIDTH`] characters, on a character boundary, with an ellipsis saying so.
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)
    }

    /// A command is the statement for `shell`. One that runs over several lines says what it
    /// starts with, because the rest of it is on the row's toggle, not on the row.
    #[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"
        );
    }

    /// A write is a path and a size. The content is the wall of text the reader asked to fold,
    /// so it must not be in the statement.
    #[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");
    }

    /// A patch replaced something: the path and the size of the replacement are the act.
    #[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");
    }

    /// The tools whose argument *is* a target read as the target: a skill is named, a file is a
    /// path, a fetch is a URL. No braces, no key names.
    #[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"
        );
    }

    /// Anything unrecognised is still one line, cut with an ellipsis, and never more than the
    /// width. The row is a glance; the toggle holds the truth.
    #[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}");

        // Arguments that are not even an object are shown as they came.
        assert_eq!(at("weird", "not json at all"), "weird not json at all");
    }

    /// Cutting happens on characters, not bytes: half a multi-byte character is not a string.
    #[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 == '…'));
    }

    /// `execute_code` carries a program, not an argument: its length is the honest summary.
    #[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"
        );
    }

    /// A replayed row has no `is_error` to lean on — the stored result is text and nothing else —
    /// so the verdict is read off what the result says: a shell call opens with its exit code.
    #[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
        );
        // No exit code and no refusal: a tool that returned normally. Reading that as a failure
        // would paint every `read_file` red.
        assert_eq!(outcome("wrote 46080 bytes", None), Outcome::Ok);
        assert_eq!(outcome("", None), Outcome::Ok);
    }

    /// A refusal is not a failure: nothing broke, someone said no. It gets the third mark, and the
    /// same sentence produces it live and on replay.
    #[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"
        );
    }

    /// `#392`: the word is not the refusal. A call that *succeeded* and whose output happens to
    /// contain "declined" — a grep over this module, a diff, a log line — replayed as ⊘, and a
    /// refusal that says it some other way would still have to be one. The check is anchored to the
    /// sentence the denial path writes.
    #[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"
        );
        // The anchored sentence, which is the only thing a refusal starts with.
        assert_eq!(
            outcome("the user declined to run `shell`: that is a delete", None),
            Outcome::Refused
        );
    }

    /// While a call is running there is no result, and the mark says so. Live, the tool's own flag
    /// is authoritative even when the text would read differently.
    #[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");
    }

    /// The marks are the terminal's, character for character, because the two surfaces are read as
    /// one product.
    #[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");
    }
}