agentty 0.14.4

Agentty is an ADE (Agentic Development Environment) for structured, controllable AI-assisted software development.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
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
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
use std::cell::RefCell;
use std::collections::{HashMap, VecDeque};
use std::hash::Hasher;
use std::ops::Range;
use std::path::Path;
use std::sync::Arc;

use ag_tui_text::text_util::{self, inline_text};
use ratatui::Frame;
use ratatui::layout::Rect;
use ratatui::style::Style;
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Paragraph};
use rustc_hash::FxHasher;

use crate::domain::session::Session;
use crate::presentation::app_mode::{DiffPreview, DiffPreviewUnavailableReason};
use crate::presentation::help_action;
use crate::ui::component::file_explorer::FileExplorer;
use crate::ui::component::vertical_scrollbar::VerticalScrollbar;
#[cfg(test)]
use crate::ui::component::vertical_scrollbar::{SCROLLBAR_THUMB_SYMBOL, SCROLLBAR_TRACK_SYMBOL};
use crate::ui::diff_util::{
    DiffLine, DiffLineKind, FileTreeItem, diff_header_new_path, parse_diff_lines,
};
use crate::ui::{Component, Page, diff_util, markdown, style};

const WRAPPED_CHUNK_START_INDEX: usize = 0;
const DIFF_CONTENT_CACHE_ENTRY_LIMIT: usize = 8;
const DIFF_LAYOUT_CACHE_ENTRY_LIMIT: usize = 16;

/// Compact identity for one raw diff string.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct DiffContentCacheKey {
    content_hash: u64,
    content_len: usize,
}

/// Cache key for one fully assembled diff-panel layout.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct DiffLayoutCacheKey {
    diff_area_height: u16,
    diff_area_width: u16,
    diff_content: DiffContentCacheKey,
    reserve_scrollbar_width: bool,
    selected_index: usize,
    style_version: u64,
}

/// Owned diff line retained by the parsed diff cache.
#[derive(Clone, Debug, Eq, PartialEq)]
struct OwnedDiffLine {
    content: String,
    kind: DiffLineKind,
    new_line: Option<u32>,
    old_line: Option<u32>,
}

impl OwnedDiffLine {
    /// Copies one borrowed parsed diff line into the content cache.
    fn from_diff_line(diff_line: DiffLine<'_>) -> Self {
        Self {
            content: diff_line.content.to_string(),
            kind: diff_line.kind,
            new_line: diff_line.new_line,
            old_line: diff_line.old_line,
        }
    }

    /// Returns this cached line as the borrowed representation expected by
    /// existing diff formatting helpers.
    fn borrowed(&self) -> DiffLine<'_> {
        DiffLine {
            content: &self.content,
            kind: self.kind,
            new_line: self.new_line,
            old_line: self.old_line,
        }
    }
}

/// Parsed diff data reused by file-tree rendering and diff layout assembly.
#[derive(Clone)]
pub(crate) struct DiffContentSnapshot {
    all_files_summary: DiffSelectionChangeSummary,
    file_line_ranges: Arc<HashMap<String, Vec<Range<usize>>>>,
    file_list_lines: Arc<[Line<'static>]>,
    key: DiffContentCacheKey,
    parsed_lines: Arc<[OwnedDiffLine]>,
    selection_summaries: Arc<[DiffSelectionChangeSummary]>,
    tree_items: Arc<[FileTreeItem]>,
}

/// Change totals for the currently selected diff tree item.
#[derive(Clone)]
struct DiffSelectionChangeSummary {
    added_lines: usize,
    label: String,
    removed_lines: usize,
}

/// Added/removed line totals accumulated while building cached summaries.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
struct DiffChangeTotals {
    added_lines: usize,
    removed_lines: usize,
}

impl DiffChangeTotals {
    /// Returns the change represented by one parsed diff line.
    fn from_line_kind(kind: DiffLineKind) -> Option<Self> {
        match kind {
            DiffLineKind::Addition => Some(Self {
                added_lines: 1,
                removed_lines: 0,
            }),
            DiffLineKind::Deletion => Some(Self {
                added_lines: 0,
                removed_lines: 1,
            }),
            DiffLineKind::Context | DiffLineKind::FileHeader | DiffLineKind::HunkHeader => None,
        }
    }

    /// Adds another set of totals to this accumulator.
    fn add(&mut self, totals: Self) {
        self.added_lines = self.added_lines.saturating_add(totals.added_lines);
        self.removed_lines = self.removed_lines.saturating_add(totals.removed_lines);
    }
}

impl DiffContentSnapshot {
    /// Returns cached file-explorer lines for the left diff panel.
    pub(crate) fn file_list_lines(&self) -> Arc<[Line<'static>]> {
        Arc::clone(&self.file_list_lines)
    }

    /// Returns the number of selectable file-tree entries in this diff.
    pub(crate) fn item_count(&self) -> usize {
        self.tree_items.len()
    }

    /// Returns cached diff body rows for `path` without walking unrelated
    /// files.
    pub(crate) fn file_lines(&self, path: &str) -> Vec<DiffLine<'_>> {
        let Some(ranges) = self.file_line_ranges.get(path) else {
            return Vec::new();
        };

        ranges
            .iter()
            .flat_map(|range| self.parsed_lines[range.clone()].iter())
            .filter(|line| {
                matches!(
                    line.kind,
                    DiffLineKind::Addition | DiffLineKind::Deletion | DiffLineKind::Context
                )
            })
            .map(OwnedDiffLine::borrowed)
            .collect()
    }

    /// Returns the selected repository-relative markdown file path.
    pub(crate) fn selected_markdown_path(&self, selected_index: usize) -> Option<&str> {
        let FileTreeItem::File(path) = self.tree_items.get(selected_index)? else {
            return None;
        };
        let extension = Path::new(path).extension()?.to_str()?;
        if !extension.eq_ignore_ascii_case("md") {
            return None;
        }

        Some(path)
    }

    /// Returns the label and added/removed line totals for the active
    /// file-tree selection, or the whole diff when the selection is stale.
    fn selected_change_summary(&self, selected_index: usize) -> &DiffSelectionChangeSummary {
        if let Some(summary) = self.selection_summaries.get(selected_index) {
            return summary;
        }

        &self.all_files_summary
    }

    /// Returns parsed lines for the active file-tree selection.
    fn selected_lines(&self, selected_index: usize) -> Vec<DiffLine<'_>> {
        let parsed_lines = self.borrowed_lines();
        let Some(selected_item) = self.tree_items.get(selected_index) else {
            return parsed_lines;
        };

