rustimal 0.6.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! The agent's process: started without a window, given the message on standard input, and
//! read line by line on threads of its own.

use std::io::{BufRead, BufReader, Read, Write};
use std::os::windows::process::CommandExt;
use std::path::Path;
use std::process::{Command, Stdio};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};

use super::agent::{Agent, Event, parse_line};

const CREATE_NO_WINDOW: u32 = 0x0800_0000;

/// What a running agent sends back.
pub enum Update {
    Events(Vec<Event>),
    /// The process ended; if it failed, the end of what it printed as errors.
    Exited(String),
}

/// A running agent. Dropping it ends the process and everything it started.
pub struct Run {
    /// Tells this run's messages from those of one that was stopped.
    pub id: u64,
    pid: u32,
    exited: Arc<AtomicBool>,
}

impl Run {
    pub fn start(
        agent: Agent,
        dir: &Path,
        session: Option<&str>,
        allowed: &[String],
        message: String,
        send: impl Fn(u64, Update) + Send + 'static,
    ) -> Result<Run, String> {
        static NEXT: AtomicU64 = AtomicU64::new(1);
        let id = NEXT.fetch_add(1, Ordering::Relaxed);
        let mut command = Command::new(agent.program());
        command
            .args(agent.args(session, allowed))
            .current_dir(dir)
            // PATH and friends from the registry, as new panes get them.
            .envs(crate::winenv::fresh())
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .creation_flags(CREATE_NO_WINDOW);
        let mut child = command.spawn().map_err(|e| match e.kind() {
            std::io::ErrorKind::NotFound => format!("`{}` isn't installed, or isn't on PATH", agent.program()),
            _ => format!("could not start `{}`: {e}", agent.program()),
        })?;
        let pid = child.id();
        let exited = Arc::new(AtomicBool::new(false));
        let (Some(mut stdin), Some(stdout), Some(mut stderr)) =
            (child.stdin.take(), child.stdout.take(), child.stderr.take())
        else {
            return Err("could not connect to the agent".to_string());
        };
        std::thread::spawn(move || {
            // Closing standard input (by dropping it) tells the agent the message is whole.
            if let Err(e) = stdin.write_all(message.as_bytes()) {
                log::warn!("could not send the message: {e}");
            }
        });
        let errors = std::thread::spawn(move || {
            let mut bytes = Vec::new();
            let _ = stderr.read_to_end(&mut bytes);
            String::from_utf8_lossy(&bytes).into_owned()
        });
        let root = dir.to_string_lossy().into_owned();
        let done = exited.clone();
        std::thread::spawn(move || {
            let mut reader = BufReader::new(stdout);
            let mut line = Vec::new();
            loop {
                line.clear();
                match reader.read_until(b'\n', &mut line) {
                    Ok(0) | Err(_) => break,
                    Ok(_) => {
                        let events = parse_line(agent, &String::from_utf8_lossy(&line), &root);
                        if !events.is_empty() {
                            send(id, Update::Events(events));
                        }
                    }
                }
            }
            let status = child.wait();
            done.store(true, Ordering::SeqCst);
            let errors = errors.join().unwrap_or_default();
            let failed = !status.is_ok_and(|s| s.success());
            send(id, Update::Exited(if failed { last_lines(&errors, 4) } else { String::new() }));
        });
        Ok(Run { id, pid, exited })
    }
}

fn last_lines(text: &str, n: usize) -> String {
    let lines: Vec<&str> = text.trim().lines().collect();
    lines[lines.len().saturating_sub(n)..].join("\n")
}

impl Drop for Run {
    fn drop(&mut self) {
        if !self.exited.load(Ordering::SeqCst) {
            // The agent runs commands of its own, which have to end with it.
            let _ = Command::new("taskkill")
                .args(["/T", "/F", "/PID", &self.pid.to_string()])
                .creation_flags(CREATE_NO_WINDOW)
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .status();
        }
    }
}

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

    #[test]
    fn only_the_end_of_the_errors_is_kept() {
        assert_eq!(last_lines("a\nb\nc\n", 2), "b\nc");
        assert_eq!(last_lines("", 2), "");
    }
}