rho-coding-agent 1.48.0

A lightweight agent harness inspired by Pi
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
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
use pretty_assertions::assert_eq;

use super::*;
use crate::tui::{
    feed_image::FeedImage,
    render::entry_lines,
    syntax::{reset_highlight_line_calls, take_highlight_line_calls, warm_syntax_set},
};

fn no_images(_: usize, _: &[MarkdownImageSource]) -> Vec<(usize, FeedImage)> {
    Vec::new()
}

fn settings(width: usize) -> HistoryRenderSettings {
    HistoryRenderSettings {
        width,
        max_tool_output_lines: 10,
        zen_mode: false,
        theme_generation: 0,
        max_image_height: crate::tui::feed_image::DEFAULT_IMAGE_HEIGHT,
    }
}

fn settings_with(
    width: usize,
    max_tool_output_lines: usize,
    zen_mode: bool,
) -> HistoryRenderSettings {
    HistoryRenderSettings {
        width,
        max_tool_output_lines,
        zen_mode,
        theme_generation: 0,
        max_image_height: crate::tui::feed_image::DEFAULT_IMAGE_HEIGHT,
    }
}

#[test]
fn caches_code_block_copy_target_and_raw_contents() {
    let mut cache = HistoryLineCache::default();
    let entries = vec![Entry::Assistant(
        "before\n```rust\nlet x = 1;\nprintln!(\"{x}\");\n```\nafter".into(),
    )];

    let blocks = cache.code_blocks(&entries, settings(40), &no_images);

    assert_eq!(blocks.len(), 1);
    assert_eq!(blocks[0].text.as_ref(), "let x = 1;\nprintln!(\"{x}\");");
    assert_eq!(blocks[0].line, 1);
    assert_eq!(blocks[0].copy_columns, 32..38);
}

#[test]
fn caches_unicode_wrapped_lines_and_code_copy_target_without_rendering_drift() {
    // Rendered lines are compared across separate render passes; hold the lock
    // so theme-switching tests cannot restyle the second pass mid-test.
    let _guard = crate::tui::theme::theme_test_lock();
    let mut cache = HistoryLineCache::default();
    let entries = vec![Entry::Assistant("你好你好你好\n```text\nλ🙂\n```".into())];
    let expected_lines = entry_lines(
        &entries[0],
        12,
        10,
        crate::tui::feed_image::DEFAULT_IMAGE_HEIGHT,
    );

    let mut cached_lines = Vec::new();
    cache.extend_visible_lines(
        &entries,
        settings(12),
        HistoryLineSlice {
            start: 0,
            count: usize::MAX,
        },
        &mut cached_lines,
        &no_images,
    );
    let blocks = cache.code_blocks(&entries, settings(12), &no_images);

    assert_eq!(cached_lines, expected_lines);
    assert_eq!(
        blocks,
        &[CachedCodeBlock {
            line: 2,
            copy_columns: 4..10,
            text: Arc::from("λ🙂"),
        }]
    );
}

