retach 0.10.0

Persistent terminal sessions with native scrollback passthrough
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 super::*;
use crate::screen::cell::{Cell, Row};
use crate::screen::grid::{CursorShape, Grid, MouseEncoding};
use crate::screen::style::{Color, Style, StyleId, StyleTable};

/// Helper: intern a style and assign it to a cell in tests.
fn set_style(cell: &mut Cell, style: Style, st: &mut StyleTable) {
    cell.style_id = st.intern(style);
}

#[test]
fn render_line_blank() {
    let row = Row::new(80);
    let st = StyleTable::new();
    let result = render_line(&row, &st);
    assert!(result.is_empty(), "blank line should produce empty vec");
}

#[test]
fn render_line_with_text() {
    let mut row = Row::new(10);
    row[0].c = 'H';
    row[1].c = 'i';
    let st = StyleTable::new();
    let result = render_line(&row, &st);
    assert_eq!(result, b"Hi");
}

#[test]
fn render_line_with_style() {
    let mut st = StyleTable::new();
    let mut row = Row::new(10);
    row[0].c = 'R';
    set_style(
        &mut row[0],
        Style {
            fg: Some(Color::Indexed(1)),
            ..Style::default()
        },
        &mut st,
    );
    let result = render_line(&row, &st);
    // Should have combined reset+set SGR, then 'R', then reset
    assert!(
        result.starts_with(b"\x1b[0;31mR"),
        "expected combined reset+set, got: {:?}",
        String::from_utf8_lossy(&result)
    );
    assert!(result.ends_with(b"\x1b[0m"));
}

#[test]
fn render_line_with_matches_render_line() {
    let mut st = StyleTable::new();
    let mut row = Row::new(12);
    row[0].c = 'A';
    set_style(
        &mut row[0],
        Style {
            fg: Some(Color::Indexed(2)),
            bold: true,
            ..Style::default()
        },
        &mut st,
    );
    row[1].c = '';
    row[1].width = 2;
    row[2].width = 0; // wide continuation
    row[3].c = 'x';
    row.push_combining(3, '\u{0301}');
    let old = render_line(&row, &st);
    let new = render_line_with(&row, |id| st.get(id));
    assert_eq!(
        old, new,
        "render_line_with must produce byte-identical output"
    );
}

#[test]
fn render_screen_full() {
    let grid = Grid::new(10, 3, 0);
    let mut cache = RenderCache::new();
    let result = render_screen(&grid, "", true, &mut cache);
    let text = String::from_utf8_lossy(&result);
    // Full render must clear the screen and home cursor
    assert!(
        text.contains("\x1b[2J\x1b[H"),
        "full render must emit screen clear"
    );
    // Should contain cursor position
    assert!(text.contains("\x1b[1;1H"));
}

#[test]
fn render_screen_incremental() {
    let grid = Grid::new(10, 3, 0);
    let mut cache = RenderCache::new();
    let result = render_screen(&grid, "", false, &mut cache);
    let text = String::from_utf8_lossy(&result);
    // Should NOT contain clear screen
    assert!(!text.contains("\x1b[2J"));
}

#[test]
fn render_line_skips_wide_char_continuation() {
    let mut row = Row::new(10);
    row[0] = Cell::new('', StyleId::default(), 2);
    row[1] = Cell::new('\0', StyleId::default(), 0);
    row[2].c = 'A';
    let st = StyleTable::new();
    let result = render_line(&row, &st);
    let text = String::from_utf8_lossy(&result);
    assert!(text.contains(''));
    assert!(text.contains('A'));
    // Should not contain null bytes
    assert!(!text.contains('\0'));
}

#[test]
fn render_screen_includes_title() {
    let grid = Grid::new(10, 3, 0);
    let mut cache = RenderCache::new();
    let result = render_screen(&grid, "My Title", false, &mut cache);
    let text = String::from_utf8_lossy(&result);
    assert!(text.contains("\x1b]2;My Title\x07"));
}

#[test]
fn render_screen_no_title_when_empty() {
    let grid = Grid::new(10, 3, 0);
    let mut cache = RenderCache::new();
    let result = render_screen(&grid, "", false, &mut cache);
    let text = String::from_utf8_lossy(&result);
    assert!(!text.contains("\x1b]2;"));
}

#[test]
fn render_screen_hidden_cursor() {
    let mut grid = Grid::new(10, 3, 0);
    grid.set_cursor_visible(false);
    let mut cache = RenderCache::new();
    let result = render_screen(&grid, "", false, &mut cache);
    let text = String::from_utf8_lossy(&result);
    // Should hide cursor at top
    assert!(text.contains("\x1b[?25l"));
    // Should NOT restore cursor (it was hidden)
    assert!(!text.contains("\x1b[?25h"));
}

#[test]
fn render_screen_incremental_dirty_tracking() {
    let mut grid = Grid::new(10, 5, 0);
    // Move cursor to a unique position so cursor-position output doesn't
    // collide with row-position sequences we're checking.
    grid.set_cursor_x_unclamped(3);
    grid.set_cursor_y_unclamped(4);
    let mut cache = RenderCache::new();
    // First render: all rows are drawn
    let result1 = render_screen(&grid, "", false, &mut cache);
    let text1 = String::from_utf8_lossy(&result1);
    // All 5 rows should be positioned
    assert!(
        text1.contains("\x1b[1;1H"),
        "row 1 should be drawn on first render"
    );
    assert!(
        text1.contains("\x1b[2;1H"),
        "row 2 should be drawn on first render"
    );
    assert!(
        text1.contains("\x1b[3;1H"),
        "row 3 should be drawn on first render"
    );

    // Second render without changes: content rows should be skipped
    let result2 = render_screen(&grid, "", false, &mut cache);
    let text2 = String::from_utf8_lossy(&result2);
    // Row-content positioning should NOT appear (cache hit)
    // (Note: \x1b[5;4H will still appear for cursor positioning)
    assert!(
        !text2.contains("\x1b[1;1H"),
        "unchanged rows should be skipped in incremental render"
    );
    assert!(
        !text2.contains("\x1b[2;1H"),
        "unchanged rows should be skipped in incremental render"
    );

    // Now change row 2 (0-indexed=1) and render again
    grid.visible_row_mut(1)[0].c = 'X';
    let result3 = render_screen(&grid, "", false, &mut cache);
    let text3 = String::from_utf8_lossy(&result3);
    // Row 2 (1-indexed) should be redrawn
    assert!(
        text3.contains("\x1b[2;1H"),
        "changed row should be redrawn in incremental render"
    );
    // Other rows should still be skipped
    assert!(
        !text3.contains("\x1b[1;1H"),
        "unchanged row 1 should be skipped"
    );
    assert!(
        !text3.contains("\x1b[3;1H"),
        "unchanged row 3 should be skipped"
    );
}

#[test]
fn render_screen_synchronized_output() {
    let grid = Grid::new(10, 3, 0);
    let mut cache = RenderCache::new();
    let result = render_screen(&grid, "", false, &mut cache);
    let text = String::from_utf8_lossy(&result);
    // Must start with sync begin and end with sync end
    assert!(
        text.starts_with("\x1b[?2026h"),
        "render should start with synchronized output begin"
    );
    assert!(
        text.ends_with("\x1b[?2026l"),
        "render should end with synchronized output end"
    );
}

