eclipse-core 0.13.4

Core library for eclipse: providers, tools, sessions, config, runtime
Documentation
//! The context bar: how much of the model's window the last prompt took, drawn the same way
//! wherever it is read.
//!
//! Three surfaces show this number — the line under the composer, the full-screen read-out, and the
//! dashboard's stats row — and they had three arithmetics. The dashboard's was the one that was
//! wrong: its denominator was the compaction rail because that was the only number the stats event
//! carried, so `ctx 12.3K/279K` was saying the prompt was 4% of a number the model had never been
//! told, and the rail's own share of the window was drawn nowhere.
//!
//! So the shape lives here, and a surface only chooses a width and a colour. That is the whole
//! point: a bar whose denominator differs per screen is a bar two screens can disagree about.

/// The column where compaction begins. `│` is one cell wide in a monospaced terminal and reads as
/// a tripwire even where there is no colour at all.
pub const MARKER: char = '│';

/// The fill once it has reached the marker: the "living on borrowed time" zone. A shape rather
/// than a colour, so it survives a pipe, a `--no-color` run, and a screenshot.
pub const PAST_MARKER: char = '▓';

/// `1234` → `1.2K`, `1234567` → `1.2M`. One decimal below 100 units, none above, so the
/// numbers stop changing width on every turn.
pub fn short_tokens(n: u64) -> String {
    match n {
        0..=999 => n.to_string(),
        1_000..=999_999 => {
            let v = n as f64 / 1_000.0;
            if v < 100.0 {
                format!("{v:.1}K")
            } else {
                format!("{v:.0}K")
            }
        }
        _ => {
            let v = n as f64 / 1_000_000.0;
            if v < 100.0 {
                format!("{v:.1}M")
            } else {
                format!("{v:.0}M")
            }
        }
    }
}

/// A proportional bar. `width` cells; the fill is clamped, so an over-budget prompt shows a
/// full bar rather than a panic or a negative count.
///
/// A tiny but non-zero fill would otherwise round to nothing and read as "empty", so it gets
/// a one-eighth block — the smallest thing that is still true.
pub fn bar(fraction: f64, width: usize) -> String {
    let fraction = fraction.clamp(0.0, 1.0);
    let filled = ((fraction * width as f64).round() as usize).min(width);
    if filled == 0 && fraction > 0.0 {
        return format!("▏{}", "░".repeat(width - 1));
    }
    format!("{}{}", "█".repeat(filled), "░".repeat(width - filled))
}

/// A bar whose denominator is the whole window, with the compaction threshold marked as one
/// column. `share` and `marker` are both shares of that window; `marker` outside `(0, 1)` is
/// not a tripwire (`0` is off, `1` is the hard limit the bar's own end already is) and the bar
/// falls back to being unmarked.
///
/// The marker takes its cell from the fill, so it stays visible at every share including
/// zero — a tripwire nobody can see before it trips is not a tripwire. It lands on the cell
/// that *contains* the threshold (floor), so `marker = 0.85` on a 10-cell bar is column 8 of
/// 0–9, between the 80% and 90% cells. Once the fill reaches the marker the fill itself changes
/// shape: `▓` is the "living on borrowed time" zone, a fact a pipe and a monochrome terminal
/// both keep, rather than a silent relabelling of the denominator.
pub fn bar_marked(share: f64, marker: f64, width: usize) -> String {
    if width == 0 {
        return String::new();
    }
    let show = !marker.is_nan() && marker > 0.0 && marker < 1.0;
    if !show {
        return bar(share, width);
    }
    let column = ((marker * width as f64) as usize).min(width - 1);
    let share = share.clamp(0.0, 1.0);
    let filled = ((share * width as f64).round() as usize).min(width);
    let fill = if share >= marker { PAST_MARKER } else { '█' };
    let mut cells: Vec<char> = (0..width)
        .map(|i| {
            if i == column {
                MARKER
            } else if i < filled {
                fill
            } else {
                '░'
            }
        })
        .collect();
    // The sliver rule of `bar`, unless the marker already owns that first cell.
    if filled == 0 && share > 0.0 && column != 0 {
        cells[0] = '▏';
    }
    cells.into_iter().collect()
}