#[test]
fn incrementally_extends_assistant_markdown_without_rendering_drift() {
    // Rendered lines are compared across separate render passes; hold the lock
    // so theme-switching tests cannot restyle the second pass mid-test.
    let _guard = crate::tui::theme::theme_test_lock();
    let mut cache = HistoryLineCache::default();
    let mut entries = vec![Entry::Assistant("intro\n\nheader | value\n".into())];
    let mut cached_lines = Vec::new();
    cache.extend_visible_lines(
        &entries,
        settings(32),
        HistoryLineSlice {
            start: 0,
            count: usize::MAX,
        },
        &mut cached_lines,
        &no_images,
    );

    let Entry::Assistant(text) = &mut entries[0] else {
        unreachable!();
    };
    text.push_str("--- | ---\nrow | `one`\n");
    cache.entry_appended(0);
    cached_lines.clear();
    cache.extend_visible_lines(
        &entries,
        settings(32),
        HistoryLineSlice {
            start: 0,
            count: usize::MAX,
        },
        &mut cached_lines,
        &no_images,
    );
    assert_eq!(
        cached_lines,
        entry_lines(
            &entries[0],
            32,
            10,
            crate::tui::feed_image::DEFAULT_IMAGE_HEIGHT
        )
    );

    let Entry::Assistant(text) = &mut entries[0] else {
        unreachable!();
    };
    text.push_str("\n## streamed heading\n");
    cache.entry_appended(0);
    cached_lines.clear();
    cache.extend_visible_lines(
        &entries,
        settings(32),
        HistoryLineSlice {
            start: 0,
            count: usize::MAX,
        },
        &mut cached_lines,
        &no_images,
    );
    assert_eq!(
        cached_lines,
        entry_lines(
            &entries[0],
            32,
            10,
            crate::tui::feed_image::DEFAULT_IMAGE_HEIGHT
        )
    );

    let Entry::Assistant(text) = &mut entries[0] else {
        unreachable!();
    };
    text.push_str("\n```rust\nlet answer = 42;\n");
    cache.entry_appended(0);
    cached_lines.clear();
    cache.extend_visible_lines(
        &entries,
        settings(32),
        HistoryLineSlice {
            start: 0,
            count: usize::MAX,
        },
        &mut cached_lines,
        &no_images,
    );
    assert_eq!(
        cached_lines,
        entry_lines(
            &entries[0],
            32,
            10,
            crate::tui::feed_image::DEFAULT_IMAGE_HEIGHT
        )
    );

    let Entry::Assistant(text) = &mut entries[0] else {
        unreachable!();
    };
    text.push_str("println!(\"{answer}\");\n```\ndone\n");
    cache.entry_appended(0);
    cached_lines.clear();
    cache.extend_visible_lines(
        &entries,
        settings(32),
        HistoryLineSlice {
            start: 0,
            count: usize::MAX,
        },
        &mut cached_lines,
        &no_images,
    );

    assert_eq!(
        cached_lines,
        entry_lines(
            &entries[0],
            32,
            10,
            crate::tui::feed_image::DEFAULT_IMAGE_HEIGHT
        )
    );
    assert_eq!(
        cache.code_blocks(&entries, settings(32), &no_images).len(),
        1
    );
    assert!(cache.entries[0]
        .incremental
        .as_ref()
        .is_some_and(|cached| cached.stable_source_len > "intro\n\n".len()));
}

// Covers: streamed reasoning extends the cached entry without re-render drift;
// closing the thought falls back to a full re-render for the summary suffix.
// Owner: history line cache (incremental append)
#[test]
fn incrementally_extends_reasoning_text_without_rendering_drift() {
    // Rendered lines are compared across separate render passes; hold the lock
    // so theme-switching tests cannot restyle the second pass mid-test.
    let _guard = crate::tui::theme::theme_test_lock();
    let full_slice = HistoryLineSlice {
        start: 0,
        count: usize::MAX,
    };
    let mut cache = HistoryLineCache::default();
    let mut entries = vec![Entry::Reasoning(crate::tui::ReasoningEntry::new(
        "weighing the first option\n",
    ))];
    let mut cached_lines = Vec::new();
    cache.extend_visible_lines(
        &entries,
        settings(32),
        full_slice,
        &mut cached_lines,
        &no_images,
    );

    let Entry::Reasoning(reasoning) = &mut entries[0] else {
        unreachable!();
    };
    reasoning
        .text
        .push_str("against a `second` option\n\n## verdict\nkeep it simple\n");
    cache.entry_appended(0);
    cached_lines.clear();
    cache.extend_visible_lines(
        &entries,
        settings(32),
        full_slice,
        &mut cached_lines,
        &no_images,
    );
    assert_eq!(
        cached_lines,
        entry_lines(
            &entries[0],
            32,
            10,
            crate::tui::feed_image::DEFAULT_IMAGE_HEIGHT
        )
    );
    assert!(cache.entries[0]
        .incremental
        .as_ref()
        .is_some_and(|cached| { cached.stable_source_len > "weighing the first option\n".len() }));

    // Closing the thought appends the summary line, which the incremental path
    // cannot produce; the entry re-renders whole and must still match.
    let Entry::Reasoning(reasoning) = &mut entries[0] else {
        unreachable!();
    };
    reasoning.thought_for = Some(std::time::Duration::from_secs(3));
    cache.invalidate_from(0);
    cached_lines.clear();
    cache.extend_visible_lines(
        &entries,
        settings(32),
        full_slice,
        &mut cached_lines,
        &no_images,
    );
    assert_eq!(
        cached_lines,
        entry_lines(
            &entries[0],
            32,
            10,
            crate::tui::feed_image::DEFAULT_IMAGE_HEIGHT
        )
    );
}

