koda-cli 0.6.1

A high-performance AI coding agent for macOS and Linux
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
//! Render cache for fullscreen TUI history panel.
//!
//! Stores styled `Line`s in a `VecDeque` and provides virtual scrolling
//! with "sticky bottom" behavior. The buffer is a **render cache** — the
//! DB is the source of truth. Lines evicted from the buffer can be
//! re-rendered from DB on demand.
//!
//! See #472 for the fullscreen migration RFC.

use ratatui::text::Line;
use std::collections::VecDeque;

/// Maximum lines held in the render cache, folded-away lines included.
/// A full read keeps its content here for the full view, so this is set
/// for a session's worth of those, not just ~50 pages of what's shown.
const MAX_CACHE_LINES: usize = 10_000;

/// Which view a line belongs to.
///
/// Tool output is shown folded by default: a read as one summary line, other
/// output as its first lines and a "… +N lines" marker. The full view
/// (Ctrl+O) shows every line instead. Both live in the buffer at once, each
/// line tagged, so switching is a redraw, not a re-render.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Fold {
    /// Shown in both views: everything that isn't folded tool output.
    #[default]
    Always,
    /// Folded view only: a summary or a "… +N lines" marker.
    Folded,
    /// Full view only: the lines folding hides.
    Full,
}

/// One rendered line and how to show it.
struct Entry {
    line: Line<'static>,
    /// Columns to skip during NoSelect copy. 0 = no gutter (normal text).
    gutter: u16,
    fold: Fold,
}

/// Scrollable buffer of rendered `Line`s with sticky-bottom auto-scroll.
pub struct ScrollBuffer {
    /// The rendered lines (ring buffer).
    entries: VecDeque<Entry>,

    /// Sequence number of `entries[0]`: each pushed line gets the next one,
    /// so a caller can find lines it pushed earlier after older ones were
    /// evicted ([`Self::next_seq`], [`Self::fold_since`]).
    first_seq: u64,

    /// The full view is on: [`Fold::Full`] lines are shown instead of
    /// [`Fold::Folded`] ones.
    full: bool,

    /// Scroll offset: number of lines scrolled UP from the bottom.
    /// 0 = viewing the bottom (latest content).
    scroll_offset: usize,

    /// When true, new lines auto-scroll to keep the bottom visible.
    /// Disengages when the user scrolls up; re-engages when they
    /// scroll back to the bottom.
    sticky_bottom: bool,

    /// Oldest DB message ID currently rendered in the buffer.
    /// Used by virtual scroll to know which page to fetch next.
    /// `None` means no DB messages have been loaded yet.
    oldest_message_id: Option<i64>,

    /// Cached terminal width for eviction offset adjustment.
    /// Updated on scroll operations and used by `enforce_capacity()`
    /// to compute visual height of evicted lines.
    cached_term_width: usize,
}

impl ScrollBuffer {
    pub fn new(capacity: usize) -> Self {
        let cap = capacity.min(4096);
        Self {
            entries: VecDeque::with_capacity(cap),
            first_seq: 0,
            full: false,
            scroll_offset: 0,
            sticky_bottom: true,
            oldest_message_id: None,
            cached_term_width: 80,
        }
    }

    fn shows(&self, fold: Fold) -> bool {
        match fold {
            Fold::Always => true,
            Fold::Folded => !self.full,
            Fold::Full => self.full,
        }
    }

    fn visible(&self) -> impl Iterator<Item = &Entry> {
        self.entries.iter().filter(|e| self.shows(e.fold))
    }

    fn push_entry(&mut self, entry: Entry) {
        self.entries.push_back(entry);
        self.enforce_capacity();
        // If sticky, keep scroll at bottom
        if self.sticky_bottom {
            self.scroll_offset = 0;
        }
    }

    /// Append a single line to the buffer.
    ///
    /// If sticky bottom is active, the view stays pinned to the latest
    /// content. If the buffer exceeds the max cache size, the oldest
    /// lines are evicted from the front.
    pub fn push(&mut self, line: Line<'static>) {
        self.push_folded(line, Fold::Always);
    }

    /// Append a line that only one of the two views shows.
    pub fn push_folded(&mut self, line: Line<'static>, fold: Fold) {
        self.push_entry(Entry {
            line,
            gutter: 0,
            fold,
        });
    }