#[test]
fn render_screen_cursor_position() {
    let mut grid = Grid::new(10, 5, 0);
    grid.set_cursor_x_unclamped(4);
    grid.set_cursor_y_unclamped(2);
    let mut cache = RenderCache::new();
    let result = render_screen(&grid, "", true, &mut cache);
    let text = String::from_utf8_lossy(&result);
    // Cursor should be positioned at row 3, col 5 (1-indexed)
    assert!(
        text.contains("\x1b[3;5H"),
        "cursor should be at row 3, col 5 (1-indexed), got: {:?}",
        text.matches("\x1b[").collect::<Vec<_>>()
    );
}

#[test]
fn render_screen_title_cached() {
    let grid = Grid::new(10, 3, 0);
    let mut cache = RenderCache::new();
    // First render with title
    let result1 = render_screen(&grid, "Title1", false, &mut cache);
    assert!(String::from_utf8_lossy(&result1).contains("\x1b]2;Title1\x07"));

    // Second render with same title: should NOT re-emit
    let result2 = render_screen(&grid, "Title1", false, &mut cache);
    assert!(
        !String::from_utf8_lossy(&result2).contains("\x1b]2;"),
        "same title should not be re-emitted"
    );

    // Third render with different title: should emit
    let result3 = render_screen(&grid, "Title2", false, &mut cache);
    assert!(
        String::from_utf8_lossy(&result3).contains("\x1b]2;Title2\x07"),
        "changed title should be emitted"
    );
}

#[test]
fn render_screen_title_sanitized() {
    let grid = Grid::new(10, 3, 0);
    let mut cache = RenderCache::new();
    // Title with BEL (0x07) that would break OSC
    let evil_title = "bad\x07title";
    let result = render_screen(&grid, evil_title, false, &mut cache);
    let text = String::from_utf8_lossy(&result);
    // The OSC should contain "badtitle" (BEL stripped), not terminate early
    assert!(
        text.contains("\x1b]2;badtitle\x07"),
        "control chars should be stripped from title"
    );
}

#[test]
fn render_line_multiple_style_changes() {
    let mut st = StyleTable::new();
    let mut row = Row::new(10);
    row[0].c = 'R';
    set_style(
        &mut row[0],
        Style {
            fg: Some(Color::Indexed(1)),
            ..Style::default()
        },
        &mut st,
    );
    row[1].c = 'G';
    set_style(
        &mut row[1],
        Style {
            fg: Some(Color::Indexed(2)),
            ..Style::default()
        },
        &mut st,
    );
    row[2].c = 'N'; // default style
    let result = render_line(&row, &st);
    let text = String::from_utf8_lossy(&result);
    // Should have red, then reset+green, then reset
    assert!(text.contains("R"), "should contain 'R'");
    assert!(text.contains("G"), "should contain 'G'");
    assert!(text.contains("N"), "should contain 'N'");
    // With to_sgr_with_reset, style changes use combined reset+set (e.g., \x1b[0;31m)
    // Only transitions back to default produce a bare \x1b[0m
    let combined_sgr_count = text.matches("\x1b[0;").count() + text.matches("\x1b[0m").count();
    assert!(
        combined_sgr_count >= 2,
        "expected at least 2 combined reset+set SGR sequences, got {}",
        combined_sgr_count
    );
}

#[test]
fn render_screen_full_mode_emits_mouse_modes() {
    let mut grid = Grid::new(10, 3, 0);
    grid.modes_mut().mouse_modes.any = true;
    let mut cache = RenderCache::new();
    let result = render_screen(&grid, "", true, &mut cache);
    let text = String::from_utf8_lossy(&result);
    // Full render should disable inactive modes and enable active
    assert!(
        text.contains("\x1b[?1000l"),
        "full render should disable mouse mode 1000"
    );
    assert!(
        text.contains("\x1b[?1002l"),
        "full render should disable mouse mode 1002"
    );
    assert!(
        text.contains("\x1b[?1003h"),
        "full render should enable active mouse mode 1003"
    );
}

#[test]
fn render_screen_mode_delta_mouse_switch() {
    let mut grid = Grid::new(10, 3, 0);
    grid.modes_mut().mouse_modes.click = true;
    let mut cache = RenderCache::new();
    // Initial render (full)
    let _ = render_screen(&grid, "", true, &mut cache);

    // Switch: disable click, enable any
    grid.modes_mut().mouse_modes.click = false;
    grid.modes_mut().mouse_modes.any = true;
    let result = render_screen(&grid, "", false, &mut cache);
    let text = String::from_utf8_lossy(&result);
    // Should disable old mode
    assert!(
        text.contains("\x1b[?1000l"),
        "delta should disable old mouse mode 1000"
    );
    // Should enable new mode
    assert!(
        text.contains("\x1b[?1003h"),
        "delta should enable new mouse mode 1003"
    );
}

#[test]
fn render_screen_mode_delta_bracketed_paste() {
    let mut grid = Grid::new(10, 3, 0);
    let mut cache = RenderCache::new();
    let _ = render_screen(&grid, "", true, &mut cache);

    // Enable bracketed paste
    grid.modes_mut().bracketed_paste = true;
    let result = render_screen(&grid, "", false, &mut cache);
    let text = String::from_utf8_lossy(&result);
    assert!(
        text.contains("\x1b[?2004h"),
        "delta should emit bracketed paste enable"
    );
}

#[test]
fn render_cache_invalidate() {
    let grid = Grid::new(10, 3, 0);
    let mut cache = RenderCache::new();
    // Populate cache
    let _ = render_screen(&grid, "test", false, &mut cache);
    assert!(!cache.rows.is_empty());
    assert!(cache.last_modes.is_some());

    // Invalidate
    cache.invalidate();
    assert!(cache.rows.is_empty());
    assert!(cache.last_modes.is_none());
    assert!(cache.last_title.is_empty());

    // Next render should redraw everything (all rows emitted)
    let result = render_screen(&grid, "", false, &mut cache);
    let text = String::from_utf8_lossy(&result);
    assert!(
        text.contains("\x1b[1;1H"),
        "after invalidate, all rows should be redrawn"
    );
    assert!(
        text.contains("\x1b[2;1H"),
        "after invalidate, all rows should be redrawn"
    );
    assert!(
        text.contains("\x1b[3;1H"),
        "after invalidate, all rows should be redrawn"
    );
}

// --- New tests ---

#[test]
fn render_line_styled_spaces_not_blank() {
    // Row of spaces with colored bg should render SGR, not b" "
    let mut st = StyleTable::new();
    let mut row = Row::new(10);
    let red_bg = st.intern(Style {
        bg: Some(Color::Indexed(1)),
        ..Style::default()
    });
    for cell in row.iter_mut() {
        cell.c = ' ';
        cell.style_id = red_bg;
    }
    let result = render_line(&row, &st);
    // Should contain SGR for the background color, not just a plain space
    let text = String::from_utf8_lossy(&result);
    assert!(
        text.contains("\x1b["),
        "styled spaces should produce SGR sequences"
    );
    assert!(text.contains("41m"), "red bg should produce code 41");
}