        diff_util::filter_diff_lines(&parsed_lines, selected_item)
    }

    /// Returns the complete cached diff snapshot as borrowed lines.
    fn borrowed_lines(&self) -> Vec<DiffLine<'_>> {
        self.parsed_lines
            .iter()
            .map(OwnedDiffLine::borrowed)
            .collect()
    }

    /// Builds cached added/removed summaries for the full diff and each
    /// selectable tree item in one pass over parsed lines.
    fn change_summaries(
        parsed_lines: &[DiffLine<'_>],
        tree_items: &[FileTreeItem],
    ) -> (DiffSelectionChangeSummary, Vec<DiffSelectionChangeSummary>) {
        let mut all_files_totals = DiffChangeTotals::default();
        let mut current_path = None;
        let mut file_totals: HashMap<String, DiffChangeTotals> = HashMap::new();

        for diff_line in parsed_lines {
            if diff_line.kind == DiffLineKind::FileHeader
                && diff_line.content.starts_with("diff --git")
            {
                current_path = diff_header_new_path(diff_line.content);
                if let Some(path) = &current_path {
                    file_totals.entry(path.clone()).or_default();
                }

                continue;
            }

            let Some(line_totals) = DiffChangeTotals::from_line_kind(diff_line.kind) else {
                continue;
            };
            all_files_totals.add(line_totals);

            if let Some(totals) = current_path
                .as_ref()
                .and_then(|path| file_totals.get_mut(path))
            {
                totals.add(line_totals);
            }
        }

        let folder_totals = Self::folder_totals(&file_totals);
        let all_files_summary = DiffSelectionChangeSummary {
            added_lines: all_files_totals.added_lines,
            label: "all files".to_string(),
            removed_lines: all_files_totals.removed_lines,
        };
        let selection_summaries = tree_items
            .iter()
            .map(|item| {
                let totals = Self::tree_item_change_totals(item, &file_totals, &folder_totals);

                DiffSelectionChangeSummary {
                    added_lines: totals.added_lines,
                    label: tree_item_label(item),
                    removed_lines: totals.removed_lines,
                }
            })
            .collect();

        (all_files_summary, selection_summaries)
    }

    /// Indexes each old and new file path to its parsed-line ranges.
    fn file_line_ranges(parsed_lines: &[DiffLine<'_>]) -> HashMap<String, Vec<Range<usize>>> {
        let mut file_line_ranges = HashMap::new();
        let mut current_paths = None;
        let mut current_start_index = 0;

        for (line_index, line) in parsed_lines.iter().enumerate() {
            if line.kind != DiffLineKind::FileHeader || !line.content.starts_with("diff --git") {
                continue;
            }

            if let Some(paths) = current_paths.take() {
                Self::store_file_line_range(
                    &mut file_line_ranges,
                    paths,
                    current_start_index..line_index,
                );
            }
            current_paths = diff_util::diff_header_paths(line.content);
            current_start_index = line_index.saturating_add(1);
        }

        if let Some(paths) = current_paths {
            Self::store_file_line_range(
                &mut file_line_ranges,
                paths,
                current_start_index..parsed_lines.len(),
            );
        }

        file_line_ranges
    }

    /// Adds one file block under both rename-aware paths without duplication.
    fn store_file_line_range(
        file_line_ranges: &mut HashMap<String, Vec<Range<usize>>>,
        (old_path, new_path): (String, String),
        range: Range<usize>,
    ) {
        file_line_ranges
            .entry(old_path.clone())
            .or_default()
            .push(range.clone());
        if new_path != old_path {
            file_line_ranges.entry(new_path).or_default().push(range);
        }
    }

    /// Aggregates file-level change totals into folder-prefix totals.
    fn folder_totals(
        file_totals: &HashMap<String, DiffChangeTotals>,
    ) -> HashMap<String, DiffChangeTotals> {
        let mut folder_totals: HashMap<String, DiffChangeTotals> = HashMap::new();

        for (path, totals) in file_totals {
            for folder_prefix in Self::folder_prefixes(path) {
                folder_totals.entry(folder_prefix).or_default().add(*totals);
            }
        }

        folder_totals
    }

    /// Returns every folder prefix for a repository-relative path.
    fn folder_prefixes(path: &str) -> Vec<String> {
        path.char_indices()
            .filter_map(|(char_index, character)| {
                if character == '/' {
                    return Some(path[..=char_index].to_string());
                }

                None
            })
            .collect()
    }

    /// Looks up cached change totals for one file-tree item.
    fn tree_item_change_totals(
        item: &FileTreeItem,
        file_totals: &HashMap<String, DiffChangeTotals>,
        folder_totals: &HashMap<String, DiffChangeTotals>,
    ) -> DiffChangeTotals {
        match item {
            FileTreeItem::File(path) => file_totals.get(path.as_str()).copied().unwrap_or_default(),
            FileTreeItem::Folder(path) => folder_totals.get(path).copied().unwrap_or_default(),
        }
    }
}

/// Cached fully assembled diff lines for one render-affecting key.
#[derive(Clone)]
struct DiffCachedLayout {
    line_count: usize,
    lines: Arc<[Line<'static>]>,
    render_layout: diff_util::DiffRenderLayout,
}

/// Borrowed inputs used to derive or look up one cached diff layout.
#[derive(Clone, Copy)]
struct DiffLayoutRequest<'a> {
    content: &'a DiffContentSnapshot,
    diff_area: Rect,
    reserve_scrollbar_width: bool,
    selected_index: usize,
}

/// Final diff layout selected for the current panel and scrollbar state.
#[derive(Clone)]
pub(crate) struct DiffResolvedLayout {
    pub(crate) line_count: usize,
    pub(crate) lines: Arc<[Line<'static>]>,
    pub(crate) render_layout: diff_util::DiffRenderLayout,
    pub(crate) show_scrollbar: bool,
}

/// Final markdown-preview rows selected for the current panel width.
struct DiffPreviewLayout {
    lines: Arc<[Line<'static>]>,
    show_scrollbar: bool,
    viewport_height: u16,
}

/// Cached parsed diff snapshot entry.
struct DiffContentCacheEntry {
    key: DiffContentCacheKey,
    snapshot: DiffContentSnapshot,
}

/// Cached rendered diff layout entry.
struct DiffLayoutCacheEntry {
    key: DiffLayoutCacheKey,
    layout: DiffCachedLayout,
}

/// Bounded cache for parsed diff content and fully assembled diff layouts.
///
/// The parsed-content layer avoids re-parsing the same raw diff and rebuilding
/// file-tree metadata or per-path line ranges on every frame. Its key is the
/// raw diff's hash and byte length, so replacing the diff invalidates the
/// snapshot. The rendered-layout layer sits above styled diff assembly so
/// scroll metrics and frame painting
/// reuse the same rows until diff content, selection, panel width/height,
/// scrollbar gutter state, or the active style version changes. Both LRU
/// layers evict their oldest entries at their fixed limits.
pub struct DiffLayoutCache {
    content_entries: RefCell<VecDeque<DiffContentCacheEntry>>,
    layout_entries: RefCell<VecDeque<DiffLayoutCacheEntry>>,
}

impl Default for DiffLayoutCache {
    fn default() -> Self {
        Self {
            content_entries: RefCell::new(VecDeque::with_capacity(DIFF_CONTENT_CACHE_ENTRY_LIMIT)),
            layout_entries: RefCell::new(VecDeque::with_capacity(DIFF_LAYOUT_CACHE_ENTRY_LIMIT)),
        }
    }
}

impl DiffLayoutCache {
    /// Returns parsed diff and file-tree data from cache or derives it once.
    pub(crate) fn content(&self, diff: &str) -> DiffContentSnapshot {
        let key = Self::content_cache_key(diff);
        if let Some(snapshot) = self.cached_content(key) {
            return snapshot;
        }

        let parsed_lines = parse_diff_lines(diff);
        let (file_list_lines, tree_items) = FileExplorer::file_tree(&parsed_lines);
        let (all_files_summary, selection_summaries) =
            DiffContentSnapshot::change_summaries(&parsed_lines, &tree_items);
        let file_line_ranges = DiffContentSnapshot::file_line_ranges(&parsed_lines);
        let snapshot = DiffContentSnapshot {
            all_files_summary,
            file_line_ranges: Arc::new(file_line_ranges),
            file_list_lines: Arc::from(file_list_lines),
            key,
            parsed_lines: Arc::from(
                parsed_lines
                    .into_iter()
                    .map(OwnedDiffLine::from_diff_line)
                    .collect::<Vec<_>>(),
            ),
            selection_summaries: Arc::from(selection_summaries),
            tree_items: Arc::from(tree_items),
        };
        self.store_content(DiffContentCacheEntry {
            key,
            snapshot: snapshot.clone(),
        });

        snapshot
    }

    /// Returns the resolved diff layout for the current panel, using cached
    /// no-scrollbar line count to decide whether a gutter-reserved layout is
    /// required.
    pub(crate) fn resolved_layout(
        &self,
        content: &DiffContentSnapshot,
        selected_index: usize,
        diff_area: Rect,
    ) -> DiffResolvedLayout {
        let layout_without_scrollbar = self.layout(DiffLayoutRequest {
            content,
            diff_area,
            reserve_scrollbar_width: false,
            selected_index,
        });
        let show_scrollbar = diff_util::diff_has_scrollable_overflow(
            layout_without_scrollbar.line_count,
            layout_without_scrollbar.render_layout.viewport_height,
        );
        if !show_scrollbar {
            return DiffResolvedLayout {
                line_count: layout_without_scrollbar.line_count,
                lines: layout_without_scrollbar.lines,
                render_layout: layout_without_scrollbar.render_layout,
                show_scrollbar: false,
            };
        }

        let layout_with_scrollbar = self.layout(DiffLayoutRequest {
            content,
            diff_area,
            reserve_scrollbar_width: true,
            selected_index,
        });
        let show_scrollbar = diff_util::diff_has_scrollable_overflow(
            layout_with_scrollbar.line_count,
            layout_with_scrollbar.render_layout.viewport_height,
        );

        DiffResolvedLayout {
            line_count: layout_with_scrollbar.line_count,
            lines: layout_with_scrollbar.lines,
            render_layout: layout_with_scrollbar.render_layout,
            show_scrollbar,
        }
    }

    /// Returns cached parsed content for a matching diff fingerprint and
    /// promotes the entry to the front of the LRU queue.
    fn cached_content(&self, key: DiffContentCacheKey) -> Option<DiffContentSnapshot> {
        let mut entries = self.content_entries.borrow_mut();
        let entry_index = entries.iter().position(|entry| entry.key == key)?;
        let entry = entries.remove(entry_index)?;
        let snapshot = entry.snapshot.clone();
        entries.push_front(entry);

        Some(snapshot)
    }

    /// Stores one parsed-content entry and evicts the oldest entry when the
    /// bounded capacity is exceeded.
    fn store_content(&self, entry: DiffContentCacheEntry) {
        let mut entries = self.content_entries.borrow_mut();
        entries.push_front(entry);

        while entries.len() > DIFF_CONTENT_CACHE_ENTRY_LIMIT {
            entries.pop_back();
        }
    }

    /// Returns cached rendered diff rows, or assembles and stores them when
    /// any render-affecting input changed.
    fn layout(&self, request: DiffLayoutRequest<'_>) -> DiffCachedLayout {
        let DiffLayoutRequest {
            content,
            diff_area,
            reserve_scrollbar_width,
            selected_index,
        } = request;
        let key = DiffLayoutCacheKey {
            diff_area_height: diff_area.height,
            diff_area_width: diff_area.width,
            diff_content: content.key,
            reserve_scrollbar_width,
            selected_index,
            style_version: style::active_theme_cache_version(),
        };
        if let Some(layout) = self.cached_layout(&key) {
            return layout;
        }

        let selected_lines = content.selected_lines(selected_index);
        let render_layout =
            diff_util::diff_render_layout(&selected_lines, diff_area, reserve_scrollbar_width);
        let lines = DiffPage::build_diff_lines(&selected_lines, render_layout);
        let layout = DiffCachedLayout {
            line_count: lines.len(),
            lines: Arc::from(lines),
            render_layout,
        };
        self.store_layout(DiffLayoutCacheEntry {
            key,
            layout: layout.clone(),
        });

        layout
    }

    /// Returns cached rendered layout for a matching entry and promotes it to
    /// the front of the LRU queue.
    fn cached_layout(&self, key: &DiffLayoutCacheKey) -> Option<DiffCachedLayout> {
        let mut entries = self.layout_entries.borrow_mut();
        let entry_index = entries.iter().position(|entry| &entry.key == key)?;
        let entry = entries.remove(entry_index)?;
        let layout = entry.layout.clone();
        entries.push_front(entry);

        Some(layout)
    }

    /// Stores one rendered layout and evicts the oldest entries over the
    /// bounded capacity.
    fn store_layout(&self, entry: DiffLayoutCacheEntry) {
        let mut entries = self.layout_entries.borrow_mut();
        entries.push_front(entry);

        while entries.len() > DIFF_LAYOUT_CACHE_ENTRY_LIMIT {
            entries.pop_back();
        }
    }

    /// Returns a compact key for the raw diff string.
    fn content_cache_key(diff: &str) -> DiffContentCacheKey {
        let mut hasher = FxHasher::default();
        hasher.write(diff.as_bytes());

        DiffContentCacheKey {
            content_hash: hasher.finish(),
            content_len: diff.len(),
        }
    }
}

/// Renders the current session's git diff in a scrollable page.
pub struct DiffPage<'a> {
    /// Raw unified diff currently shown by the page.
    pub diff: &'a str,
    /// Shared cache for parsed diff content and rendered layouts.
    pub diff_layout_cache: &'a DiffLayoutCache,
    /// Selected file-tree row in the left panel.
    pub file_explorer_selected_index: usize,
    /// Shared cache for rendered markdown preview rows.
    pub markdown_render_cache: &'a markdown::MarkdownRenderCache,
    /// Rendered-markdown preview state for the selected file.
    pub preview: &'a DiffPreview,
    /// Vertical scroll offset inside the diff panel.
    pub scroll_offset: u16,
    /// Session whose diff is being rendered.
    pub session: &'a Session,
}

/// Borrowed inputs required to construct a [`DiffPage`] for one frame.
#[derive(Clone, Copy)]
pub struct DiffPageInput<'a> {
    /// Raw unified diff currently shown by the page.
    pub diff: &'a str,
    /// Shared cache for parsed diff content and rendered diff layouts.
    pub diff_layout_cache: &'a DiffLayoutCache,
    /// Selected file-tree row in the left panel.
    pub file_explorer_selected_index: usize,
    /// Shared cache for rendered markdown preview rows.
    pub markdown_render_cache: &'a markdown::MarkdownRenderCache,
    /// Rendered-markdown preview state for the selected file.
    pub preview: &'a DiffPreview,
    /// Vertical scroll offset inside the diff panel.
    pub scroll_offset: u16,
    /// Session whose diff is being rendered.
    pub session: &'a Session,
}

impl<'a> DiffPage<'a> {
    /// Creates a diff page for the given session and scroll position.
    pub fn new(input: DiffPageInput<'a>) -> Self {
        let DiffPageInput {
            diff,
            diff_layout_cache,
            file_explorer_selected_index,
            markdown_render_cache,
            preview,
            scroll_offset,
            session,
        } = input;

        Self {
            diff,
            diff_layout_cache,
            file_explorer_selected_index,
            markdown_render_cache,
            preview,
            scroll_offset,
            session,
        }
    }

    /// Renders the right-side diff panel with line-number gutters and
    /// change totals prefixed in the title.
    fn render_diff_content(
        &self,
        f: &mut Frame,
        area: Rect,
        content: &DiffContentSnapshot,
        total_added_lines: u64,
        total_removed_lines: u64,
    ) {
        let selection_summary = content.selected_change_summary(self.file_explorer_selected_index);
        let title = Line::from(vec![
            Span::styled(" (", Style::default().fg(style::palette::warning())),
            Span::styled(
                format!("+{total_added_lines}"),
                Style::default().fg(style::palette::success()),
            ),
            Span::styled(" ", Style::default().fg(style::palette::warning())),
            Span::styled(
                format!("-{total_removed_lines}"),
                Style::default().fg(style::palette::danger()),
            ),
            Span::styled(
                format!(") Diff — {} ", inline_text(self.session.display_title())),
                Style::default().fg(style::palette::warning()),
            ),
            Span::styled("· ", Style::default().fg(style::palette::warning())),
            Span::styled(
                format!("{} ", inline_text(&selection_summary.label)),
                Style::default().fg(style::palette::text_muted()),
            ),
            Span::styled(
                format!("+{}", selection_summary.added_lines),
                Style::default().fg(style::palette::success()),
            ),
            Span::styled(" ", Style::default().fg(style::palette::warning())),
            Span::styled(
                format!("-{}", selection_summary.removed_lines),
                Style::default().fg(style::palette::danger()),
            ),
            Span::styled(" ", Style::default().fg(style::palette::warning())),
        ]);

        let layout = self.diff_layout_cache.resolved_layout(
            content,
            self.file_explorer_selected_index,
            area,
        );

        let scroll_offset = diff_util::clamp_diff_scroll_offset(
            self.scroll_offset,
            layout.line_count,
            layout.render_layout.viewport_height,
        );
        let paint_lines = Self::borrowed_visible_lines(
            &layout.lines,
            scroll_offset,
            layout.render_layout.viewport_height,
        );

        let paragraph = Paragraph::new(paint_lines).block(
            Block::default()
                .borders(Borders::ALL)
                .title(title)
                .border_style(style::border_style()),
        );

        f.render_widget(paragraph, area);

        if layout.show_scrollbar {
            let scrollbar_area =
                diff_util::diff_scrollbar_area(area, layout.render_layout.viewport_height);

            VerticalScrollbar::new(scroll_offset, layout.line_count).render(f, scrollbar_area);
        }
    }

    /// Renders ready markdown content or a preview availability notice.
    fn render_preview_content(&self, frame: &mut Frame, area: Rect, path: &str) {
        let title = Line::from(Span::styled(
            format!(" Preview — {} ", inline_text(path)),
            Style::default().fg(style::palette::warning()),
        ));
        match self.preview {
            DiffPreview::Ready { content, .. } => {
                let layout = diff_preview_layout(content, area, self.markdown_render_cache);
                let scroll_offset = diff_util::clamp_diff_scroll_offset(
                    self.scroll_offset,
                    layout.lines.len(),
                    layout.viewport_height,
                );
                let paint_lines = Self::borrowed_visible_lines(
                    &layout.lines,
                    scroll_offset,
                    layout.viewport_height,
                );
                let paragraph = Paragraph::new(paint_lines).block(
                    Block::default()
                        .borders(Borders::ALL)
                        .title(title)
                        .border_style(style::border_style()),
                );
                frame.render_widget(paragraph, area);

                if layout.show_scrollbar {
                    let scrollbar_area =
                        diff_util::diff_scrollbar_area(area, layout.viewport_height);
                    VerticalScrollbar::new(scroll_offset, layout.lines.len())
                        .render(frame, scrollbar_area);
                }
            }
            DiffPreview::Loading { .. } => {
                render_preview_notice(frame, area, title, " Loading preview… ");
            }
            DiffPreview::Unavailable { reason, .. } => {
                render_preview_notice(frame, area, title, preview_unavailable_message(reason));
            }
            DiffPreview::Off { .. } | DiffPreview::Unsupported { .. } => {}
        }
    }

    /// Builds short-lived paint rows for the visible viewport slice, borrowing
    /// span content from cached static diff rows instead of cloning the whole
    /// diff on every scroll repaint.
    fn borrowed_visible_lines<'line>(
        lines: &'line [Line<'static>],
        scroll_offset: u16,
        viewport_height: u16,
    ) -> Vec<Line<'line>> {
        let start_index = usize::from(scroll_offset).min(lines.len());
        let end_index = start_index
            .saturating_add(usize::from(viewport_height))
            .min(lines.len());

        lines[start_index..end_index]
            .iter()
            .map(text_util::borrowed_paint_line)
            .collect()
    }

    /// Builds wrapped diff lines for the diff panel, optionally reserving one
    /// column for the scrollbar thumb.
    fn build_diff_lines(
        parsed: &[DiffLine<'_>],
        layout: diff_util::DiffRenderLayout,
    ) -> Vec<Line<'static>> {
        let gutter_style = diff_util::body_diff_line_gutter_style();
        let mut lines: Vec<Line<'static>> = Vec::with_capacity(parsed.len());

        for diff_line in parsed {
            if Self::append_special_diff_line(&mut lines, diff_line) {
                continue;
            }

            Self::append_body_diff_line(&mut lines, diff_line, layout, gutter_style);
        }

        if lines.is_empty() {
            lines.push(Line::from(" No changes found. "));
        }

        lines
    }

    /// Appends file and hunk headers, returning whether the line was consumed.
    fn append_special_diff_line(lines: &mut Vec<Line<'static>>, diff_line: &DiffLine<'_>) -> bool {
        match diff_line.kind {
            DiffLineKind::FileHeader => {
                Self::append_file_header_diff_line(lines, diff_line);

                true
            }
            DiffLineKind::HunkHeader => {
                lines.push(Line::from(Span::styled(
                    diff_line.content.to_string(),
                    Style::default().fg(style::palette::accent()),
                )));

                true
            }
            DiffLineKind::Addition | DiffLineKind::Deletion | DiffLineKind::Context => false,
        }
    }

    /// Appends one file-header diff line.
    fn append_file_header_diff_line(lines: &mut Vec<Line<'static>>, diff_line: &DiffLine<'_>) {
        if diff_line.content.starts_with("diff ") && !lines.is_empty() {
            lines.push(Line::from(""));
        }
        lines.push(Line::from(Span::styled(
            diff_line.content.to_string(),
            Style::default().fg(style::palette::warning()),
        )));
    }

    /// Appends one addition, deletion, or context line with wrapped content.
    fn append_body_diff_line(
        lines: &mut Vec<Line<'static>>,
        diff_line: &DiffLine<'_>,
        layout: diff_util::DiffRenderLayout,
        gutter_style: Style,
    ) {
        let (sign, content_style) = diff_util::body_diff_line_style(diff_line.kind);
        let gutter_text = diff_util::body_diff_line_gutter(diff_line, layout.gutter_width);
        let content_available = layout.content_width.saturating_sub(layout.prefix_width);
        let chunks = diff_util::wrap_diff_content(diff_line.content, content_available);

        for (index, chunk) in chunks.iter().enumerate() {
            if index == WRAPPED_CHUNK_START_INDEX {
                lines.push(Line::from(vec![
                    Span::styled(gutter_text.clone(), gutter_style),
                    Span::styled(sign, content_style),
                    Span::styled((*chunk).to_string(), content_style),
                ]));
            } else {
                lines.push(Line::from(vec![
                    Span::styled(" ".repeat(layout.prefix_width), gutter_style),
                    Span::styled((*chunk).to_string(), content_style),
                ]));
            }
        }
    }
}

