Cotton code
123 lines · 4.9 KB · RustRaw
//! **WHY A SESSION ENDED, IN ITS OWN LAST WORDS.** A child that fails to start//! — Claude Code refusing its settings file, a missing binary — exits within a second, and its terminal's last line is the//! only account of why. The host keeps that line as the session's error, so//! the session row says the real reason and not merely that it ended.//!//! A session that ends within [`QUICK_EXIT`] of starting always carries an//! error, even one that printed nothing and exited 0: no session that works//! ends that fast, so silence there is itself the failure to report.use std::time::Duration;use crate::pty::Exited;/// An end this soon after the start is a failed launch, whatever the code.pub const QUICK_EXIT: Duration = Duration::from_secs(1);/// The most of a last line an error keeps.pub const MAX_CHARS: usize = 500;/// How much of the terminal's tail is held to find the last line in.const TAIL_BYTES: usize = 4096;/// The last few kilobytes a terminal wrote.#[derive(Debug, Default)]pub struct Tail {    bytes: Vec<u8>,}impl Tail {    /// Take in what the terminal wrote next.    pub fn push(&mut self, chunk: &[u8]) {        self.bytes.extend_from_slice(chunk);        if self.bytes.len() > TAIL_BYTES {            self.bytes.drain(..self.bytes.len() - TAIL_BYTES);        }    }    /// The last line with printable words — a letter or a digit — its    /// terminal escapes removed: a line of nothing but control sequences, or    /// what is left of one, is never the reason a session ended.    pub fn last_line(&self) -> Option<String> {        let text = strip_escapes(&String::from_utf8_lossy(&self.bytes));        let line = text.split(['\n', '\r']).map(words).rfind(|line| line.chars().any(char::is_alphanumeric))?;        Some(line.chars().take(MAX_CHARS).collect())    }}/// A line with its runs of spaces made one and its ends trimmed.fn words(line: &str) -> String {    line.split_whitespace().collect::<Vec<_>>().join(" ")}/// `text` without terminal control sequences or other control characters/// but line breaks. A cursor move is a space — a full-screen interface places/// its words by moving the cursor, not by printing spaces.fn strip_escapes(text: &str) -> String {    let mut out = String::with_capacity(text.len());    let mut chars = text.chars().peekable();    while let Some(c) = chars.next() {        match c {            '\u{1b}' => match chars.next() {                // CSI: parameters and intermediates, then one final byte.                Some('[') => {                    for c in chars.by_ref() {                        if ('@'..='~').contains(&c) {                            if matches!(c, 'A'..='H' | 'f' | '`' | 'a' | 'd' | 'e') { out.push(' '); }                            break;                        }                    }                }                // OSC, DCS, SOS, PM, APC: a string up to BEL or ESC \ (an                // escaped ESC inside, as tmux's passthrough has, does not end it).                Some(']' | 'P' | 'X' | '^' | '_') => {                    while let Some(c) = chars.next() {                        if c == '\u{7}' { break; }                        if c == '\u{1b}' {                            match chars.peek() {                                Some('\\') => { chars.next(); break; }                                Some('\u{1b}') => { chars.next(); }                                _ => {}                            }                        }                    }                }                // Intermediates, then one final byte: `ESC ( B` and its kin.                Some(' '..='/') => {                    for c in chars.by_ref() {                        if !(' '..='/').contains(&c) { break; }                    }                }                // Any other two-byte escape (`ESC 7`, `ESC =`, `ESC M`).                _ => {}            },            '\n' | '\r' => out.push(c),            '\t' => out.push(' '),            c if c.is_control() => {}            c => out.push(c),        }    }    out}/// The error a session's end carries, or `None` for an ordinary end: a/// non-zero exit, or any end within [`QUICK_EXIT`] of the start.pub fn exit_error(exit: Exited, lived: Duration, last_line: Option<String>) -> Option<String> {    let failed = exit.code.is_some_and(|code| code != 0);    let quick = lived < QUICK_EXIT;    if !failed && !quick {        return None;    }    Some(last_line.unwrap_or_else(|| {        let how = match (exit.code, exit.signal) {            (Some(code), _) => format!("exited with code {code}"),            (None, Some(signal)) => format!("was ended by signal {signal}"),            (None, None) => "ended".to_string(),        };        if quick { format!("the session {how} within a second of starting and printed nothing") } else { format!("the session {how} and printed nothing") }    }))}#[cfg(test)]#[path = "exit_reason_tests.rs"]mod tests;