#[test]
fn render_line_styled_trailing_space() {
    // Trailing styled space should be included in output
    let mut st = StyleTable::new();
    let mut row = Row::new(5);
    row[0].c = 'A';
    row[4].c = ' ';
    set_style(
        &mut row[4],
        Style {
            bg: Some(Color::Indexed(4)),
            ..Style::default()
        },
        &mut st,
    );
    let result = render_line(&row, &st);
    let text = String::from_utf8_lossy(&result);
    assert!(
        text.contains("44m"),
        "trailing styled space should include blue bg SGR"
    );
}

#[test]
fn render_line_wide_char_at_end() {
    // Wide char at last two positions renders correctly
    let mut row = Row::new(10);
    row[8] = Cell::new('\u{4e16}', StyleId::default(), 2); //    row[9] = Cell::new('\0', StyleId::default(), 0); // continuation
    let st = StyleTable::new();
    let result = render_line(&row, &st);
    let text = String::from_utf8_lossy(&result);
    assert!(
        text.contains('\u{4e16}'),
        "wide char at end should be rendered"
    );
    assert!(
        !text.contains('\0'),
        "continuation cell should not produce output"
    );
}

#[test]
fn render_line_rgb_color() {
    let mut st = StyleTable::new();
    let mut row = Row::new(5);
    row[0].c = 'X';
    set_style(
        &mut row[0],
        Style {
            fg: Some(Color::Rgb(100, 150, 200)),
            ..Style::default()
        },
        &mut st,
    );
    let result = render_line(&row, &st);
    let text = String::from_utf8_lossy(&result);
    assert!(
        text.contains("38;2;100;150;200m"),
        "RGB color should produce 38;2;R;G;B"
    );
}

#[test]
fn render_line_combined_attributes() {
    let mut st = StyleTable::new();
    let mut row = Row::new(5);
    row[0].c = 'Z';
    set_style(
        &mut row[0],
        Style {
            bold: true,
            italic: true,
            underline: super::super::style::UnderlineStyle::Single,
            fg: Some(Color::Indexed(3)),
            bg: Some(Color::Indexed(4)),
            ..Style::default()
        },
        &mut st,
    );
    let result = render_line(&row, &st);
    let text = String::from_utf8_lossy(&result);
    assert!(text.contains("1;"), "bold should be present");
    assert!(text.contains("3;"), "italic should be present");
    assert!(text.contains(";4;"), "underline should be present");
    assert!(text.contains("33"), "yellow fg should be present");
    assert!(text.contains("44"), "blue bg should be present");
}

#[test]
fn render_line_256_color() {
    let mut st = StyleTable::new();
    let mut row = Row::new(5);
    row[0].c = 'P';
    set_style(
        &mut row[0],
        Style {
            fg: Some(Color::Indexed(200)),
            ..Style::default()
        },
        &mut st,
    );
    let result = render_line(&row, &st);
    let text = String::from_utf8_lossy(&result);
    assert!(
        text.contains("38;5;200m"),
        "palette index 200 should produce 38;5;200"
    );
}

#[test]
fn render_screen_title_cleared() {
    // Bug 1 regression test: title change to "" should emit empty OSC
    let grid = Grid::new(10, 3, 0);
    let mut cache = RenderCache::new();
    // First render with a non-empty title
    let _ = render_screen(&grid, "Hello", false, &mut cache);
    // Now clear the title
    let result = render_screen(&grid, "", false, &mut cache);
    let text = String::from_utf8_lossy(&result);
    assert!(
        text.contains("\x1b]2;\x07"),
        "clearing title should emit empty OSC, got: {:?}",
        text
    );
}

#[test]
fn render_screen_after_resize() {
    // When row count changes, all rows should be redrawn
    let grid = Grid::new(10, 3, 0);
    let mut cache = RenderCache::new();
    let _ = render_screen(&grid, "", false, &mut cache);

    // Simulate resize: new grid with more rows
    let grid2 = Grid::new(10, 5, 0);
    let result = render_screen(&grid2, "", false, &mut cache);
    let text = String::from_utf8_lossy(&result);
    // Cache had 3 rows, now 5 — row_hashes resized with sentinels for new rows.
    // Rows 1-3 are still blank (same hash), so dirty tracking skips them.
    // Rows 4-5 have sentinel u64::MAX so they get redrawn.
    assert!(
        !text.contains("\x1b[1;1H"),
        "unchanged row 1 should be skipped after resize"
    );
    assert!(
        text.contains("\x1b[4;1H"),
        "new row 4 should be redrawn after resize"
    );
    assert!(
        text.contains("\x1b[5;1H"),
        "new row 5 should be redrawn after resize"
    );
}

#[test]
fn render_screen_style_only_change_detected() {
    // Cell changes color but same char → row should be redrawn
    let mut grid = Grid::new(10, 3, 0);
    let mut cache = RenderCache::new();
    let _ = render_screen(&grid, "", false, &mut cache);

    // Change style of a cell without changing the char
    let sid = grid.style_table_mut().intern(Style {
        fg: Some(Color::Indexed(1)),
        ..Style::default()
    });
    grid.visible_row_mut(1)[0].style_id = sid;
    let result = render_screen(&grid, "", false, &mut cache);
    let text = String::from_utf8_lossy(&result);
    assert!(
        text.contains("\x1b[2;1H"),
        "row with style-only change should be redrawn"
    );
}

#[test]
fn render_screen_1x1_grid() {
    let grid = Grid::new(1, 1, 0);
    let mut cache = RenderCache::new();
    // Should not panic
    let result = render_screen(&grid, "", true, &mut cache);
    let text = String::from_utf8_lossy(&result);
    assert!(
        text.contains("\x1b[1;1H"),
        "1x1 grid should position at 1,1"
    );
}

#[test]
fn render_screen_cursor_bottom_right() {
    let mut grid = Grid::new(80, 24, 0);
    grid.set_cursor_x_unclamped(79);
    grid.set_cursor_y_unclamped(23);
    let mut cache = RenderCache::new();
    let result = render_screen(&grid, "", true, &mut cache);
    let text = String::from_utf8_lossy(&result);
    assert!(
        text.contains("\x1b[24;80H"),
        "cursor at bottom-right should position at row 24, col 80"
    );
}

#[test]
fn render_screen_mouse_encoding_1006() {
    let mut grid = Grid::new(10, 3, 0);
    grid.modes_mut().mouse_encoding = MouseEncoding::Sgr;
    let mut cache = RenderCache::new();
    let result = render_screen(&grid, "", true, &mut cache);
    let text = String::from_utf8_lossy(&result);
    assert!(
        text.contains("\x1b[?1006h"),
        "SGR mouse encoding should be enabled"
    );
}

#[test]
fn render_screen_mouse_encoding_1005() {
    let mut grid = Grid::new(10, 3, 0);
    grid.modes_mut().mouse_encoding = MouseEncoding::Utf8;
    let mut cache = RenderCache::new();
    let result = render_screen(&grid, "", true, &mut cache);
    let text = String::from_utf8_lossy(&result);
    assert!(
        text.contains("\x1b[?1005h"),
        "UTF-8 mouse encoding should be enabled"
    );
}

