eclipse-cli 0.13.4

Command-line interface for eclipse
//! The last thing an interactive run says.
//!
//! The interface draws in the terminal's ordinary buffer — no alternate screen, on purpose, so
//! scrolling, selection and the clipboard stay the terminal's own. The consequence is that its
//! last frame outlives the process: the shell prompt lands under a half-drawn screen, and a run
//! that ended cleanly is indistinguishable from one that died. So the CLI clears what it drew
//! and says one line about what happened, then gets out of the way.
//!
//! The visible screen is cleared by default and the scrollback is not. `\x1b[3J` wipes what the
//! reader scrolled past, which is their copy/paste history and the one thing this program does
//! not own; `[cli] clear_on_exit = "all"` opts into it, `"off"` opts out of both.

use crate::status::{short_duration, short_session, short_tokens, Status};
use eclipse_core::config::ClearOnExit;
use std::io::Write;

/// The escape sequence a mode begins with. Empty for `off`, so a caller can assert on it rather
/// than on a captured terminal.
pub fn prefix(mode: ClearOnExit) -> &'static str {
    match mode {
        // Clear the visible screen and home the cursor: the two escapes every terminal has had
        // since the VT100. Not `3J`, which also drops the scrollback.
        ClearOnExit::Screen => "\x1b[2J\x1b[H",
        ClearOnExit::All => "\x1b[2J\x1b[H\x1b[3J",
        ClearOnExit::Off => "",
    }
}

/// `eclipse 0.6.0 · session …a1b2c3d4 · 12 turns · 93.3K tokens · 3m20s`
///
/// Every part is something the process actually knows: a figure the server did not report is
/// left out rather than printed as zero, because a goodbye that lies is worse than a short one.
pub fn line(status: &Status) -> String {
    let mut parts: Vec<String> = vec![format!("eclipse {}", env!("CARGO_PKG_VERSION"))];
    if let Some(session) = &status.session {
        parts.push(format!("session {}", short_session(session)));
    }
    parts.push(match status.totals.turns {
        0 => "no turns".to_string(),
        1 => "1 turn".to_string(),
        n => format!("{n} turns"),
    });
    let tokens = status.totals.prompt_tokens + status.totals.completion_tokens;
    if tokens > 0 {
        parts.push(format!("{} tokens", short_tokens(tokens)));
    }
    // A run measured in milliseconds has no duration worth the columns.
    let elapsed = status.started.elapsed().as_millis() as u64;
    if elapsed >= 1_000 {
        parts.push(short_duration(elapsed));
    }
    parts.join(" · ")
}

/// Print the goodbye exactly once, clearing first if the mode asks for it.
pub fn print(mode: ClearOnExit, text: &str) {
    let mut out = std::io::stdout();
    let _ = write!(out, "{}", prefix(mode));
    let _ = writeln!(out, "{text}");
    let _ = out.flush();
}

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

    fn status() -> Status {
        let mut s = Status::new("m", "host:1", 1000, "/work".to_string());
        s.session = Some("sess-0123456789abcdef".to_string());
        s
    }

    /// Off writes nothing of its own: the line lands where the frame ended.
    #[test]
    fn only_the_clearing_modes_carry_escapes() {
        assert_eq!(prefix(ClearOnExit::Off), "");
        assert!(prefix(ClearOnExit::Screen).contains("\x1b[2J"));
        assert!(!prefix(ClearOnExit::Screen).contains("\x1b[3J"));
        assert!(
            prefix(ClearOnExit::All).contains("\x1b[3J"),
            "all is the one that takes the scrollback with it"
        );
    }

    /// A goodbye that lies is worse than a short one: nothing is reported that did not happen.
    #[test]
    fn a_run_with_no_turns_says_so_and_prints_no_figures() {
        let text = line(&status());
        assert!(text.starts_with(&format!("eclipse {}", env!("CARGO_PKG_VERSION"))));
        assert!(text.contains("no turns"), "{text}");
        assert!(!text.contains("tokens"), "no turn reported usage: {text}");
        assert!(
            text.contains("session …"),
            "the id's tail, not the whole id: {text}"
        );
    }

    #[test]
    fn the_figures_are_the_ones_the_run_recorded() {
        let mut s = status();
        s.totals.turns = 12;
        s.totals.prompt_tokens = 90_000;
        s.totals.completion_tokens = 3_300;
        let text = line(&s);
        assert!(text.contains("12 turns"), "{text}");
        assert!(text.contains("93.3K tokens"), "{text}");
    }

    #[test]
    fn one_turn_is_not_one_turns() {
        let mut s = status();
        s.totals.turns = 1;
        assert!(line(&s).contains("1 turn ·") || line(&s).ends_with("1 turn"));
    }
}