/// Returns the max valid scroll offset for the selected diff panel.
pub(crate) fn diff_view_max_scroll_offset(
    diff: &str,
    selected_index: usize,
    terminal_area: Rect,
    diff_layout_cache: &DiffLayoutCache,
    markdown_render_cache: &markdown::MarkdownRenderCache,
    preview: &DiffPreview,
) -> u16 {
    let diff_area = diff_util::diff_page_areas(terminal_area).diff_area;
    let content = diff_layout_cache.content(diff);
    if preview_path_for_selection(preview, &content, selected_index).is_some() {
        return match preview {
            DiffPreview::Ready {
                content: markdown_content,
                ..
            } => {
                let layout =
                    diff_preview_layout(markdown_content, diff_area, markdown_render_cache);

                diff_util::clamp_diff_scroll_offset(
                    u16::MAX,
                    layout.lines.len(),
                    layout.viewport_height,
                )
            }
            _ => 0,
        };
    }
    let layout = diff_layout_cache.resolved_layout(&content, selected_index, diff_area);
    if layout.render_layout.viewport_height == 0 {
        return 0;
    }

    diff_util::clamp_diff_scroll_offset(
        u16::MAX,
        layout.line_count,
        layout.render_layout.viewport_height,
    )
}

impl Page for DiffPage<'_> {
    fn render(&mut self, f: &mut Frame, area: Rect) {
        let areas = diff_util::diff_page_areas(area);
        let content = self.diff_layout_cache.content(self.diff);

        FileExplorer::from_cached_lines(content.file_list_lines())
            .selected_index(self.file_explorer_selected_index)
            .render(f, areas.file_list_area);

        if let Some(path) =
            preview_path_for_selection(self.preview, &content, self.file_explorer_selected_index)
        {
            self.render_preview_content(f, areas.diff_area, path);
        } else {
            self.render_diff_content(
                f,
                areas.diff_area,
                &content,
                self.session.stats.added_lines,
                self.session.stats.deleted_lines,
            );
        }

        let help_message = Paragraph::new(crate::ui::help_format::footer_line(
            &help_action::diff_footer_actions(),
        ));
        f.render_widget(help_message, areas.footer_area);
    }
}

