curd-editor 0.27.2

A terminal code editor: file tree, tabs, git, language servers, run and jump to errors, and a panel for Claude or any other assistant
//! Reading what an assistant prints while it works: its answer in pieces,
//! what it did, and how it ended.

use super::*;

/// Something one line of the command's output says.
#[derive(Debug, PartialEq)]
pub enum Update {
    /// The name of the conversation, for carrying it on later.
    Session(String),
    /// The model that is answering.
    Model(String),
    /// The next few words of the answer, as they are written.
    Partial(String),
    /// A finished piece of the answer.
    Text(String),
    /// Something Claude did: read a file, searched, edited.
    Step(String),
    /// What an edit changed: lines that start with `-` were taken out,
    /// lines that start with `+` put in.
    Diff(Vec<String>),
    /// What a command it ran printed.
    Output(String),
    /// A line the command printed about a problem.
    Problem(String),
    /// The answer is complete.
    Done,
    /// It ended without an answer, and why.
    Failed(String),
}

/// Reads one line of `stream-json` output. Lines that say nothing the
/// panel shows give no updates.
pub fn parse(line: &str) -> Vec<Update> {
    let Ok(message) = serde_json::from_str::<Value>(line) else {
        return Vec::new();
    };
    let text = |value: &Value| value.as_str().unwrap_or_default().to_string();
    let mut updates = Vec::new();
    if let Some(session) = message["session_id"].as_str() {
        updates.push(Update::Session(session.to_string()));
    }
    match message["type"].as_str() {
        Some("system") => {
            if let Some(model) = message["model"].as_str() {
                updates.push(Update::Model(model.to_string()));
            }
        }
        Some("assistant") => {
            for block in message["message"]["content"].as_array().into_iter().flatten() {
                match block["type"].as_str() {
                    Some("text") if !text(&block["text"]).trim().is_empty() => {
                        updates.push(Update::Text(text(&block["text"]).trim().to_string()));
                    }
                    Some("tool_use") => {
                        updates.push(Update::Step(step(block)));
                        updates.extend(changed(&block["input"]).map(Update::Diff));
                    }
                    _ => {}
                }
            }
        }
        // What a tool gave back comes as a message "from the user".
        Some("user") => {
            for block in message["message"]["content"].as_array().into_iter().flatten() {
                if block["type"].as_str() == Some("tool_result") {
                    let content = &block["content"];
                    let printed = match content.as_str() {
                        Some(printed) => printed.to_string(),
                        None => {
                            let parts = content.as_array().into_iter().flatten();
                            parts.filter_map(|part| part["text"].as_str()).collect::<Vec<_>>().join("\n")
                        }
                    };
                    if !printed.trim().is_empty() {
                        updates.push(Update::Output(printed));
                    }
                }
            }
        }
        // Cursor says what it does in events of their own:
        // {"type":"tool_call","subtype":"started","tool_call":{"readToolCall":{"args":{"path":...}}}}
        Some("tool_call") if message["subtype"].as_str() == Some("started") => {
            for (kind, call) in message["tool_call"].as_object().into_iter().flatten() {
                let name = kind.trim_end_matches("ToolCall");
                let name = match call["name"].as_str() {
                    Some(function) => function.to_string(),
                    None => name[..1].to_uppercase() + &name[1..],
                };
                let call = json!({ "name": name, "input": call["args"] });
                updates.push(Update::Step(step(&call)));
            }
        }
        Some("result") => {
            let failed = message["is_error"].as_bool().unwrap_or(false)
                || message["subtype"].as_str().is_some_and(|kind| kind != "success");
            updates.push(if failed {
                let why = text(&message["result"]);
                Update::Failed(if why.is_empty() { text(&message["subtype"]) } else { why })
            } else {
                Update::Done
            });
        }
        Some("stream_event") => {
            let delta = &message["event"]["delta"];
            if delta["type"].as_str() == Some("text_delta") {
                updates.push(Update::Partial(text(&delta["text"])));
            }
        }
        Some("stderr") => updates.push(Update::Problem(text(&message["text"]))),
        _ => {}
    }
    updates
}

/// The most lines of an edit or of a command's output shown in the panel.
pub(super) const SHOWN_LINES: usize = 12;

/// What an edit changed, from what the tool was given: the text it took
/// out and the text it put in (`old_string`, `new_string`), or the whole
/// of a file it wrote (`content`). `None` for tools that change nothing.
pub(super) fn changed(input: &Value) -> Option<Vec<String>> {
    let marked = |text: &Value, mark: char| -> Vec<String> {
        let lines = text.as_str().map(|text| text.lines()).into_iter().flatten();
        lines.map(|line| format!("{mark} {line}")).collect()
    };
    let mut lines = marked(&input["old_string"], '-');
    lines.extend(marked(&input["new_string"], '+'));
    lines.extend(marked(&input["content"], '+'));
    (!lines.is_empty()).then_some(lines)
}

/// `lines` cut to as many as the panel shows of such a thing, with a
/// last line saying how many more there are.
pub(super) fn shortened(mut lines: Vec<String>) -> Vec<String> {
    if lines.len() > SHOWN_LINES {
        let more = lines.len() - SHOWN_LINES;
        lines.truncate(SHOWN_LINES);
        lines.push(format!("... {more} more lines"));
    }
    lines
}

/// A short description of a tool Claude used: its name and what on.
pub(super) fn step(block: &Value) -> String {
    let name = block["name"].as_str().unwrap_or("tool");
    let input = &block["input"];
    let on = ["file_path", "path", "pattern", "command", "query", "url", "description"]
        .iter()
        .find_map(|key| input[*key].as_str())
        .unwrap_or_default();
    let on = on.lines().next().unwrap_or_default();
    format!("{name} {on}").trim_end().to_string()
}

/// A step as the panel shows it: files named from the project folder
/// `root` rather than the top of the disk, and not too long.
pub fn shorten(step: &str, root: &Path) -> String {
    let root = format!("{}/", root.display());
    step.replace(&root, "").chars().take(STEP_CHARS).collect()
}