ratto 0.12.0

Ratatui-powered terminal primitives for shell dashboards: flicker-free repaints, progress bars, prompts, and portable time tools
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
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
//! Pane rendering: one source's output pinned into its declared box.
//!
//! `PaneBox::title` is the *declaration* and `PaneChrome::title` is the
//! *resolution*: only the loop knows the source's name, so the default
//! is applied there and `render_pane` uses `chrome.title` verbatim.

use crate::color::ColorProfile;
use crate::core::box_model::{BoxSpec, render_box};
use crate::core::measure::{
    Align, Chunk, ELLIPSIS, chunks, display_width, kept_chars, pad_display, truncate_display,
};
use crate::core::registry::{LayoutNode, Overflow, PaneBox, PaneGeometry};
use crate::style_spec::StyleSpec;
use crate::term::marks::LineMark;
use crate::theme::Palette;

/// A rendered block and its marks in the block's own line coordinates.
#[derive(Clone, PartialEq, Debug, Default)]
pub struct PaneBlock {
    pub lines: Vec<String>,
    pub marks: Vec<LineMark>,
}

/// The chrome row's inputs, resolved by the loop.
pub struct PaneChrome<'a> {
    pub title: &'a str,
    /// "every 60s" | "every 60s or on trigger" | "on trigger" | "once".
    pub cadence: &'a str,
    /// "12:04:31" or "2m ago" — the pane's last-CHANGE time.
    pub stamp: &'a str,
    /// "exit 3" when the pane failed.
    pub failure: Option<&'a str>,
    /// Whether the suspicion test currently implicates this pane. A
    /// SEPARATE slot from `failure`, never a reuse of it: that one is
    /// outcome-derived and recomputed every tick, this one spans ticks,
    /// and a pane can legitimately be both failing and looping.
    pub looping: bool,
    /// "1.2k lines dropped" when this tick's output outran what the
    /// pane retains. A THIRD independent slot, for the same reason the
    /// second one exists: a pane can fail, loop and overflow at once,
    /// and each says something the others do not.
    pub truncated: Option<&'a str>,
}

/// Pin one pane's output into its declared box: apply the overflow
/// rule, pad to the inner height, chop/pad to the inner width, append
/// the chrome row, draw the border. EXACTLY `geom.rows` lines of
/// `geom.cells` display cells. Marks arrive in output-line coordinates
/// and leave in box coordinates; marks on truncated lines are dropped.
///
/// The char shift is `border + padding.left` only because `align` is
/// `Align::Left`; a centered or right-aligned pane would need the shift
/// computed per line from the rendered row, and the horizontal mark
/// re-basing in `compose_panes` would move with it.
pub fn render_pane(
    output: &[String],
    marks: &[LineMark],
    pane: &PaneBox,
    geom: PaneGeometry,
    chrome: &PaneChrome<'_>,
    palette: &Palette,
    profile: ColorProfile,
) -> PaneBlock {
    let rows = geom.inner_rows as usize;
    let cols = geom.inner_cols as usize;

    // The overflow rule picks the surviving window and, with it, how
    // far the surviving marks moved.
    let dropped = match pane.overflow {
        Overflow::KeepTop => 0,
        Overflow::KeepBottom => output.len().saturating_sub(rows),
    };
    let mut content: Vec<String> = output.iter().skip(dropped).take(rows).cloned().collect();
    // Short output pads: the height is declared, never measured.
    content.resize(rows, String::new());
    if pane.chrome {
        content.push(chrome_row(chrome, cols, profile));
    }

    let spec = BoxSpec {
        // Some(_) is what squares the right edge — a bare spec would
        // leave ragged rows and the pin would be a lie.
        width: Some(cols),
        // Left is load-bearing: the char shift below assumes the
        // content starts at the left padding.
        align: Align::Left,
        padding: pane.padding,
        border: pane.border,
        border_style: StyleSpec {
            foreground: Some(palette.border),
            ..StyleSpec::default()
        },
        title: Some(chrome.title),
        ..BoxSpec::default()
    };
    let lines = render_box(&content, &spec, profile);

    let row_shift = pane.edge_cells() as usize + pane.padding.top;
    let char_shift = pane.edge_cells() as usize + pane.padding.left;
    let mut shifted = vec![LineMark::default(); lines.len()];
    for (i, mark) in marks.iter().enumerate().skip(dropped).take(rows) {
        if !mark.changed {
            continue;
        }
        let Some(slot) = shifted.get_mut(i - dropped + row_shift) else {
            continue;
        };
        slot.changed = true;
        // Marks are computed against the pane's own untruncated output;
        // the box cut them to `cols` cells. Clip each run to the chars
        // that survived — via the same rule the cut used, never
        // re-derived — or a run past the cut addresses the border, the
        // gap, and the neighbour once the panes are joined. The clip
        // limit includes the ellipsis, so a run reaching the cut marks
        // `…` ("continues past the edge" — a decision, pinned by test).
        // `changed` stays true even when every run clips away: the
        // line DID change, and the gutter must still say so.
        let limit = output
            .get(i)
            .map_or(0, |line| kept_chars(line, cols, ELLIPSIS));
        slot.cells = mark
            .cells
            .iter()
            .map(|run| run.start.min(limit)..run.end.min(limit))
            .filter(|run| !run.is_empty())
            .map(|run| run.start + char_shift..run.end + char_shift)
            .collect();
    }
    PaneBlock {
        lines,
        marks: shifted,
    }
}

