curd-editor 0.11.0

A small terminal code editor: file tree, git status and change markers, tabs, undo, selection, search and replace, a git menu, and language-server colours, errors and completion
//! The Claude panel: ask Claude about the project, or to change it.
//!
//! `curd` does not talk to Anthropic itself and never sees a login. It
//! runs the `claude` command the user has installed and signed in to
//! (their Claude subscription), once per question, the way the docs
//! describe for other programs: `claude -p ... --output-format stream-json`.
//! The command prints one JSON object per line as it works, which is read
//! here and shown in the panel.

use std::io::{BufRead, BufReader};
use std::path::Path;
use std::process::{Child, Command, Stdio};

use serde_json::{json, Value};

use crate::screen::{fit, Row, Span, Style};

#[cfg(test)]
mod tests;

/// The tools Claude is refused while the panel is read-only.
const WRITING_TOOLS: &str = "Edit,Write,NotebookEdit,Bash";

/// One question for Claude.
pub struct Request<'a> {
    pub prompt: &'a str,
    /// The conversation to carry on, if one was started.
    pub session: Option<&'a str>,
    /// Whether Claude may change files.
    pub can_edit: bool,
    /// What the editor is showing, for Claude to know.
    pub context: &'a str,
}

/// The command line to run for `request`.
///
/// `setting` is the CURD_AGENT environment variable: "off" turns the panel
/// off, and anything else is used in place of `claude`.
pub fn command_line(setting: Option<&str>, request: &Request) -> Option<Vec<String>> {
    let program = match setting.map(str::trim) {
        Some("off") => return None,
        Some(custom) if !custom.is_empty() => custom,
        _ => "claude",
    };
    let mut words: Vec<String> = program.split_whitespace().map(String::from).collect();
    let mut add = |extra: &[&str]| words.extend(extra.iter().map(|word| word.to_string()));
    add(&["--print", request.prompt]);
    add(&["--output-format", "stream-json", "--verbose"]);
    if let Some(session) = request.session {
        add(&["--resume", session]);
    }
    if request.can_edit {
        add(&["--permission-mode", "acceptEdits"]);
    } else {
        add(&["--disallowedTools", WRITING_TOOLS]);
    }
    if !request.context.is_empty() {
        add(&["--append-system-prompt", request.context]);
    }
    Some(words)
}

/// Starts `words` (a command and its arguments) in `dir`. Every line it
/// prints is passed to `forward`, and `None` when it has finished.
pub fn start(
    words: &[String],
    dir: &Path,
    forward: impl Fn(Option<String>) + Send + Clone + 'static,
) -> std::io::Result<Child> {
    let mut child = Command::new(&words[0])
        .args(&words[1..])
        .current_dir(dir)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()?;
    // What it says when it fails is passed on in the same form as the rest.
    if let Some(errors) = child.stderr.take() {
        let forward = forward.clone();
        std::thread::spawn(move || {
            for line in BufReader::new(errors).lines().map_while(Result::ok) {
                forward(Some(json!({"type": "stderr", "text": line}).to_string()));
            }
        });
    }
    if let Some(output) = child.stdout.take() {
        std::thread::spawn(move || {
            for line in BufReader::new(output).lines().map_while(Result::ok) {
                forward(Some(line));
            }
            forward(None);
        });
    }
    Ok(child)
}

/// 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),
    /// Words from Claude.
    Text(String),
    /// Something Claude did: read a file, searched, edited.
    Step(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("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))),
                    _ => {}
                }
            }
        }
        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("stderr") => updates.push(Update::Problem(text(&message["text"]))),
        _ => {}
    }
    updates
}

/// A short description of a tool Claude used: its name and what on.
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: String = on.lines().next().unwrap_or_default().chars().take(60).collect();
    format!("{name} {on}").trim_end().to_string()
}

/// Who a line in the panel is from.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Who {
    You,
    Claude,
    /// The editor itself: what Claude did, and problems.
    Note,
}

/// The panel under the text: the conversation so far and the line being
/// typed.
#[derive(Default)]
pub struct Panel {
    pub entries: Vec<(Who, String)>,
    /// The question being typed.
    pub input: String,
    pub session: Option<String>,
    pub can_edit: bool,
    /// True while Claude is working on an answer.
    pub running: bool,
    /// How many rows the view is scrolled up from the newest line.
    scroll: usize,
}