// Covers: a growing rust fence must not re-highlight already committed body
// Owner: history line cache (incremental append)
#[test]
fn incrementally_extends_open_fence_without_rehighlighting_committed_lines() {
    let _guard = crate::tui::theme::theme_test_lock();
    warm_syntax_set();
    let mut cache = HistoryLineCache::default();
    let mut body = String::from("```rust\n");
    for index in 0..40 {
        body.push_str(&format!("    let value_{index} = {index};\n"));
    }
    let mut entries = vec![Entry::Assistant(body.into())];
    let mut cached_lines = Vec::new();
    reset_highlight_line_calls();
    cache.extend_visible_lines(
        &entries,
        settings(80),
        HistoryLineSlice {
            start: 0,
            count: usize::MAX,
        },
        &mut cached_lines,
        &no_images,
    );
    let first_highlights = take_highlight_line_calls();
    assert!(first_highlights >= 40, "{first_highlights}");

    let Entry::Assistant(text) = &mut entries[0] else {
        unreachable!();
    };
    text.push_str("    let extra = 1;\n    let more = 2;\n");
    cache.entry_appended(0);
    cached_lines.clear();
    reset_highlight_line_calls();
    cache.extend_visible_lines(
        &entries,
        settings(80),
        HistoryLineSlice {
            start: 0,
            count: usize::MAX,
        },
        &mut cached_lines,
        &no_images,
    );
    let second_highlights = take_highlight_line_calls();
    assert!(
        second_highlights < first_highlights / 2,
        "second={second_highlights} first={first_highlights}"
    );
    assert_eq!(
        cached_lines,
        entry_lines(
            &entries[0],
            80,
            10,
            crate::tui::feed_image::DEFAULT_IMAGE_HEIGHT
        )
    );
}

fn paint_cached(
    cache: &mut HistoryLineCache,
    entries: &[Entry],
    width: usize,
) -> Vec<ratatui::text::Line<'static>> {
    let mut lines = Vec::new();
    cache.extend_visible_lines(
        entries,
        settings(width),
        HistoryLineSlice {
            start: 0,
            count: usize::MAX,
        },
        &mut lines,
        &no_images,
    );
    lines
}

fn expected_entry_lines(entry: &Entry, width: usize) -> Vec<ratatui::text::Line<'static>> {
    entry_lines(
        entry,
        width,
        10,
        crate::tui::feed_image::DEFAULT_IMAGE_HEIGHT,
    )
}

// Covers: prose after a closed fence in the same buffer must stay visible.
// Owner: history line cache (incremental append)
#[test]
fn incrementally_keeps_prose_after_a_closed_fence() {
    let _guard = crate::tui::theme::theme_test_lock();
    let mut cache = HistoryLineCache::default();
    let mut entries = vec![Entry::Assistant("```rust\nlet value = 1;\n".into())];
    let _ = paint_cached(&mut cache, &entries, 80);

    let Entry::Assistant(text) = &mut entries[0] else {
        unreachable!();
    };
    text.push_str("```\nThe function");
    cache.entry_appended(0);
    assert_eq!(
        paint_cached(&mut cache, &entries, 80),
        expected_entry_lines(&entries[0], 80)
    );
}