#[test]
fn render_screen_cursor_shape_delta() {
    let mut grid = Grid::new(10, 3, 0);
    let mut cache = RenderCache::new();
    let _ = render_screen(&grid, "", true, &mut cache);

    // Change cursor shape to blinking bar (5)
    grid.modes_mut().cursor_shape = CursorShape::BlinkBar;
    let result = render_screen(&grid, "", false, &mut cache);
    let text = String::from_utf8_lossy(&result);
    assert!(
        text.contains("\x1b[5 q"),
        "cursor shape change should emit DECSCUSR"
    );
}

#[test]
fn render_screen_keypad_mode_delta() {
    let mut grid = Grid::new(10, 3, 0);
    let mut cache = RenderCache::new();
    let _ = render_screen(&grid, "", true, &mut cache);

    // Enable keypad app mode
    grid.modes_mut().keypad_app_mode = true;
    let result = render_screen(&grid, "", false, &mut cache);
    let text = String::from_utf8_lossy(&result);
    assert!(text.contains("\x1b="), "keypad app mode should emit ESC =");

    // Disable keypad app mode
    grid.modes_mut().keypad_app_mode = false;
    let result2 = render_screen(&grid, "", false, &mut cache);
    let text2 = String::from_utf8_lossy(&result2);
    assert!(
        text2.contains("\x1b>"),
        "keypad normal mode should emit ESC >"
    );
}

#[test]
fn render_line_combining_mark() {
    let mut row = Row::new(10);
    row[0].c = 'e';
    row.push_combining(0, '\u{0301}'); // combining acute accent → é
    let st = StyleTable::new();
    let result = render_line(&row, &st);
    let text = String::from_utf8_lossy(&result);
    assert!(
        text.contains("e\u{0301}"),
        "combining mark should be rendered after base char"
    );
}

#[test]
fn render_line_combining_on_wide_char() {
    let mut row = Row::new(10);
    row[0] = Cell::new('\u{4e16}', StyleId::default(), 2);
    row.push_combining(0, '\u{0308}');
    row[1] = Cell::new('\0', StyleId::default(), 0);
    let st = StyleTable::new();
    let result = render_line(&row, &st);
    let text = String::from_utf8_lossy(&result);
    assert!(
        text.contains("\u{4e16}\u{0308}"),
        "combining mark on wide char should render"
    );
}

// --- Scrollback injection tests ---

#[test]
fn scrollback_positions_cursor_at_bottom() {
    let grid = Grid::new(80, 24, 0);
    let mut cache = RenderCache::new();
    let scrollback = vec![b"line one".to_vec()];
    let result = render_screen_with_scrollback(&grid, "", &scrollback, &mut cache);
    let text = String::from_utf8_lossy(&result);
    // Cursor must be positioned at the last row (24) before scrollback content
    assert!(
        text.contains("\x1b[24;1H"),
        "scrollback should position cursor at bottom row"
    );
}

#[test]
fn scrollback_lines_appear_before_screen_clear() {
    let grid = Grid::new(80, 24, 0);
    let mut cache = RenderCache::new();
    let scrollback = vec![b"old prompt".to_vec(), b"ls output".to_vec()];
    let result = render_screen_with_scrollback(&grid, "", &scrollback, &mut cache);
    let text = String::from_utf8_lossy(&result);

    let pos_line1 = text.find("old prompt").expect("scrollback line 1 missing");
    let pos_line2 = text.find("ls output").expect("scrollback line 2 missing");
    let pos_clear = text.find("\x1b[2J").expect("screen clear missing");

    assert!(pos_line1 < pos_line2, "scrollback lines must be in order");
    assert!(
        pos_line2 < pos_clear,
        "scrollback must precede screen clear"
    );
}

#[test]
fn scrollback_lines_use_cursor_positioning() {
    let grid = Grid::new(80, 24, 0);
    let mut cache = RenderCache::new();
    let scrollback = vec![b"AAA".to_vec(), b"BBB".to_vec()];
    let result = render_screen_with_scrollback(&grid, "", &scrollback, &mut cache);
    let text = String::from_utf8_lossy(&result);

    // Lines should be written at rows 1 and 2 via CUP
    assert!(text.contains("AAA"), "AAA should be present");
    assert!(text.contains("BBB"), "BBB should be present");
    // Should end each line with EL (erase to end of line)
    let raw = &result;
    let pos_a = raw
        .windows(3)
        .position(|w| w == b"AAA")
        .expect("AAA missing");
    // After "AAA" there should be \x1b[K (erase to end of line)
    assert_eq!(
        &raw[pos_a + 3..pos_a + 6],
        b"\x1b[K",
        "scrollback line should end with EL"
    );
}

#[test]
fn scrollback_outside_sync_block() {
    let grid = Grid::new(80, 24, 0);
    let mut cache = RenderCache::new();
    let scrollback = vec![b"scroll line".to_vec()];
    let result = render_screen_with_scrollback(&grid, "", &scrollback, &mut cache);
    let text = String::from_utf8_lossy(&result);

    let sync_begin = text.find("\x1b[?2026h").expect("sync begin missing");
    let pos_scroll = text
        .find("scroll line")
        .expect("scrollback content missing");
    let sync_end = text.rfind("\x1b[?2026l").expect("sync end missing");

    // Scrollback injection must be BEFORE the sync block
    assert!(
        pos_scroll < sync_begin,
        "scrollback must be before sync begin (scrollback at {}, sync at {})",
        pos_scroll,
        sync_begin
    );
    assert!(sync_begin < sync_end, "sync begin must precede sync end");
}

#[test]
fn scrollback_forces_full_redraw() {
    let mut grid = Grid::new(10, 3, 0);
    let mut cache = RenderCache::new();
    // Populate cache with an initial render
    let _ = render_screen(&grid, "", false, &mut cache);
    assert!(!cache.rows.is_empty());

    // Modify only row 2 — normally only row 2 would be redrawn
    grid.visible_row_mut(1)[0].c = 'X';

    // Render with scrollback — all rows must be redrawn (full redraw)
    let scrollback = vec![b"old".to_vec()];
    let result = render_screen_with_scrollback(&grid, "", &scrollback, &mut cache);
    let text = String::from_utf8_lossy(&result);

    assert!(
        text.contains("\x1b[1;1H"),
        "row 1 must be redrawn after scrollback"
    );
    assert!(
        text.contains("\x1b[2;1H"),
        "row 2 must be redrawn after scrollback"
    );
    assert!(
        text.contains("\x1b[3;1H"),
        "row 3 must be redrawn after scrollback"
    );
}

#[test]
fn no_scrollback_no_crlf_in_output() {
    let grid = Grid::new(80, 24, 0);
    let mut cache = RenderCache::new();
    let result = render_screen(&grid, "", false, &mut cache);
    // Normal render must never contain \r\n — that's only emitted for scrollback
    assert!(
        !result.windows(2).any(|w| w == b"\r\n"),
        "render without scrollback must not contain \\r\\n"
    );
}

