codewhale-tui 0.9.8

Terminal UI for open-source and open-weight coding models
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
//! Session metrics strip: the compact `turns · steps │ LLM · tools │ TTFT ·
//! tok/s │ cache │ in` ledger painted on the phase strip.
//!
//! Every number here is sourced from runtime evidence the engine already
//! emits — never from transcript timestamps or estimates:
//!
//! - **turns**: `Event::TurnStarted` count (`App::turn_counter`).
//! - **steps**: model calls (`Event::TurnUsage`) plus tool calls
//!   (`Event::ToolCallComplete`) — the agent's step count.
//! - **LLM**: sum of model-call wall time. Uses `TurnUsage::request_ms`
//!   (dispatch → usage receipt) when the engine measured dispatch, else the
//!   stream duration it always reports.
//! - **tools**: sum of tool wall time from `ToolCallStarted` → `ToolCallComplete`
//!   by tool id (the runtime's own clock, taken when the events drain).
//! - **TTFT avg**: mean of `TurnUsage::first_token_ms` over the model calls
//!   that reported one.
//! - **tok/s**: provider-reported output tokens over the streamed seconds of
//!   the same calls (`duration_ms`); calls without a stream duration are
//!   excluded from both sides.
//! - **cache**: provider-reported prompt-cache hit tokens over hit + miss
//!   (`SessionState::total_cache_hit_tokens` / `total_cache_miss_tokens`).
//! - **in**: provider-reported input tokens (`SessionState::total_input_tokens`).
//!
//! When a provider never reports a metric, or its evidence has not arrived
//! yet, the cell is omitted. Nothing here is estimated or captioned.
//!
//! The strip is one row wide and never grows the layout: it lives in the
//! phase-strip ledger tail (`crate::tui::phase_strip`), between the phase
//! marker and the right-hand key hints, and drops its lowest-value groups
//! until it fits the columns that are genuinely available.

use std::collections::HashMap;
use std::time::{Duration, Instant};

use crate::localization::{Locale, MessageId, tr};

/// Runtime accumulators behind the strip. Lives on [`crate::tui::app::App`],
/// resets with the token breakdown when a session is loaded, so the numbers
/// describe this runtime session — the same scope as the token ledger.
#[derive(Debug, Clone, Default)]
pub struct SessionMetrics {
    /// Model calls that reported usage (`Event::TurnUsage`).
    pub model_calls: u64,
    /// Tool calls that completed (`Event::ToolCallComplete`).
    pub tool_calls: u64,
    /// Sum of model-call wall time.
    pub llm_time: Duration,
    /// Sum of tool wall time.
    pub tool_time: Duration,
    /// Sum of reported time-to-first-token values.
    ttft_total: Duration,
    /// How many model calls reported a time-to-first-token.
    ttft_samples: u64,
    /// Output tokens from calls that also reported a stream duration.
    rate_output_tokens: u64,
    /// Stream time from the same calls.
    rate_stream_time: Duration,
    /// Tools currently running, keyed by tool id, with the instant their
    /// start event drained.
    tool_started: HashMap<String, Instant>,
}

impl SessionMetrics {
    /// Fold one model-call usage receipt into the accumulators.
    pub fn record_model_call(
        &mut self,
        output_tokens: u32,
        stream_ms: u64,
        first_token_ms: Option<u64>,
        request_ms: Option<u64>,
    ) {
        self.model_calls = self.model_calls.saturating_add(1);
        let call_ms = request_ms.unwrap_or(stream_ms);
        self.llm_time = self.llm_time.saturating_add(Duration::from_millis(call_ms));
        if let Some(ttft) = first_token_ms {
            self.ttft_total = self.ttft_total.saturating_add(Duration::from_millis(ttft));
            self.ttft_samples = self.ttft_samples.saturating_add(1);
        }
        if stream_ms > 0 {
            self.rate_output_tokens = self
                .rate_output_tokens
                .saturating_add(u64::from(output_tokens));
            self.rate_stream_time = self
                .rate_stream_time
                .saturating_add(Duration::from_millis(stream_ms));
        }
    }

    /// Note that a tool started; the matching completion closes the timer.
    pub fn record_tool_started(&mut self, tool_id: &str) {
        self.record_tool_started_at(tool_id, Instant::now());
    }

    fn record_tool_started_at(&mut self, tool_id: &str, at: Instant) {
        self.tool_started.insert(tool_id.to_string(), at);
    }

