use std::collections::HashMap;
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
use std::time::SystemTime;
use std::process::{Child, Command, Stdio};
use std::time::Instant;
use crossterm::style::Color;
use serde_json::{json, Value};
use crate::highlight::{self, LineState};
use crate::screen::{fit, Decoration, Row, Span, Style};
use crate::snippets::Language;
#[cfg(test)]
mod tests;
const WRITING_TOOLS: &str = "Edit,Write,NotebookEdit,Bash";
const STEP_CHARS: usize = 70;
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", "--include-partial-messages"]);
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),
Partial(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("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
}
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()
}
pub fn shorten(step: &str, root: &Path) -> String {
let root = format!("{}/", root.display());
step.replace(&root, "").chars().take(STEP_CHARS).collect()
}
const MAX_KEPT_BYTES: u64 = 512 * 1024;
const MAX_SNAPSHOT_BYTES: u64 = 32 * 1024 * 1024;
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ChangeKind {
Created,
Modified,
Deleted,
}
#[derive(Debug, PartialEq)]
pub struct Change {
pub file: String,
pub kind: ChangeKind,
}
struct Before {
len: u64,
modified: Option<SystemTime>,
content: Option<Vec<u8>>,
}
pub struct Snapshot {
root: PathBuf,
files: HashMap<String, Before>,
}
impl Snapshot {
pub fn take(root: &Path, files: &[String]) -> Self {
let mut kept = 0;
let mut before = HashMap::new();
for file in files {
let path = root.join(file);
let Ok(data) = std::fs::metadata(&path) else {
continue;
};
let fits = data.len() <= MAX_KEPT_BYTES && kept + data.len() <= MAX_SNAPSHOT_BYTES;
let content = fits.then(|| std::fs::read(&path).ok()).flatten();
kept += content.as_ref().map_or(0, |content| content.len() as u64);
before.insert(
file.clone(),
Before {
len: data.len(),
modified: data.modified().ok(),
content,
},
);
}
Self {
root: root.to_path_buf(),
files: before,
}
}
pub fn changes(&self, files: &[String]) -> Vec<Change> {
let mut changes = Vec::new();
for file in files {
let path = self.root.join(file);
let kind = match self.files.get(file) {
None if !path.exists() => continue,
None => ChangeKind::Created,
Some(before) => {
let same = match (&before.content, std::fs::metadata(&path)) {
(Some(content), Ok(_)) => std::fs::read(&path).is_ok_and(|now| now == *content),
(None, Ok(data)) => {
data.len() == before.len && data.modified().ok() == before.modified
}
(_, Err(_)) => true,
};
if same {
continue;
}
ChangeKind::Modified
}
};
changes.push(Change { file: file.clone(), kind });
}
for file in self.files.keys() {
if !self.root.join(file).exists() {
changes.push(Change { file: file.clone(), kind: ChangeKind::Deleted });
}
}
changes.sort_by(|a, b| a.file.cmp(&b.file));
changes
}
pub fn restore(&self, changes: &[Change]) -> (usize, usize) {
let (mut restored, mut failed) = (0, 0);
for change in changes {
let path = self.root.join(&change.file);
let done = match (change.kind, self.files.get(&change.file)) {
(ChangeKind::Created, _) => std::fs::remove_file(&path).is_ok(),
(_, Some(Before { content: Some(content), .. })) => {
let folder = path.parent().unwrap_or(&self.root);
std::fs::create_dir_all(folder).is_ok() && std::fs::write(&path, content).is_ok()
}
_ => false,
};
if done {
restored += 1;
} else {
failed += 1;
}
}
(restored, failed)
}
}
pub fn describe(changes: &[Change]) -> String {
let names: Vec<String> = changes
.iter()
.map(|change| match change.kind {
ChangeKind::Created => format!("new {}", change.file),
ChangeKind::Modified => change.file.clone(),
ChangeKind::Deleted => format!("deleted {}", change.file),
})
.collect();
let files = if changes.len() == 1 { "file" } else { "files" };
format!("Changed {} {files}: {}", changes.len(), names.join(", "))
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Who {
You,
Claude,
Note,
}
#[derive(Default)]
pub struct Panel {
pub entries: Vec<(Who, String)>,
pub input: String,
cursor: usize,
history: Vec<String>,
history_at: Option<usize>,
pub session: Option<String>,
pub can_edit: bool,
pub running: bool,
started: Option<Instant>,
partial: bool,
scroll: usize,
}
const SPINNER: [char; 10] = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
const HINTS: [&str; 4] = [
"Ask about this project and press Enter.",
"Text selected in the file is sent along with the question.",
"Claude may change files; Alt+M makes it read only. Alt+U undoes its changes.",
"Esc goes back to the text. Alt+Z makes this panel bigger.",
];
impl Panel {
pub fn new() -> Self {
Self {
can_edit: true,
..Self::default()
}
}
pub fn say(&mut self, who: Who, text: impl Into<String>) {
self.entries.push((who, text.into()));
self.partial = false;
self.scroll = 0;
}
pub fn start(&mut self) {
self.running = true;
self.started = Some(Instant::now());
}
pub fn apply(&mut self, update: Update) -> bool {
match update {
Update::Session(session) => self.session = Some(session),
Update::Partial(words) => match self.entries.last_mut() {
Some((Who::Claude, text)) if self.partial => text.push_str(&words),
_ => {
self.say(Who::Claude, words);
self.partial = true;
}
},
Update::Text(text) => {
if self.partial {
self.entries.pop();
}
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 last_answer(&self) -> Option<&str> {
self.entries
.iter()
.rev()
.find(|(who, _)| *who == Who::Claude)
.map(|(_, text)| text.as_str())
}
pub fn scroll_by(&mut self, rows: isize) {
self.scroll = (self.scroll as isize + rows).max(0) as usize;
}
fn byte(&self, at: usize) -> usize {
self.input.char_indices().nth(at).map_or(self.input.len(), |(byte, _)| byte)
}
pub fn type_char(&mut self, c: char) {
let at = self.byte(self.cursor);
self.input.insert(at, c);
self.cursor += 1;
}
pub fn backspace(&mut self) {
if self.cursor > 0 {
self.cursor -= 1;
self.delete();
}
}
pub fn delete(&mut self) {
let at = self.byte(self.cursor);
if at < self.input.len() {
self.input.remove(at);
}
}
pub fn move_cursor(&mut self, step: isize) {
let end = self.input.chars().count() as isize;
self.cursor = (self.cursor as isize).saturating_add(step).clamp(0, end) as usize;
}
pub fn recall(&mut self, step: isize) {
let count = self.history.len() as isize;
let at = self.history_at.map_or(count, |at| at as isize) + step;
if at < 0 || count == 0 {
return;
}
self.history_at = (at < count).then_some(at as usize);
self.input = self.history_at.map(|at| self.history[at].clone()).unwrap_or_default();
self.cursor = self.input.chars().count();
}
pub fn take_input(&mut self) -> Option<String> {
let question = self.input.trim().to_string();
if question.is_empty() {
return None;
}
self.input.clear();
self.cursor = 0;
self.history_at = None;
if self.history.last() != Some(&question) {
self.history.push(question.clone());
}
Some(question)
}
fn lines(&self, width: usize) -> Vec<Row> {
let mut lines: Vec<Row> = Vec::new();
let plain = |style: Style, text: String| vec![Span::new(style, fit(&text, width))];
for (who, text) in &self.entries {
if *who == Who::You && !lines.is_empty() {
lines.push(plain(Style::Plain, String::new()));
}
let (style, first, rest) = match who {
Who::You => (Style::Bold, "> ", " "),
Who::Note => (Style::Dim, "· ", " "),
Who::Claude => {
lines.extend(markdown(text, width));
continue;
}
};
for (index, line) in wrap(text, width.saturating_sub(2)).into_iter().enumerate() {
let prefix = if index == 0 { first } else { rest };
lines.push(plain(style, format!("{prefix}{line}")));
}
}
lines
}
pub fn render(&mut self, width: usize, height: usize, focused: bool) -> (Vec<Row>, usize) {
let state = if self.running {
let waited = self.started.map_or(0, |started| started.elapsed().as_millis());
let spinner = SPINNER[(waited / 120) as usize % SPINNER.len()];
format!("{spinner} working {}s (Esc stops it)", waited / 1000)
} else if self.can_edit {
"may change files (Alt+M: read only)".into()
} else {
"read only (Alt+M: let it change files)".into()
};
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<Row> = lines.into_iter().skip(first).take(body).collect();
if shown.is_empty() {
let hints = HINTS.iter().take(body);
shown.extend(hints.map(|hint| vec![Span::new(Style::Dim, fit(hint, width))]));
}
shown.resize(body, vec![Span::new(Style::Plain, fit("", width))]);
rows.extend(shown);
let room = width.saturating_sub(3).max(1);
let from = (self.cursor + 1).saturating_sub(room);
let part: String = self.input.chars().skip(from).take(room).collect();
if height > 1 {
rows.push(vec![Span::new(Style::Plain, fit(&format!("> {part}"), width))]);
}
rows.truncate(height);
(rows, 2 + self.cursor - from)
}
}
pub fn wrap(text: &str, width: usize) -> Vec<String> {
let mut lines = Vec::new();
for line in text.split('\n') {
let chars: Vec<(char, Style)> = line.chars().map(|c| (c, Style::Plain)).collect();
let pieces = wrap_chars(&chars, width);
lines.extend(pieces.iter().map(|piece| piece.iter().map(|(c, _)| *c).collect()));
}
lines
}
fn wrap_chars(chars: &[(char, Style)], width: usize) -> Vec<&[(char, Style)]> {
let width = width.max(1);
let mut pieces = Vec::new();
let mut start = 0;
while chars.len() - start > width {
let limit = start + width;
let cut = (start + 1..=limit).rev().find(|at| chars[*at].0 == ' ').unwrap_or(limit);
pieces.push(&chars[start..cut]);
start = cut + (chars[cut].0 == ' ') as usize;
}
pieces.push(&chars[start..]);
pieces
}
fn row_of(prefix: Option<Span>, chars: &[(char, Style)], width: usize) -> Row {
let mut row: Row = prefix.into_iter().collect();
let mut used: usize = row.iter().map(|span| span.text.chars().count()).sum();
for (c, style) in chars {
match row.last_mut() {
Some(last) if last.style == *style => last.text.push(*c),
_ => row.push(Span::new(*style, c.to_string())),
}
}
used += chars.len();
row.push(Span::new(Style::Plain, " ".repeat(width.saturating_sub(used))));
row
}
fn fence_language(tag: &str) -> Option<Language> {
let extension = match tag.trim().to_ascii_lowercase().as_str() {
"rust" => "rs".into(),
"python" => "py".into(),
"javascript" | "typescript" => "js".into(),
"c++" => "cpp".into(),
"golang" => "go".into(),
other => other.to_string(),
};
Language::from_path(&format!("code.{extension}"))
}
fn inline(text: &str, base: Style) -> Vec<(char, Style)> {
let code = Style::Colored(Color::Cyan);
let chars: Vec<char> = text.chars().collect();
let (mut in_code, mut bold) = (false, false);
let mut styled = Vec::new();
let mut i = 0;
while i < chars.len() {
match chars[i] {
'`' => in_code = !in_code,
'*' if !in_code && chars.get(i + 1) == Some(&'*') => {
bold = !bold;
i += 1;
}
c if in_code => styled.push((c, code)),
c if bold => styled.push((c, Style::Bold)),
c => styled.push((c, base)),
}
i += 1;
}
styled
}
pub fn markdown(text: &str, width: usize) -> Vec<Row> {
let mut rows = Vec::new();
let mut code: Option<(Option<Language>, LineState)> = None;
for line in text.split('\n') {
if let Some(tag) = line.trim_start().strip_prefix("```") {
code = match code {
Some(_) => None,
None => Some((fence_language(tag), LineState::Code)),
};
continue;
}
let Some((language, state)) = &mut code else {
let trimmed = line.trim_start();
let indent = &line[..line.len() - trimmed.len()];
let heading = trimmed.trim_start_matches('#');
let chars = if heading.len() < trimmed.len() && heading.starts_with(' ') {
inline(heading.trim_start(), Style::Bold)
} else if let Some(item) = trimmed.strip_prefix("- ").or(trimmed.strip_prefix("* ")) {
inline(&format!("{indent}• {item}"), Style::Plain)
} else {
inline(line, Style::Plain)
};
for piece in wrap_chars(&chars, width) {
rows.push(row_of(None, piece, width));
}
continue;
};
let mut chars: Vec<(char, Style)> = line.chars().map(|c| (c, Style::Plain)).collect();
if let Some(language) = language {
let mut tokens = Vec::new();
*state = highlight::lex_line(line, *language, *state, &mut tokens);
for token in tokens {
let decoration = Decoration { kind: token.kind, ..Decoration::default() };
let end = token.end.min(chars.len());
for (_, style) in &mut chars[token.start.min(end)..end] {
*style = Style::Code(decoration);
}
}
}
for piece in wrap_chars(&chars, width.saturating_sub(2)) {
rows.push(row_of(Some(Span::new(Style::Dim, "│ ")), piece, width));
}
}
rows
}