/// Simulates the reattach scenario: history lines are written by the
/// client with `\r\n`, leaving the last `rows - 1` lines on screen.
/// The server prepends exactly `rows - 1` newlines to the ScreenUpdate
/// to flush them into the real terminal's scrollback buffer.
///
/// If too few `\n`s are sent, some history lines are lost (cleared by
/// `\x1b[2J`).  If too many, a blank line leaks into the scrollback.
#[test]
fn reattach_history_flush_count() {
    let rows: u16 = 5;
    let grid = Grid::new(80, rows, 0);
    let mut cache = RenderCache::new();
    let render = render_screen(&grid, "", true, &mut cache);

    // Build the ScreenUpdate data the same way send_initial_state does:
    // prepend (rows - 1) newlines, then the full render.
    let mut reattach_data = Vec::new();
    let flush_count = rows.saturating_sub(1) as usize;
    reattach_data.extend(std::iter::repeat(b'\n').take(flush_count));
    reattach_data.extend_from_slice(&render);

    // Count leading \n bytes before any escape sequence
    let leading_newlines = reattach_data.iter().take_while(|&&b| b == b'\n').count();
    assert_eq!(
        leading_newlines,
        (rows - 1) as usize,
        "reattach should prepend exactly rows-1 newlines, got {}",
        leading_newlines
    );

    // The render portion must still start with sync begin
    assert_eq!(
        &reattach_data[flush_count..flush_count + 8],
        b"\x1b[?2026h",
        "render must start with synchronized output after flush newlines"
    );
}

#[test]
fn reattach_no_flush_without_history() {
    let grid = Grid::new(80, 5, 0);
    let mut cache = RenderCache::new();
    let render = render_screen(&grid, "", true, &mut cache);
    // Without history, no leading newlines should be added
    assert_eq!(
        render[0], b'\x1b',
        "render without history must start directly with escape, not newline"
    );
}

// --- BEL-in-render tests ---

/// Every BEL (0x07) in render output must be inside an OSC sequence,
/// never a standalone bell that would trigger an audible beep.
#[test]
fn render_no_standalone_bell() {
    let grid = Grid::new(80, 24, 0);
    let mut cache = RenderCache::new();
    let result = render_screen(&grid, "My Title", true, &mut cache);
    // Find all BEL bytes and verify each is preceded by an OSC intro
    for (i, &byte) in result.iter().enumerate() {
        if byte == 0x07 {
            // This BEL must be a terminator for an OSC sequence.
            // Scan backward to find \x1b] (ESC ])
            let prefix = &result[..i];
            let osc_start = prefix.windows(2).rposition(|w| w == b"\x1b]");
            assert!(
                osc_start.is_some(),
                "BEL at byte offset {} is standalone (not inside an OSC sequence)",
                i
            );
        }
    }
}

/// Full redraw should not produce standalone BEL even with title changes.
#[test]
fn render_full_redraw_no_standalone_bell() {
    let grid = Grid::new(80, 24, 0);
    let mut cache = RenderCache::new();
    // First render with title
    let _ = render_screen(&grid, "Title1", false, &mut cache);
    // Full redraw with different title
    cache.invalidate();
    let result = render_screen(&grid, "Title2", true, &mut cache);
    for (i, &byte) in result.iter().enumerate() {
        if byte == 0x07 {
            let prefix = &result[..i];
            let osc_start = prefix.windows(2).rposition(|w| w == b"\x1b]");
            assert!(
                osc_start.is_some(),
                "BEL at byte offset {} is standalone after cache invalidate",
                i
            );
        }
    }
}

/// Render without title should produce zero BEL bytes.
#[test]
fn render_no_title_no_bell_bytes() {
    let grid = Grid::new(80, 24, 0);
    let mut cache = RenderCache::new();
    let result = render_screen(&grid, "", false, &mut cache);
    let bell_count = result.iter().filter(|&&b| b == 0x07).count();
    assert_eq!(
        bell_count, 0,
        "render with empty title should produce zero BEL bytes, got {}",
        bell_count
    );
}

/// Repeated renders with the same title should not produce BEL on second render.
#[test]
fn render_cached_title_no_bell() {
    let grid = Grid::new(80, 24, 0);
    let mut cache = RenderCache::new();
    let _ = render_screen(&grid, "Hello", false, &mut cache);
    // Second render with same title — should skip title OSC entirely
    let result = render_screen(&grid, "Hello", false, &mut cache);
    let bell_count = result.iter().filter(|&&b| b == 0x07).count();
    assert_eq!(
        bell_count, 0,
        "cached title should produce zero BEL bytes, got {}",
        bell_count
    );
}

// --- AnsiRenderer trait-path dirty tracking tests ---

#[test]
fn trait_render_incremental_skips_unchanged_rows() {
    use super::super::Screen;

    let mut screen = Screen::new(10, 5, 0);
    // Write text on row 0
    screen.process(b"Hello");
    // Move cursor to row 3 col 3 so CUP doesn't collide with row positions
    screen.process(b"\x1b[4;4H");

    let mut renderer = AnsiRenderer::new();
    // First render — all rows drawn
    let result1 = renderer.render(&screen, false);
    let text1 = String::from_utf8_lossy(&result1);
    assert!(
        text1.contains("\x1b[1;1H"),
        "first render should draw row 1"
    );
    assert!(
        text1.contains("\x1b[2;1H"),
        "first render should draw row 2"
    );
    assert!(
        text1.contains("\x1b[3;1H"),
        "first render should draw row 3"
    );

    // Second render without changes — content rows should be skipped
    let result2 = renderer.render(&screen, false);
    let text2 = String::from_utf8_lossy(&result2);
    assert!(
        !text2.contains("\x1b[1;1H"),
        "unchanged row 1 should be skipped in trait incremental render"
    );
    assert!(
        !text2.contains("\x1b[2;1H"),
        "unchanged row 2 should be skipped in trait incremental render"
    );
}

#[test]
fn trait_render_incremental_redraws_changed_row() {
    use super::super::Screen;

    let mut screen = Screen::new(10, 5, 0);
    screen.process(b"Hello");
    screen.process(b"\x1b[4;4H");

    let mut renderer = AnsiRenderer::new();
    // First render to populate cache
    let _ = renderer.render(&screen, false);

    // Change row 0 by overwriting
    screen.process(b"\x1b[1;1HWorld");
    screen.process(b"\x1b[4;4H");

    let result = renderer.render(&screen, false);
    let text = String::from_utf8_lossy(&result);
    // Row 1 changed — should be redrawn
    assert!(
        text.contains("\x1b[1;1H"),
        "changed row should be redrawn via trait path"
    );
    // Row 3 unchanged — should be skipped
    assert!(
        !text.contains("\x1b[3;1H"),
        "unchanged row 3 should be skipped via trait path"
    );
}

#[test]
fn trait_render_full_redraws_all_rows() {
    use super::super::Screen;

    let mut screen = Screen::new(10, 3, 0);
    screen.process(b"Hi");

    let mut renderer = AnsiRenderer::new();
    // Populate cache
    let _ = renderer.render(&screen, false);

    // Full render should redraw everything regardless of cache
    let result = renderer.render(&screen, true);
    let text = String::from_utf8_lossy(&result);
    assert!(text.contains("\x1b[1;1H"), "full render should draw row 1");
    assert!(text.contains("\x1b[2;1H"), "full render should draw row 2");
    assert!(text.contains("\x1b[3;1H"), "full render should draw row 3");
}