    /// Note that a tool completed. Counts the call even when its start was
    /// never seen (a replayed or foreign completion), but only accrues time
    /// when the runtime saw both edges.
    pub fn record_tool_completed(&mut self, tool_id: &str) {
        self.record_tool_completed_at(tool_id, Instant::now());
    }

    fn record_tool_completed_at(&mut self, tool_id: &str, at: Instant) {
        self.tool_calls = self.tool_calls.saturating_add(1);
        if let Some(started) = self.tool_started.remove(tool_id) {
            self.tool_time = self
                .tool_time
                .saturating_add(at.saturating_duration_since(started));
        }
    }

    /// Drop in-flight tool timers (turn interrupted or failed): a tool that
    /// never completed must not leak into the next turn's accounting.
    pub fn clear_in_flight(&mut self) {
        self.tool_started.clear();
    }

    /// Model calls plus tool calls.
    #[must_use]
    pub fn steps(&self) -> u64 {
        self.model_calls.saturating_add(self.tool_calls)
    }

    /// Mean time-to-first-token, when at least one call reported it.
    #[must_use]
    pub fn ttft_average(&self) -> Option<Duration> {
        if self.ttft_samples == 0 {
            return None;
        }
        Some(self.ttft_total / u32::try_from(self.ttft_samples).unwrap_or(u32::MAX))
    }

    /// Output tokens per streamed second, when the evidence exists.
    #[must_use]
    pub fn tokens_per_second(&self) -> Option<f64> {
        let secs = self.rate_stream_time.as_secs_f64();
        if self.rate_output_tokens == 0 || !secs.is_finite() || secs <= 0.0 {
            return None;
        }
        Some(self.rate_output_tokens as f64 / secs)
    }
}

/// Everything the strip needs, decoupled from `App` so rendering can be
/// unit-tested without a full app.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct MetricsSnapshot {
    pub turns: u64,
    pub steps: u64,
    pub llm_time: Duration,
    pub tool_time: Duration,
    pub ttft_avg: Option<Duration>,
    pub tokens_per_second: Option<f64>,
    /// `None` when no provider reported prompt-cache classes this session.
    pub cache_hit_percent: Option<u8>,
    pub input_tokens: u64,
}

impl MetricsSnapshot {
    /// True when there is nothing to say yet (fresh session).
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.turns == 0 && self.steps == 0 && self.input_tokens == 0
    }
}

/// One rendered cell: a value with its localized short label.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MetricCell {
    pub label: String,
    pub value: String,
    /// `label` first (`4 turns`) or value first (`LLM 11m46s`).
    pub value_first: bool,
}

impl MetricCell {
    fn width(&self) -> usize {
        use unicode_width::UnicodeWidthStr;
        self.label.width() + 1 + self.value.width()
    }
}

/// Group priority, highest kept first. When the row is too narrow, groups
/// are dropped from the end of this list; inside a group the second cell
/// (steps, tools, tok/s) is dropped before the group itself.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MetricGroup {
    Input,
    Cache,
    Llm,
    Turns,
    Latency,
}

const GROUP_PRIORITY: [MetricGroup; 5] = [
    MetricGroup::Input,
    MetricGroup::Cache,
    MetricGroup::Llm,
    MetricGroup::Turns,
    MetricGroup::Latency,
];

/// The DSH-style layout order, left to right.
const GROUP_ORDER: [MetricGroup; 5] = [
    MetricGroup::Turns,
    MetricGroup::Llm,
    MetricGroup::Latency,
    MetricGroup::Cache,
    MetricGroup::Input,
];

/// A group of one or two cells separated by ` · `.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MetricGroupCells {
    pub group: MetricGroup,
    pub cells: Vec<MetricCell>,
}

/// Separators used between cells and between groups.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Separators {
    pub cell: &'static str,
    pub group: &'static str,
}

impl Separators {
    /// Unicode: ` · ` inside a group, ` │ ` between groups.
    pub const UNICODE: Self = Self {
        cell: " · ",
        group: "",
    };
    /// ASCII-safe: ` . ` and ` | `.
    pub const ASCII: Self = Self {
        cell: " . ",
        group: " | ",
    };

    #[must_use]
    pub fn for_ascii(ascii_safe: bool) -> Self {
        if ascii_safe {
            Self::ASCII
        } else {
            Self::UNICODE
        }
    }
}