impl Panel {
    pub fn say(&mut self, who: Who, text: impl Into<String>) {
        self.entries.push((who, text.into()));
        // Something new: show it.
        self.scroll = 0;
    }

    /// Takes in what a line of output said. Returns true when the answer
    /// has ended, one way or the other.
    pub fn apply(&mut self, update: Update) -> bool {
        match update {
            Update::Session(session) => self.session = Some(session),
            Update::Text(text) => self.say(Who::Claude, text),
            Update::Step(step) => self.say(Who::Note, step),
            Update::Problem(problem) => self.say(Who::Note, problem),
            Update::Done => self.running = false,
            Update::Failed(why) => {
                self.running = false;
                self.say(Who::Note, format!("Stopped: {why}"));
            }
        }
        !self.running
    }

    /// Forgets the conversation, to start a new one.
    pub fn clear(&mut self) {
        self.entries.clear();
        self.session = None;
        self.scroll = 0;
    }

    /// Scrolls `rows` towards older lines (newer, when negative).
    pub fn scroll_by(&mut self, rows: isize) {
        self.scroll = (self.scroll as isize + rows).max(0) as usize;
    }

    /// The conversation as rows of at most `width` characters.
    fn lines(&self, width: usize) -> Vec<Span> {
        let mut lines = Vec::new();
        for (who, text) in &self.entries {
            let (style, first, rest) = match who {
                Who::You => (Style::Bold, "> ", "  "),
                Who::Claude => (Style::Plain, "", ""),
                Who::Note => (Style::Dim, "· ", "  "),
            };
            // An empty row sets each question apart from the answer before.
            if *who == Who::You && !lines.is_empty() {
                lines.push(Span::new(Style::Plain, fit("", width)));
            }
            for (index, line) in wrap(text, width.saturating_sub(2)).into_iter().enumerate() {
                let prefix = if index == 0 { first } else { rest };
                lines.push(Span::new(style, fit(&format!("{prefix}{line}"), width)));
            }
        }
        lines
    }

    /// The panel as `height` rows: a title, the conversation, and the line
    /// being typed. Also where the cursor goes on that last line.
    pub fn render(&mut self, width: usize, height: usize, focused: bool) -> (Vec<Row>, usize) {
        let state = if self.running {
            "working... (Esc stops it)"
        } else if self.can_edit {
            "may change files (Alt+M: read only)"
        } else {
            "read only (Alt+M: let it change files)"
        };
        let title_style = if focused { Style::Reverse } else { Style::Menu };
        let mut rows = vec![vec![Span::new(title_style, fit(&format!(" Claude · {state}"), width))]];

        let body = height.saturating_sub(2);
        let lines = self.lines(width);
        self.scroll = self.scroll.min(lines.len().saturating_sub(body));
        let first = lines.len().saturating_sub(body + self.scroll);
        let mut shown: Vec<Span> = lines.into_iter().skip(first).take(body).collect();
        if shown.is_empty() && body > 0 {
            let hint = "Ask about this project and press Enter. Esc goes back to the text.";
            shown.push(Span::new(Style::Dim, fit(hint, width)));
        }
        shown.resize(body, Span::new(Style::Plain, fit("", width)));
        rows.extend(shown.into_iter().map(|line| vec![line]));

        // Of a long question, the end is what is shown.
        let room = width.saturating_sub(3);
        let typed = self.input.chars().count();
        let tail: String = self.input.chars().skip(typed.saturating_sub(room)).collect();
        if height > 1 {
            rows.push(vec![Span::new(Style::Plain, fit(&format!("> {tail}"), width))]);
        }
        rows.truncate(height);
        (rows, 2 + typed.min(room))
    }
}

/// Breaks `text` into lines of at most `width` characters, at spaces where
/// it can.
pub fn wrap(text: &str, width: usize) -> Vec<String> {
    let width = width.max(1);
    let mut lines = Vec::new();
    for line in text.split('\n') {
        let chars: Vec<char> = line.chars().collect();
        let mut start = 0;
        while chars.len() - start > width {
            let limit = start + width;
            let cut = (start + 1..=limit).rev().find(|at| chars[*at] == ' ').unwrap_or(limit);
            lines.push(chars[start..cut].iter().collect());
            start = cut + (chars[cut] == ' ') as usize;
        }
        lines.push(chars[start..].iter().collect());
    }
    lines
}