// ====================================================================
// Rendering optimality tests
//
// These tests verify that the renderer avoids unnecessary work:
// redundant escape sequences, no-op renders, and re-rendering of
// unchanged state. They catch regressions that waste bandwidth
// or cause visual artifacts (flicker).
// ====================================================================

/// Helper: count occurrences of a byte pattern in a byte slice.
fn count_pattern(haystack: &[u8], needle: &[u8]) -> usize {
    haystack
        .windows(needle.len())
        .filter(|w| *w == needle)
        .count()
}

// --- No-op render detection ---

#[test]
fn noop_render_returns_empty() {
    let grid = Grid::new(10, 3, 0);
    let mut cache = RenderCache::new();
    // First render populates the cache
    let _ = render_screen(&grid, "", false, &mut cache);
    // Second render with nothing changed: must return empty
    let result = render_screen(&grid, "", false, &mut cache);
    assert!(
        result.is_empty(),
        "no-op render should return empty, got {} bytes: {:?}",
        result.len(),
        String::from_utf8_lossy(&result)
    );
}

#[test]
fn noop_render_trait_returns_empty() {
    use super::super::Screen;

    let mut screen = Screen::new(10, 3, 0);
    screen.process(b"Test");
    screen.process(b"\x1b[2;3H");

    let mut renderer = AnsiRenderer::new();
    let _ = renderer.render(&screen, false);
    // Second render — nothing changed
    let result = renderer.render(&screen, false);
    assert!(
        result.is_empty(),
        "trait path no-op render should return empty, got {} bytes",
        result.len()
    );
}

#[test]
fn noop_render_after_cursor_only_change() {
    let mut grid = Grid::new(10, 3, 0);
    let mut cache = RenderCache::new();
    let _ = render_screen(&grid, "", false, &mut cache);
    // Move cursor — this should produce output (CUP)
    grid.set_cursor_x_unclamped(5);
    let result = render_screen(&grid, "", false, &mut cache);
    assert!(!result.is_empty(), "cursor move should produce output");
    // Render again without change — should be no-op
    let result2 = render_screen(&grid, "", false, &mut cache);
    assert!(
        result2.is_empty(),
        "second render after cursor-only change should be no-op"
    );
}

// --- Cursor position caching ---

#[test]
fn cursor_position_cached_across_renders() {
    let mut grid = Grid::new(10, 5, 0);
    grid.set_cursor_x_unclamped(3);
    grid.set_cursor_y_unclamped(2);
    let mut cache = RenderCache::new();
    let _ = render_screen(&grid, "", false, &mut cache);
    // Same cursor position — CUP should not be re-emitted
    let result = render_screen(&grid, "", false, &mut cache);
    assert!(
        result.is_empty(),
        "same cursor position should not produce output"
    );
    // Change cursor position — CUP should be emitted
    grid.set_cursor_x_unclamped(7);
    let result = render_screen(&grid, "", false, &mut cache);
    let text = String::from_utf8_lossy(&result);
    assert!(
        text.contains("\x1b[3;8H"),
        "new cursor position should emit CUP, got: {:?}",
        text
    );
}

#[test]
fn cursor_position_always_emitted_on_full() {
    let mut grid = Grid::new(10, 3, 0);
    grid.set_cursor_x_unclamped(2);
    grid.set_cursor_y_unclamped(1);
    let mut cache = RenderCache::new();
    let _ = render_screen(&grid, "", false, &mut cache);
    // Full render with same cursor — CUP must still be emitted
    let result = render_screen(&grid, "", true, &mut cache);
    let text = String::from_utf8_lossy(&result);
    assert!(
        text.contains("\x1b[2;3H"),
        "full render must always emit CUP even if cached"
    );
}

// --- Cursor visibility caching ---

#[test]
fn cursor_visibility_cached() {
    let grid = Grid::new(10, 3, 0);
    let mut cache = RenderCache::new();
    // First render — cursor visible, emitted
    let result = render_screen(&grid, "", false, &mut cache);
    let text = String::from_utf8_lossy(&result);
    assert!(
        text.contains("\x1b[?25h"),
        "first render should emit cursor show"
    );
    // Second render — same visibility, should be no-op
    let result2 = render_screen(&grid, "", false, &mut cache);
    assert!(
        !String::from_utf8_lossy(&result2).contains("\x1b[?25h"),
        "cached cursor visibility should not be re-emitted"
    );
}

#[test]
fn cursor_visibility_change_detected() {
    let mut grid = Grid::new(10, 3, 0);
    let mut cache = RenderCache::new();
    let _ = render_screen(&grid, "", false, &mut cache);
    // Hide cursor
    grid.set_cursor_visible(false);
    let result = render_screen(&grid, "", false, &mut cache);
    let text = String::from_utf8_lossy(&result);
    assert!(
        text.contains("\x1b[?25l"),
        "cursor hide should be emitted when visibility changes"
    );
    // Render again — same state, should not re-emit
    let result2 = render_screen(&grid, "", false, &mut cache);
    assert!(
        result2.is_empty(),
        "same cursor visibility should produce no-op render"
    );
}

// --- Scroll region caching ---

#[test]
fn scroll_region_cached() {
    let grid = Grid::new(10, 5, 0);
    let mut cache = RenderCache::new();
    let result1 = render_screen(&grid, "", false, &mut cache);
    let text1 = String::from_utf8_lossy(&result1);
    assert!(text1.contains("r"), "first render should emit DECSTBM");
    // Second render — same scroll region
    let result2 = render_screen(&grid, "", false, &mut cache);
    assert!(
        result2.is_empty(),
        "same scroll region should produce no-op render"
    );
}

#[test]
fn scroll_region_change_emitted() {
    let mut grid = Grid::new(10, 10, 0);
    let mut cache = RenderCache::new();
    let _ = render_screen(&grid, "", false, &mut cache);
    // Change scroll region to rows 2-8 (0-indexed: 1-7)
    grid.set_scroll_region(1, 7);
    let result = render_screen(&grid, "", false, &mut cache);
    let text = String::from_utf8_lossy(&result);
    assert!(
        text.contains("\x1b[2;8r"),
        "changed scroll region should emit DECSTBM"
    );
}

// --- Origin mode (DECOM) cursor positioning ---

/// Regression: with origin mode (DECOM, ?6) active and a non-default scroll
/// region, the cursor is stored absolutely but the outer terminal interprets
/// CUP relative to the scroll region top. The full render must emit the CUP
/// row origin-relative so the cursor does not land scroll_top rows too low.
#[test]
fn origin_mode_cursor_is_origin_relative() {
    let mut grid = Grid::new(10, 10, 0);
    // Scroll region rows 3..=8 (0-indexed 2..=7), origin mode on.
    grid.set_scroll_region(2, 7);
    grid.modes_mut().origin_mode = true;
    // Absolute cursor at row 5 (a relative row 4 inside the region).
    grid.set_cursor_y_unclamped(5);
    grid.set_cursor_x_unclamped(0);

    let mut cache = RenderCache::new();
    let result = render_screen(&grid, "", true, &mut cache);
    let text = String::from_utf8_lossy(&result);

    // DECOM must be enabled and the scroll region emitted.
    assert!(text.contains("\x1b[?6h"), "origin mode should be emitted");
    assert!(
        text.contains("\x1b[3;8r"),
        "scroll region should be emitted"
    );
    // The cursor CUP is the one emitted AFTER the mode sequences (the row
    // loop also emits per-row CUPs). It must be origin-relative:
    // absolute 5 - scroll_top 2 = 3 → 1-indexed 4, not the absolute 6.
    let after_modes = &text[text.find("\x1b[?6h").unwrap()..];
    assert!(
        after_modes.contains("\x1b[4;1H"),
        "origin-mode cursor CUP must be relative to scroll_top, got: {:?}",
        text
    );
    assert!(
        !after_modes.contains("\x1b[6;1H"),
        "absolute cursor CUP must not be emitted under origin mode, got: {:?}",
        text
    );
}