// Covers: new table rows paint against frozen widths without a full reflow.
// Owner: history line cache (incremental append)
#[test]
fn incrementally_extends_table_rows_without_rendering_drift() {
    let _guard = crate::tui::theme::theme_test_lock();
    let mut cache = HistoryLineCache::default();
    let mut entries = vec![Entry::Assistant(
        "| Name | Value |\n| --- | --- |\n| rho | 1 |\n".into(),
    )];
    assert_eq!(
        paint_cached(&mut cache, &entries, 40),
        expected_entry_lines(&entries[0], 40)
    );

    let Entry::Assistant(text) = &mut entries[0] else {
        unreachable!();
    };
    text.push_str("| agent | 2 |\n");
    cache.entry_appended(0);
    assert_eq!(
        paint_cached(&mut cache, &entries, 40),
        expected_entry_lines(&entries[0], 40)
    );
}

// Covers: a later wider cell must reflow instead of wrapping at frozen widths.
// Owner: history line cache (incremental append)
#[test]
fn incrementally_reflows_a_table_when_a_later_cell_is_wider() {
    let _guard = crate::tui::theme::theme_test_lock();
    let mut cache = HistoryLineCache::default();
    let mut entries = vec![Entry::Assistant(
        "| A | B |\n| --- | --- |\n| x | y |\n".into(),
    )];
    let _ = paint_cached(&mut cache, &entries, 40);

    let Entry::Assistant(text) = &mut entries[0] else {
        unreachable!();
    };
    text.push_str("| much-longer-cell | z |\n");
    cache.entry_appended(0);
    assert_eq!(
        paint_cached(&mut cache, &entries, 40),
        expected_entry_lines(&entries[0], 40)
    );
}

// Covers: leftover prose after a table must not disappear before the newline.
// Owner: history line cache (incremental append)
#[test]
fn incrementally_keeps_prose_after_a_table() {
    let _guard = crate::tui::theme::theme_test_lock();
    let mut cache = HistoryLineCache::default();
    let mut entries = vec![Entry::Assistant(
        "| Name | Value |\n| --- | --- |\n| rho | 1 |\n".into(),
    )];
    let _ = paint_cached(&mut cache, &entries, 40);

    let Entry::Assistant(text) = &mut entries[0] else {
        unreachable!();
    };
    text.push_str("After the table");
    cache.entry_appended(0);
    assert_eq!(
        paint_cached(&mut cache, &entries, 40),
        expected_entry_lines(&entries[0], 40)
    );
}

#[test]
fn streams_mermaid_as_source_then_caches_the_closed_diagram_by_width() {
    // Rendered lines are compared across separate render passes; hold the lock
    // so theme-switching tests cannot restyle the second pass mid-test.
    let _guard = crate::tui::theme::theme_test_lock();
    let mut cache = HistoryLineCache::default();
    let mut entries = vec![Entry::Assistant(
        "```mermaid\nflowchart LR\nA[Parse] --> B[Render]".into(),
    )];
    let mut cached_lines = Vec::new();
    cache.extend_visible_lines(
        &entries,
        settings(80),
        HistoryLineSlice {
            start: 0,
            count: usize::MAX,
        },
        &mut cached_lines,
        &no_images,
    );
    assert_eq!(
        cached_lines,
        entry_lines(
            &entries[0],
            80,
            10,
            crate::tui::feed_image::DEFAULT_IMAGE_HEIGHT
        )
    );

    let Entry::Assistant(text) = &mut entries[0] else {
        unreachable!();
    };
    text.push_str("\n```");
    cache.entry_appended(0);
    cached_lines.clear();
    cache.extend_visible_lines(
        &entries,
        settings(80),
        HistoryLineSlice {
            start: 0,
            count: usize::MAX,
        },
        &mut cached_lines,
        &no_images,
    );

    assert_eq!(
        cached_lines,
        entry_lines(
            &entries[0],
            80,
            10,
            crate::tui::feed_image::DEFAULT_IMAGE_HEIGHT
        )
    );
    assert_eq!(
        cache.code_blocks(&entries, settings(80), &no_images)[0]
            .text
            .as_ref(),
        "flowchart LR\nA[Parse] --> B[Render]"
    );

    let mut narrow_lines = Vec::new();
    cache.extend_visible_lines(
        &entries,
        settings(36),
        HistoryLineSlice {
            start: 0,
            count: usize::MAX,
        },
        &mut narrow_lines,
        &no_images,
    );
    assert_eq!(
        narrow_lines,
        entry_lines(
            &entries[0],
            36,
            10,
            crate::tui::feed_image::DEFAULT_IMAGE_HEIGHT
        )
    );
    assert_ne!(cached_lines, narrow_lines);
}