    /// Append a line with a gutter width (for NoSelect diff lines).
    pub fn push_with_gutter(&mut self, line: Line<'static>, gutter_width: u16) {
        self.push_entry(Entry {
            line,
            gutter: gutter_width,
            fold: Fold::Always,
        });
    }

    /// Append multiple lines at once.
    pub fn push_lines(&mut self, lines: impl IntoIterator<Item = Line<'static>>) {
        self.push_folded_lines(lines.into_iter().map(|l| (l, Fold::Always)));
    }

    /// Append lines, each with the view it belongs to.
    pub fn push_folded_lines(&mut self, lines: impl IntoIterator<Item = (Line<'static>, Fold)>) {
        for (line, fold) in lines {
            self.entries.push_back(Entry {
                line,
                gutter: 0,
                fold,
            });
        }
        self.enforce_capacity();

        if self.sticky_bottom {
            self.scroll_offset = 0;
        }
    }

    /// Sequence number the next pushed line will get.
    pub fn next_seq(&self) -> u64 {
        self.first_seq + self.entries.len() as u64
    }

    /// Fold the lines pushed since `start` (a [`Self::next_seq`] value) the
    /// way finished tool output is folded: keep the first `head` and last
    /// `tail` in both views, and show the rest only in the full view, with
    /// `marker(hidden)` in their place in the folded one. For output that
    /// streamed in line by line before anyone knew how long it would be.
    /// Does nothing when no more than one line would be hidden.
    pub fn fold_since(
        &mut self,
        start: u64,
        head: usize,
        tail: usize,
        marker: impl FnOnce(usize) -> Line<'static>,
    ) {
        let from = start.saturating_sub(self.first_seq) as usize;
        let count = self.entries.len().saturating_sub(from);
        if count <= head + tail + 1 {
            return;
        }
        let hidden = count - head - tail;
        for entry in self.entries.range_mut(from + head..from + head + hidden) {
            entry.fold = Fold::Full;
        }
        self.entries.insert(
            from + head,
            Entry {
                line: marker(hidden),
                gutter: 0,
                fold: Fold::Folded,
            },
        );
        if self.sticky_bottom {
            self.scroll_offset = 0;
        }
    }

    /// Whether the full view is on.
    pub fn is_full(&self) -> bool {
        self.full
    }

    /// Switch between the folded and the full view. The view goes to the
    /// bottom: what was on screen may have moved by any amount.
    pub fn set_full(&mut self, full: bool) {
        if self.full != full {
            self.full = full;
            self.scroll_to_bottom();
        }
    }

    /// Scroll up by `n` visual lines. Disengages sticky bottom.
    pub fn scroll_up(&mut self, n: usize, term_width: usize, viewport_height: usize) {
        self.cached_term_width = term_width;
        let total = self.total_visual_lines(term_width);
        let max_offset = total.saturating_sub(viewport_height);
        self.scroll_offset = (self.scroll_offset + n).min(max_offset);
        self.sticky_bottom = false;
    }

    /// Scroll down by `n` lines. Re-engages sticky bottom if we reach
    /// the bottom.
    pub fn scroll_down(&mut self, n: usize) {
        self.scroll_offset = self.scroll_offset.saturating_sub(n);
        if self.scroll_offset == 0 {
            self.sticky_bottom = true;
        }
    }

    /// Re-clamp `scroll_offset` to valid bounds for the current
    /// terminal dimensions. Must be called after any resize so the
    /// offset doesn't exceed `total_visual - viewport_height`.
    pub fn clamp_offset(&mut self, term_width: usize, viewport_height: usize) {
        self.cached_term_width = term_width;
        let total = self.total_visual_lines(term_width);
        let max_offset = total.saturating_sub(viewport_height);
        if self.scroll_offset > max_offset {
            self.scroll_offset = max_offset;
        }
        if self.scroll_offset == 0 {
            self.sticky_bottom = true;
        }
    }

    /// Jump to the bottom and re-engage sticky mode.
    pub fn scroll_to_bottom(&mut self) {
        self.scroll_offset = 0;
        self.sticky_bottom = true;
    }

    /// Jump to the top of the buffer.
    pub fn scroll_to_top(&mut self, term_width: usize, viewport_height: usize) {
        self.cached_term_width = term_width;
        if !self.entries.is_empty() {
            let total = self.total_visual_lines(term_width);
            self.scroll_offset = total.saturating_sub(viewport_height);
            self.sticky_bottom = false;
        }
    }

    /// Returns `true` when the user has scrolled to the very top of the
    /// buffer. Used to trigger loading older messages from the DB.
    #[allow(dead_code)] // wired when virtual scroll pagination lands
    pub fn at_top(&self, term_width: usize, viewport_height: usize) -> bool {
        if self.entries.is_empty() {
            return false;
        }
        let total = self.total_visual_lines(term_width);
        let max_offset = total.saturating_sub(viewport_height);
        self.scroll_offset >= max_offset && max_offset > 0
    }

    /// Return the lines the current view shows.
    ///
    /// Used by `render_history()` which passes everything to
    /// `Paragraph::wrap().scroll()` — ratatui handles the visual
    /// line math for word-wrapped content.
    pub fn all_lines(&self) -> impl Iterator<Item = &Line<'static>> {
        self.visible().map(|e| &e.line)
    }