/// The DECOM fix must apply on the public renderer path too,
/// since both paths share the same core emitter.
#[test]
fn trait_origin_mode_cursor_is_origin_relative() {
    use super::super::Screen;

    let mut screen = Screen::new(10, 10, 0);
    // DECSTBM rows 3..=8, enable origin mode, relative CUP to region row 4.
    screen.process(b"\x1b[3;8r");
    screen.process(b"\x1b[?6h");
    screen.process(b"\x1b[4;1H");

    let mut renderer = AnsiRenderer::new();
    let result = renderer.render(&screen, true);
    let text = String::from_utf8_lossy(&result);

    assert!(text.contains("\x1b[?6h"), "origin mode should be emitted");
    // Absolute cursor is scroll_top(2) + 4 - 1 = 5; origin-relative CUP is row 4.
    let after_modes = &text[text.find("\x1b[?6h").unwrap()..];
    assert!(
        after_modes.contains("\x1b[4;1H"),
        "trait-path origin-mode cursor CUP must be origin-relative, got: {:?}",
        text
    );
    assert!(
        !after_modes.contains("\x1b[6;1H"),
        "trait path must not emit absolute cursor CUP under origin mode, got: {:?}",
        text
    );
}

/// Without origin mode the CUP must remain absolute even with a scroll region.
#[test]
fn no_origin_mode_cursor_is_absolute() {
    let mut grid = Grid::new(10, 10, 0);
    grid.set_scroll_region(2, 7);
    grid.set_cursor_y_unclamped(5);
    grid.set_cursor_x_unclamped(0);

    let mut cache = RenderCache::new();
    let result = render_screen(&grid, "", true, &mut cache);
    let text = String::from_utf8_lossy(&result);
    // The cursor CUP (after the mode sequences, which emit ?6l) must be the
    // absolute row 6, not an origin-relative one.
    let after_modes = &text[text.find("\x1b[?6l").unwrap()..];
    assert!(
        after_modes.contains("\x1b[6;1H"),
        "without origin mode cursor CUP must be absolute, got: {:?}",
        text
    );
}

// --- Mode delta encoding ---

#[test]
fn modes_delta_skips_unchanged() {
    let mut grid = Grid::new(10, 3, 0);
    let mut cache = RenderCache::new();
    // First render establishes baseline modes
    let _ = render_screen(&grid, "", false, &mut cache);
    // Change only bracketed paste
    grid.modes_mut().bracketed_paste = true;
    let result = render_screen(&grid, "", false, &mut cache);
    let text = String::from_utf8_lossy(&result);
    // Should have bracketed paste enable
    assert!(
        text.contains("\x1b[?2004h"),
        "changed mode should be emitted"
    );
    // Should NOT re-emit unchanged modes like cursor shape, autowrap, etc.
    assert!(
        !text.contains(" q"),
        "unchanged cursor shape should not be re-emitted in delta"
    );
    assert!(
        !text.contains("\x1b[?7"),
        "unchanged autowrap should not be re-emitted in delta"
    );
}

#[test]
fn modes_full_always_emitted() {
    let grid = Grid::new(10, 3, 0);
    let mut cache = RenderCache::new();
    let _ = render_screen(&grid, "", false, &mut cache);
    // Full render with no mode changes — all modes must still be emitted
    let result = render_screen(&grid, "", true, &mut cache);
    let text = String::from_utf8_lossy(&result);
    assert!(text.contains(" q"), "full render must emit cursor shape");
    assert!(text.contains("\x1b[?7"), "full render must emit autowrap");
}

// --- Title caching ---

#[test]
fn title_not_reemitted_when_unchanged() {
    let grid = Grid::new(10, 3, 0);
    let mut cache = RenderCache::new();
    let _ = render_screen(&grid, "MyApp", false, &mut cache);
    // Same title — should not be in output
    let result = render_screen(&grid, "MyApp", false, &mut cache);
    assert_eq!(
        count_pattern(&result, b"\x1b]2;"),
        0,
        "unchanged title should not produce OSC"
    );
}

#[test]
fn title_emitted_when_changed() {
    let grid = Grid::new(10, 3, 0);
    let mut cache = RenderCache::new();
    let _ = render_screen(&grid, "OldTitle", false, &mut cache);
    let result = render_screen(&grid, "NewTitle", false, &mut cache);
    assert_eq!(
        count_pattern(&result, b"\x1b]2;"),
        1,
        "changed title should emit exactly one OSC"
    );
    assert!(
        result.windows(8).any(|w| w == b"NewTitle"),
        "new title should be in output"
    );
}

// --- Incremental render byte efficiency ---

#[test]
fn incremental_render_smaller_than_full() {
    let mut grid = Grid::new(80, 24, 0);
    // Fill several rows with text
    for i in 0..24 {
        grid.visible_row_mut(i)[0].c = 'A';
    }
    let mut cache = RenderCache::new();
    // Full render
    let full = render_screen(&grid, "Title", true, &mut cache);
    // Change only one row
    grid.visible_row_mut(5)[1].c = 'B';
    let incr = render_screen(&grid, "Title", false, &mut cache);
    assert!(
        incr.len() < full.len(),
        "incremental single-row change ({} bytes) should be smaller than full ({} bytes)",
        incr.len(),
        full.len()
    );
}

#[test]
fn incremental_no_screen_clear() {
    let grid = Grid::new(10, 3, 0);
    let mut cache = RenderCache::new();
    let _ = render_screen(&grid, "", false, &mut cache);
    // Change one cell
    let mut grid2 = grid;
    grid2.visible_row_mut(0)[0].c = 'X';
    let result = render_screen(&grid2, "", false, &mut cache);
    assert_eq!(
        count_pattern(&result, b"\x1b[2J"),
        0,
        "incremental render must never emit screen clear"
    );
}

// --- Sync block structure ---

#[test]
fn noop_render_no_sync_block() {
    let grid = Grid::new(10, 3, 0);
    let mut cache = RenderCache::new();
    let _ = render_screen(&grid, "", false, &mut cache);
    let result = render_screen(&grid, "", false, &mut cache);
    // No-op should not even start a sync block
    assert_eq!(
        count_pattern(&result, b"\x1b[?2026h"),
        0,
        "no-op render should not emit sync begin"
    );
    assert_eq!(
        count_pattern(&result, b"\x1b[?2026l"),
        0,
        "no-op render should not emit sync end"
    );
}