/// Format a duration the way the strip does: `11m46s`, `1h02m`, `1.5s`, `320ms`.
#[must_use]
pub fn format_duration(duration: Duration) -> String {
    let ms = duration.as_millis();
    if ms == 0 {
        return "0s".to_string();
    }
    if ms < 1_000 {
        return format!("{ms}ms");
    }
    let secs = duration.as_secs();
    if secs < 60 {
        let tenths = (ms + 50) / 100;
        return format!("{}.{}s", tenths / 10, tenths % 10);
    }
    if secs < 3_600 {
        return format!("{}m{:02}s", secs / 60, secs % 60);
    }
    format!("{}h{:02}m", secs / 3_600, (secs % 3_600) / 60)
}

/// Format a token count: `842`, `12.3K`, `9.3M`, `1.2B`.
#[must_use]
pub fn format_tokens(tokens: u64) -> String {
    const UNITS: [(u64, &str); 3] = [(1_000_000_000, "B"), (1_000_000, "M"), (1_000, "K")];
    for (scale, suffix) in UNITS {
        if tokens >= scale {
            let scaled = tokens as f64 / scale as f64;
            return if scaled >= 100.0 {
                format!("{scaled:.0}{suffix}")
            } else {
                format!("{scaled:.1}{suffix}")
            };
        }
    }
    tokens.to_string()
}

/// Format an output rate: `120` or `7.5` (the label carries `tok/s`).
#[must_use]
pub fn format_rate(rate: f64) -> String {
    if rate < 10.0 {
        format!("{rate:.1}")
    } else {
        format!("{rate:.0}")
    }
}

/// Build the cells for every group that has something truthful to show.
///
/// A cell whose evidence has not arrived is omitted — never a placeholder:
/// `TTFT avg` / `tok/s` appear only once a model call reported them, `Cache
/// hit` only when a provider reported cache classes, `Input` only after the
/// first usage receipt. Turn, step, and time cells are always present once
/// the session has started (zero is a real count).
#[must_use]
pub fn build_groups(snapshot: MetricsSnapshot, locale: Locale) -> Vec<MetricGroupCells> {
    let label = |id: MessageId| tr(locale, id).into_owned();
    let mut groups = Vec::new();
    for group in GROUP_ORDER {
        let cells = match group {
            MetricGroup::Turns => vec![
                MetricCell {
                    label: label(if snapshot.turns == 1 {
                        MessageId::SessionMetricsTurn
                    } else {
                        MessageId::SessionMetricsTurns
                    }),
                    value: snapshot.turns.to_string(),
                    value_first: true,
                },
                MetricCell {
                    label: label(if snapshot.steps == 1 {
                        MessageId::SessionMetricsStep
                    } else {
                        MessageId::SessionMetricsSteps
                    }),
                    value: snapshot.steps.to_string(),
                    value_first: true,
                },
            ],
            MetricGroup::Llm => vec![
                MetricCell {
                    label: label(MessageId::SessionMetricsLlm),
                    value: format_duration(snapshot.llm_time),
                    value_first: false,
                },
                MetricCell {
                    label: label(MessageId::SessionMetricsTools),
                    value: format_duration(snapshot.tool_time),
                    value_first: false,
                },
            ],
            MetricGroup::Latency => {
                let mut cells = Vec::new();
                if let Some(ttft) = snapshot.ttft_avg {
                    cells.push(MetricCell {
                        label: label(MessageId::SessionMetricsTtft),
                        value: format_duration(ttft),
                        value_first: false,
                    });
                }
                if let Some(rate) = snapshot.tokens_per_second {
                    cells.push(MetricCell {
                        label: label(MessageId::SessionMetricsTokensPerSecond),
                        value: format_rate(rate),
                        value_first: true,
                    });
                }
                if cells.is_empty() {
                    continue;
                }
                cells
            }
            MetricGroup::Cache => {
                let Some(pct) = snapshot.cache_hit_percent else {
                    continue;
                };
                vec![MetricCell {
                    label: label(MessageId::SessionMetricsCache),
                    value: format!("{pct}%"),
                    value_first: false,
                }]
            }
            MetricGroup::Input => {
                if snapshot.input_tokens == 0 {
                    continue;
                }
                vec![MetricCell {
                    label: label(MessageId::SessionMetricsInput),
                    value: format_tokens(snapshot.input_tokens),
                    value_first: false,
                }]
            }
        };
        groups.push(MetricGroupCells { group, cells });
    }
    groups
}