/// Returns the preview path when it still matches the active markdown row.
fn preview_path_for_selection<'a>(
    preview: &'a DiffPreview,
    content: &DiffContentSnapshot,
    selected_index: usize,
) -> Option<&'a str> {
    let selected_path = content.selected_markdown_path(selected_index)?;
    let preview_path = preview.path()?;
    if preview_path != selected_path {
        return None;
    }

    Some(preview_path)
}

/// Resolves cached markdown rows with a scrollbar-width second pass.
fn diff_preview_layout(
    content: &str,
    area: Rect,
    markdown_render_cache: &markdown::MarkdownRenderCache,
) -> DiffPreviewLayout {
    let viewport_height = area.height.saturating_sub(2);
    let content_width = usize::from(area.width.saturating_sub(2));
    let lines_without_scrollbar = markdown_render_cache.render(content, content_width);
    let show_scrollbar =
        diff_util::diff_has_scrollable_overflow(lines_without_scrollbar.len(), viewport_height);
    let lines = if show_scrollbar {
        markdown_render_cache.render(content, content_width.saturating_sub(1))
    } else {
        lines_without_scrollbar
    };

    DiffPreviewLayout {
        show_scrollbar: diff_util::diff_has_scrollable_overflow(lines.len(), viewport_height),
        lines,
        viewport_height,
    }
}