#[test]
fn non_noop_render_has_sync_block() {
    let mut grid = Grid::new(10, 3, 0);
    let mut cache = RenderCache::new();
    let _ = render_screen(&grid, "", false, &mut cache);
    grid.visible_row_mut(0)[0].c = 'X';
    let result = render_screen(&grid, "", false, &mut cache);
    assert_eq!(
        count_pattern(&result, b"\x1b[?2026h"),
        1,
        "non-noop render must have exactly one sync begin"
    );
    assert_eq!(
        count_pattern(&result, b"\x1b[?2026l"),
        1,
        "non-noop render must have exactly one sync end"
    );
}

// --- Full redraw does NOT emit per-row EL ---

#[test]
fn full_render_no_erase_line() {
    let mut grid = Grid::new(10, 3, 0);
    grid.visible_row_mut(0)[0].c = 'A';
    let mut cache = RenderCache::new();
    let result = render_screen(&grid, "", true, &mut cache);
    // Full render clears screen with \x1b[2J so per-row \x1b[K is redundant
    assert_eq!(
        count_pattern(&result, b"\x1b[K"),
        0,
        "full render should not emit per-row erase (screen already cleared)"
    );
}

#[test]
fn incremental_render_uses_erase_line() {
    let mut grid = Grid::new(10, 3, 0);
    let mut cache = RenderCache::new();
    let _ = render_screen(&grid, "", false, &mut cache);
    grid.visible_row_mut(0)[0].c = 'A';
    let result = render_screen(&grid, "", false, &mut cache);
    assert!(
        count_pattern(&result, b"\x1b[K") >= 1,
        "incremental render should use erase-to-EOL for changed rows"
    );
}

// --- Trait path optimality parity ---

#[test]
fn trait_noop_render_no_sync_block() {
    use super::super::Screen;

    let mut screen = Screen::new(10, 3, 0);
    screen.process(b"Hi");

    let mut renderer = AnsiRenderer::new();
    let _ = renderer.render(&screen, false);
    let result = renderer.render(&screen, false);
    assert!(result.is_empty(), "trait no-op should be empty");
    assert_eq!(
        count_pattern(&result, b"\x1b[?2026h"),
        0,
        "trait no-op should not emit sync begin"
    );
}

#[test]
fn trait_cursor_position_cached() {
    use super::super::Screen;

    let mut screen = Screen::new(10, 5, 0);
    screen.process(b"\x1b[3;4H"); // cursor at row 3, col 4

    let mut renderer = AnsiRenderer::new();
    let result1 = renderer.render(&screen, false);
    let text1 = String::from_utf8_lossy(&result1);
    assert!(text1.contains("\x1b[3;4H"), "first render should emit CUP");

    // Same position — no CUP
    let result2 = renderer.render(&screen, false);
    assert!(
        result2.is_empty(),
        "trait path: same cursor position should produce no-op"
    );

    // Move cursor — CUP emitted
    screen.process(b"\x1b[1;1H");
    let result3 = renderer.render(&screen, false);
    let text3 = String::from_utf8_lossy(&result3);
    assert!(
        text3.contains("\x1b[1;1H"),
        "trait path: new cursor position should emit CUP"
    );
}

#[test]
fn trait_mode_delta_only_changed() {
    use super::super::Screen;

    let mut screen = Screen::new(10, 3, 0);
    let mut renderer = AnsiRenderer::new();
    let _ = renderer.render(&screen, false);

    // Enable bracketed paste
    screen.process(b"\x1b[?2004h");
    let result = renderer.render(&screen, false);
    let text = String::from_utf8_lossy(&result);
    assert!(
        text.contains("\x1b[?2004h"),
        "changed mode should be emitted"
    );
    // Should not re-emit all modes
    assert!(
        !text.contains(" q"),
        "unchanged cursor shape should be skipped"
    );
}

#[test]
fn trait_title_cached() {
    use super::super::Screen;

    let mut screen = Screen::new(10, 3, 0);
    screen.process(b"\x1b]2;AppTitle\x07");

    let mut renderer = AnsiRenderer::new();
    let result1 = renderer.render(&screen, false);
    assert!(
        count_pattern(&result1, b"\x1b]2;") == 1,
        "first render emits title"
    );

    let result2 = renderer.render(&screen, false);
    assert!(result2.is_empty(), "same title should produce no-op");

    // Change title
    screen.process(b"\x1b]2;NewTitle\x07");
    let result3 = renderer.render(&screen, false);
    assert!(
        count_pattern(&result3, b"\x1b]2;") == 1,
        "changed title emitted"
    );
}

#[test]
fn trait_incremental_smaller_than_full() {
    use super::super::Screen;

    let mut screen = Screen::new(80, 24, 0);
    for i in 0..24u8 {
        screen.process(format!("\x1b[{};1H{}", i + 1, (b'A' + i) as char).as_bytes());
    }

    let mut renderer = AnsiRenderer::new();
    let full = renderer.render(&screen, true);

    // Change one row
    screen.process(b"\x1b[5;1HCHANGED");
    let incr = renderer.render(&screen, false);
    assert!(
        incr.len() < full.len(),
        "trait incremental ({} bytes) should be smaller than full ({} bytes)",
        incr.len(),
        full.len()
    );
}

/// Byte-equivalence pin: the production trait-driven assembly
/// (`render_emulator_impl`) and the test-only Grid-driven assembly
/// (`render_screen_impl`, reached here via `render_screen`) must emit
/// identical bytes for the same non-trivial screen state. This guards the
/// two assembly paths in core.rs against divergence.
#[test]
fn grid_and_trait_assembly_paths_are_byte_identical() {
    // Build a screen with non-trivial state: styled text, scroll region,
    // modes, title, cursor moved.
    let mut screen = crate::screen::Screen::new(20, 6, 50);
    screen.process(b"\x1b[2;5r\x1b[?6h\x1b]2;t\x07\x1b[31mhi\x1b[0m\r\nworld");
    let mut c1 = RenderCache::new();
    let mut c2 = RenderCache::new();
    let via_grid = render_screen(&screen.grid, screen.title(), true, &mut c1);
    let via_trait = super::core::render_emulator_impl(&screen, &[], true, &mut c2);
    assert_eq!(via_grid, via_trait);
}

/// Companion to [`grid_and_trait_assembly_paths_are_byte_identical`] pinning the
/// NON-EMPTY scrollback path. `render_screen_with_scrollback` forces `full=true`
/// internally (via `render_screen_impl(.., scrollback, true, ..)`), so the trait
/// side is called with the same `full=true` for an apples-to-apples comparison.
/// This guards the capacity branch, scrollback injection, and full-promotion —
/// the duplicated, drift-prone logic between the two assembly fns.
#[test]
fn grid_and_trait_assembly_paths_byte_identical_with_scrollback() {
    let mut screen = crate::screen::Screen::new(20, 6, 50);
    screen.process(b"\x1b[2;5r\x1b[?6h\x1b]2;t\x07\x1b[31mhi\x1b[0m\r\nworld");
    let lines: Vec<Vec<u8>> = vec![b"old line 1".to_vec(), b"old line 2".to_vec()];
    let mut c1 = RenderCache::new();
    let mut c2 = RenderCache::new();
    let via_grid = render_screen_with_scrollback(&screen.grid, screen.title(), &lines, &mut c1);
    let via_trait = super::core::render_emulator_impl(&screen, &lines, true, &mut c2);
    assert_eq!(via_grid, via_trait);
}