#[test]
fn resizing_keeps_mermaid_code_block_source_stable() {
    // Rendered lines are compared across separate render passes; hold the lock
    // so theme-switching tests cannot restyle the second pass mid-test.
    let _guard = crate::tui::theme::theme_test_lock();
    let source = crate::tui::markdown::PHASE_CHAIN_FLOWCHART;
    let entries = vec![Entry::Assistant(
        format!("```mermaid\n{source}\n```").into(),
    )];
    let mut cache = HistoryLineCache::default();

    let mut wide = Vec::new();
    cache.extend_visible_lines(
        &entries,
        settings(100),
        HistoryLineSlice {
            start: 0,
            count: usize::MAX,
        },
        &mut wide,
        &no_images,
    );
    let mut narrow = Vec::new();
    cache.extend_visible_lines(
        &entries,
        settings(40),
        HistoryLineSlice {
            start: 0,
            count: usize::MAX,
        },
        &mut narrow,
        &no_images,
    );

    assert_ne!(wide, narrow);
    assert_eq!(
        wide,
        entry_lines(
            &entries[0],
            100,
            10,
            crate::tui::feed_image::DEFAULT_IMAGE_HEIGHT
        )
    );
    assert_eq!(
        narrow,
        entry_lines(
            &entries[0],
            40,
            10,
            crate::tui::feed_image::DEFAULT_IMAGE_HEIGHT
        )
    );
    for width in [100, 40] {
        assert_eq!(
            cache.code_blocks(&entries, settings(width), &no_images)[0]
                .text
                .as_ref(),
            source
        );
    }
}

#[test]
fn invalidating_an_assistant_entry_refreshes_code_block_contents() {
    let mut cache = HistoryLineCache::default();
    let mut entries = vec![Entry::Assistant("```\nfirst\n```".into())];
    assert_eq!(
        cache.code_blocks(&entries, settings(30), &no_images)[0]
            .text
            .as_ref(),
        "first"
    );

    entries[0] = Entry::Assistant("```\nsecond\n```".into());
    cache.invalidate_from(0);

    assert_eq!(
        cache.code_blocks(&entries, settings(30), &no_images)[0]
            .text
            .as_ref(),
        "second"
    );
}

#[test]
fn open_stream_tail_omits_trailing_blank_until_closed() {
    // Rendered lines are compared across separate render passes; hold the lock
    // so theme-switching tests cannot restyle the second pass mid-test.
    let _guard = crate::tui::theme::theme_test_lock();
    use crate::tui::render::{render_entry_with_options, TrailingBlank};

    let mut cache = HistoryLineCache::default();
    let entries = vec![Entry::Assistant("Hello committed line\n".into())];

    cache.set_open_stream_tail(true);
    let open_count = cache.line_count(&entries, settings(60), &no_images);
    let mut open_lines = Vec::new();
    cache.extend_visible_lines(
        &entries,
        settings(60),
        HistoryLineSlice {
            start: 0,
            count: usize::MAX,
        },
        &mut open_lines,
        &no_images,
    );
    assert_eq!(open_lines.len(), open_count);
    assert_eq!(
        open_lines,
        render_entry_with_options(
            &entries[0],
            60,
            10,
            crate::tui::feed_image::DEFAULT_IMAGE_HEIGHT,
            TrailingBlank::Omit
        )
        .lines
    );

    cache.set_open_stream_tail(false);
    let closed_count = cache.line_count(&entries, settings(60), &no_images);
    assert_eq!(closed_count, open_count + 1);
    let mut closed_lines = Vec::new();
    cache.extend_visible_lines(
        &entries,
        settings(60),
        HistoryLineSlice {
            start: 0,
            count: usize::MAX,
        },
        &mut closed_lines,
        &no_images,
    );
    assert_eq!(
        closed_lines,
        entry_lines(
            &entries[0],
            60,
            10,
            crate::tui::feed_image::DEFAULT_IMAGE_HEIGHT
        )
    );
}