/// Renders one bordered preview loading or availability message.
fn render_preview_notice(frame: &mut Frame, area: Rect, title: Line<'static>, message: &str) {
    let paragraph = Paragraph::new(Line::from(message.to_string())).block(
        Block::default()
            .borders(Borders::ALL)
            .title(title)
            .border_style(style::border_style()),
    );
    frame.render_widget(paragraph, area);
}

/// Returns the concise notice for one unavailable preview reason.
fn preview_unavailable_message(reason: &DiffPreviewUnavailableReason) -> &str {
    match reason {
        DiffPreviewUnavailableReason::Deleted => " File deleted in this change. ",
        DiffPreviewUnavailableReason::Binary => " Binary file — no preview. ",
        DiffPreviewUnavailableReason::TooLarge => " File too large to preview. ",
        DiffPreviewUnavailableReason::LoadFailed(error) => error,
    }
}

/// Returns a compact display label for one file-tree selection.
fn tree_item_label(item: &FileTreeItem) -> String {
    match item {
        FileTreeItem::Folder(path) | FileTreeItem::File(path) => path.clone(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::domain::theme::ColorTheme;
    use crate::test_support::SessionFixtureBuilder;
    use crate::ui::diff_util::{parse_diff_lines, selected_diff_lines};

    const SAMPLE_DIFF: &str = concat!(
        "diff --git a/src/main.rs b/src/main.rs\n",
        "+added in main\n",
        "diff --git a/README.md b/README.md\n",
        "+added in readme\n"
    );

    fn session_fixture() -> Session {
        SessionFixtureBuilder::new()
            .title(Some("Diff Session".to_string()))
            .build()
    }

    fn new_diff_page<'a>(
        session: &'a Session,
        diff: &'a str,
        scroll_offset: u16,
        file_explorer_selected_index: usize,
    ) -> DiffPage<'a> {
        DiffPage::new(DiffPageInput {
            diff,
            diff_layout_cache: test_diff_layout_cache(),
            file_explorer_selected_index,
            markdown_render_cache: test_markdown_render_cache(),
            preview: test_diff_preview(),
            scroll_offset,
            session,
        })
    }

    fn new_diff_page_with_preview<'a>(
        session: &'a Session,
        diff: &'a str,
        scroll_offset: u16,
        file_explorer_selected_index: usize,
        preview: &'a DiffPreview,
    ) -> DiffPage<'a> {
        DiffPage::new(DiffPageInput {
            diff,
            diff_layout_cache: test_diff_layout_cache(),
            file_explorer_selected_index,
            markdown_render_cache: test_markdown_render_cache(),
            preview,
            scroll_offset,
            session,
        })
    }

    fn test_diff_layout_cache() -> &'static DiffLayoutCache {
        Box::leak(Box::new(DiffLayoutCache::default()))
    }

    fn test_markdown_render_cache() -> &'static markdown::MarkdownRenderCache {
        Box::leak(Box::new(markdown::MarkdownRenderCache::default()))
    }

    fn test_diff_preview() -> &'static DiffPreview {
        Box::leak(Box::new(DiffPreview::default()))
    }

    fn buffer_text(buffer: &ratatui::buffer::Buffer) -> String {
        buffer
            .content()
            .iter()
            .map(ratatui::buffer::Cell::symbol)
            .collect()
    }

    fn background_cell_count(
        buffer: &ratatui::buffer::Buffer,
        color: ratatui::style::Color,
    ) -> usize {
        buffer
            .content()
            .iter()
            .filter(|cell| cell.bg == color)
            .count()
    }

    fn foreground_symbol_cell_count(buffer: &ratatui::buffer::Buffer, symbol: &str) -> usize {
        buffer
            .content()
            .iter()
            .filter(|cell| cell.symbol() == symbol && cell.fg == style::palette::border())
            .count()
    }

    #[test]
    fn test_diff_layout_cache_reuses_parsed_content_snapshot() {
        // Arrange
        let cache = DiffLayoutCache::default();

        // Act
        let first_content = cache.content(SAMPLE_DIFF);
        let second_content = cache.content(SAMPLE_DIFF);

        // Assert
        assert!(Arc::ptr_eq(
            &first_content.parsed_lines,
            &second_content.parsed_lines
        ));
        assert!(Arc::ptr_eq(
            &first_content.file_line_ranges,
            &second_content.file_line_ranges
        ));
        assert!(Arc::ptr_eq(
            &first_content.file_list_lines,
            &second_content.file_list_lines
        ));
        assert!(Arc::ptr_eq(
            &first_content.selection_summaries,
            &second_content.selection_summaries
        ));
    }

    #[test]
    fn test_diff_content_snapshot_indexes_repeated_and_renamed_file_blocks() {
        // Arrange
        let cache = DiffLayoutCache::default();
        let content = cache.content(concat!(
            "diff --git a/src/old.rs b/src/new.rs\n",
            "index 111..222 100644\n",
            "@@ -1 +1 @@\n",
            "-old first\n",
            "+new first\n",
            "diff --git malformed\n",
            "+ignored malformed\n",
            "diff --git a/src/new.rs b/src/new.rs\n",
            "@@ -2 +2 @@\n",
            " unchanged second\n",
        ));

        // Act
        let old_path_lines = content.file_lines("src/old.rs");
        let new_path_lines = content.file_lines("src/new.rs");
        let missing_path_lines = content.file_lines("src/missing.rs");

        // Assert
        assert_eq!(
            old_path_lines
                .iter()
                .map(|line| line.content)
                .collect::<Vec<_>>(),
            vec!["old first", "new first"]
        );
        assert_eq!(
            new_path_lines
                .iter()
                .map(|line| line.content)
                .collect::<Vec<_>>(),
            vec!["old first", "new first", "unchanged second"]
        );
        assert!(missing_path_lines.is_empty());
    }

    #[test]
    fn test_diff_content_snapshot_caches_selection_change_summaries() {
        // Arrange
        let cache = DiffLayoutCache::default();
        let content = cache.content(concat!(
            "diff --git a/src/main.rs b/src/main.rs\n",
            "@@ -1,2 +1,3 @@\n",
            " unchanged\n",
            "+added main\n",
            "-removed main\n",
            "diff --git a/src/ui/diff.rs b/src/ui/diff.rs\n",
            "@@ -1 +1,2 @@\n",
            "+added nested\n",
            "diff --git a/README.md b/README.md\n",
            "@@ -1 +1,2 @@\n",
            "+added readme\n",
        ));

        // Act
        let folder_summary = content.selected_change_summary(0);
        let nested_folder_summary = content.selected_change_summary(1);
        let file_summary = content.selected_change_summary(3);
        let stale_summary = content.selected_change_summary(usize::MAX);

        // Assert
        assert_eq!(folder_summary.label, "src/");
        assert_eq!(folder_summary.added_lines, 2);
        assert_eq!(folder_summary.removed_lines, 1);
        assert_eq!(nested_folder_summary.label, "src/ui/");
        assert_eq!(nested_folder_summary.added_lines, 1);
        assert_eq!(nested_folder_summary.removed_lines, 0);
        assert_eq!(file_summary.label, "src/main.rs");
        assert_eq!(file_summary.added_lines, 1);
        assert_eq!(file_summary.removed_lines, 1);
        assert_eq!(stale_summary.label, "all files");
        assert_eq!(stale_summary.added_lines, 3);
        assert_eq!(stale_summary.removed_lines, 1);
    }

    #[test]
    fn test_selected_markdown_path_accepts_case_insensitive_file_extension_only() {
        // Arrange
        let cache = DiffLayoutCache::default();
        let content = cache.content(concat!(
            "diff --git a/docs/GUIDE.MD b/docs/GUIDE.MD\n+guide\n",
            "diff --git a/src/main.rs b/src/main.rs\n+code\n",
        ));

        // Act
        let folder = content.selected_markdown_path(0);
        let markdown = content.selected_markdown_path(1);
        let rust = content.selected_markdown_path(3);
        let stale = content.selected_markdown_path(usize::MAX);

        // Assert
        assert_eq!(folder, None);
        assert_eq!(markdown, Some("docs/GUIDE.MD"));
        assert_eq!(rust, None);
        assert_eq!(stale, None);
    }

    #[test]
    fn test_selected_markdown_preview_path_decodes_git_quoted_filename() {
        // Arrange
        let cache = DiffLayoutCache::default();
        let content = cache.content(concat!(
            "diff --git \"a/docs/\\346\\227\\245\\346\\234\\254.md\" ",
            "\"b/docs/\\346\\227\\245\\346\\234\\254.md\"\n+preview\n",
        ));
        let preview = DiffPreview::Ready {
            content: "# Preview".to_string(),
            path: "docs/日本.md".to_string(),
            request_id: 1,
        };

        // Act
        let selected_path = content.selected_markdown_path(1);
        let preview_path = preview_path_for_selection(&preview, &content, 1);

        // Assert
        assert_eq!(selected_path, Some("docs/日本.md"));
        assert_eq!(preview_path, Some("docs/日本.md"));
    }

    #[test]
    fn test_disabled_preview_states_do_not_resolve_or_render_preview_content() {
        // Arrange
        let session = session_fixture();
        let cache = DiffLayoutCache::default();
        let content = cache.content(SAMPLE_DIFF);
        let previews = [
            DiffPreview::Off { request_id: 1 },
            DiffPreview::Unsupported { request_id: 2 },
        ];
        let backend = ratatui::backend::TestBackend::new(80, 20);
        let mut terminal = ratatui::Terminal::new(backend).expect("failed to create terminal");

        // Act
        for preview in &previews {
            assert!(preview_path_for_selection(preview, &content, 1).is_none());
            terminal
                .draw(|frame| {
                    new_diff_page_with_preview(&session, SAMPLE_DIFF, 0, 1, preview)
                        .render_preview_content(frame, frame.area(), "README.md");
                })
                .expect("failed to draw disabled preview state");
        }

        // Assert
        assert_eq!(buffer_text(terminal.backend().buffer()).trim(), "");
    }

    #[test]
    fn test_diff_layout_cache_reuses_rendered_layout_rows() {
        // Arrange
        let cache = DiffLayoutCache::default();
        let content = cache.content(SAMPLE_DIFF);
        let area = Rect::new(0, 0, 80, 12);

        // Act
        let first_layout = cache.resolved_layout(&content, 0, area);
        let second_layout = cache.resolved_layout(&content, 0, area);

        // Assert
        assert!(Arc::ptr_eq(&first_layout.lines, &second_layout.lines));
        assert_eq!(first_layout.line_count, second_layout.line_count);
    }

    #[test]
    fn test_render_shows_updated_diff_help_hint() {
        // Arrange
        let _theme_scope = style::scoped_active_theme(ColorTheme::Current);
        let mut session = session_fixture();
        session.stats.added_lines = 1;
        session.stats.deleted_lines = 0;
        let diff = "diff --git a/src/main.rs b/src/main.rs\n+added";
        let mut diff_page = new_diff_page(&session, diff, 0, 0);
        let backend = ratatui::backend::TestBackend::new(120, 30);
        let mut terminal = ratatui::Terminal::new(backend).expect("failed to create terminal");

        // Act
        terminal
            .draw(|frame| {
                let area = frame.area();
                Page::render(&mut diff_page, frame, area);
            })
            .expect("failed to draw diff page");

        // Assert
        let buffer = terminal.backend().buffer();
        let text = buffer_text(buffer);
        assert!(text.contains("(+1 -0) Diff — Diff Session"));
        assert!(text.contains("src/ +1 -0"));
        assert!(text.contains("j/k: select file"));
        assert!(text.contains("?: help"));
        assert!(foreground_symbol_cell_count(buffer, "┌") >= 2);
    }

    #[test]
    fn test_render_diff_title_uses_persisted_session_line_totals() {
        // Arrange
        let mut session = session_fixture();
        session.stats.added_lines = 9;
        session.stats.deleted_lines = 4;
        let diff = "diff --git a/src/main.rs b/src/main.rs\n+added";
        let mut diff_page = new_diff_page(&session, diff, 0, 0);
        let backend = ratatui::backend::TestBackend::new(120, 30);
        let mut terminal = ratatui::Terminal::new(backend).expect("failed to create terminal");

        // Act
        terminal
            .draw(|frame| {
                let area = frame.area();
                Page::render(&mut diff_page, frame, area);
            })
            .expect("failed to draw diff page");

        // Assert
        let text = buffer_text(terminal.backend().buffer());
        assert!(text.contains("(+9 -4) Diff — Diff Session"));
        assert!(text.contains("src/ +1 -0"));
        assert!(!text.contains("(+1 -0) Diff — Diff Session"));
    }

    #[test]
    fn test_selected_diff_lines_returns_filtered_section_for_selected_file() {
        // Arrange
        let parsed_lines = parse_diff_lines(SAMPLE_DIFF);
        let tree_items = FileExplorer::file_tree_items(&parsed_lines);

        // Act
        let selected_lines = selected_diff_lines(&parsed_lines, &tree_items, 1);

        // Assert
        assert_eq!(selected_lines.len(), 2);
        assert_eq!(
            selected_lines[0].content,
            "diff --git a/src/main.rs b/src/main.rs"
        );
        assert_eq!(selected_lines[1].content, "added in main");
    }

    #[test]
    fn test_selected_diff_lines_returns_full_diff_when_index_is_out_of_bounds() {
        // Arrange
        let parsed_lines = parse_diff_lines(SAMPLE_DIFF);
        let tree_items = FileExplorer::file_tree_items(&parsed_lines);

        // Act
        let selected_lines = selected_diff_lines(&parsed_lines, &tree_items, usize::MAX);

        // Assert
        assert_eq!(selected_lines.len(), parsed_lines.len());
        assert_eq!(selected_lines[0].content, parsed_lines[0].content);
        assert_eq!(selected_lines[3].content, parsed_lines[3].content);
    }

    #[test]
    fn test_render_applies_background_tints_to_changed_lines() {
        // Arrange
        let session = session_fixture();
        let diff = concat!(
            "diff --git a/src/main.rs b/src/main.rs\n",
            "@@ -1,2 +1,2 @@\n",
            "-old content\n",
            "+new content\n"
        );
        let mut diff_page = new_diff_page(&session, diff, 0, 0);
        let backend = ratatui::backend::TestBackend::new(120, 30);
        let mut terminal = ratatui::Terminal::new(backend).expect("failed to create terminal");

        // Act
        terminal
            .draw(|frame| {
                let area = frame.area();
                Page::render(&mut diff_page, frame, area);
            })
            .expect("failed to draw diff page");

        // Assert
        let buffer = terminal.backend().buffer();
        assert!(
            background_cell_count(buffer, style::palette::surface_success()) > 0,
            "expected added lines to include success background tint"
        );
        assert!(
            background_cell_count(buffer, style::palette::surface_danger()) > 0,
            "expected removed lines to include danger background tint"
        );
    }

    #[test]
    fn test_render_shows_scrollbar_for_overflowing_diff() {
        // Arrange
        let session = session_fixture();
        let diff = (0..80)
            .map(|index| format!("+line {index}"))
            .collect::<Vec<_>>()
            .join("\n");
        let mut diff_page = new_diff_page(&session, &diff, 12, 0);
        let backend = ratatui::backend::TestBackend::new(80, 12);
        let mut terminal = ratatui::Terminal::new(backend).expect("failed to create terminal");

        // Act
        terminal
            .draw(|frame| {
                let area = frame.area();
                Page::render(&mut diff_page, frame, area);
            })
            .expect("failed to draw diff page");

        // Assert
        let text = buffer_text(terminal.backend().buffer());
        assert!(text.contains(SCROLLBAR_TRACK_SYMBOL));
        assert!(text.contains(SCROLLBAR_THUMB_SYMBOL));
    }

    #[test]
    fn test_render_ready_preview_uses_shared_markdown_and_mermaid_renderer() {
        // Arrange
        let session = session_fixture();
        let diff = "diff --git a/README.md b/README.md\n+preview";
        let preview = DiffPreview::Ready {
            content: concat!(
                "# Preview Title\n\n",
                "| Name | Value |\n| --- | --- |\n| mode | ready |\n\n",
                "```mermaid\ngraph TD\nA[Input] --> B[Rendered]\n```\n",
            )
            .to_string(),
            path: "README.md".to_string(),
            request_id: 1,
        };
        let mut diff_page = new_diff_page_with_preview(&session, diff, 0, 0, &preview);
        let backend = ratatui::backend::TestBackend::new(120, 30);
        let mut terminal = ratatui::Terminal::new(backend).expect("failed to create terminal");

        // Act
        terminal
            .draw(|frame| {
                let area = frame.area();
                Page::render(&mut diff_page, frame, area);
            })
            .expect("failed to draw markdown preview");

        // Assert
        let text = buffer_text(terminal.backend().buffer());
        assert!(text.contains("Preview — README.md"));
        assert!(text.contains("Preview Title"));
        assert!(text.contains("mode"));
        assert!(text.contains("Input"));
        assert!(text.contains("Rendered"));
        assert!(!text.contains("+preview"));
    }

    #[test]
    fn test_render_preview_loading_and_unavailable_notices() {
        // Arrange
        let session = session_fixture();
        let diff = "diff --git a/README.md b/README.md\n+preview";
        let previews = [
            (
                DiffPreview::Loading {
                    path: "README.md".to_string(),
                    request_id: 1,
                },
                "Loading preview…",
            ),
            (
                DiffPreview::Unavailable {
                    path: "README.md".to_string(),
                    reason: DiffPreviewUnavailableReason::Deleted,
                    request_id: 2,
                },
                "File deleted in this change.",
            ),
            (
                DiffPreview::Unavailable {
                    path: "README.md".to_string(),
                    reason: DiffPreviewUnavailableReason::Binary,
                    request_id: 3,
                },
                "Binary file — no preview.",
            ),
            (
                DiffPreview::Unavailable {
                    path: "README.md".to_string(),
                    reason: DiffPreviewUnavailableReason::TooLarge,
                    request_id: 4,
                },
                "File too large to preview.",
            ),
            (
                DiffPreview::Unavailable {
                    path: "README.md".to_string(),
                    reason: DiffPreviewUnavailableReason::LoadFailed(
                        "Preview read failed".to_string(),
                    ),
                    request_id: 5,
                },
                "Preview read failed",
            ),
        ];

        // Act
        let rendered_text = previews
            .iter()
            .map(|(preview, _)| {
                let mut diff_page = new_diff_page_with_preview(&session, diff, 0, 0, preview);
                let backend = ratatui::backend::TestBackend::new(100, 16);
                let mut terminal =
                    ratatui::Terminal::new(backend).expect("failed to create terminal");
                terminal
                    .draw(|frame| {
                        let area = frame.area();
                        Page::render(&mut diff_page, frame, area);
                    })
                    .expect("failed to draw preview notice");

                buffer_text(terminal.backend().buffer())
            })
            .collect::<Vec<_>>();

        // Assert
        for ((_, expected), text) in previews.iter().zip(rendered_text) {
            assert!(text.contains(expected));
            assert!(text.contains("Preview — README.md"));
        }
    }

    #[test]
    fn test_render_preview_falls_back_when_path_no_longer_matches_selection() {
        // Arrange
        let session = session_fixture();
        let diff = "diff --git a/README.md b/README.md\n+current diff";
        let preview = DiffPreview::Ready {
            content: "# Stale preview".to_string(),
            path: "OTHER.md".to_string(),
            request_id: 1,
        };
        let mut diff_page = new_diff_page_with_preview(&session, diff, 0, 0, &preview);
        let backend = ratatui::backend::TestBackend::new(100, 16);
        let mut terminal = ratatui::Terminal::new(backend).expect("failed to create terminal");

        // Act
        terminal
            .draw(|frame| {
                let area = frame.area();
                Page::render(&mut diff_page, frame, area);
            })
            .expect("failed to draw diff fallback");

        // Assert
        let text = buffer_text(terminal.backend().buffer());
        assert!(text.contains("current diff"));
        assert!(!text.contains("Stale preview"));
    }

    #[test]
    fn test_render_preview_scrollbar_and_max_scroll_share_layout() {
        // Arrange
        let session = session_fixture();
        let diff = "diff --git a/README.md b/README.md\n+preview";
        let markdown_content = (0..80)
            .map(|index| format!("- preview line {index}"))
            .collect::<Vec<_>>()
            .join("\n");
        let preview = DiffPreview::Ready {
            content: markdown_content,
            path: "README.md".to_string(),
            request_id: 1,
        };
        let diff_layout_cache = DiffLayoutCache::default();
        let markdown_render_cache = markdown::MarkdownRenderCache::default();
        let mut diff_page = DiffPage::new(DiffPageInput {
            diff,
            diff_layout_cache: &diff_layout_cache,
            file_explorer_selected_index: 0,
            markdown_render_cache: &markdown_render_cache,
            preview: &preview,
            scroll_offset: 12,
            session: &session,
        });
        let terminal_area = Rect::new(0, 0, 80, 12);
        let backend = ratatui::backend::TestBackend::new(80, 12);
        let mut terminal = ratatui::Terminal::new(backend).expect("failed to create terminal");

        // Act
        let max_scroll_offset = diff_view_max_scroll_offset(
            diff,
            0,
            terminal_area,
            &diff_layout_cache,
            &markdown_render_cache,
            &preview,
        );
        terminal
            .draw(|frame| Page::render(&mut diff_page, frame, terminal_area))
            .expect("failed to draw scrollable preview");

        // Assert
        let text = buffer_text(terminal.backend().buffer());
        assert!(max_scroll_offset > 0);
        assert!(text.contains(SCROLLBAR_TRACK_SYMBOL));
        assert!(text.contains(SCROLLBAR_THUMB_SYMBOL));
    }

    #[test]
    fn test_preview_notice_has_zero_max_scroll_offset() {
        // Arrange
        let diff = "diff --git a/README.md b/README.md\n+preview";
        let diff_layout_cache = DiffLayoutCache::default();
        let markdown_render_cache = markdown::MarkdownRenderCache::default();
        let preview = DiffPreview::Loading {
            path: "README.md".to_string(),
            request_id: 1,
        };

        // Act
        let max_scroll_offset = diff_view_max_scroll_offset(
            diff,
            0,
            Rect::new(0, 0, 80, 12),
            &diff_layout_cache,
            &markdown_render_cache,
            &preview,
        );

        // Assert
        assert_eq!(max_scroll_offset, 0);
    }

    #[test]
    fn test_render_clamps_overscroll_to_last_visible_diff_lines() {
        // Arrange
        let session = session_fixture();
        let diff = (0..40)
            .map(|index| format!("+line {index}"))
            .collect::<Vec<_>>()
            .join("\n");
        let mut diff_page = new_diff_page(&session, &diff, u16::MAX, 0);
        let backend = ratatui::backend::TestBackend::new(80, 12);
        let mut terminal = ratatui::Terminal::new(backend).expect("failed to create terminal");

        // Act
        terminal
            .draw(|frame| {
                let area = frame.area();
                Page::render(&mut diff_page, frame, area);
            })
            .expect("failed to draw diff page");

        // Assert
        let text = buffer_text(terminal.backend().buffer());
        assert!(text.contains("line 39"));
    }
}