/// One reading of the context bar: what was used, out of what, with the tripwire where the
/// compaction policy puts it.
///
/// `used` is `None` before the first turn, which is not the same as zero: a bar that is 0% full
/// and a bar that has not been measured look identical, and only one of them is a fact.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Reading {
    /// Tokens in the last assembled prompt. The server's own count when it gave one, else the
    /// runtime's estimate from characters.
    pub used: Option<u64>,
    /// The model's window where it is known, else the configured rail, else 0 for "nobody
    /// stated a number".
    pub denominator: usize,
    /// Where compaction starts, as a share of the denominator. `None` when it is off or unknown.
    pub marker: Option<f64>,
}

impl Reading {
    pub fn new(used: Option<u64>, denominator: usize, marker: Option<f64>) -> Self {
        Self {
            used,
            denominator,
            marker,
        }
    }

    /// The fill as a share of the window. `None` when there is nothing to be a share of.
    pub fn share(&self) -> Option<f64> {
        let used = self.used?;
        (self.denominator > 0).then(|| used as f64 / self.denominator as f64)
    }

    /// Whether the prompt has gone past the tripwire. False when there is no tripwire.
    pub fn passed(&self) -> bool {
        match (self.share(), self.marker) {
            (Some(share), Some(marker)) => share >= marker,
            _ => false,
        }
    }

    /// The bar itself, `width` cells wide. Never empty: before the first turn it is the empty
    /// bar with the tripwire on it, which is what the terminal has always drawn.
    pub fn bar(&self, width: usize) -> String {
        bar_marked(
            self.share().unwrap_or(0.0),
            self.marker.unwrap_or(0.0),
            width,
        )
    }

    /// The read-out's parts, for a surface that colours them differently: `12.3K/328K`, the bar
    /// with its tripwire, `4%`, and — when nobody stated a denominator — the reason there is no
    /// bar instead of a bar against a number the model was never told.
    pub fn pieces(&self, width: usize) -> Pieces {
        if self.denominator == 0 {
            return Pieces {
                numbers: match self.used {
                    Some(used) => format!("{} tokens", short_tokens(used)),
                    None => "--".to_string(),
                },
                bar: String::new(),
                percent: None,
                note: Some("no budget"),
            };
        }
        let denom = short_tokens(self.denominator as u64);
        Pieces {
            numbers: match self.used {
                Some(used) => format!("{}/{}", short_tokens(used), denom),
                None => format!("--/{denom}"),
            },
            bar: self.bar(width),
            percent: self.share().map(|s| format!("{:.0}%", s * 100.0)),
            note: None,
        }
    }

    /// The whole read-out in words: `ctx 12.3K/328K ██░░░░░░│░░ 4%`, `ctx --/328K ░░░░░░░░│░`
    /// before the first turn, or a plain token count when nobody stated a denominator.
    ///
    /// The three surfaces read this, and the two that draw colour read [`Self::pieces`], so none
    /// of them can drift into a second opinion about a percentage.
    pub fn text(&self, width: usize) -> String {
        self.pieces(width).text()
    }
}

/// One read-out, in the pieces a surface needs to colour it.
#[derive(Debug, Clone, PartialEq)]
pub struct Pieces {
    /// `12.3K/328K`, `--/328K`, or `12.3K tokens`.
    pub numbers: String,
    /// The bar, tripwire included. Empty when there is no denominator.
    pub bar: String,
    /// `4%` — absent before the first turn, and when there is nothing to be a share of.
    pub percent: Option<String>,
    /// Why there is no bar: `no budget`.
    pub note: Option<&'static str>,
}

