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;
const WRITING_TOOLS: &str = "Edit,Write,NotebookEdit,Bash";
pub struct Request<'a> {
pub prompt: &'a str,
pub session: Option<&'a str>,
pub can_edit: bool,
pub context: &'a str,
}
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)
}
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()?;
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)
}
#[derive(Debug, PartialEq)]
pub enum Update {
Session(String),
Text(String),
Step(String),
Problem(String),
Done,
Failed(String),
}
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
}
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()
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Who {
You,
Claude,
Note,
}
#[derive(Default)]
pub struct Panel {
pub entries: Vec<(Who, String)>,
pub input: String,
pub session: Option<String>,
pub can_edit: bool,
pub running: bool,
scroll: usize,
}
impl Panel {
pub fn say(&mut self, who: Who, text: impl Into<String>) {
self.entries.push((who, text.into()));
self.scroll = 0;
}
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
}
pub fn clear(&mut self) {
self.entries.clear();
self.session = None;
self.scroll = 0;
}
pub fn scroll_by(&mut self, rows: isize) {
self.scroll = (self.scroll as isize + rows).max(0) as usize;
}
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, "· ", " "),
};
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
}
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]));
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))
}
}
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
}