rustimal 0.6.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! The conversation a pane shows for `do <task>`: what was asked, a few small lines about
//! what the agent is doing, and its answer. The agent runs unseen ([`run`]); its output is
//! read by [`agent`] and drawn by [`draw`].

pub mod agent;
mod draw;
mod run;

use std::path::PathBuf;
use std::time::Instant;

pub use agent::{Agent, Denied, Event, StepKind};
pub use draw::draw;
pub use run::{Run, Update};

use crate::settings::Input;

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Step {
    id: String,
    pub label: String,
    pub kind: StepKind,
    /// `None` while it runs.
    pub ok: Option<bool>,
}

/// One message and everything that came of it.
#[derive(Default)]
pub struct Turn {
    pub asked: String,
    /// What the agent did and said, in order.
    pub items: Vec<Item>,
    pub denied: Vec<Denied>,
    pub error: Option<String>,
    /// How long it took, once it has ended.
    pub took: Option<f32>,
}

#[derive(Debug, PartialEq, Eq)]
pub enum Item {
    Step(Step),
    Text(String),
    Note(String),
}

impl Turn {
    pub fn done(&self) -> bool {
        self.took.is_some()
    }

    /// The answer: the last thing the agent said, once it has finished.
    pub fn answer(&self) -> Option<&str> {
        if !self.done() {
            return None;
        }
        self.items.iter().rev().find_map(|i| match i {
            Item::Text(t) => Some(t.as_str()),
            _ => None,
        })
    }

    pub fn steps(&self) -> impl Iterator<Item = &Step> {
        self.items.iter().filter_map(|i| match i {
            Item::Step(s) => Some(s),
            _ => None,
        })
    }
}

/// What the app should do after a key.
#[derive(Debug, PartialEq, Eq)]
pub enum Request {
    Nothing,
    /// Start a turn with this message.
    Send(String),
    /// Show the terminal again. A running task carries on.
    Hide,
    Stop,
    /// Copy this to the clipboard.
    Copy(String),
}

pub struct Chat {
    pub agent: Agent,
    /// The folder the agent works in.
    pub dir: PathBuf,
    pub session: Option<String>,
    /// Permissions the person has granted in this conversation.
    pub allowed: Vec<String>,
    pub turns: Vec<Turn>,
    /// The agent's process, while a turn runs.
    pub run: Option<Run>,
    started: Instant,
    /// What is being typed, and the cursor's position in characters.
    pub input: String,
    pub cursor: usize,
    /// Lines scrolled up from the end; 0 follows the output.
    pub scroll: usize,
    /// Switched away from: the terminal is showing.
    pub hidden: bool,
}

/// What is sent to the agent after the person allows what was refused.
const RETRY: &str = "I approved it. Please try what was blocked again.";

impl Chat {
    pub fn new(agent: Agent, dir: PathBuf) -> Self {
        Self {
            agent,
            dir,
            session: None,
            allowed: Vec::new(),
            turns: Vec::new(),
            run: None,
            started: Instant::now(),
            input: String::new(),
            cursor: 0,
            scroll: 0,
            hidden: false,
        }
    }

    pub fn running(&self) -> bool {
        self.turns.last().is_some_and(|t| !t.done())
    }

    /// Seconds the running turn has taken.
    pub fn elapsed(&self) -> f32 {
        self.started.elapsed().as_secs_f32()
    }

    /// Record a new turn. The caller starts the agent.
    pub fn begin(&mut self, message: String) {
        self.turns.push(Turn { asked: message, ..Turn::default() });
        self.started = Instant::now();
        self.scroll = 0;
    }

    /// What the last turn was refused and can be allowed.
    pub fn grantable(&self) -> Vec<String> {
        let Some(turn) = self.turns.last().filter(|t| t.done()) else { return Vec::new() };
        let mut rules: Vec<String> = Vec::new();
        for rule in turn.denied.iter().filter_map(|d| d.rule.clone()) {
            if !self.allowed.contains(&rule) && !rules.contains(&rule) {
                rules.push(rule);
            }
        }
        rules
    }