impl Pieces {
    /// The pieces as one line, with the `ctx` word that keeps a bar from reading as a stray
    /// drawing next to `first 5.2s`.
    pub fn text(&self) -> String {
        let mut out = format!("ctx {}", self.numbers);
        if !self.bar.is_empty() {
            out.push(' ');
            out.push_str(&self.bar);
        }
        if let Some(percent) = &self.percent {
            out.push(' ');
            out.push_str(percent);
        }
        if let Some(note) = self.note {
            out.push_str(" · ");
            out.push_str(note);
        }
        out
    }
}

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

    #[test]
    fn the_bar_is_the_same_shape_when_the_denominator_is_the_window() {
        let r = Reading::new(Some(30_000), 100_000, Some(0.8));
        assert_eq!(r.text(10), "ctx 30.0K/100K ███░░░░░│░ 30%");
        // Where the rail sits, and that the fill changes shape past it.
        assert!(!r.passed());
        let past = Reading::new(Some(90_000), 100_000, Some(0.8));
        assert!(past.passed());
        assert!(past.bar(10).contains(PAST_MARKER), "{}", past.bar(10));
    }

    #[test]
    fn no_turn_yet_is_not_zero_percent() {
        let r = Reading::new(None, 328_000, Some(0.85));
        assert_eq!(r.text(10), "ctx --/328K ░░░░░░░░│░");
        assert_eq!(r.share(), None);
        assert!(!r.passed());
    }

    #[test]
    fn a_window_nobody_stated_says_so_instead_of_dividing_by_it() {
        let r = Reading::new(Some(5_000), 0, None);
        assert_eq!(r.text(10), "ctx 5.0K tokens · no budget");
        assert_eq!(Reading::new(None, 0, None).text(10), "ctx -- · no budget");
        assert_eq!(r.bar(10), "░░░░░░░░░░");
    }

    /// One decimal below a hundred units, none above, so a number stops changing width as it
    /// grows — the reason a bar next to it does not shuffle sideways every turn.
    #[test]
    fn token_counts_stay_short_and_stable_width() {
        assert_eq!(short_tokens(0), "0");
        assert_eq!(short_tokens(999), "999");
        assert_eq!(short_tokens(1_234), "1.2K");
        assert_eq!(short_tokens(23_100), "23.1K");
        assert_eq!(short_tokens(327_680), "328K");
        assert_eq!(short_tokens(1_234_567), "1.2M");
        assert_eq!(short_tokens(12_000_000), "12.0M");
    }

    #[test]
    fn a_tiny_fill_still_shows_a_sliver() {
        assert_eq!(bar(0.002, 4), "▏░░░");
        assert_eq!(bar(0.0, 4), "░░░░", "zero really is empty");
    }

    #[test]
    fn the_bar_clamps_instead_of_overflowing() {
        assert_eq!(bar(0.0, 4), "░░░░");
        assert_eq!(bar(0.5, 4), "██░░");
        assert_eq!(bar(1.0, 4), "████");
        assert_eq!(bar(4.0, 4), "████", "an over-budget prompt fills the bar");
        assert_eq!(
            bar(-1.0, 4),
            "░░░░",
            "and a nonsense value cannot underflow"
        );
    }

    #[test]
    fn a_marked_bar_puts_the_tripwire_where_the_policy_says_and_never_hides_it() {
        // 0.85 of a 10-cell bar is the cell covering 80–90%, so column 8 (0-indexed).
        assert_eq!(bar_marked(0.0, 0.85, 10), "░░░░░░░░│░", "visible at zero");
        assert_eq!(bar_marked(0.5, 0.85, 10), "█████░░░│░");
        assert_eq!(
            bar_marked(1.0, 0.85, 10),
            "▓▓▓▓▓▓▓▓│▓",
            "a full window is past the tripwire, and the marker still owns its cell"
        );
    }

    #[test]
    fn a_marked_bar_marks_the_edges_of_the_scale_honestly() {
        // The cell containing the threshold, not the nearest one: 0.85 * 10 = 8.5 floors to 8.
        assert_eq!(
            bar_marked(0.82, 0.85, 10),
            "████████│░",
            "just under is not passed"
        );
        assert_eq!(
            bar_marked(0.85, 0.85, 10),
            "▓▓▓▓▓▓▓▓│░",
            "at the threshold the fill itself changes state"
        );
        // A threshold in the first cell still leaves a bar behind it.
        assert_eq!(bar_marked(0.0, 0.05, 10), "│░░░░░░░░░");
        assert_eq!(
            bar_marked(0.0, 0.85, 1),
            "│",
            "a one-cell bar has no room but the marker"
        );
        assert_eq!(bar_marked(0.5, 0.85, 0), "", "no width, no bar");
    }

    #[test]
    fn a_marker_outside_the_scale_is_not_drawn_at_all() {
        assert_eq!(
            bar_marked(0.5, 0.0, 10),
            bar(0.5, 10),
            "compact_at = 0 is off: an unmarked bar"
        );
        assert_eq!(
            bar_marked(0.5, 1.0, 10),
            bar(0.5, 10),
            "the hard limit is the bar's own end"
        );
        assert_eq!(bar_marked(0.5, f64::NAN, 10), bar(0.5, 10));
    }
}