Skip to main content

eclipse_core/
contextbar.rs

1//! The context bar: how much of the model's window the last prompt took, drawn the same way
2//! wherever it is read.
3//!
4//! Three surfaces show this number — the line under the composer, the full-screen read-out, and the
5//! dashboard's stats row — and they had three arithmetics. The dashboard's was the one that was
6//! wrong: its denominator was the compaction rail because that was the only number the stats event
7//! carried, so `ctx 12.3K/279K` was saying the prompt was 4% of a number the model had never been
8//! told, and the rail's own share of the window was drawn nowhere.
9//!
10//! So the shape lives here, and a surface only chooses a width and a colour. That is the whole
11//! point: a bar whose denominator differs per screen is a bar two screens can disagree about.
12
13/// The column where compaction begins. `│` is one cell wide in a monospaced terminal and reads as
14/// a tripwire even where there is no colour at all.
15pub const MARKER: char = '│';
16
17/// The fill once it has reached the marker: the "living on borrowed time" zone. A shape rather
18/// than a colour, so it survives a pipe, a `--no-color` run, and a screenshot.
19pub const PAST_MARKER: char = '▓';
20
21/// `1234` → `1.2K`, `1234567` → `1.2M`. One decimal below 100 units, none above, so the
22/// numbers stop changing width on every turn.
23pub fn short_tokens(n: u64) -> String {
24    match n {
25        0..=999 => n.to_string(),
26        1_000..=999_999 => {
27            let v = n as f64 / 1_000.0;
28            if v < 100.0 {
29                format!("{v:.1}K")
30            } else {
31                format!("{v:.0}K")
32            }
33        }
34        _ => {
35            let v = n as f64 / 1_000_000.0;
36            if v < 100.0 {
37                format!("{v:.1}M")
38            } else {
39                format!("{v:.0}M")
40            }
41        }
42    }
43}
44
45/// A proportional bar. `width` cells; the fill is clamped, so an over-budget prompt shows a
46/// full bar rather than a panic or a negative count.
47///
48/// A tiny but non-zero fill would otherwise round to nothing and read as "empty", so it gets
49/// a one-eighth block — the smallest thing that is still true.
50pub fn bar(fraction: f64, width: usize) -> String {
51    let fraction = fraction.clamp(0.0, 1.0);
52    let filled = ((fraction * width as f64).round() as usize).min(width);
53    if filled == 0 && fraction > 0.0 {
54        return format!("▏{}", "░".repeat(width - 1));
55    }
56    format!("{}{}", "█".repeat(filled), "░".repeat(width - filled))
57}
58
59/// A bar whose denominator is the whole window, with the compaction threshold marked as one
60/// column. `share` and `marker` are both shares of that window; `marker` outside `(0, 1)` is
61/// not a tripwire (`0` is off, `1` is the hard limit the bar's own end already is) and the bar
62/// falls back to being unmarked.
63///
64/// The marker takes its cell from the fill, so it stays visible at every share including
65/// zero — a tripwire nobody can see before it trips is not a tripwire. It lands on the cell
66/// that *contains* the threshold (floor), so `marker = 0.85` on a 10-cell bar is column 8 of
67/// 0–9, between the 80% and 90% cells. Once the fill reaches the marker the fill itself changes
68/// shape: `▓` is the "living on borrowed time" zone, a fact a pipe and a monochrome terminal
69/// both keep, rather than a silent relabelling of the denominator.
70pub fn bar_marked(share: f64, marker: f64, width: usize) -> String {
71    if width == 0 {
72        return String::new();
73    }
74    let show = !marker.is_nan() && marker > 0.0 && marker < 1.0;
75    if !show {
76        return bar(share, width);
77    }
78    let column = ((marker * width as f64) as usize).min(width - 1);
79    let share = share.clamp(0.0, 1.0);
80    let filled = ((share * width as f64).round() as usize).min(width);
81    let fill = if share >= marker { PAST_MARKER } else { '█' };
82    let mut cells: Vec<char> = (0..width)
83        .map(|i| {
84            if i == column {
85                MARKER
86            } else if i < filled {
87                fill
88            } else {
89                '░'
90            }
91        })
92        .collect();
93    // The sliver rule of `bar`, unless the marker already owns that first cell.
94    if filled == 0 && share > 0.0 && column != 0 {
95        cells[0] = '▏';
96    }
97    cells.into_iter().collect()
98}
99
100/// One reading of the context bar: what was used, out of what, with the tripwire where the
101/// compaction policy puts it.
102///
103/// `used` is `None` before the first turn, which is not the same as zero: a bar that is 0% full
104/// and a bar that has not been measured look identical, and only one of them is a fact.
105#[derive(Debug, Clone, Copy, PartialEq)]
106pub struct Reading {
107    /// Tokens in the last assembled prompt. The server's own count when it gave one, else the
108    /// runtime's estimate from characters.
109    pub used: Option<u64>,
110    /// The model's window where it is known, else the configured rail, else 0 for "nobody
111    /// stated a number".
112    pub denominator: usize,
113    /// Where compaction starts, as a share of the denominator. `None` when it is off or unknown.
114    pub marker: Option<f64>,
115}
116
117impl Reading {
118    pub fn new(used: Option<u64>, denominator: usize, marker: Option<f64>) -> Self {
119        Self {
120            used,
121            denominator,
122            marker,
123        }
124    }
125
126    /// The fill as a share of the window. `None` when there is nothing to be a share of.
127    pub fn share(&self) -> Option<f64> {
128        let used = self.used?;
129        (self.denominator > 0).then(|| used as f64 / self.denominator as f64)
130    }
131
132    /// Whether the prompt has gone past the tripwire. False when there is no tripwire.
133    pub fn passed(&self) -> bool {
134        match (self.share(), self.marker) {
135            (Some(share), Some(marker)) => share >= marker,
136            _ => false,
137        }
138    }
139
140    /// The bar itself, `width` cells wide. Never empty: before the first turn it is the empty
141    /// bar with the tripwire on it, which is what the terminal has always drawn.
142    pub fn bar(&self, width: usize) -> String {
143        bar_marked(
144            self.share().unwrap_or(0.0),
145            self.marker.unwrap_or(0.0),
146            width,
147        )
148    }
149
150    /// The read-out's parts, for a surface that colours them differently: `12.3K/328K`, the bar
151    /// with its tripwire, `4%`, and — when nobody stated a denominator — the reason there is no
152    /// bar instead of a bar against a number the model was never told.
153    pub fn pieces(&self, width: usize) -> Pieces {
154        if self.denominator == 0 {
155            return Pieces {
156                numbers: match self.used {
157                    Some(used) => format!("{} tokens", short_tokens(used)),
158                    None => "--".to_string(),
159                },
160                bar: String::new(),
161                percent: None,
162                note: Some("no budget"),
163            };
164        }
165        let denom = short_tokens(self.denominator as u64);
166        Pieces {
167            numbers: match self.used {
168                Some(used) => format!("{}/{}", short_tokens(used), denom),
169                None => format!("--/{denom}"),
170            },
171            bar: self.bar(width),
172            percent: self.share().map(|s| format!("{:.0}%", s * 100.0)),
173            note: None,
174        }
175    }
176
177    /// The whole read-out in words: `ctx 12.3K/328K ██░░░░░░│░░ 4%`, `ctx --/328K ░░░░░░░░│░`
178    /// before the first turn, or a plain token count when nobody stated a denominator.
179    ///
180    /// The three surfaces read this, and the two that draw colour read [`Self::pieces`], so none
181    /// of them can drift into a second opinion about a percentage.
182    pub fn text(&self, width: usize) -> String {
183        self.pieces(width).text()
184    }
185}
186
187/// One read-out, in the pieces a surface needs to colour it.
188#[derive(Debug, Clone, PartialEq)]
189pub struct Pieces {
190    /// `12.3K/328K`, `--/328K`, or `12.3K tokens`.
191    pub numbers: String,
192    /// The bar, tripwire included. Empty when there is no denominator.
193    pub bar: String,
194    /// `4%` — absent before the first turn, and when there is nothing to be a share of.
195    pub percent: Option<String>,
196    /// Why there is no bar: `no budget`.
197    pub note: Option<&'static str>,
198}
199
200impl Pieces {
201    /// The pieces as one line, with the `ctx` word that keeps a bar from reading as a stray
202    /// drawing next to `first 5.2s`.
203    pub fn text(&self) -> String {
204        let mut out = format!("ctx {}", self.numbers);
205        if !self.bar.is_empty() {
206            out.push(' ');
207            out.push_str(&self.bar);
208        }
209        if let Some(percent) = &self.percent {
210            out.push(' ');
211            out.push_str(percent);
212        }
213        if let Some(note) = self.note {
214            out.push_str(" · ");
215            out.push_str(note);
216        }
217        out
218    }
219}
220
221#[cfg(test)]
222mod tests {
223    use super::*;
224
225    #[test]
226    fn the_bar_is_the_same_shape_when_the_denominator_is_the_window() {
227        let r = Reading::new(Some(30_000), 100_000, Some(0.8));
228        assert_eq!(r.text(10), "ctx 30.0K/100K ███░░░░░│░ 30%");
229        // Where the rail sits, and that the fill changes shape past it.
230        assert!(!r.passed());
231        let past = Reading::new(Some(90_000), 100_000, Some(0.8));
232        assert!(past.passed());
233        assert!(past.bar(10).contains(PAST_MARKER), "{}", past.bar(10));
234    }
235
236    #[test]
237    fn no_turn_yet_is_not_zero_percent() {
238        let r = Reading::new(None, 328_000, Some(0.85));
239        assert_eq!(r.text(10), "ctx --/328K ░░░░░░░░│░");
240        assert_eq!(r.share(), None);
241        assert!(!r.passed());
242    }
243
244    #[test]
245    fn a_window_nobody_stated_says_so_instead_of_dividing_by_it() {
246        let r = Reading::new(Some(5_000), 0, None);
247        assert_eq!(r.text(10), "ctx 5.0K tokens · no budget");
248        assert_eq!(Reading::new(None, 0, None).text(10), "ctx -- · no budget");
249        assert_eq!(r.bar(10), "░░░░░░░░░░");
250    }
251
252    /// One decimal below a hundred units, none above, so a number stops changing width as it
253    /// grows — the reason a bar next to it does not shuffle sideways every turn.
254    #[test]
255    fn token_counts_stay_short_and_stable_width() {
256        assert_eq!(short_tokens(0), "0");
257        assert_eq!(short_tokens(999), "999");
258        assert_eq!(short_tokens(1_234), "1.2K");
259        assert_eq!(short_tokens(23_100), "23.1K");
260        assert_eq!(short_tokens(327_680), "328K");
261        assert_eq!(short_tokens(1_234_567), "1.2M");
262        assert_eq!(short_tokens(12_000_000), "12.0M");
263    }
264
265    #[test]
266    fn a_tiny_fill_still_shows_a_sliver() {
267        assert_eq!(bar(0.002, 4), "▏░░░");
268        assert_eq!(bar(0.0, 4), "░░░░", "zero really is empty");
269    }
270
271    #[test]
272    fn the_bar_clamps_instead_of_overflowing() {
273        assert_eq!(bar(0.0, 4), "░░░░");
274        assert_eq!(bar(0.5, 4), "██░░");
275        assert_eq!(bar(1.0, 4), "████");
276        assert_eq!(bar(4.0, 4), "████", "an over-budget prompt fills the bar");
277        assert_eq!(
278            bar(-1.0, 4),
279            "░░░░",
280            "and a nonsense value cannot underflow"
281        );
282    }
283
284    #[test]
285    fn a_marked_bar_puts_the_tripwire_where_the_policy_says_and_never_hides_it() {
286        // 0.85 of a 10-cell bar is the cell covering 80–90%, so column 8 (0-indexed).
287        assert_eq!(bar_marked(0.0, 0.85, 10), "░░░░░░░░│░", "visible at zero");
288        assert_eq!(bar_marked(0.5, 0.85, 10), "█████░░░│░");
289        assert_eq!(
290            bar_marked(1.0, 0.85, 10),
291            "▓▓▓▓▓▓▓▓│▓",
292            "a full window is past the tripwire, and the marker still owns its cell"
293        );
294    }
295
296    #[test]
297    fn a_marked_bar_marks_the_edges_of_the_scale_honestly() {
298        // The cell containing the threshold, not the nearest one: 0.85 * 10 = 8.5 floors to 8.
299        assert_eq!(
300            bar_marked(0.82, 0.85, 10),
301            "████████│░",
302            "just under is not passed"
303        );
304        assert_eq!(
305            bar_marked(0.85, 0.85, 10),
306            "▓▓▓▓▓▓▓▓│░",
307            "at the threshold the fill itself changes state"
308        );
309        // A threshold in the first cell still leaves a bar behind it.
310        assert_eq!(bar_marked(0.0, 0.05, 10), "│░░░░░░░░░");
311        assert_eq!(
312            bar_marked(0.0, 0.85, 1),
313            "│",
314            "a one-cell bar has no room but the marker"
315        );
316        assert_eq!(bar_marked(0.5, 0.85, 0), "", "no width, no bar");
317    }
318
319    #[test]
320    fn a_marker_outside_the_scale_is_not_drawn_at_all() {
321        assert_eq!(
322            bar_marked(0.5, 0.0, 10),
323            bar(0.5, 10),
324            "compact_at = 0 is off: an unmarked bar"
325        );
326        assert_eq!(
327            bar_marked(0.5, 1.0, 10),
328            bar(0.5, 10),
329            "the hard limit is the bar's own end"
330        );
331        assert_eq!(bar_marked(0.5, f64::NAN, 10), bar(0.5, 10));
332    }
333}