/// Compose the layout AND map every pane's marks into composed
/// coordinates in ONE walk, so the join rule can never drift between
/// the two: the horizontal offsets ARE the padding decisions, and a
/// separate mark mapper would have to re-derive them.
pub fn compose_panes(
    root: &LayoutNode,
    blocks: &[PaneBlock],
    gap: usize,
    row_gap: usize,
) -> PaneBlock {
    match root {
        LayoutNode::Pane(id) => blocks.get(id.0).cloned().unwrap_or_default(),
        LayoutNode::Column(children) => {
            let parts: Vec<PaneBlock> = children
                .iter()
                .map(|child| compose_panes(child, blocks, gap, row_gap))
                .collect();
            stack(&parts, row_gap)
        }
        LayoutNode::Row(children) => {
            let parts: Vec<PaneBlock> = children
                .iter()
                .map(|child| compose_panes(child, blocks, gap, row_gap))
                .collect();
            beside(&parts, gap)
        }
    }
}

/// Stack blocks with `row_gap` blank rows between. Mirrors
/// `join_vertical(.., Align::Left)`: lines are cloned verbatim, no
/// padding invented, so a mark's char indices are unchanged and only
/// its row moves.
fn stack(parts: &[PaneBlock], row_gap: usize) -> PaneBlock {
    let mut out = PaneBlock::default();
    for (i, part) in parts.iter().enumerate() {
        if i > 0 {
            for _ in 0..row_gap {
                out.lines.push(String::new());
                out.marks.push(LineMark::default());
            }
        }
        for (row, line) in part.lines.iter().enumerate() {
            out.lines.push(line.clone());
            // Pushed in lockstep, so lines and marks cannot fall out of
            // step even if a part arrives short.
            out.marks
                .push(part.marks.get(row).cloned().unwrap_or_default());
        }
    }
    out
}

/// Join blocks side by side and re-base their marks in the same pass.
///
/// The line rule is `join_horizontal`'s (`src/core/join.rs:93-107`),
/// restated here because the mark offsets are derived from the SAME
/// padding decisions: if `join_horizontal` changes, this changes with
/// it — which is exactly why lines and marks compose in one function,
/// and why the tests assert the composed lines equal `join_horizontal`
/// byte for byte (the restatement's standing witness).
fn beside(parts: &[PaneBlock], gap: usize) -> PaneBlock {
    let widths: Vec<usize> = parts
        .iter()
        .map(|part| {
            part.lines
                .iter()
                .map(|l| display_width(l))
                .max()
                .unwrap_or(0)
        })
        .collect();
    let height = parts.iter().map(|part| part.lines.len()).max().unwrap_or(0);
    let gap_text = " ".repeat(gap);
    let mut out = PaneBlock::default();
    for row in 0..height {
        let segments: Vec<&str> = parts
            .iter()
            .map(|part| part.lines.get(row).map(String::as_str).unwrap_or(""))
            .collect();
        // Nothing after the last non-empty segment is emitted — and a
        // row with no non-empty segment is one empty string.
        let Some(last) = segments.iter().rposition(|s| !s.is_empty()) else {
            out.lines.push(String::new());
            out.marks.push(LineMark::default());
            continue;
        };
        let mut line = String::new();
        let mut mark = LineMark::default();
        let mut chars = 0usize;
        for (i, segment) in segments[..=last].iter().enumerate() {
            if i > 0 {
                line.push_str(&gap_text);
                chars += gap;
            }
            // Everything before the last segment pads to its block's
            // width; the last one is emitted verbatim.
            let padded = if i < last {
                pad_display(segment, widths[i], Align::Left)
            } else {
                (*segment).to_string()
            };
            if let Some(source) = parts[i].marks.get(row) {
                mark.changed |= source.changed;
                // Left to right with a monotonically growing offset, so
                // the merged runs stay sorted and non-overlapping —
                // what `mark_cells` requires.
                mark.cells.extend(
                    source
                        .cells
                        .iter()
                        .map(|run| run.start + chars..run.end + chars),
                );
            }
            // CHARS, not display cells: LineMark.cells index the
            // stripped line, while the join pads by display cells.
            chars += chunks(&padded)
                .filter(|c| matches!(c, Chunk::Text(..)))
                .count();
            line.push_str(&padded);
        }
        out.lines.push(line);
        out.marks.push(mark);
    }
    out
}