    /// Something the agent reported. Returns true if that ended the turn.
    pub fn apply(&mut self, event: Event) -> bool {
        if let Event::Session(id) = event {
            self.session = Some(id);
            return false;
        }
        let took = self.elapsed();
        let Some(turn) = self.turns.last_mut().filter(|t| !t.done()) else { return false };
        match event {
            Event::Session(_) => {}
            Event::Step { id, label, kind } => {
                // Codex names a command when it starts and again when it ends.
                if !turn.steps().any(|s| s.id == id) {
                    turn.items.push(Item::Step(Step { id, label, kind, ok: None }));
                }
            }
            Event::StepDone { id, ok } => {
                for item in turn.items.iter_mut() {
                    if let Item::Step(s) = item
                        && s.id == id
                    {
                        s.ok = Some(ok);
                    }
                }
            }
            Event::Text(text) => turn.items.push(Item::Text(text)),
            Event::Note(note) => turn.items.push(Item::Note(note)),
            Event::Denied(denied) => {
                if !turn.denied.contains(&denied) {
                    turn.denied.push(denied);
                }
            }
            Event::Finished { error } => {
                turn.error = error;
                turn.took = Some(took);
                return true;
            }
        }
        false
    }

    /// The agent's process ended. If it never said the turn was over, it failed. Returns
    /// true if that ended the turn.
    pub fn exited(&mut self, problem: &str) -> bool {
        self.run = None;
        let error = if problem.is_empty() { "it stopped without an answer".to_string() } else { problem.to_string() };
        self.apply(Event::Finished { error: Some(format!("{}: {error}", self.agent.name())) })
    }

    pub fn stop(&mut self) {
        // Dropping the run ends the process.
        self.run = None;
        self.apply(Event::Finished { error: Some("Stopped".to_string()) });
    }

    fn byte_at(&self, chars: usize) -> usize {
        self.input.char_indices().nth(chars).map_or(self.input.len(), |(i, _)| i)
    }

    pub fn insert(&mut self, text: &str) {
        let clean: String = text
            .replace("\r\n", "\n")
            .replace('\t', "    ")
            .chars()
            .filter(|&c| c == '\n' || !c.is_control())
            .collect();
        let at = self.byte_at(self.cursor);
        self.input.insert_str(at, &clean);
        self.cursor += clean.chars().count();
    }

    fn remove(&mut self, from: usize, to: usize) {
        let (a, b) = (self.byte_at(from), self.byte_at(to));
        self.input.replace_range(a..b, "");
        self.cursor = from;
    }

    fn delete_word(&mut self) {
        let chars: Vec<char> = self.input.chars().take(self.cursor).collect();
        let mut from = chars.len();
        while from > 0 && chars[from - 1].is_whitespace() {
            from -= 1;
        }
        while from > 0 && !chars[from - 1].is_whitespace() {
            from -= 1;
        }
        self.remove(from, self.cursor);
    }

    fn send(&mut self) -> Request {
        let message = self.input.trim().to_string();
        if message.is_empty() || self.running() {
            return Request::Nothing;
        }
        self.input.clear();
        self.cursor = 0;
        Request::Send(message)
    }

    /// A key the app did not take for itself. `shift` is for Shift+Enter, a new line.
    pub fn key(&mut self, input: Input, shift: bool) -> Request {
        let len = self.input.chars().count();
        match input {
            Input::Escape => return Request::Hide,
            Input::Enter if shift => self.insert("\n"),
            Input::Enter => return self.send(),
            Input::Space => self.insert(" "),
            Input::Text(t) => self.insert(&t),
            Input::Backspace if self.cursor > 0 => self.remove(self.cursor - 1, self.cursor),
            Input::ClearAll => self.delete_word(),
            Input::Delete if self.cursor < len => self.remove(self.cursor, self.cursor + 1),
            Input::Left => self.cursor = self.cursor.saturating_sub(1),
            Input::Right => self.cursor = (self.cursor + 1).min(len),
            Input::Home => self.cursor = 0,
            Input::End => self.cursor = len,
            Input::Up => self.scroll += 1,
            Input::Down => self.scroll = self.scroll.saturating_sub(1),
            Input::PageUp => self.scroll += 10,
            Input::PageDown => self.scroll = self.scroll.saturating_sub(10),
            Input::Chord(chord) if chord.ctrl && !chord.alt && !chord.shift => match chord.key.as_str() {
                "c" if self.running() => return Request::Stop,
                "c" => return self.copy_answer(),
                // Allow exactly what was refused, and have the agent try again.
                "y" => {
                    let rules = self.grantable();
                    if !rules.is_empty() {
                        self.allowed.extend(rules);
                        return Request::Send(RETRY.to_string());
                    }
                }
                _ => {}
            },
            _ => {}
        }
        Request::Nothing
    }