    /// Return the per-line gutter widths (parallel with `all_lines()`).
    ///
    /// Used by mouse selection to skip gutter columns during copy.
    pub fn gutter_widths(&self) -> impl Iterator<Item = u16> + '_ {
        self.visible().map(|e| e.gutter)
    }

    /// Compute the total number of visual (wrapped) lines at a given
    /// terminal width. Used for scrollbar state and offset clamping.
    pub fn total_visual_lines(&self, term_width: usize) -> usize {
        let w = term_width.max(1);
        self.visible().map(|e| visual_height(&e.line, w)).sum()
    }

    /// Compute the Paragraph scroll-from-top offset for the current
    /// scroll position. Returns `(row_offset, 0)` for `Paragraph::scroll()`.
    ///
    /// `scroll_offset` is visual lines from the bottom.
    /// Paragraph wants visual lines from the top.
    pub fn paragraph_scroll(&self, viewport_height: usize, term_width: usize) -> (u16, u16) {
        let total = self.total_visual_lines(term_width);
        let from_top = total
            .saturating_sub(viewport_height)
            .saturating_sub(self.scroll_offset);
        // Clamp to u16::MAX to prevent silent truncation (#528).
        (from_top.min(u16::MAX as usize) as u16, 0)
    }

    /// Total number of lines in the buffer, both views' included.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Whether the buffer is empty.
    #[allow(dead_code)]
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Current scroll offset (lines from bottom).
    pub fn offset(&self) -> usize {
        self.scroll_offset
    }

    /// Whether sticky bottom is active.
    pub fn is_sticky(&self) -> bool {
        self.sticky_bottom
    }

    /// Get the oldest DB message ID rendered in this buffer.
    #[allow(dead_code)] // wired when virtual scroll pagination lands
    pub fn oldest_message_id(&self) -> Option<i64> {
        self.oldest_message_id
    }

    /// Set the oldest DB message ID (called after rendering history).
    pub fn set_oldest_message_id(&mut self, id: i64) {
        self.oldest_message_id = Some(id);
    }

    /// Clear all lines and reset scroll state.
    #[allow(dead_code)]
    pub fn clear(&mut self) {
        self.first_seq += self.entries.len() as u64;
        self.entries.clear();
        self.scroll_offset = 0;
        self.sticky_bottom = true;
    }

    /// Evict oldest lines if we exceed capacity.
    ///
    /// Adjusts `scroll_offset` by the evicted line's visual height
    /// (not a flat 1) to prevent scroll position drift when wrapped
    /// lines are evicted (#528). A line the current view hides takes up
    /// no rows, so it moves nothing.
    fn enforce_capacity(&mut self) {
        let w = self.cached_term_width.max(1);
        while self.entries.len() > MAX_CACHE_LINES {
            if let Some(evicted) = self.entries.pop_front() {
                self.first_seq += 1;
                if self.scroll_offset > 0 && self.shows(evicted.fold) {
                    let vis = visual_height(&evicted.line, w);
                    self.scroll_offset = self.scroll_offset.saturating_sub(vis);
                }
            }
        }
    }

    /// Prepend lines at the top of the buffer (for DB-backed virtual scroll).
    ///
    /// Used when the user scrolls past the top of the cache and older
    /// messages are fetched from the DB and re-rendered.
    #[allow(dead_code)] // wired in a follow-up PR
    pub fn prepend_lines(&mut self, lines: impl IntoIterator<Item = Line<'static>>) {
        let lines: Vec<_> = lines.into_iter().collect();
        let count = lines.len();
        for line in lines.into_iter().rev() {
            self.entries.push_front(Entry {
                line,
                gutter: 0,
                fold: Fold::Always,
            });
        }
        self.first_seq = self.first_seq.saturating_sub(count as u64);
        // Adjust scroll offset to keep the viewport stable
        // (content shifted down by `count` logical lines)
        self.scroll_offset += count;
        self.enforce_capacity();
    }
}