// Covers: zen mode suppresses tool/reasoning lines while keeping entry indices stable.
// Owner: history line cache display policy.
#[test]
fn zen_mode_hides_tool_and_reasoning_lines_and_restores_them() {
    // Rendered lines are compared across separate render passes; hold the lock
    // so theme-switching tests cannot restyle the second pass mid-test.
    let _guard = crate::tui::theme::theme_test_lock();
    use crate::tui::{ReasoningEntry, ToolEntry};

    let tool = Entry::Tool(ToolEntry::new(
        rho_tools::tool_card::ToolCard::new(
            rho_tools::tool_card::ToolStatus::Running,
            rho_tools::tool_card::ToolFamily::Default,
            rho_tools::tool_card::ToolHeader::call("read_file(a.rs)", None),
        ),
        false,
        None,
        None,
    ));
    let entries = vec![
        Entry::User("hi".into()),
        tool,
        Entry::Reasoning(ReasoningEntry::new("secret plan")),
        Entry::Assistant("hello".into()),
    ];

    let mut cache = HistoryLineCache::default();
    let full = cache.line_count(&entries, settings(40), &no_images);
    assert!(full > 2);

    let zen_count = cache.line_count(&entries, settings_with(40, 10, true), &no_images);
    let user_lines = entry_lines(
        &entries[0],
        40,
        10,
        crate::tui::feed_image::DEFAULT_IMAGE_HEIGHT,
    )
    .len();
    let assistant_lines = entry_lines(
        &entries[3],
        40,
        10,
        crate::tui::feed_image::DEFAULT_IMAGE_HEIGHT,
    )
    .len();
    assert_eq!(zen_count, user_lines + assistant_lines);

    // Toggling zen off rebuilds the suppressed entries.
    let restored = cache.line_count(&entries, settings(40), &no_images);
    assert_eq!(restored, full);
}