/// `{cadence} · {stamp}`, plus each badge the pane currently carries:
/// faint, right-aligned, never wider than the inner box. The stamp is
/// the pane's last-CHANGE time — a produced-at stamp would repaint
/// every tick and cost byte-silence. The row truncates from the right
/// like every other line, so a pane too narrow for the badges loses
/// their tail rather than the cadence — behavior, not accident.
///
/// The word is `looping`: nine cells with its separator, the word a
/// user would type into a search box, and confident in the way
/// `CrashLoopBackOff` is confident over a mechanism that only counts.
/// The hedging belongs where there is room for it — a notice row and
/// the key reference — never in a nine-cell badge.
fn chrome_row(chrome: &PaneChrome<'_>, cols: usize, profile: ColorProfile) -> String {
    let mut text = format!("{} · {}", chrome.cadence, chrome.stamp);
    push_badge(&mut text, chrome.failure);
    push_badge(&mut text, chrome.looping.then_some("looping"));
    push_badge(&mut text, chrome.truncated);
    let faint = StyleSpec {
        faint: true,
        ..StyleSpec::default()
    };
    let text = truncate_display(&text, cols, ELLIPSIS);
    pad_display(&faint.render(&text, profile), cols, Align::Right)
}

/// One badge in the chrome row's separator form. Two of them ride this
/// row independently, so the join is written once rather than nested.
fn push_badge(text: &mut String, badge: Option<&str>) {
    if let Some(badge) = badge {
        text.push_str(" · ");
        text.push_str(badge);
    }
}

#[cfg(test)]
// A one-range vec like `vec![0..1]` is exactly what a single marked run
// looks like — not a mistyped `(0..1).collect()`.
#[allow(clippy::single_range_in_vec_init)]
mod tests {
    use super::*;
    // `Sides` is imported here, not at module scope: nothing in the
    // non-test half names the type, and an unused import is a warning
    // `just lint` denies.
    use crate::core::box_model::{BorderPreset, Sides};
    use crate::core::join::{VAlign, join_horizontal, join_vertical};
    use crate::core::registry::{PaneWidth, SourceId};
    use crate::theme::{Appearance, AppearanceSource};

    fn palette() -> Palette {
        Palette::builtin(Appearance::Dark, AppearanceSource::Default)
    }

    fn pane(height: u16, border: BorderPreset, padding: Sides, chrome: bool) -> PaneBox {
        PaneBox {
            height,
            width: PaneWidth::Weight(1),
            overflow: Overflow::default(),
            border,
            padding,
            title: None,
            chrome,
        }
    }

    /// The geometry the registry would resolve for this pane at `cells`
    /// wide — computed the same way, so a test never hand-waves a size.
    fn geom(pane: &PaneBox, cells: u16) -> PaneGeometry {
        PaneGeometry {
            cells,
            rows: pane.height,
            inner_cols: cells - pane.frame_cols(),
            inner_rows: pane.height - pane.frame_rows(),
        }
    }