/// Extract plain text from a `Line` by concatenating all span contents.
fn line_text(line: &Line<'_>) -> String {
    line.spans.iter().map(|s| s.content.as_ref()).collect()
}

/// Compute how many visual rows a `Line` occupies at the given terminal width.
///
/// Delegates to `wrap_util::visual_line_count` — the single source of truth
/// for word-boundary wrapping consistent with `Wrap { trim: false }`.
fn visual_height(line: &Line<'_>, term_width: usize) -> usize {
    crate::wrap_util::visual_line_count(&line_text(line), term_width)
}

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

    const W: usize = 80; // test terminal width
    const H: usize = 50; // test viewport height

    fn make_line(text: &str) -> Line<'static> {
        Line::from(Span::raw(text.to_string()))
    }

    /// Collect the visible lines via paragraph_scroll logic.
    /// For tests with short lines that don't wrap, this matches the old visible_lines().
    fn visible_text(buf: &ScrollBuffer, height: usize) -> Vec<String> {
        let lines: Vec<Line<'_>> = buf.all_lines().cloned().collect();
        let total_visual = buf.total_visual_lines(W);
        let from_top = total_visual
            .saturating_sub(height)
            .saturating_sub(buf.offset());
        // Simulate what Paragraph would show
        lines
            .iter()
            .skip(from_top)
            .take(height)
            .map(line_text)
            .collect()
    }

    #[test]
    fn the_full_view_swaps_folded_lines_for_full_ones() {
        let mut buf = ScrollBuffer::new(100);
        buf.push(make_line("header"));
        buf.push_folded(make_line("summary"), Fold::Folded);
        buf.push_folded(make_line("detail"), Fold::Full);
        buf.push(make_line("after"));
        assert_eq!(visible_text(&buf, H), vec!["header", "summary", "after"]);
        buf.set_full(true);
        assert_eq!(visible_text(&buf, H), vec!["header", "detail", "after"]);
        assert_eq!(buf.gutter_widths().count(), 3);
        assert_eq!(buf.len(), 4);
    }

    #[test]
    fn fold_since_folds_the_lines_pushed_after_a_point() {
        let mut buf = ScrollBuffer::new(100);
        buf.push(make_line("before"));
        let start = buf.next_seq();
        for i in 1..=10 {
            buf.push(make_line(&format!("l{i}")));
        }
        buf.fold_since(start, 2, 1, |n| make_line(&format!("+{n}")));
        assert_eq!(
            visible_text(&buf, H),
            vec!["before", "l1", "l2", "+7", "l10"]
        );
        buf.set_full(true);
        assert_eq!(visible_text(&buf, H).len(), 11);

        // Too few lines to be worth a marker: left alone.
        let mut buf = ScrollBuffer::new(100);
        let start = buf.next_seq();
        for i in 1..=3 {
            buf.push(make_line(&format!("l{i}")));
        }
        buf.fold_since(start, 2, 0, |n| make_line(&format!("+{n}")));
        assert_eq!(visible_text(&buf, H), vec!["l1", "l2", "l3"]);
    }

    #[test]
    fn switching_views_returns_to_the_bottom() {
        let mut buf = ScrollBuffer::new(100);
        for i in 0..100 {
            buf.push(make_line(&format!("line {i}")));
        }
        buf.scroll_up(30, W, H);
        assert!(!buf.is_sticky());
        buf.set_full(true);
        assert!(buf.is_sticky());
        assert_eq!(buf.offset(), 0);
    }

    #[test]
    fn evicting_a_hidden_line_moves_nothing_on_screen() {
        let mut buf = ScrollBuffer::new(100);
        buf.push_folded(make_line("hidden"), Fold::Full);
        for i in 0..(MAX_CACHE_LINES - 1) {
            buf.push(make_line(&format!("line {i}")));
        }
        buf.scroll_up(10, W, H);
        let before = buf.offset();
        buf.push(make_line("one more"));
        assert_eq!(buf.offset(), before);
        assert_eq!(buf.len(), MAX_CACHE_LINES);
    }

    #[test]
    fn test_push_and_visible() {
        let mut buf = ScrollBuffer::new(2500);
        for i in 0..10 {
            buf.push(make_line(&format!("line {i}")));
        }
        assert_eq!(buf.len(), 10);

        // Viewport of 3 lines at bottom
        let visible = visible_text(&buf, 3);
        assert_eq!(visible.len(), 3);
        assert_eq!(visible[0], "line 7");
        assert_eq!(visible[1], "line 8");
        assert_eq!(visible[2], "line 9");
    }

    #[test]
    fn test_sticky_bottom() {
        let mut buf = ScrollBuffer::new(2500);
        for i in 0..5 {
            buf.push(make_line(&format!("line {i}")));
        }
        assert!(buf.is_sticky());
        assert_eq!(buf.offset(), 0);

        // New lines keep us at bottom
        buf.push(make_line("line 5"));
        assert_eq!(buf.offset(), 0);
        let visible = visible_text(&buf, 2);
        assert_eq!(visible[1], "line 5");
    }

    #[test]
    fn test_scroll_up_breaks_sticky() {
        let mut buf = ScrollBuffer::new(2500);
        for i in 0..10 {
            buf.push(make_line(&format!("line {i}")));
        }

        // Use viewport smaller than content so scroll has room
        buf.scroll_up(3, W, 5);
        assert!(!buf.is_sticky());
        assert_eq!(buf.offset(), 3);
    }

    #[test]
    fn test_scroll_down_restores_sticky() {
        let mut buf = ScrollBuffer::new(2500);
        for i in 0..10 {
            buf.push(make_line(&format!("line {i}")));
        }

        buf.scroll_up(5, W, 5);
        assert!(!buf.is_sticky());

        buf.scroll_down(5);
        assert!(buf.is_sticky());
        assert_eq!(buf.offset(), 0);
    }

    #[test]
    fn test_scroll_up_clamped() {
        let mut buf = ScrollBuffer::new(2500);
        for i in 0..5 {
            buf.push(make_line(&format!("line {i}")));
        }

        // Viewport height 3, 5 lines total → max offset = 5-3 = 2
        buf.scroll_up(100, W, 3);
        assert_eq!(buf.offset(), 2);
    }

    #[test]
    fn test_eviction() {
        let mut buf = ScrollBuffer::new(2500);
        for i in 0..MAX_CACHE_LINES + 100 {
            buf.push(make_line(&format!("line {i}")));
        }
        assert_eq!(buf.len(), MAX_CACHE_LINES);
        // Latest line should be at the bottom
        let visible = visible_text(&buf, 1);
        assert_eq!(visible[0], format!("line {}", MAX_CACHE_LINES + 99));
    }

    #[test]
    fn test_empty_buffer() {
        let buf = ScrollBuffer::new(2500);
        assert_eq!(buf.all_lines().count(), 0);
        assert_eq!(buf.total_visual_lines(80), 0);
    }

    #[test]
    fn test_scroll_to_top_and_bottom() {
        let mut buf = ScrollBuffer::new(2500);
        for i in 0..20 {
            buf.push(make_line(&format!("line {i}")));
        }

        // 20 lines, viewport 10 → max offset = 10
        buf.scroll_to_top(W, 10);
        assert!(!buf.is_sticky());
        assert_eq!(buf.offset(), 10);

        buf.scroll_to_bottom();
        assert!(buf.is_sticky());
        assert_eq!(buf.offset(), 0);
    }

    #[test]
    fn test_push_lines_batch() {
        let mut buf = ScrollBuffer::new(2500);
        let batch: Vec<Line<'static>> = (0..5).map(|i| make_line(&format!("line {i}"))).collect();
        buf.push_lines(batch);
        assert_eq!(buf.len(), 5);
    }

    #[test]
    fn test_eviction_adjusts_scroll_offset() {
        let mut buf = ScrollBuffer::new(2500);
        // Fill to capacity
        for i in 0..MAX_CACHE_LINES {
            buf.push(make_line(&format!("line {i}")));
        }
        // Scroll up
        buf.scroll_up(100, W, H);
        let offset_before = buf.offset();

        // Push more lines, triggering eviction
        for i in 0..50 {
            buf.push(make_line(&format!("new {i}")));
        }

        // Offset should have been adjusted down
        assert!(buf.offset() < offset_before);
        assert_eq!(buf.len(), MAX_CACHE_LINES);
    }

    // ── Visual line math ──

    #[test]
    fn test_visual_height_short_line() {
        let line = make_line("hello"); // 5 chars
        assert_eq!(visual_height(&line, 80), 1);
    }

    #[test]
    fn test_visual_height_wrapping_line() {
        // 160 chars in an 80-column terminal = 2 visual lines
        let line = make_line(&"x".repeat(160));
        assert_eq!(visual_height(&line, 80), 2);
    }

    #[test]
    fn test_visual_height_empty_line() {
        let line = make_line("");
        assert_eq!(visual_height(&line, 80), 1);
    }

    // ── Word-wrap regression tests (#520) ──

    #[test]
    fn test_visual_height_word_wrap_breaks_before_word() {
        // 76 chars of 'a' + space + 6-char word = 83 chars
        // Character wrap: row 1 = 80 chars, row 2 = 3 chars = 2 rows
        // Word wrap: row 1 = 76 chars + space (77), row 2 = 6-char word = 2 rows
        let text = format!("{}  foobar", "a".repeat(76));
        let line = make_line(&text);
        assert_eq!(visual_height(&line, 80), 2);
    }

    #[test]
    fn test_visual_height_word_wrap_longer_word() {
        // 78 chars + space + 5-char word = 84 chars
        // Character wrap: row 1 = 80 chars, row 2 = 4 chars = 2 rows
        // Word wrap: row 1 = 78+space (79), word "hello" doesn't fit (79+5=84>80)
        //   -> wrap before "hello": row 1 = 79, row 2 = 5 = 2 rows
        let text = format!("{} hello", "x".repeat(78));
        let line = make_line(&text);
        assert_eq!(visual_height(&line, 80), 2);
    }

    #[test]
    fn test_visual_height_word_wrap_three_rows() {
        // Two long words that each nearly fill a row + a short word
        // "<75 a's> <75 b's> end"
        let text = format!("{} {} end", "a".repeat(75), "b".repeat(75));
        let line = make_line(&text);
        // Row 1: 75 a's + space (76), "b"*75 doesn't fit (76+75=151>80)
        // Row 2: 75 b's + space (76), "end" fits (76+3=79<=80) -> actually...
        // Wait: row 2 starts with 75 b's = 75, + space = 76, + "end" = 79 <= 80
        // So: 2 rows
        // Actually: row 1 = "aaa... " (76), b's don't fit, wrap
        // row 2 = "bbb... end" (75+1+3=79)
        // = 2 rows
        assert_eq!(visual_height(&line, 80), 2);
    }

    #[test]
    fn test_visual_height_single_word_longer_than_width() {
        // Single word with no spaces, 200 chars at width 80
        // Must force-break: ceil(200/80) = 3 rows
        let line = make_line(&"x".repeat(200));
        assert_eq!(visual_height(&line, 80), 3);
    }

    #[test]
    fn test_visual_height_exact_width() {
        // Exactly 80 chars = 1 row, not 2
        let line = make_line(&"x".repeat(80));
        assert_eq!(visual_height(&line, 80), 1);
    }

    #[test]
    fn test_visual_height_exact_width_plus_one() {
        let line = make_line(&"x".repeat(81));
        assert_eq!(visual_height(&line, 80), 2);
    }

    #[test]
    fn test_total_visual_lines() {
        let mut buf = ScrollBuffer::new(2500);
        buf.push(make_line("short")); // 1 visual line
        buf.push(make_line(&"x".repeat(160))); // 2 visual lines
        buf.push(make_line("")); // 1 visual line
        assert_eq!(buf.total_visual_lines(80), 4);
    }

    #[test]
    fn test_paragraph_scroll_at_bottom() {
        let mut buf = ScrollBuffer::new(2500);
        for i in 0..20 {
            buf.push(make_line(&format!("line {i}")));
        }
        // At bottom: offset=0, viewport=10, total=20
        // → scroll from top = 20 - 10 - 0 = 10
        let (row, _) = buf.paragraph_scroll(10, 80);
        assert_eq!(row, 10);
    }

    #[test]
    fn test_paragraph_scroll_at_top() {
        let mut buf = ScrollBuffer::new(2500);
        for i in 0..20 {
            buf.push(make_line(&format!("line {i}")));
        }
        buf.scroll_to_top(80, 10);
        // At top: offset=10, viewport=10, total=20
        // → scroll from top = 20 - 10 - 10 = 0
        let (row, _) = buf.paragraph_scroll(10, 80);
        assert_eq!(row, 0);
    }

    // ── Prepend ──

    // ── Clamp offset ──

    #[test]
    fn test_clamp_offset_after_resize() {
        let mut buf = ScrollBuffer::new(2500);
        for i in 0..20 {
            buf.push(make_line(&format!("line {i}")));
        }
        // Scroll to top: 20 lines, viewport 10 → offset = 10
        buf.scroll_to_top(W, 10);
        assert_eq!(buf.offset(), 10);
        assert!(!buf.is_sticky());

        // Simulate resize to viewport height 18 → max_offset = 2
        buf.clamp_offset(W, 18);
        assert_eq!(buf.offset(), 2);
    }

    #[test]
    fn test_clamp_offset_restores_sticky() {
        let mut buf = ScrollBuffer::new(2500);
        for i in 0..5 {
            buf.push(make_line(&format!("line {i}")));
        }
        // Scroll up then grow viewport to fit everything
        buf.scroll_up(3, W, 3);
        assert!(!buf.is_sticky());

        buf.clamp_offset(W, 10); // viewport bigger than content
        assert_eq!(buf.offset(), 0);
        assert!(buf.is_sticky());
    }

    /// Regression: clamp_offset must use the history panel viewport height,
    /// NOT the full terminal height. Using a too-large viewport computes
    /// max_offset too small, clamping the user's scroll position toward
    /// the bottom and re-engaging sticky during inference streaming.
    #[test]
    fn test_clamp_offset_with_correct_viewport_preserves_scroll() {
        let mut buf = ScrollBuffer::new(2500);
        // 50 lines of content
        for i in 0..50 {
            buf.push(make_line(&format!("line {i}")));
        }

        // User scrolls up 15 lines from the bottom
        buf.scroll_up(15, W, 30);
        assert_eq!(buf.offset(), 15);
        assert!(!buf.is_sticky());

        // With correct viewport (30 lines): max_offset = 50 - 30 = 20.
        // 15 < 20 → no clamping.
        buf.clamp_offset(W, 30);
        assert_eq!(buf.offset(), 15);
        assert!(
            !buf.is_sticky(),
            "correct viewport must NOT re-engage sticky"
        );

        // BUG CASE: if caller mistakenly passes full terminal height (40),
        // max_offset = 50 - 40 = 10.  15 > 10 → clamped to 10.
        // This is the wrong behavior the fix prevents.
        buf.clamp_offset(W, 40);
        assert_eq!(buf.offset(), 10, "over-large viewport incorrectly clamps");
    }

    /// Streaming new content while scrolled up must not snap to bottom.
    #[test]
    fn test_push_during_scrolled_up_preserves_position() {
        let mut buf = ScrollBuffer::new(2500);
        for i in 0..30 {
            buf.push(make_line(&format!("line {i}")));
        }

        // User scrolls up 10 lines
        buf.scroll_up(10, W, 20);
        assert!(!buf.is_sticky());
        assert_eq!(buf.offset(), 10);

        // New content arrives (simulating inference streaming)
        buf.push(make_line("streamed token"));
        buf.push(make_line("another token"));

        // Offset and sticky must be unchanged
        assert_eq!(buf.offset(), 10);
        assert!(
            !buf.is_sticky(),
            "push must not re-engage sticky when user scrolled up"
        );
    }

    #[test]
    fn test_prepend_lines() {
        let mut buf = ScrollBuffer::new(2500);
        buf.push(make_line("current"));
        buf.scroll_up(0, W, H); // stay at bottom

        let old_lines = vec![make_line("old1"), make_line("old2")];
        buf.prepend_lines(old_lines);

        assert_eq!(buf.len(), 3);
        // Offset adjusted by prepend count
        assert_eq!(buf.offset(), 2);
        // First line is now "old1"
        let first = line_text(buf.all_lines().next().unwrap());
        assert_eq!(first, "old1");
    }
}