    pub fn copy_answer(&self) -> Request {
        self.turns.iter().rev().find_map(Turn::answer).map_or(Request::Nothing, |a| Request::Copy(a.to_string()))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::keys::Chord;

    fn chat() -> Chat {
        let mut chat = Chat::new(Agent::Claude, PathBuf::from("."));
        chat.begin("hi".into());
        chat
    }

    fn ctrl(key: &str) -> Input {
        Input::Chord(Chord::parse(&format!("ctrl+{key}")).unwrap())
    }

    #[test]
    fn the_answer_is_the_last_thing_said_once_done() {
        let mut c = chat();
        c.apply(Event::Text("let me look".into()));
        c.apply(Event::Step { id: "1".into(), label: "Read a".into(), kind: StepKind::Other });
        c.apply(Event::Step { id: "1".into(), label: "Read a".into(), kind: StepKind::Other });
        c.apply(Event::StepDone { id: "1".into(), ok: true });
        c.apply(Event::Text("it works".into()));
        assert_eq!(c.turns[0].answer(), None, "not an answer until the turn ends");
        assert_eq!(c.key(ctrl("c"), false), Request::Stop);
        assert!(c.apply(Event::Finished { error: None }));
        assert_eq!(c.turns[0].answer(), Some("it works"));
        assert_eq!(c.turns[0].steps().map(|s| s.ok).collect::<Vec<_>>(), [Some(true)]);
        assert_eq!(c.key(ctrl("c"), false), Request::Copy("it works".into()));
        assert!(!c.exited("late"), "a finished turn stays as it is");
        assert_eq!(c.turns[0].error, None);
    }

    #[test]
    fn what_was_refused_is_allowed_only_when_asked() {
        let mut c = chat();
        c.apply(Event::Denied(Denied { label: "$ ls".into(), rule: Some("Bash(ls)".into()) }));
        c.apply(Event::Denied(Denied { label: "Wrote x".into(), rule: None }));
        assert_eq!(c.key(ctrl("y"), false), Request::Nothing, "not while it runs");
        assert!(c.allowed.is_empty());
        c.apply(Event::Finished { error: None });
        assert_eq!(c.key(ctrl("y"), false), Request::Send(RETRY.into()));
        assert_eq!(c.allowed, ["Bash(ls)"]);
        assert_eq!(c.key(ctrl("y"), false), Request::Nothing, "already allowed");
    }

    #[test]
    fn a_process_that_just_ends_is_an_error() {
        let mut c = chat();
        assert!(c.exited(""));
        assert_eq!(c.turns[0].error.as_deref(), Some("Claude: it stopped without an answer"));
    }

    #[test]
    fn typing_edits_the_message() {
        let mut c = Chat::new(Agent::Codex, PathBuf::from("."));
        c.insert("héllo wörld");
        c.key(Input::ClearAll, false);
        c.key(Input::Home, false);
        c.key(Input::Delete, false);
        c.key(Input::Text("J".into()), false);
        assert_eq!(c.input, "Jéllo ");
        c.key(Input::End, false);
        c.key(Input::Enter, true);
        c.insert("two\r\nthree\x1b");
        assert_eq!(c.input, "Jéllo \ntwo\nthree");
        assert_eq!(c.key(Input::Enter, false), Request::Send("Jéllo \ntwo\nthree".into()));
        assert_eq!(c.key(Input::Enter, false), Request::Nothing, "nothing to send");
        assert_eq!(c.key(Input::Escape, false), Request::Hide);
    }
}