    fn chrome<'a>(failure: Option<&'a str>) -> PaneChrome<'a> {
        PaneChrome {
            title: "plan",
            cadence: "every 5s",
            stamp: "12:04:31",
            failure,
            looping: false,
            truncated: None,
        }
    }

    fn lines(items: &[&str]) -> Vec<String> {
        items.iter().map(|s| s.to_string()).collect()
    }

    fn sides(top: usize, right: usize, bottom: usize, left: usize) -> Sides {
        Sides {
            top,
            right,
            bottom,
            left,
        }
    }

    /// A hand-built block: what `render_pane` would have produced, without
    /// paying for a box to test the join.
    fn block(lines_in: &[&str], marks_in: &[LineMark]) -> PaneBlock {
        PaneBlock {
            lines: lines(lines_in),
            marks: marks_in.to_vec(),
        }
    }

    fn marked(cells: std::ops::Range<usize>) -> LineMark {
        LineMark {
            changed: true,
            cells: vec![cells],
        }
    }

    fn row(n: usize) -> LayoutNode {
        LayoutNode::Row((0..n).map(|i| LayoutNode::Pane(SourceId(i))).collect())
    }

    fn column(n: usize) -> LayoutNode {
        LayoutNode::Column((0..n).map(|i| LayoutNode::Pane(SourceId(i))).collect())
    }

    #[test]
    fn a_column_of_rows_has_a_run_constant_height() {
        let top = block(
            &["aaa", "bbb", "ccc"],
            &[
                LineMark::default(),
                LineMark::default(),
                LineMark::default(),
            ],
        );
        let bottom = block(
            &["ddd", "eee", "fff", "ggg"],
            &[
                marked(0..3),
                LineMark::default(),
                LineMark::default(),
                LineMark::default(),
            ],
        );
        let composed = compose_panes(&column(2), &[top.clone(), bottom.clone()], 1, 1);
        assert_eq!(composed.lines.len(), 3 + 1 + 4);
        assert_eq!(composed.marks.len(), composed.lines.len());
        assert_eq!(
            composed.lines,
            join_vertical(&[top.lines.clone(), bottom.lines.clone()], 1, Align::Left)
        );
        // The gap row belongs to no pane and carries no mark.
        assert_eq!(composed.marks[3], LineMark::default());
        // The lower pane's mark moved down by the upper pane and the gap.
        assert_eq!(composed.marks[4], marked(0..3));

        // Run-constant: different content of the same declared size
        // composes to the same row count — the equal-length gate's premise.
        let top2 = block(&["zzz", "yyy", "xxx"], &vec![LineMark::default(); 3]);
        let again = compose_panes(&column(2), &[top2, bottom], 1, 1);
        assert_eq!(again.lines.len(), composed.lines.len());
    }

    #[test]
    fn a_row_takes_the_max_height_of_its_panes() {
        let short = block(&["a", "b", "c"], &vec![LineMark::default(); 3]);
        let tall = block(&["1", "2", "3", "4", "5"], &vec![LineMark::default(); 5]);
        let composed = compose_panes(&row(2), &[short.clone(), tall.clone()], 1, 0);
        assert_eq!(composed.lines.len(), 5);
        assert_eq!(composed.marks.len(), composed.lines.len());
        assert_eq!(
            composed.lines,
            join_horizontal(&[short.lines, tall.lines], 1, VAlign::Top)
        );
    }

    #[test]
    fn marks_rebase_across_a_horizontal_join() {
        let left = block(&["aaaa"], &[LineMark::default()]);
        let right = block(&["bb"], &[marked(0..2)]);
        let composed = compose_panes(&row(2), &[left.clone(), right.clone()], 1, 0);
        assert_eq!(composed.lines, vec!["aaaa bb".to_string()]);
        // Four chars of the left pane plus one gap.
        assert_eq!(composed.marks[0].cells, vec![5..7]);
        assert!(composed.marks[0].changed);
        assert_eq!(
            composed.lines,
            join_horizontal(&[left.lines, right.lines], 1, VAlign::Top)
        );
    }

    #[test]
    fn marks_rebase_by_chars_not_cells() {
        // The CJK pin: "日本語ab" is 5 CHARS and 8 DISPLAY CELLS;
        // LineMark.cells are char indices, so the right pane shifts by 5.
        // Row two pads "z" out to the block's 8 cells — 8 chars of spaces —
        // so the shift is per row, read off the PADDED segment.
        let left = block(
            &["日本語ab", "z"],
            &[LineMark::default(), LineMark::default()],
        );
        let right = block(&["xy", "xy"], &[marked(0..2), marked(0..2)]);
        assert_eq!(display_width("日本語ab"), 8);
        assert_eq!("日本語ab".chars().count(), 5);

        let composed = compose_panes(&row(2), &[left.clone(), right.clone()], 0, 0);
        assert_eq!(composed.lines, lines(&["日本語abxy", "z       xy"]));
        assert_eq!(composed.marks[0].cells, vec![5..7]);
        assert_eq!(composed.marks[1].cells, vec![8..10]);
        assert_eq!(
            composed.lines,
            join_horizontal(&[left.lines, right.lines], 0, VAlign::Top)
        );

        // The marks land on the characters they came from.
        for (line, mark) in composed.lines.iter().zip(&composed.marks) {
            let chars: Vec<char> = line.chars().collect();
            let run = &mark.cells[0];
            assert_eq!(&chars[run.start..run.end], &['x', 'y'], "in {line:?}");
        }
    }

    #[test]
    fn a_ragged_tail_row_marks_nothing() {
        // The left pane is taller; below the right pane's last row the
        // composed row is the left pane's own content, and past the left
        // pane's content it is whitespace or nothing at all. Neither can
        // mark: no pane owns a mark there, and the whitespace rule means
        // the padding a join invents never marks either.
        let tall = block(
            &["aaa", "bbb", "   ", ""],
            &[
                marked(0..3),
                LineMark::default(),
                LineMark::default(),
                LineMark::default(),
            ],
        );
        let short = block(&["zz"], &[marked(0..2)]);
        let composed = compose_panes(&row(2), &[tall.clone(), short.clone()], 1, 0);
        assert_eq!(composed.marks.len(), 4);
        assert_eq!(composed.marks[1], LineMark::default());
        assert_eq!(composed.marks[2], LineMark::default(), "whitespace tail");
        assert_eq!(composed.marks[3], LineMark::default(), "empty tail");
        // Both panes contribute to the first row: `changed` is an OR.
        assert!(composed.marks[0].changed);
        assert_eq!(composed.marks[0].cells, vec![0..3, 4..6]);
        assert_eq!(
            composed.lines,
            join_horizontal(&[tall.lines, short.lines], 1, VAlign::Top)
        );
    }

    #[test]
    fn an_empty_registry_composes_nothing() {
        assert_eq!(
            compose_panes(&LayoutNode::Column(Vec::new()), &[], 1, 1),
            PaneBlock::default()
        );
        assert_eq!(
            compose_panes(&LayoutNode::Row(Vec::new()), &[], 1, 1),
            PaneBlock::default()
        );
        // A layout the blocks do not cover composes empty rather than
        // panicking — validation is the registry's job, not a paint's.
        assert_eq!(
            compose_panes(&LayoutNode::Pane(SourceId(9)), &[], 1, 1),
            PaneBlock::default()
        );
    }

    #[test]
    fn a_pane_is_exactly_its_declared_size() {
        // Borderless: the block IS the inner box, so the whole frame is
        // assertable byte for byte.
        let bare = pane(4, BorderPreset::None, Sides::default(), true);
        let block = render_pane(
            &lines(&["ab"]),
            &[LineMark::default()],
            &bare,
            geom(&bare, 20),
            &PaneChrome {
                cadence: "once",
                ..chrome(None)
            },
            &palette(),
            ColorProfile::Ascii,
        );
        assert_eq!(
            block.lines,
            lines(&[
                "ab                  ",
                "                    ",
                "                    ",
                "     once · 12:04:31",
            ])
        );

        // Bordered and padded: 7 rows of 30 cells, every row, regardless
        // of how little the child printed.
        let boxed = pane(7, BorderPreset::Normal, sides(0, 1, 0, 1), true);
        let block = render_pane(
            &lines(&["line one", "line two"]),
            &[LineMark::default(), LineMark::default()],
            &boxed,
            geom(&boxed, 30),
            &chrome(None),
            &palette(),
            ColorProfile::Ascii,
        );
        assert_eq!(block.lines.len(), 7);
        for line in &block.lines {
            assert_eq!(display_width(line), 30, "ragged row: {line:?}");
        }
        assert_eq!(block.marks.len(), block.lines.len());
        assert!(
            block.lines[0].contains("plan"),
            "the title rides the border"
        );
    }

    #[test]
    fn overflow_keep_top_drops_the_tail() {
        let pane = pane(3, BorderPreset::None, Sides::default(), false);
        let block = render_pane(
            &lines(&["1", "2", "3", "4", "5"]),
            &vec![LineMark::default(); 5],
            &pane,
            geom(&pane, 5),
            &chrome(None),
            &palette(),
            ColorProfile::Ascii,
        );
        assert_eq!(block.lines, lines(&["1    ", "2    ", "3    "]));
    }

    #[test]
    fn overflow_keep_bottom_keeps_the_tail() {
        let pane = PaneBox {
            overflow: Overflow::KeepBottom,
            ..pane(3, BorderPreset::None, Sides::default(), false)
        };
        // The last output line changed; its mark must ride along to the
        // row the tail actually landed on.
        let mut marks = vec![LineMark::default(); 5];
        marks[4] = LineMark {
            changed: true,
            cells: vec![0..1],
        };
        let block = render_pane(
            &lines(&["1", "2", "3", "4", "5"]),
            &marks,
            &pane,
            geom(&pane, 5),
            &chrome(None),
            &palette(),
            ColorProfile::Ascii,
        );
        assert_eq!(block.lines, lines(&["3    ", "4    ", "5    "]));
        assert_eq!(block.marks[2].cells, vec![0..1]);
        assert!(!block.marks[0].changed && !block.marks[1].changed);
    }

    #[test]
    fn a_short_pane_pads_with_blank_rows() {
        let pane = pane(3, BorderPreset::None, Sides::default(), false);
        let block = render_pane(
            &lines(&["only"]),
            &[LineMark::default()],
            &pane,
            geom(&pane, 5),
            &chrome(None),
            &palette(),
            ColorProfile::Ascii,
        );
        assert_eq!(block.lines, lines(&["only ", "     ", "     "]));
        // Empty output is the same case, not a special one.
        let block = render_pane(
            &[],
            &[],
            &pane,
            geom(&pane, 5),
            &chrome(None),
            &palette(),
            ColorProfile::Ascii,
        );
        assert_eq!(block.lines, lines(&["     ", "     ", "     "]));
    }

    #[test]
    fn the_chrome_row_is_the_last_inner_row_and_right_aligned() {
        // Bottom padding proves the status row sits inside the content
        // block, not on the bottom border.
        let pane = pane(8, BorderPreset::Normal, sides(0, 1, 1, 1), true);
        let block = render_pane(
            &lines(&["x"]),
            &[LineMark::default()],
            &pane,
            geom(&pane, 30),
            &chrome(None),
            &palette(),
            ColorProfile::Ascii,
        );
        assert_eq!(block.lines.len(), 8);
        assert_eq!(block.lines[5], "│        every 5s · 12:04:31 │");
        assert_eq!(block.lines[6], format!("{}", " ".repeat(28)));
    }

    #[test]
    fn a_failure_badge_rides_the_chrome_row_without_changing_the_height() {
        let pane = pane(7, BorderPreset::Normal, sides(0, 1, 0, 1), true);
        let block = render_pane(
            &lines(&["boom"]),
            &[LineMark::default()],
            &pane,
            geom(&pane, 40),
            &chrome(Some("exit 3")),
            &palette(),
            ColorProfile::Ascii,
        );
        assert_eq!(block.lines.len(), 7, "a failure never changes the height");
        assert!(
            block.lines[5].contains("every 5s · 12:04:31 · exit 3"),
            "got {:?}",
            block.lines[5]
        );

        // Too narrow for the badge: the row still fits its box exactly.
        let block = render_pane(
            &lines(&["boom"]),
            &[LineMark::default()],
            &pane,
            geom(&pane, 24),
            &chrome(Some("exit 3")),
            &palette(),
            ColorProfile::Ascii,
        );
        assert_eq!(block.lines.len(), 7);
        for line in &block.lines {
            assert_eq!(display_width(line), 24, "ragged row: {line:?}");
        }
    }

    #[test]
    fn marks_shift_by_the_border_and_padding_rows() {
        let pane = pane(8, BorderPreset::Normal, sides(1, 2, 0, 2), true);
        let marks = vec![
            LineMark {
                changed: true,
                cells: vec![0..3],
            },
            LineMark::default(),
        ];
        let block = render_pane(
            &lines(&["abc", "d"]),
            &marks,
            &pane,
            geom(&pane, 30),
            &chrome(None),
            &palette(),
            ColorProfile::Ascii,
        );
        assert_eq!(block.marks.len(), block.lines.len());
        // Down by the top border (1) and the top padding (1).
        assert!(block.marks[2].changed);
        assert!(!block.marks[0].changed && !block.marks[1].changed);
        // Right by the border glyph (1 char) and the left padding (2).
        assert_eq!(block.marks[2].cells, vec![3..6]);
        // The shifted range lands on the same characters it started on.
        let stripped: Vec<char> = crate::core::measure::strip_escapes(&block.lines[2])
            .chars()
            .collect();
        assert_eq!(&stripped[3..6], &['a', 'b', 'c']);
    }

    #[test]
    fn marks_past_the_truncation_cut_never_leave_the_pane() {
        // Normal border, no padding, inner 20 cells: a 30-char line
        // keeps 19 chars + the ellipsis. A run wholly past the cut
        // vanishes (the gutter bit still says the line changed); a
        // straddling run clips at the cut and marks the ellipsis —
        // "continues past the edge", a decision, not an accident.
        let pane = pane(4, BorderPreset::Normal, sides(0, 0, 0, 0), false);
        let source = "abcdefghijklmnopqrstuvwxyz0123";
        let hidden = vec![marked(20..25), LineMark::default()];
        let block = render_pane(
            &lines(&[source, "x"]),
            &hidden,
            &pane,
            geom(&pane, 22),
            &chrome(None),
            &palette(),
            ColorProfile::Ascii,
        );
        assert!(
            block.marks[1].changed,
            "the line DID change — the gutter must still say so"
        );
        assert!(
            block.marks[1].cells.is_empty(),
            "a change hidden in the tail paints no highlight: {:?}",
            block.marks[1].cells
        );

        let straddling = vec![marked(15..25), LineMark::default()];
        let block = render_pane(
            &lines(&[source, "x"]),
            &straddling,
            &pane,
            geom(&pane, 22),
            &chrome(None),
            &palette(),
            ColorProfile::Ascii,
        );
        assert_eq!(block.marks[1].cells, vec![16..21]);
        let stripped: Vec<char> = crate::core::measure::strip_escapes(&block.lines[1])
            .chars()
            .collect();
        assert_eq!(
            stripped[20], '',
            "a run reaching the cut marks the ellipsis"
        );
    }

    #[test]
    fn a_wide_rune_cut_clips_marks_in_chars_not_cells() {
        // "日本語abcd" is 10 cells over 7 chars; an inner width of 6
        // cells keeps 日本 (4 cells, the straddling 語 drops whole)
        // plus the ellipsis: 3 CHARS survive. The clip must count
        // chars, not cells, or wide runes shift every boundary.
        let pane = pane(3, BorderPreset::Normal, sides(0, 0, 0, 0), false);
        let source = "日本語abcd";
        let marks = vec![marked(1..5)];
        let block = render_pane(
            &lines(&[source]),
            &marks,
            &pane,
            geom(&pane, 8),
            &chrome(None),
            &palette(),
            ColorProfile::Ascii,
        );
        // char_shift 1 (border); clip at 3 kept chars → 2..4, inside
        // the box, ending on the ellipsis.
        assert_eq!(block.marks[1].cells, vec![2..4]);
    }

    #[test]
    fn a_truncated_panes_highlight_never_reaches_its_neighbour() {
        // The composed regression: a change past the left pane's cut
        // must not mark the gap or the right pane — composed marks
        // never index at or past the left block's own chars.
        let pane_box = pane(3, BorderPreset::Normal, sides(0, 0, 0, 0), false);
        let long = "abcdefghijklmnopqrstuvwxyz0123";
        let left = render_pane(
            &lines(&[long]),
            &[marked(20..25)],
            &pane_box,
            geom(&pane_box, 22),
            &chrome(None),
            &palette(),
            ColorProfile::Ascii,
        );
        let right = render_pane(
            &lines(&["quiet"]),
            &[LineMark::default()],
            &pane_box,
            geom(&pane_box, 22),
            &chrome(None),
            &palette(),
            ColorProfile::Ascii,
        );
        let left_chars = crate::core::measure::strip_escapes(&left.lines[1])
            .chars()
            .count();
        let composed = compose_panes(&row(2), &[left, right], 1, 0);
        for (i, mark) in composed.marks.iter().enumerate() {
            for run in &mark.cells {
                assert!(
                    run.end <= left_chars,
                    "row {i}: run {run:?} leaks past the left pane ({left_chars} chars)"
                );
            }
        }
    }

    #[test]
    fn a_looping_pane_shows_the_badge() {
        let row = chrome_row(
            &PaneChrome {
                looping: true,
                ..chrome(None)
            },
            40,
            ColorProfile::Ascii,
        );
        assert!(row.contains("· looping"), "got {row:?}");
    }

    #[test]
    fn a_pane_can_be_both_failing_and_looping() {
        // Two independent slots: one is outcome-derived and recomputed
        // every tick, the other spans ticks. Neither replaces the other.
        let row = chrome_row(
            &PaneChrome {
                looping: true,
                ..chrome(Some("exit 3"))
            },
            60,
            ColorProfile::Ascii,
        );
        assert!(
            row.contains("every 5s · 12:04:31 · exit 3 · looping"),
            "got {row:?}"
        );
    }

    #[test]
    fn a_truncated_pane_shows_the_marker_after_the_other_badges() {
        // A third independent slot: a pane can fail, loop and truncate
        // at once, and the newest badge appends rather than displacing.
        let row = chrome_row(
            &PaneChrome {
                looping: true,
                truncated: Some("1.2k lines dropped"),
                ..chrome(Some("exit 3"))
            },
            80,
            ColorProfile::Ascii,
        );
        assert!(
            row.contains("every 5s · 12:04:31 · exit 3 · looping · 1.2k lines dropped"),
            "got {row:?}"
        );
    }

    #[test]
    fn a_narrow_pane_loses_the_marker_before_it_loses_the_cadence() {
        // The same append-and-truncate-tail rule the other badges obey.
        // `on trigger · 12:04:31 · 90 lines dropped` is 40 cells, which
        // makes 40 the exact width at which the marker survives whole.
        let truncated = PaneChrome {
            cadence: "on trigger",
            truncated: Some("90 lines dropped"),
            ..chrome(None)
        };
        assert_eq!(
            chrome_row(&truncated, 40, ColorProfile::Ascii),
            "on trigger · 12:04:31 · 90 lines dropped"
        );
        let narrow = chrome_row(&truncated, 39, ColorProfile::Ascii);
        assert!(
            narrow.starts_with("on trigger · 12:04:31"),
            "got {narrow:?}"
        );
        assert!(!narrow.contains("dropped"), "got {narrow:?}");
    }

    #[test]
    fn a_narrow_pane_loses_the_badge_rather_than_the_cadence() {
        // Shipped behaviour asserted rather than assumed: the row
        // truncates from the RIGHT, so the badge's tail goes before the
        // cadence does. `on trigger · 12:04:31 · looping` is 31 cells,
        // which makes 31 the exact width at which the badge survives.
        let looping = PaneChrome {
            cadence: "on trigger",
            looping: true,
            ..chrome(None)
        };
        assert_eq!(
            chrome_row(&looping, 31, ColorProfile::Ascii),
            "on trigger · 12:04:31 · looping"
        );
        let narrow = chrome_row(&looping, 30, ColorProfile::Ascii);
        assert!(
            narrow.starts_with("on trigger · 12:04:31"),
            "the cadence and the stamp survive: {narrow:?}"
        );
        assert!(!narrow.contains("looping"), "got {narrow:?}");
        assert_eq!(display_width(&narrow), 30, "and the row still fits");
    }

    #[test]
    fn a_pane_with_no_chrome_row_renders_no_badge_and_does_not_panic() {
        // `chrome = #false` is legal and shipped, and `· exit 3` is
        // ALREADY invisible on such a pane. The badge inherits that
        // hole rather than opening a new one — which is exactly why a
        // notice row that names the panes has to exist too.
        let bare = pane(4, BorderPreset::None, Sides::default(), false);
        let block = render_pane(
            &lines(&["ab"]),
            &[LineMark::default()],
            &bare,
            geom(&bare, 20),
            &PaneChrome {
                looping: true,
                ..chrome(Some("exit 3"))
            },
            &palette(),
            ColorProfile::Ascii,
        );
        assert_eq!(block.lines.len(), 4, "a chrome-less pane is all content");
        assert!(!block.lines.iter().any(|l| l.contains("looping")));
        assert!(!block.lines.iter().any(|l| l.contains("exit 3")));
    }
}