/// A rendered strip: the plain text (for tests, `/status`, and width math)
/// plus the cells that survived the budget, so the painter can style labels
/// and values differently.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RenderedStrip {
    pub groups: Vec<MetricGroupCells>,
    pub separators: Separators,
}

impl RenderedStrip {
    /// Plain-text form: `4 turns · 108 steps │ LLM 11m46s · tools 1m52s │ …`.
    #[must_use]
    pub fn text(&self) -> String {
        let mut out = String::new();
        for (index, group) in self.groups.iter().enumerate() {
            if index > 0 {
                out.push_str(self.separators.group);
            }
            for (cell_index, cell) in group.cells.iter().enumerate() {
                if cell_index > 0 {
                    out.push_str(self.separators.cell);
                }
                if cell.value_first {
                    out.push_str(&cell.value);
                    out.push(' ');
                    out.push_str(&cell.label);
                } else {
                    out.push_str(&cell.label);
                    out.push(' ');
                    out.push_str(&cell.value);
                }
            }
        }
        out
    }

    #[cfg(test)]
    #[must_use]
    pub fn width(&self) -> usize {
        use unicode_width::UnicodeWidthStr;
        self.text().width()
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.groups.is_empty()
    }
}

fn strip_width(groups: &[MetricGroupCells], separators: Separators) -> usize {
    use unicode_width::UnicodeWidthStr;
    let mut width = 0;
    for (index, group) in groups.iter().enumerate() {
        if index > 0 {
            width += separators.group.width();
        }
        for (cell_index, cell) in group.cells.iter().enumerate() {
            if cell_index > 0 {
                width += separators.cell.width();
            }
            width += cell.width();
        }
    }
    width
}

/// Fit the strip into `budget` columns by shedding the lowest-priority
/// evidence first: second cells (steps, tools, tok/s) go before whole
/// groups, and groups go from latency → turns → LLM time → cache → input.
/// Returns an empty strip when even the input count does not fit.
#[must_use]
pub fn fit_to_width(
    mut groups: Vec<MetricGroupCells>,
    budget: usize,
    separators: Separators,
) -> RenderedStrip {
    // Pass one: shed second cells (steps, tools, tok/s) from the lowest
    // priority group upward, so every group keeps its headline fact.
    for group in GROUP_PRIORITY.iter().rev() {
        if strip_width(&groups, separators) <= budget {
            break;
        }
        if let Some(position) = groups.iter().position(|g| g.group == *group) {
            groups[position].cells.truncate(1);
        }
    }
    // Pass two: drop whole groups from the lowest priority upward.
    for group in GROUP_PRIORITY.iter().rev() {
        if strip_width(&groups, separators) <= budget {
            break;
        }
        if let Some(position) = groups.iter().position(|g| g.group == *group) {
            groups.remove(position);
        }
    }
    if strip_width(&groups, separators) > budget {
        groups.clear();
    }
    RenderedStrip { groups, separators }
}

/// Snapshot the live app state into the strip's inputs.
#[must_use]
pub fn snapshot_from_app(app: &crate::tui::app::App) -> MetricsSnapshot {
    let hit = u64::from(app.session.total_cache_hit_tokens);
    let miss = u64::from(app.session.total_cache_miss_tokens);
    let cache_hit_percent = (hit + miss > 0).then(|| {
        // Widen before adding so saturated counters never exceed 100%.
        u8::try_from((hit * 100 + (hit + miss) / 2) / (hit + miss)).unwrap_or(100)
    });
    MetricsSnapshot {
        turns: app.turn_counter,
        steps: app.session_metrics.steps(),
        llm_time: app.session_metrics.llm_time,
        tool_time: app.session_metrics.tool_time,
        ttft_avg: app.session_metrics.ttft_average(),
        tokens_per_second: app.session_metrics.tokens_per_second(),
        cache_hit_percent,
        input_tokens: u64::from(app.session.total_input_tokens),
    }
}