// Covers: tool expand/collapse resplices only the toggled card; later assistant
// markdown is not re-rendered (line identity of the suffix is preserved).
// Owner: history line cache surgical update
#[test]
fn resplice_tool_expand_preserves_later_assistant_lines() {
    // Rendered lines are compared across separate render passes; hold the lock
    // so theme-switching tests cannot restyle the second pass mid-test.
    let _guard = crate::tui::theme::theme_test_lock();
    use crate::tui::ToolEntry;
    use rho_tools::tool_card::{
        DiffRow, DiffRowKind, ToolBody, ToolCard, ToolFamily, ToolHeader, ToolStatus,
    };

    // Long body so collapsed vs expanded heights differ under max_tool_output_lines=2.
    let rows: Vec<_> = (0..20)
        .map(|i| DiffRow::new(DiffRowKind::Added, Some(i + 1), format!("line_{i}")))
        .collect();
    let card = ToolCard::new(
        ToolStatus::Ok,
        ToolFamily::FileDiff,
        ToolHeader::call("str_replace", Some("f.rs".into())),
    )
    .with_body(ToolBody::Diff(rows));

    let mut entries = vec![
        Entry::User("go".into()),
        Entry::Tool(ToolEntry::new(card, false, None, None)),
        Entry::Assistant(("# big\n\n".to_string() + &"paragraph\n\n".repeat(30)).into()),
    ];

    let mut cache = HistoryLineCache::default();
    let width = 40usize;
    let max_lines = 2usize;
    let s = settings_with(width, max_lines, false);

    let mut before = Vec::new();
    cache.extend_visible_lines(
        &entries,
        s,
        HistoryLineSlice {
            start: 0,
            count: usize::MAX,
        },
        &mut before,
        &no_images,
    );
    let assistant_range = cache.entry_ranges[2].clone();
    let assistant_before = before[assistant_range.clone()].to_vec();
    let total_before = before.len();

    // Expand the tool surgically.
    if let Entry::Tool(tool) = &mut entries[1] {
        tool.expanded = true;
    }
    cache.resplice_entries([1]);
    let mut after = Vec::new();
    cache.extend_visible_lines(
        &entries,
        s,
        HistoryLineSlice {
            start: 0,
            count: usize::MAX,
        },
        &mut after,
        &no_images,
    );

    let assistant_range_after = cache.entry_ranges[2].clone();
    assert!(
        after.len() > total_before,
        "expanded tool should grow the transcript"
    );
    assert_eq!(
        &after[assistant_range_after.clone()],
        &assistant_before[..],
        "assistant suffix lines must be preserved by content"
    );
    // Range must have shifted by the tool height delta.
    let delta = after.len() as isize - total_before as isize;
    assert_eq!(
        assistant_range_after.start as isize,
        assistant_range.start as isize + delta
    );

    // Full rebuild must match surgical result (correctness oracle).
    cache.invalidate_from(0);
    let mut rebuilt = Vec::new();
    cache.extend_visible_lines(
        &entries,
        s,
        HistoryLineSlice {
            start: 0,
            count: usize::MAX,
        },
        &mut rebuilt,
        &no_images,
    );
    assert_eq!(after, rebuilt);

    // Collapse again.
    if let Entry::Tool(tool) = &mut entries[1] {
        tool.expanded = false;
    }
    cache.resplice_entries([1]);
    let mut collapsed = Vec::new();
    cache.extend_visible_lines(
        &entries,
        s,
        HistoryLineSlice {
            start: 0,
            count: usize::MAX,
        },
        &mut collapsed,
        &no_images,
    );
    assert_eq!(collapsed.len(), total_before);
}

// Covers: per-entry image-height flags keep soft image-budget updates from
// re-rendering text-only entries.
// Owner: history line cache
#[test]
fn image_height_only_change_uses_cached_dependency_flags() {
    use image::{DynamicImage, ImageFormat};
    use ratatui_image::picker::{Picker, ProtocolType};
    use std::io::Cursor;

    let image = {
        let rgba = DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(
            300,
            600,
            image::Rgba([20, 40, 60, 255]),
        ));
        let mut bytes = Cursor::new(Vec::new());
        rgba.write_to(&mut bytes, ImageFormat::Png).unwrap();
        let mut picker = Picker::halfblocks();
        picker.set_protocol_type(ProtocolType::Kitty);
        FeedImage::load(
            &rho_sdk::tool::ToolAsset::new("image/png", bytes.into_inner()),
            &picker,
        )
        .unwrap()
    };
    let tool = Entry::Tool(crate::tui::ToolEntry::new(
        rho_tools::tool_card::ToolCard::new(
            rho_tools::tool_card::ToolStatus::Ok,
            rho_tools::tool_card::ToolFamily::Default,
            rho_tools::tool_card::ToolHeader::call("read_file photo.png", None),
        ),
        false,
        Some(image),
        None,
    ));
    let mut cache = HistoryLineCache::default();
    let entries = vec![
        Entry::User("prompt".into()),
        Entry::Assistant("text only".into()),
        tool,
    ];
    let mut base = settings(80);
    let _ = cache.line_count(&entries, base, &no_images);
    assert_eq!(
        cache
            .entries
            .iter()
            .map(|entry| entry.depends_on_image_height)
            .collect::<Vec<_>>(),
        vec![false, false, true]
    );

    let renders_before = cache.entry_render_count();
    base.max_image_height = base.max_image_height.saturating_add(8);
    let _ = cache.line_count(&entries, base, &no_images);
    assert_eq!(
        cache.entry_render_count(),
        renders_before + 1,
        "only the image-bearing entry must resplice when the budget moves"
    );
}

// Covers: composer/activity height changes must not re-render a text-only
// transcript when only the feed image budget moved.
// Owner: history line cache
#[test]
fn image_height_only_change_skips_text_only_entry_renders() {
    let mut cache = HistoryLineCache::default();
    let entries = vec![
        Entry::User("prompt".into()),
        Entry::Assistant("reply with `code` and **bold**".into()),
        Entry::Reasoning(crate::tui::ReasoningEntry::new("plan")),
    ];
    let mut base = settings(80);
    let _ = cache.line_count(&entries, base, &no_images);
    let renders_after_cold = cache.entry_render_count();
    assert!(renders_after_cold >= 3);

    base.max_image_height = base.max_image_height.saturating_add(8);
    let mut lines = Vec::new();
    cache.extend_visible_lines(
        &entries,
        base,
        HistoryLineSlice {
            start: 0,
            count: usize::MAX,
        },
        &mut lines,
        &no_images,
    );
    assert_eq!(
        cache.entry_render_count(),
        renders_after_cold,
        "text-only soft image-budget updates must not re-render entries"
    );
    assert!(!lines.is_empty());
}

// Covers: mouse hit-testing still maps lines to entries after binary search.
// Owner: history line cache
#[test]
fn entry_index_at_line_finds_ranges_across_transcript() {
    let mut cache = HistoryLineCache::default();
    let entries = vec![
        Entry::User("one".into()),
        Entry::Assistant("two\nthree".into()),
        Entry::Notice("four".into()),
    ];
    let s = settings(40);
    let total = cache.line_count(&entries, s, &no_images);
    assert!(total > 3);
    assert_eq!(
        cache.entry_index_at_line(&entries, s, 0, &no_images),
        Some(0)
    );
    let assistant_start = cache.entry_ranges[1].start;
    assert_eq!(
        cache.entry_index_at_line(&entries, s, assistant_start, &no_images),
        Some(1)
    );
    let last_line = total.saturating_sub(1);
    assert_eq!(
        cache.entry_index_at_line(&entries, s, last_line, &no_images),
        Some(2)
    );
    assert_eq!(
        cache.entry_index_at_line(&entries, s, total + 5, &no_images),
        None
    );
}

// Covers: resume-style unmeasured transcripts must wrap only a tail, not 0..n.
// Owner: history line cache
#[test]
fn ensure_suffix_does_not_render_unmeasured_prefix() {
    let mut cache = HistoryLineCache::default();
    let entries = (0..20)
        .map(|index| Entry::User(format!("message {index}")))
        .collect::<Vec<_>>();
    cache.mark_unmeasured(entries.len());

    cache.ensure_suffix(&entries, settings(80), 9, &no_images);

    // Each user entry is one content line + trailing blank (2 rows).
    assert_eq!(cache.line_count(&entries, settings(80), &no_images), 10);
    assert_eq!(cache.entry_render_count(), 5);
    let first_visible = cache
        .entry_index_at_line(&entries, settings(80), 0, &no_images)
        .expect("measured suffix starts at line 0");
    assert_eq!(first_visible, 15);
    assert_eq!(cache.entry_line_range(first_visible), Some(0..2));
    assert_eq!(cache.entry_line_range(0), None);
}

// Covers: scrolling above the measured suffix must wrap earlier entries only.
// Owner: history line cache
#[test]
fn grow_prefix_renders_earlier_entries_and_shifts_line_zero() {
    let mut cache = HistoryLineCache::default();
    let entries = (0..20)
        .map(|index| Entry::User(format!("message {index}")))
        .collect::<Vec<_>>();
    cache.mark_unmeasured(entries.len());
    cache.ensure_suffix(&entries, settings(80), 9, &no_images);
    let rendered = cache.entry_render_count();
    let prepended = cache.grow_prefix(&entries, settings(80), 4, &no_images);

    assert_eq!(prepended, 4);
    assert_eq!(cache.entry_render_count(), rendered + 2);
    assert_eq!(cache.line_count(&entries, settings(80), &no_images), 14);
    assert_eq!(
        cache.entry_index_at_line(&entries, settings(80), 0, &no_images),
        Some(13)
    );
}