/// Paint a fitted strip as styled spans: labels and separators quiet,
/// values readable.
#[must_use]
pub fn spans(
    strip: &RenderedStrip,
    theme: &crate::palette::UiTheme,
) -> Vec<ratatui::text::Span<'static>> {
    use ratatui::style::Style;
    use ratatui::text::Span;
    let dim = Style::default().fg(theme.text_dim);
    let label = Style::default().fg(theme.text_muted);
    let value = Style::default().fg(theme.text_soft);
    let mut out = Vec::new();
    for (index, group) in strip.groups.iter().enumerate() {
        if index > 0 {
            out.push(Span::styled(strip.separators.group, dim));
        }
        for (cell_index, cell) in group.cells.iter().enumerate() {
            if cell_index > 0 {
                out.push(Span::styled(strip.separators.cell, dim));
            }
            if cell.value_first {
                out.push(Span::styled(cell.value.clone(), value));
                out.push(Span::raw(" "));
                out.push(Span::styled(cell.label.clone(), label));
            } else {
                out.push(Span::styled(cell.label.clone(), label));
                out.push(Span::raw(" "));
                out.push(Span::styled(cell.value.clone(), value));
            }
        }
    }
    out
}

/// The complete, untrimmed strip text — what `/status` prints.
#[must_use]
pub fn full_text(snapshot: MetricsSnapshot, locale: Locale, ascii_safe: bool) -> String {
    RenderedStrip {
        groups: build_groups(snapshot, locale),
        separators: Separators::for_ascii(ascii_safe),
    }
    .text()
}

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

    fn sample() -> MetricsSnapshot {
        MetricsSnapshot {
            turns: 4,
            steps: 108,
            llm_time: Duration::from_secs(11 * 60 + 46),
            tool_time: Duration::from_secs(60 + 52),
            ttft_avg: Some(Duration::from_millis(1_500)),
            tokens_per_second: Some(120.0),
            cache_hit_percent: Some(99),
            input_tokens: 9_300_000,
        }
    }

    #[test]
    fn durations_format_like_the_harness_strip() {
        assert_eq!(format_duration(Duration::ZERO), "0s");
        assert_eq!(format_duration(Duration::from_millis(320)), "320ms");
        assert_eq!(format_duration(Duration::from_millis(1_500)), "1.5s");
        assert_eq!(format_duration(Duration::from_millis(1_549)), "1.5s");
        assert_eq!(format_duration(Duration::from_secs(59)), "59.0s");
        assert_eq!(format_duration(Duration::from_secs(11 * 60 + 46)), "11m46s");
        assert_eq!(format_duration(Duration::from_secs(3_600 + 120)), "1h02m");
    }

    #[test]
    fn tokens_and_rates_format_compactly() {
        assert_eq!(format_tokens(842), "842");
        assert_eq!(format_tokens(12_345), "12.3K");
        assert_eq!(format_tokens(128_000), "128K");
        assert_eq!(format_tokens(9_300_000), "9.3M");
        assert_eq!(format_tokens(1_200_000_000), "1.2B");
        assert_eq!(format_rate(120.4), "120");
        assert_eq!(format_rate(7.46), "7.5");
    }

    #[test]
    fn full_strip_matches_the_reference_layout() {
        let text = full_text(sample(), Locale::En, false);
        assert_eq!(
            text,
            "4 turns · 108 steps │ LLM 11m46s · Tool call 1m52s │ TTFT avg 1.5s · 120 tok/s │ Cache hit 99% │ Input 9.3M"
        );
        let ascii = full_text(sample(), Locale::En, true);
        assert!(ascii.is_ascii(), "{ascii}");
        assert!(ascii.contains(" | LLM 11m46s . Tool call 1m52s | "));
    }

    #[test]
    fn absent_evidence_omits_the_cell_instead_of_a_placeholder() {
        let mut snapshot = sample();
        snapshot.cache_hit_percent = None;
        snapshot.ttft_avg = None;
        snapshot.tokens_per_second = None;
        snapshot.input_tokens = 0;
        let text = full_text(snapshot, Locale::En, false);
        assert_eq!(text, "4 turns · 108 steps │ LLM 11m46s · Tool call 1m52s");
        assert!(!text.contains(''), "{text}");

        // A partially reported latency group keeps only the reported cell.
        snapshot.ttft_avg = Some(Duration::from_millis(900));
        let text = full_text(snapshot, Locale::En, false);
        assert!(text.ends_with("│ TTFT avg 900ms"), "{text}");
        snapshot.ttft_avg = None;
        snapshot.tokens_per_second = Some(88.0);
        let text = full_text(snapshot, Locale::En, false);
        assert!(text.ends_with("│ 88 tok/s"), "{text}");
    }

    #[test]
    fn singular_labels_for_one_turn_and_one_step() {
        let snapshot = MetricsSnapshot {
            turns: 1,
            steps: 1,
            ..MetricsSnapshot::default()
        };
        let text = full_text(snapshot, Locale::En, false);
        assert!(text.starts_with("1 turn · 1 step │"), "{text}");
    }

    #[test]
    fn narrow_budgets_drop_the_least_useful_evidence_first() {
        let groups = build_groups(sample(), Locale::En);
        let full = fit_to_width(groups.clone(), 200, Separators::UNICODE);
        assert_eq!(full.groups.len(), 5);

        // Just short of the full width: the latency group loses tok/s first.
        let width = full.width();
        let trimmed = fit_to_width(groups.clone(), width - 1, Separators::UNICODE);
        assert_eq!(
            trimmed.text(),
            "4 turns · 108 steps │ LLM 11m46s · Tool call 1m52s │ TTFT avg 1.5s │ Cache hit 99% │ Input 9.3M"
        );

        // Normal terminals keep turns, LLM time, cache, and input.
        let normal = fit_to_width(groups.clone(), 60, Separators::UNICODE);
        assert_eq!(
            normal.text(),
            "4 turns │ LLM 11m46s │ Cache hit 99% │ Input 9.3M"
        );

        // Compact keeps the highest-value facts only.
        let compact = fit_to_width(groups.clone(), 28, Separators::UNICODE);
        assert_eq!(compact.text(), "Cache hit 99% │ Input 9.3M");

        // Below the input cell nothing is painted rather than a truncated lie.
        let none = fit_to_width(groups, 5, Separators::UNICODE);
        assert!(none.is_empty());
    }

    #[test]
    fn every_shipped_locale_has_short_labels() {
        for locale in Locale::shipped_complete() {
            let text = full_text(sample(), *locale, false);
            assert!(text.contains("4 "), "{}: {text}", locale.tag());
            assert!(text.contains("11m46s"), "{}: {text}", locale.tag());
            for group in build_groups(sample(), *locale) {
                for cell in group.cells {
                    assert!(
                        cell.label.chars().count() <= 12,
                        "{}: label `{}` is too long for the strip",
                        locale.tag(),
                        cell.label
                    );
                }
            }
        }
    }

    #[test]
    fn accumulators_derive_ttft_and_rate_from_reported_calls() {
        let mut metrics = SessionMetrics::default();
        // 100 output tokens over a 2 s stream, first token after 500 ms, whole
        // call 2.4 s including connection setup.
        metrics.record_model_call(100, 2_000, Some(500), Some(2_400));
        // A call that reported no first token (empty response) still counts
        // for LLM time but not for TTFT.
        metrics.record_model_call(20, 1_000, None, Some(1_100));
        assert_eq!(metrics.model_calls, 2);
        assert_eq!(metrics.llm_time, Duration::from_millis(3_500));
        assert_eq!(metrics.ttft_average(), Some(Duration::from_millis(500)));
        let rate = metrics.tokens_per_second().expect("rate");
        assert!((rate - 40.0).abs() < 1e-9, "{rate}");

        // Missing request_ms falls back to the stream duration.
        metrics.record_model_call(0, 700, None, None);
        assert_eq!(metrics.llm_time, Duration::from_millis(4_200));
        // Zero output tokens must not poison the rate.
        assert!((metrics.tokens_per_second().unwrap() - 120.0 / 3.7).abs() < 1e-9);
    }

    #[test]
    fn tool_time_needs_both_edges_and_in_flight_timers_are_dropped() {
        let mut metrics = SessionMetrics::default();
        let t0 = Instant::now();
        metrics.record_tool_started_at("a", t0);
        metrics.record_tool_completed_at("a", t0 + Duration::from_millis(1_500));
        // Completion without a seen start counts the call, not the time.
        metrics.record_tool_completed_at("ghost", t0 + Duration::from_secs(9));
        assert_eq!(metrics.tool_calls, 2);
        assert_eq!(metrics.tool_time, Duration::from_millis(1_500));
        assert_eq!(metrics.steps(), 2);

        metrics.record_tool_started_at("b", t0);
        metrics.clear_in_flight();
        metrics.record_tool_completed_at("b", t0 + Duration::from_secs(5));
        assert_eq!(metrics.tool_time, Duration::from_millis(1_500));
    }
}