croft-software 0.2.232

VSCode-style TUI written in Rust
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
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
//! The Problems panel, project checks and markdown lint.

use super::*;

/// The right cluster is painted over the left paragraph, but the diagnostics
/// hit rect was clipped only to the frame edge — never to where that cluster
/// starts. So on a narrow terminal the cells that visibly read "Ln 1, Col 1"
/// still answered to the diagnostics click and opened PROBLEMS, while the
/// counts they claimed to be were not on screen at all.
#[test]
fn clicking_the_position_readout_does_not_open_problems() {
    use ratatui::{Terminal, backend::TestBackend};
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // 56 cols: the right cluster (51 cells with its │ dividers) fits, but its
    // left edge still lands inside the diagnostics cluster, so the clip below
    // is exercised.
    let mut term = Terminal::new(TestBackend::new(56, 20)).unwrap();
    term.draw(|f| app.render(f)).unwrap();

    // Find the status row and the column where the position readout paints.
    let buf = term.backend().buffer();
    let row = buf.area.height - 1;
    let text: String = (0..buf.area.width)
        .map(|x| buf[(x, row)].symbol().chars().next().unwrap_or(' '))
        .collect();
    let ln_col =
        text.find("Ln ")
            .unwrap_or_else(|| panic!("no position readout in status row {text:?}")) as u16;

    // The right cluster begins with " Ln", so its left edge is one cell before.
    let rx = ln_col.saturating_sub(1);
    assert!(
        app.status_hits.diagnostics.right() <= rx,
        "the diagnostics hit rect must stop where the right cluster starts \
         (rect {:?} reaches {}, cluster starts at {}); row reads {text:?}",
        app.status_hits.diagnostics,
        app.status_hits.diagnostics.right(),
        rx
    );
    // And concretely: the cells that visibly read "Col 1" must not be a
    // diagnostics target.
    let col_at = text.find("Col ").unwrap() as u16;
    assert!(
        !rect_contains(app.status_hits.diagnostics, col_at, row),
        "clicking the column readout opened PROBLEMS"
    );
}

#[test]
fn sync_markdown_lint_flags_a_second_top_level_heading() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("a.md");
    std::fs::write(&file, "# Title\n\nBody.\n\n# Another\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&file).unwrap();
    let changed = app.sync_markdown_lint();
    assert!(changed, "a fresh markdown tab must lint on first sync");
    assert_eq!(app.editor.diagnostics_path(), Some(file.as_path()));
    assert!(
        app.editor
            .diagnostic_spans_for_test()
            .iter()
            .any(|line| !line.is_empty()),
        "MD025 should have produced at least one squiggle"
    );
    let merged = app.merged_diagnostics(&file);
    assert!(merged.iter().any(|d| d.message.contains("MD025")));
}

#[test]
fn sync_markdown_lint_is_quiet_for_a_clean_document_and_reruns_only_on_edit() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("clean.md");
    std::fs::write(&file, "# Title\n\nA clean paragraph.\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&file).unwrap();
    // A clean document has nothing to apply, so the first sync reports no
    // change even though it did run the linter once.
    assert!(!app.sync_markdown_lint());
    assert!(
        app.merged_diagnostics(&file).is_empty(),
        "a clean document must not be flagged"
    );
    // Re-syncing an unchanged buffer must be a no-op (gated by edit_seq).
    assert!(!app.sync_markdown_lint());

    // The other half of this test's name: an EDIT must bump edit_seq, get the
    // buffer re-linted, and surface the new violation. Without this the test
    // passed on a linter that never ran a second time.
    app.editor.goto_bottom();
    app.editor
        .insert_str_as("\n# Second Title\n", crate::provenance::Seat::Navigator);
    assert!(
        app.sync_markdown_lint(),
        "an edit that introduces a second H1 must re-lint and report a change"
    );
    assert!(
        app.merged_diagnostics(&file)
            .iter()
            .any(|d| d.message.contains("MD025")),
        "the second H1 must be flagged after the edit"
    );
}

/// Split panes hold separate buffers of one file, so after an edit in one
/// they carry different `edit_seq`s. The sync must settle on one pane per
/// path rather than alternate between the two, and must not report a change
/// when the diagnostics it stores are the ones already there: either would
/// re-lint and redraw on every tick forever.
#[test]
fn sync_markdown_lint_settles_after_a_split_pane_is_edited() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("doc.md");
    std::fs::write(&file, "# Title\n\n# Second Title\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&file).unwrap();
    app.split_editor();
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 7;
    app.editor.insert_char('!');
    assert!(
        app.sync_markdown_lint(),
        "the first lint stores diagnostics"
    );
    assert!(
        app.merged_diagnostics(&file)
            .iter()
            .any(|d| d.message.contains("MD025")),
        "the edited pane still has two H1s"
    );
    assert!(
        !app.sync_markdown_lint(),
        "nothing changed since the last tick"
    );
    assert!(!app.sync_markdown_lint(), "and it stays settled");
}

/// #851: for a file rumdl reports on, the built-in lint withdraws what it
/// published (rumdl reports the same rules, so each would show twice) and
/// stays quiet; a file rumdl does not report on (one only in a split's other
/// group, never sent to the servers) keeps it; and once rumdl stops
/// reporting on a file the lint runs on it again.
#[test]
fn sync_markdown_lint_stands_down_only_for_files_rumdl_reports_on() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("a.md");
    let other = tmp.path().join("b.md");
    std::fs::write(&file, "# Title\n\nBody.\n\n# Another\n").unwrap();
    std::fs::write(&other, "# Title\n\nBody.\n\n# Another\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&other).unwrap();
    app.editor.open_pinned(&file).unwrap();
    let has_md025 = |app: &App, path: &std::path::Path| {
        app.merged_diagnostics(path)
            .iter()
            .any(|d| d.message.contains("MD025"))
    };
    assert!(app.sync_markdown_lint());
    assert!(has_md025(&app, &file), "the built-in lint reports MD025");
    assert!(has_md025(&app, &other));

    let lsp = || {
        app.lsp
            .manager
            .as_ref()
            .expect("a test App has an LSP manager")
    };
    lsp().set_document_servers_for_test(&file, &["marksman", "rumdl"]);
    lsp().set_document_servers_for_test(&other, &["marksman"]);
    assert!(app.sync_markdown_lint(), "standing down is a change");
    assert!(!has_md025(&app, &file), "withdrawn where rumdl reports");
    assert!(
        app.editor
            .diagnostic_spans_for_test()
            .iter()
            .all(|line| line.is_empty()),
        "and its squiggle is gone from the open tab"
    );
    assert!(has_md025(&app, &other), "kept where rumdl does not report");
    assert!(!app.sync_markdown_lint(), "and it stays quiet");

    // Retired from pulls, or crashed for good: rumdl leaves the file.
    app.lsp
        .manager
        .as_ref()
        .unwrap()
        .set_document_servers_for_test(&file, &["marksman"]);
    assert!(
        app.sync_markdown_lint(),
        "with rumdl gone the lint runs again"
    );
    assert!(has_md025(&app, &file));
}

/// Two panes can reach the same `edit_seq` with different text (one edit in
/// each). Switching which pane is linted must still lint it: the cursor has
/// to recognise a different buffer, not just a different sequence number.
#[test]
fn sync_markdown_lint_relints_a_pane_with_the_same_seq_but_other_text() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("doc.md");
    std::fs::write(&file, "# Title\n\nplain\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&file).unwrap();
    app.split_editor();
    // One edit per pane: the focused pane gains an MD018 heading
    // (`#Bad`), the other a harmless character, so both seqs match.
    app.editor.cursor_row = 2;
    app.editor.cursor_col = 0;
    for c in "#Bad".chars() {
        app.editor.insert_char(c);
    }
    let seq_bad = app.editor.edit_seq;
    // The split put the new, focused pane on the right; move to the left one.
    app.focus_editor_group(true);
    app.editor.cursor_row = 2;
    app.editor.cursor_col = 5;
    // A split does not copy `edit_seq`, so type harmless text until this
    // pane's count meets the other's.
    while app.editor.edit_seq < seq_bad {
        app.editor.insert_char('!');
    }
    assert_eq!(app.editor.edit_seq, seq_bad, "same seq, different text");
    assert!(!app.editor.lines.iter().any(|l| l.starts_with("#B")));
    let md018 = |app: &App| {
        app.merged_diagnostics(&file)
            .iter()
            .any(|d| d.message.contains("MD018"))
    };
    // Lint with the `#Bad` pane focused (it is walked first) ...
    app.focus_editor_group(false);
    app.sync_markdown_lint();
    assert!(md018(&app), "the focused pane has `#Bad`");
    // ... then with the clean pane focused: same seq, other text.
    app.focus_editor_group(true);
    app.sync_markdown_lint();
    assert!(
        !md018(&app),
        "the other pane has no MD018, so it must be re-linted"
    );
}

/// A `.md` held by an INACTIVE split group must still be linted. The gather
/// loop used to walk only `self.editor`, so such a tab was never linted and
/// the cleanup below then dropped its stored diagnostics while it was still
/// open - the squiggles vanished from a pane that was plainly visible.
#[test]
fn sync_markdown_lint_covers_inactive_split_groups() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("doc.md");
    std::fs::write(&file, "# Title\n\n# Second Title\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&file).unwrap();
    app.split_editor(); // both groups hold doc.md; the new one is focused
    // Move the ACTIVE group off the markdown file, so doc.md lives only in
    // the inactive group - the case the gather loop missed. `open_pinned`
    // ADDS a tab, so the old one has to be closed or the active group still
    // holds doc.md and the bug never shows.
    let other = tmp.path().join("other.txt");
    std::fs::write(&other, "plain\n").unwrap();
    app.editor.open_pinned(&other).unwrap();
    let md_idx = app
        .editor
        .iter_tabs()
        .position(|e| e.path.as_deref() == Some(file.as_path()))
        .expect("the active group still holds doc.md before the close");
    app.editor.close_tab(md_idx);
    assert!(
        !app.editor
            .iter_tabs()
            .any(|e| e.path.as_deref() == Some(file.as_path())),
        "doc.md must now live ONLY in the inactive group"
    );

    let held_inactive = app
        .editor_layout
        .inactive_groups()
        .flat_map(|g| g.editors.iter())
        .any(|e| e.path.as_deref() == Some(file.as_path()));
    assert!(held_inactive, "the inactive group holds doc.md");

    app.sync_markdown_lint();
    assert!(
        app.merged_diagnostics(&file)
            .iter()
            .any(|d| d.message.contains("MD025")),
        "a markdown tab in an inactive pane must still be linted"
    );

    // And a second sync must not retire those diagnostics as "closed".
    app.sync_markdown_lint();
    assert!(
        app.merged_diagnostics(&file)
            .iter()
            .any(|d| d.message.contains("MD025")),
        "the tab is still open, so its diagnostics must survive the sweep"
    );
}

#[test]
fn sync_markdown_lint_skips_non_markdown_files() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("a.rs");
    std::fs::write(&file, "#Not a heading, this is Rust\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&file).unwrap();
    assert!(!app.sync_markdown_lint());
    assert!(app.merged_diagnostics(&file).is_empty());
}

#[test]
fn problems_panel_aggregates_the_store_across_files() {
    use crate::lsp::manager::DiagnosticSeverity;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let a = tmp.path().join("a.rs");
    let mut s1 = std::collections::HashMap::new();
    s1.insert(
        String::from("rustc"),
        vec![
            diag(0, 1, DiagnosticSeverity::Error),
            diag(2, 3, DiagnosticSeverity::Warning),
        ],
    );
    app.lsp.diagnostics.insert(a, s1);
    let b = tmp.path().join("b.rs");
    let mut s2 = std::collections::HashMap::new();
    s2.insert(
        String::from("rustc"),
        vec![diag(0, 1, DiagnosticSeverity::Error)],
    );
    app.lsp.diagnostics.insert(b, s2);

    app.rebuild_problems();
    assert_eq!(
        app.problems.total_count(),
        3,
        "two files, three diagnostics"
    );
    assert_eq!(app.problems.error_count(), 2);
    assert_eq!(app.problems.warning_count(), 1);
}

#[test]
fn clicking_the_problems_tab_switches_the_panel_view() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    assert_eq!(app.bottom_panel_tab, BottomPanelTab::Terminal);
    let r = app.panel_hits.problems_tab;
    assert!(r.width > 0, "the PROBLEMS tab must have a hit rect");
    left_click(&mut app, r.x, r.y);
    assert_eq!(
        app.bottom_panel_tab,
        BottomPanelTab::Problems,
        "a click on the PROBLEMS tab activates that view",
    );
    // And the TERMINAL tab switches back.
    let t = app.panel_hits.terminal_tab;
    left_click(&mut app, t.x, t.y);
    assert_eq!(app.bottom_panel_tab, BottomPanelTab::Terminal);
}

/// Issue #212: typing in the focused Problems panel filters diagnostics
/// by text; Backspace pops a character; Esc clears the filter before it
/// gives the pane back to the editor.
#[test]
fn typing_in_the_problems_panel_filters_and_esc_clears_before_leaving() {
    use crate::lsp::manager::{Diagnostic, DiagnosticSeverity};
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("hello.rs");
    std::fs::write(&file, "fn a() {}\nfn b() {}\nfn run() {}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let mut by_server = std::collections::HashMap::new();
    by_server.insert(
        String::from("rustc"),
        vec![
            Diagnostic {
                start_line: 0,
                start_char: 0,
                end_line: 0,
                end_char: 1,
                severity: DiagnosticSeverity::Error,
                message: String::from("mismatched types"),
                tags: Default::default(),
                code: None,
                origin: None,
            },
            Diagnostic {
                start_line: 2,
                start_char: 3,
                end_line: 2,
                end_char: 6,
                severity: DiagnosticSeverity::Warning,
                message: String::from("function `run` is never used"),
                tags: Default::default(),
                code: None,
                origin: None,
            },
        ],
    );
    app.lsp.diagnostics.insert(file.clone(), by_server);
    app.rebuild_problems();
    app.bottom_panel_tab = BottomPanelTab::Problems;
    app.focus_pane(Pane::Terminal);

    for c in "mismatch".chars() {
        app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
            .unwrap();
    }
    assert_eq!(
        app.problems.text_filter, "mismatch",
        "plain typing must reach the panel's filter"
    );
    app.handle_key(key(KeyCode::Backspace, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.problems.text_filter, "mismatc", "Backspace pops");
    // Esc clears the filter but keeps the pane focused.
    app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
        .unwrap();
    assert!(app.problems.text_filter.is_empty(), "Esc clears the filter");
    assert!(
        app.focus == Pane::Terminal,
        "the first Esc only clears; the pane keeps focus"
    );
    // A second Esc, with nothing to clear, hands the pane back.
    app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
        .unwrap();
    assert!(app.focus == Pane::Editor, "the second Esc leaves the panel");
}

#[test]
fn clicking_a_problem_row_opens_that_file_at_the_line() {
    use crate::lsp::manager::DiagnosticSeverity;
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("hello.rs");
    std::fs::write(&file, "fn a() {}\nfn b() {}\nfn run() {}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let mut by_server = std::collections::HashMap::new();
    by_server.insert(
        String::from("rustc"),
        vec![crate::lsp::manager::Diagnostic {
            start_line: 2,
            start_char: 3,
            end_line: 2,
            end_char: 6,
            severity: DiagnosticSeverity::Warning,
            message: String::from("function `run` is never used"),
            tags: Default::default(),
            code: None,
            origin: None,
        }],
    );
    app.lsp.diagnostics.insert(file.clone(), by_server);
    app.rebuild_problems();
    app.bottom_panel_tab = BottomPanelTab::Problems;

    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    // Row 0 is the toolbar, row 1 the file header, row 2 the diagnostic.
    let list = app.problems.last_area;
    left_click(&mut app, list.x + 4, list.y + 2);
    assert_eq!(
        app.editor.path.as_deref(),
        Some(file.as_path()),
        "clicking the row opens the file",
    );
    assert_eq!(app.editor.cursor_row, 2, "and jumps to the diagnostic line");
}

/// #1523: the places a server points at to explain a diagnostic are rows
/// under it, the file named relative to the workspace, and a click on one
/// opens that place with its UTF-16 column converted (the emoji is two
/// units, one character).
#[test]
fn clicking_a_related_location_row_opens_that_place() {
    let tmp = tempfile::tempdir().unwrap();
    let main = tmp.path().join("src/main.rs");
    let lib = tmp.path().join("src/lib.rs");
    std::fs::create_dir_all(tmp.path().join("src")).unwrap();
    std::fs::write(&main, "fn main() {}\n").unwrap();
    std::fs::write(&lib, "fn a() {}\nlet s = \"😀\"; let first = &v[0];\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let wire = lsp_types::Diagnostic {
        message: "cannot borrow `v` as mutable".into(),
        related_information: Some(vec![lsp_types::DiagnosticRelatedInformation {
            location: lsp_types::Location {
                uri: lsp_types::Url::from_file_path(&lib).unwrap(),
                range: lsp_types::Range::new(
                    lsp_types::Position::new(1, 27),
                    lsp_types::Position::new(1, 28),
                ),
            },
            message: "immutable borrow occurs here".into(),
        }]),
        ..Default::default()
    };
    let d = crate::lsp::client::convert_diagnostic("rust-analyzer", &wire);
    let by_server = std::collections::HashMap::from([(String::from("rust-analyzer"), vec![d])]);
    app.lsp.diagnostics.insert(main, by_server);
    app.rebuild_problems();
    assert_eq!(
        app.problems.groups()[0].items[0].related[0].rel_path,
        "src/lib.rs"
    );
    app.bottom_panel_tab = BottomPanelTab::Problems;
    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    // Row 0 is the toolbar, 1 the file, 2 the diagnostic, 3 its related row.
    let list = app.problems.last_area;
    left_click(&mut app, list.x + 10, list.y + 3);
    assert_eq!(app.editor.path.as_deref(), Some(lib.as_path()));
    assert_eq!(
        (app.editor.cursor_row, app.editor.cursor_col),
        (1, 26),
        "on the `v` the borrow takes"
    );
}

/// #1522: unused names and unreachable code come as hints; like VS Code,
/// the PROBLEMS list and its count leave them out, while the editor (its
/// hover and quick fixes) still has them.
#[test]
fn hints_stay_out_of_the_problems_list_and_its_count() {
    use crate::lsp::manager::{Diagnostic, DiagnosticSeverity, DiagnosticTags};
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let a = tmp.path().join("a.ts");
    let unused = DiagnosticTags {
        unnecessary: true,
        deprecated: false,
    };
    let mut by_server = std::collections::HashMap::new();
    by_server.insert(
        String::from("vtsls"),
        vec![
            diag(0, 1, DiagnosticSeverity::Error),
            Diagnostic {
                tags: unused,
                ..diag(2, 5, DiagnosticSeverity::Hint)
            },
            diag(6, 9, DiagnosticSeverity::Hint),
            diag(10, 12, DiagnosticSeverity::Warning),
        ],
    );
    app.lsp.diagnostics.insert(a.clone(), by_server);
    app.rebuild_problems();
    assert_eq!(
        app.problems.total_count(),
        2,
        "only the error and the warning count"
    );
    let listed: Vec<DiagnosticSeverity> = app
        .problems
        .groups()
        .iter()
        .flat_map(|g| g.items.iter().map(|i| i.severity))
        .collect();
    assert_eq!(
        listed,
        vec![DiagnosticSeverity::Error, DiagnosticSeverity::Warning]
    );
    assert_eq!(
        app.merged_diagnostics(&a).len(),
        4,
        "the editor still gets every hint, for its hover and Ctrl+."
    );
}

/// #1522, negative: a file with nothing but hints has no PROBLEMS group,
/// while information diagnostics are still listed.
#[test]
fn a_file_with_only_hints_has_no_problems_group_but_information_is_listed() {
    use crate::lsp::manager::DiagnosticSeverity;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let hints = tmp.path().join("hints.py");
    let info = tmp.path().join("info.py");
    let mut h = std::collections::HashMap::new();
    h.insert(
        String::from("ty"),
        vec![
            diag(0, 3, DiagnosticSeverity::Hint),
            diag(4, 7, DiagnosticSeverity::Hint),
        ],
    );
    app.lsp.diagnostics.insert(hints, h);
    let mut i = std::collections::HashMap::new();
    i.insert(
        String::from("ty"),
        vec![diag(0, 3, DiagnosticSeverity::Information)],
    );
    app.lsp.diagnostics.insert(info.clone(), i);
    app.rebuild_problems();
    let paths: Vec<&std::path::PathBuf> = app.problems.groups().iter().map(|g| &g.path).collect();
    assert_eq!(paths, vec![&info]);
    assert_eq!(app.problems.total_count(), 1);
}

#[test]
fn the_problems_count_paints_an_orange_pill_in_the_tab_strip() {
    use crate::lsp::manager::DiagnosticSeverity;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // The boxed brand theme's pill; Croft Loch's tinted chip is below.
    app.apply_theme(crate::theme::Theme::BLACK);
    let a = tmp.path().join("a.rs");
    let mut s1 = std::collections::HashMap::new();
    s1.insert(
        String::from("rustc"),
        vec![diag(0, 1, DiagnosticSeverity::Error)],
    );
    app.lsp.diagnostics.insert(a, s1);
    app.rebuild_problems();
    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let buf = term.backend().buffer();
    // Somewhere along the PROBLEMS tab the count badge fills with the brand
    // gradient's orange corner, the "circle" the user asked for.
    let strip = app.panel_hits.problems_tab;
    let orange = crate::gradient::rgb_color(crate::gradient::GRAD_TR);
    let painted = (strip.x..strip.x + strip.width).any(|x| buf[(x, strip.y)].bg == orange);
    assert!(painted, "the problem count wears an orange pill");
    // And the rounded right cap of the pill sits in brand orange foreground.
    let cap_r = (strip.x..strip.x + strip.width)
        .any(|x| buf[(x, strip.y)].symbol() == "\u{e0b4}" && buf[(x, strip.y)].fg == orange);
    assert!(cap_r, "the pill has a rounded orange right cap");
}

/// Croft Loch's PROBLEMS count is a tinted chip, red while there are
/// errors, with no Powerline caps and no brand orange, as wide as the
/// boxed pill so the tab's hit rect is unchanged.
#[test]
fn croft_loch_problems_count_is_a_tinted_chip_without_caps() {
    use crate::lsp::manager::DiagnosticSeverity;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let t = crate::theme::tones(app.theme).expect("Croft Loch is the default");
    let a = tmp.path().join("a.rs");
    let mut s1 = std::collections::HashMap::new();
    s1.insert(
        String::from("rustc"),
        vec![diag(0, 1, DiagnosticSeverity::Error)],
    );
    app.lsp.diagnostics.insert(a, s1);
    app.rebuild_problems();
    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let buf = term.backend().buffer();
    let tab = app.panel_hits.problems_tab;
    let cells: Vec<_> = (tab.x..tab.right()).map(|x| &buf[(x, tab.y)]).collect();
    let text: String = cells.iter().map(|c| c.symbol()).collect();
    assert!(text.ends_with(" 1 "), "{text:?}");
    let orange = crate::gradient::rgb_color(crate::gradient::GRAD_TR);
    assert!(
        cells
            .iter()
            .all(|c| !matches!(c.symbol(), "\u{e0b6}" | "\u{e0b4}") && c.bg != orange),
        "no Powerline caps, no orange: {text:?}"
    );
    let digit = cells[cells.len() - 2];
    let red = (0xe5, 0x53, 0x4b);
    let fill = crate::gradient::rgb_color(crate::gradient::lerp_rgb(t.chrome, red, 0.22));
    assert_eq!(digit.bg, fill, "the chip is red laid into the chrome");
    assert_eq!(cells[cells.len() - 1].bg, fill, "padded both sides");
    assert_ne!(digit.fg, digit.bg);
}

#[test]
fn build_scan_installs_problems_replaces_per_pane_and_merges_with_lsp() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let cwd = tmp.path().join("proj");
    std::fs::create_dir(&cwd).unwrap();

    let cargo_out = "error[E0308]: mismatched types\n  --> src/main.rs:12:5\n";
    assert!(app.apply_build_scan(0, Some(&cwd), "cargo build", cargo_out));
    let expected = cwd.join("src/main.rs");
    let groups = app.problems.groups().to_vec();
    let g = groups
        .iter()
        .find(|g| g.path == expected)
        .expect("the resolved file must group in PROBLEMS");
    assert_eq!(g.items.len(), 1);
    assert_eq!(g.items[0].source, "rustc");
    assert_eq!((g.items[0].line, g.items[0].col), (11, 4));

    // A second pane contributes a different file; both coexist.
    assert!(app.apply_build_scan(1, Some(&cwd), "make", "main.c:7:3: error: boom\n"));
    assert_eq!(app.problems.groups().len(), 2);

    // Pane 0 rebuilds clean: its contribution clears, pane 1's stays.
    assert!(app.apply_build_scan(0, Some(&cwd), "cargo build", "   Finished dev profile\n"));
    let groups = app.problems.groups().to_vec();
    assert_eq!(groups.len(), 1, "pane 0's fixed errors must vanish");
    assert!(groups[0].path.ends_with("main.c"));

    // Clean output from a pane with no history is a no-op.
    assert!(!app.apply_build_scan(5, Some(&cwd), "true", "all good\n"));

    app.clear_build_diagnostics();
    assert!(app.problems.groups().is_empty());
    assert!(app.status.contains("Cleared 1 build diagnostic"));
}

#[test]
fn a_custom_matcher_from_matchers_json_feeds_problems() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.matchers = std::sync::Arc::new(crate::problem_matchers::MatcherSet::from_json(
        r##"[ { "name": "mylint",
               "pattern": "^(?P<file>\\S+):(?P<line>\\d+):(?P<col>\\d+) (?P<severity>\\w+) (?P<message>.+)$",
               "severity_map": { "E": "error" },
               "applies_to": "mylint*" } ]"##,
    ));
    let cwd = tmp.path().join("proj");
    std::fs::create_dir(&cwd).unwrap();
    let out = "src/a.py:12:5 E undefined name 'x'\n";
    assert!(app.apply_build_scan(0, Some(&cwd), "mylint src/", out));
    let groups = app.problems.groups().to_vec();
    let g = groups
        .iter()
        .find(|g| g.path == cwd.join("src/a.py"))
        .expect("the custom matcher's file must group in PROBLEMS");
    assert_eq!(g.items.len(), 1);
    assert_eq!(g.items[0].source, "mylint");
    assert_eq!(
        g.items[0].severity,
        crate::lsp::manager::DiagnosticSeverity::Error,
        "severity_map turns E into an error"
    );
    assert_eq!((g.items[0].line, g.items[0].col), (11, 4));

    // The applies_to glob keeps the matcher off other commands: the same
    // output under `cargo build` matches nothing, clearing the pane.
    assert!(app.apply_build_scan(0, Some(&cwd), "cargo build", out));
    assert!(app.problems.groups().is_empty(), "non-matching command");
}

/// A checker that failed to RUN must not read as a clean project (#256).
///
/// `tsc` prints global errors (`error TS5023: Unknown compiler option`)
/// with no `file(line,col)` prefix, so no matcher claims them and the row
/// count is zero - which is exactly what a clean project looks like.
/// Reporting "no problems" there tells the user their code is fine when the
/// checker never checked it. The exit status is the only thing separating
/// the two, which is why it cannot simply be ignored.
#[cfg(unix)]
#[test]
fn a_project_checker_that_failed_to_run_does_not_report_a_clean_project() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    // A failed invocation: non-zero exit, output no matcher claims.
    app.finish_project_check_for_test(
        tmp.path(),
        "error TS5023: Unknown compiler option '--nosuchflag'.\n",
        "",
        false,
    );
    assert!(
        app.status.contains("failed"),
        "an invocation failure must say so, got {:?}",
        app.status
    );
    assert!(
        !app.status.contains("no problems"),
        "and must NOT read as a clean project, got {:?}",
        app.status
    );
    assert!(
        app.status.contains("TS5023"),
        "naming the reason, got {:?}",
        app.status
    );

    // npx reports a missing compiler on STDOUT, not stderr, and opens with
    // a blank line and an ANSI-coloured banner. The earlier version of this
    // test put the text on stderr - the implementation's own wrong
    // assumption, encoded in the fixture, so the bug passed the suite.
    app.finish_project_check_for_test(
        tmp.path(),
        "\n\x1b[41m\x1b[37m This is not the tsc command you are looking for \x1b[0m\n",
        "",
        false,
    );
    assert!(
        app.status.contains("not the tsc command"),
        "the reason is found past a blank line and escapes, got {:?}",
        app.status
    );
    assert!(
        !app.status.contains('\u{1b}'),
        "and carries no escape sequences, got {:?}",
        app.status
    );
    assert_ne!(
        app.status, "The project checker failed: ",
        "an empty reason is the bug this replaced"
    );

    // A genuinely clean project: zero rows AND a zero exit.
    app.finish_project_check_for_test(tmp.path(), "", "", true);
    assert_eq!(
        app.status, "Whole-project check: no problems",
        "a real clean run still reports clean"
    );
}

/// Each producer clears only ITS OWN rows from a shared file (#532).
///
/// `build_diagnostics` held one flat `Vec` per file, so a re-run removed the
/// whole entry and took the other producer's rows with it - and
/// `install_build_diags` recorded a path in `touched` only when the entry was
/// empty, so the SECOND producer to reach a file never listed it and could
/// not clear its rows at all. Two halves of one problem: rows did not carry
/// who produced them.
///
/// #530 made this routine rather than rare: the whole-project sweep reports
/// every file in the project, so it overlaps any pane build by default.
#[test]
fn each_producer_clears_only_its_own_rows_from_a_shared_file() {
    let tmp = tempfile::tempdir().unwrap();
    let shared = tmp.path().join("shared.ts");
    std::fs::write(&shared, "export const a = 1;\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let line = |code: &str| format!("shared.ts(1,1): error {code}: boom.\n");

    // Pane 1 reports the file, then the sweep reports it too.
    app.apply_build_scan(1, Some(tmp.path()), "tsc", &line("TS1001"));
    app.ingest_project_check(Some(tmp.path()), &line("TS2002"));
    app.rebuild_problems();
    let rows = |app: &App| -> Vec<String> {
        app.problems
            .groups()
            .iter()
            .filter(|g| g.path == shared)
            .flat_map(|g| g.items.iter().map(|i| i.message.clone()))
            .collect()
    };
    assert_eq!(
        rows(&app).len(),
        2,
        "both producers' rows are on the shared file, got {:?}",
        rows(&app)
    );

    // The SECOND producer re-runs clean. Its row must go; the pane's stays.
    app.ingest_project_check(Some(tmp.path()), "");
    app.rebuild_problems();
    let after = rows(&app);
    assert_eq!(
        after.len(),
        1,
        "the sweep's row goes and the pane's remains, got {after:?}"
    );
    assert!(
        after[0].contains("TS1001"),
        "the surviving row is the PANE's, not the sweep's: {after:?}"
    );

    // And the reverse: the pane re-runs clean, leaving nothing.
    app.apply_build_scan(1, Some(tmp.path()), "tsc", "");
    app.rebuild_problems();
    assert!(
        rows(&app).is_empty(),
        "with both producers clean the file has no rows, got {:?}",
        rows(&app)
    );
}

/// A file BOTH the sweep and a pane report is counted once, by whoever is
/// reporting (#256).
///
/// `build_diagnostics[f]` holds every producer's items for that file, so
/// summing the store double-counts a shared file. Both orderings are pinned
/// because they fail in opposite directions and one alone would look
/// correct.
///
/// The undercount this doc used to also describe - the second producer never
/// listing a shared file, so it could not clear its rows - was the other half
/// of #532 and is fixed; the rows carry an owner now.
#[cfg(unix)]
#[test]
fn a_file_both_producers_report_is_not_double_counted() {
    let tmp = tempfile::tempdir().unwrap();
    let shared = tmp.path().join("shared.ts");
    let only = tmp.path().join("only.ts");
    std::fs::write(&shared, "export const a = 1;\n").unwrap();
    std::fs::write(&only, "export const b = 2;\n").unwrap();
    let line = |f: &str| format!("{f}(1,1): error TS2322: Type error.\n");

    // Sweep first, then a pane reports the SAME file.
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.finish_project_check_for_test(tmp.path(), &line("shared.ts"), "", false);
    assert_eq!(app.status, "Whole-project check: 1 problem");
    app.apply_build_scan(1, Some(tmp.path()), "tsc", &line("shared.ts"));
    app.finish_project_check_for_test(tmp.path(), &line("shared.ts"), "", false);
    assert_eq!(
        app.status, "Whole-project check: 1 problem",
        "the pane's row for the same file is not the sweep's to count"
    );

    // Pane first, then the sweep reports that file AND another.
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.apply_build_scan(1, Some(tmp.path()), "tsc", &line("shared.ts"));
    app.finish_project_check_for_test(
        tmp.path(),
        &format!("{}{}", line("shared.ts"), line("only.ts")),
        "",
        false,
    );
    assert_eq!(
        app.status, "Whole-project check: 2 problems",
        "the sweep found two, even though a pane got to one of them first"
    );
}

/// The sweep's status counts ITS OWN findings, not the whole panel (#256).
///
/// `problems.total_count()` is the panel's projection: it mixes in every
/// language server's diagnostics and every pane's build output, and the
/// Open Files scope filters it. Under that scope a sweep whose findings are
/// all in unopened files would have reported "no problems" - defeating the
/// one thing the feature exists to do.
#[cfg(unix)]
#[test]
fn the_project_check_count_is_its_own_not_the_panels() {
    use crate::lsp::manager::DiagnosticSeverity;
    let tmp = tempfile::tempdir().unwrap();
    let swept = tmp.path().join("swept.ts");
    let other = tmp.path().join("other.rs");
    std::fs::write(&swept, "export const x: string = 1;\n").unwrap();
    std::fs::write(&other, "fn main() {}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    // An unrelated language-server diagnostic is already in the panel.
    let mut by_server = std::collections::HashMap::new();
    by_server.insert(
        String::from("rust-analyzer"),
        vec![diag(0, 4, DiagnosticSeverity::Error)],
    );
    app.lsp.diagnostics.insert(other.clone(), by_server);

    app.finish_project_check_for_test(
        tmp.path(),
        "swept.ts(1,14): error TS2322: Type 'number' is not assignable.\n",
        "",
        false,
    );
    assert_eq!(
        app.status, "Whole-project check: 1 problem",
        "the sweep found one; the LSP's row is not its to count"
    );
    assert!(
        app.problems.total_count() > 1,
        "staging check: the panel really does hold more than the sweep's row"
    );

    // Under Open Files the panel hides the unopened file - the count must
    // not follow it down, or the sweep reports nothing it just found.
    app.problems.scope = crate::widgets::problems::ProblemScope::OpenFiles;
    app.rebuild_problems();
    app.finish_project_check_for_test(
        tmp.path(),
        "swept.ts(1,14): error TS2322: Type 'number' is not assignable.\n",
        "",
        false,
    );
    assert_eq!(
        app.status, "Whole-project check: 1 problem",
        "the scope filters the PANEL, not what the sweep found"
    );
}

/// "Problems: Check Whole Project" puts a whole-project checker's findings
/// into PROBLEMS for files nobody opened, and a re-run REPLACES them (#256).
///
/// Replacement is the half worth pinning. A checker that reports two errors
/// and then one after a fix must leave one row, not three: the panel is a
/// current state, and a stale row sends the reader to a line that is now
/// correct. `apply_build_scan` already owns that semantics per producer, so
/// the project check gets its own producer id rather than borrowing a
/// pane's: a pane's next command would otherwise wipe the sweep's rows, and
/// the sweep would wipe the pane's.
#[test]
fn a_project_check_reports_unopened_files_and_replaces_on_rerun() {
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.ts");
    let b = tmp.path().join("b.ts");
    std::fs::write(&a, "export const x: string = 1;\n").unwrap();
    std::fs::write(&b, "export const y: string = 2;\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    // Neither file is opened: the sweep is exactly for files with no buffer.
    assert!(app.editor.path.is_none(), "no file is open");

    // Two errors, in tsc's parenthesised form.
    app.ingest_project_check(
        None,
        "a.ts(1,14): error TS2322: Type 'number' is not assignable to type 'string'.\n\
         b.ts(1,14): error TS2322: Type 'number' is not assignable to type 'string'.\n",
    );
    app.rebuild_problems();
    let paths: Vec<_> = app
        .problems
        .groups()
        .iter()
        .map(|g| g.path.clone())
        .collect();
    assert!(
        paths.contains(&a) && paths.contains(&b),
        "both unopened files must reach PROBLEMS, got {paths:?}"
    );

    // The user fixes b.ts and re-runs: one row, not three.
    app.ingest_project_check(
        None,
        "a.ts(1,14): error TS2322: Type 'number' is not assignable to type 'string'.\n",
    );
    app.rebuild_problems();
    let paths: Vec<_> = app
        .problems
        .groups()
        .iter()
        .map(|g| g.path.clone())
        .collect();
    assert!(
        paths.contains(&a),
        "the still-broken file keeps its row, got {paths:?}"
    );
    assert!(
        !paths.contains(&b),
        "a re-run REPLACES the previous sweep: the fixed file's row must go, \
         got {paths:?}"
    );

    // A pane's own build output must not wipe the sweep, which is why the
    // sweep does not borrow a pane id. Pane 1 reports on its own file.
    let c = tmp.path().join("c.ts");
    std::fs::write(&c, "export const z = 3;\n").unwrap();
    app.apply_build_scan(
        1,
        Some(tmp.path()),
        "tsc",
        "c.ts(1,1): error TS1005: ';' expected.\n",
    );
    app.rebuild_problems();
    let paths: Vec<_> = app
        .problems
        .groups()
        .iter()
        .map(|g| g.path.clone())
        .collect();
    assert!(
        paths.contains(&a) && paths.contains(&c),
        "a pane's build output and the project sweep coexist, got {paths:?}"
    );
}

/// #256 step 1: a server that publishes project-wide diagnostics (rust-analyzer
/// does this from `cargo check`) names files the user never opened. The panel
/// builds from the diagnostics store rather than from open buffers, so those
/// rows DO appear — this pins that half, which the issue lists as unverified.
#[test]
fn problems_shows_diagnostics_for_a_file_that_was_never_opened() {
    use crate::lsp::manager::DiagnosticSeverity;
    let tmp = tempfile::tempdir().unwrap();
    let opened = tmp.path().join("opened.rs");
    let never = tmp.path().join("never_opened.rs");
    std::fs::write(&opened, "fn main() {}\n").unwrap();
    std::fs::write(&never, "fn helper() {}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&opened).unwrap();

    let mut by_server = std::collections::HashMap::new();
    by_server.insert(
        String::from("rust-analyzer"),
        vec![diag(0, 4, DiagnosticSeverity::Error)],
    );
    app.lsp.diagnostics.insert(never.clone(), by_server);
    app.rebuild_problems();

    let paths: Vec<_> = app.problems.groups().iter().map(|g| &g.path).collect();
    assert!(
        paths.contains(&&never),
        "a diagnostic for an unopened file must still reach PROBLEMS"
    );
}

/// #256: the scope toggle changes which files the panel lists, and the badge
/// counts the same list — both read one projection, so they cannot disagree.
#[test]
fn problems_scope_toggle_filters_unopened_files_and_the_badge_follows() {
    use crate::lsp::manager::DiagnosticSeverity;
    use crate::widgets::problems::ProblemScope;
    let tmp = tempfile::tempdir().unwrap();
    let opened = tmp.path().join("opened.rs");
    let never = tmp.path().join("never_opened.rs");
    std::fs::write(&opened, "fn main() {}\n").unwrap();
    std::fs::write(&never, "fn helper() {}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&opened).unwrap();

    for p in [&opened, &never] {
        let mut by_server = std::collections::HashMap::new();
        by_server.insert(
            String::from("rust-analyzer"),
            vec![diag(0, 4, DiagnosticSeverity::Error)],
        );
        app.lsp.diagnostics.insert(p.clone(), by_server);
    }

    app.problems.scope = ProblemScope::WholeProject;
    app.rebuild_problems();
    assert_eq!(
        app.problems.groups().len(),
        2,
        "whole project lists the unopened file too"
    );
    let whole_count = app.problems.total_count();

    app.problems.scope = ProblemScope::OpenFiles;
    app.rebuild_problems();
    let paths: Vec<_> = app.problems.groups().iter().map(|g| &g.path).collect();
    assert_eq!(paths, vec![&opened], "open files drops the unopened one");
    assert!(
        app.problems.total_count() < whole_count,
        "the badge counts the same filtered list"
    );
}

/// #296 review: Open Files scope filters on the open-buffer set, so the panel
/// must refresh when that set changes — not only when diagnostics do.
/// Previously `rebuild_problems` ran on diagnostic events alone, so opening a
/// file that already had stored diagnostics showed NOTHING until some
/// unrelated churn happened to trigger a rebuild.
#[test]
fn opening_a_file_refreshes_a_scoped_problems_panel() {
    use crate::lsp::manager::DiagnosticSeverity;
    use crate::widgets::problems::ProblemScope;
    let tmp = tempfile::tempdir().unwrap();
    let later = tmp.path().join("later.rs");
    std::fs::write(&later, "fn helper() {}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.problems.scope = ProblemScope::OpenFiles;

    // A diagnostic arrives for a file that is not open yet.
    let mut by_server = std::collections::HashMap::new();
    by_server.insert(
        String::from("rust-analyzer"),
        vec![diag(0, 4, DiagnosticSeverity::Error)],
    );
    app.lsp.diagnostics.insert(later.clone(), by_server);
    app.rebuild_problems();
    assert!(
        app.problems.groups().is_empty(),
        "not open yet, so Open Files scope hides it"
    );

    // Opening it must bring the row in WITHOUT any new diagnostic push.
    app.editor.open_pinned(&later).unwrap();
    app.sync_lsp();
    let paths: Vec<_> = app.problems.groups().iter().map(|g| &g.path).collect();
    assert!(
        paths.contains(&&later),
        "opening the file refreshes the scoped panel"
    );
}

/// The config token round-trips: writing a scope back and reading it must
/// yield the same scope. `label()` is display text, so using it here would
/// produce a value `from_config` only accepts by accident.
#[test]
fn problem_scope_config_tokens_round_trip() {
    use crate::widgets::problems::ProblemScope;
    for scope in [ProblemScope::OpenFiles, ProblemScope::WholeProject] {
        assert_eq!(
            ProblemScope::from_config(scope.to_config()),
            scope,
            "{} must survive a save/load cycle",
            scope.to_config()
        );
    }
    // The palette label pasted into a config is understood, not silently
    // treated as an unrecognised value.
    assert_eq!(
        ProblemScope::from_config("Open Files"),
        ProblemScope::OpenFiles
    );
    // Anything genuinely unrecognised shows more rather than hiding rows.
    assert_eq!(
        ProblemScope::from_config("nonsense"),
        ProblemScope::WholeProject
    );
}

/// A PROBLEMS count that goes to zero clears the screen only if a badge was
/// drawn: start-up and graphics re-inits no longer wipe the screen.
#[test]
fn a_zero_problem_count_clears_nothing_when_no_badge_was_drawn() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.overlays
        .activity
        .set_images(super::ActivityBarImages::default());
    app.problems_badge_count = usize::MAX;
    app.refresh_problems_badge();
    assert!(!app.consume_problems_badge_image_clear());
}

/// A solution-style tsconfig (`"files": []` plus `references`, as Vite's
/// TypeScript templates write) checks each referenced project, so their
/// errors are reported instead of "no problems" (#1291).
#[cfg(unix)]
#[test]
fn the_project_check_checks_each_referenced_tsconfig() {
    let tmp = fake_tsc_workspace(
        r#"{
  // Vite's layout
  "files": [],
  "references": [{ "path": "./tsconfig.app.json" }, { "path": "./tsconfig.node.json" }],
}"#,
    );
    let (status, calls) = run_project_check(&tmp);
    assert_eq!(
        calls,
        "-p ./tsconfig.app.json --noEmit\n-p ./tsconfig.node.json --noEmit\n"
    );
    assert_eq!(status, "Whole-project check: 1 problem");
}

/// #2562: a check whose thread crashed is no longer running. The crash
/// notice tells the user; the next Check Project then runs, instead of
/// answering "A whole-project check is already running" until a restart.
#[cfg(unix)]
#[test]
fn a_project_check_whose_thread_crashed_lets_the_next_one_run() {
    let tmp = fake_tsc_workspace(r#"{ "files": ["src/main.ts"] }"#);
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.project_check = Some(
        crate::jobs::Job::spawn("check-project", crate::jobs::Start::Now, || {
            panic!("the check crashed (on purpose, in a test)")
        })
        .unwrap(),
    );
    crate::test_budget::await_spawned(
        std::time::Duration::from_secs(1),
        "the crashed check to settle",
        || {
            app.drain_project_check();
            app.project_check.is_none()
        },
    );
    app.run_command(crate::widgets::command_palette::Command::ProblemsCheckProject);
    assert_eq!(app.status, "Checking the whole project...");
    assert!(app.project_check.is_some(), "the next check started");
}

/// A root tsconfig with `references` that also owns files gets its own
/// `--noEmit` run: tsc does not check references on a plain project
/// check, so skipping the root would hide its files' errors (#1291).
#[cfg(unix)]
#[test]
fn a_root_with_references_and_its_own_files_is_checked_too() {
    let tmp = fake_tsc_workspace(
        r#"{ "include": ["src"], "references": [{ "path": "./tsconfig.app.json" }] }"#,
    );
    let (status, calls) = run_project_check(&tmp);
    assert_eq!(calls, "--noEmit\n-p ./tsconfig.app.json --noEmit\n");
    assert_eq!(status, "Whole-project check: 1 problem");
}

/// A reference that is itself a solution-style config is followed to its
/// leaves rather than run on its own, which would compile nothing (#1291).
#[cfg(unix)]
#[test]
fn a_nested_solution_reference_is_checked_through_its_leaves() {
    let tmp = fake_tsc_workspace(r#"{ "files": [], "references": [{ "path": "./web" }] }"#);
    std::fs::create_dir_all(tmp.path().join("web")).unwrap();
    std::fs::write(
        tmp.path().join("web/tsconfig.json"),
        r#"{ "files": [], "references": [{ "path": "./tsconfig.app.json" }, { "path": ".." }] }"#,
    )
    .unwrap();
    std::fs::write(tmp.path().join("web/tsconfig.app.json"), "{}").unwrap();
    let (status, calls) = run_project_check(&tmp);
    assert_eq!(calls, "-p ./web/./tsconfig.app.json --noEmit\n");
    assert_eq!(status, "Whole-project check: 1 problem");
}

/// A diagnostic for the Problems panel, as a language server reports it.
fn problem(
    line: u32,
    severity: crate::lsp::manager::DiagnosticSeverity,
    message: &str,
) -> crate::widgets::problems::ProblemItem {
    crate::widgets::problems::ProblemItem {
        line,
        col: 0,
        col_utf16: true,
        severity,
        message: message.into(),
        source: "ruff".into(),
        code: None,
        related: Vec::new(),
    }
}

#[test]
fn the_problems_tab_is_announced_with_its_counts_and_top_entry() {
    use crate::lsp::manager::DiagnosticSeverity::{Error, Warning};
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus = Pane::Terminal;
    app.bottom_panel_tab = BottomPanelTab::Problems;
    let snap = app.a11y_snapshot();
    assert_eq!(snap.focus, "Problems, no problems");
    assert_eq!(snap.item, None);
    app.problems
        .set_groups(vec![crate::widgets::problems::ProblemGroup {
            path: tmp.path().join("app.py"),
            name: "app.py".into(),
            rel_dir: String::new(),
            items: vec![
                problem(3, Error, "Undefined name `totl`"),
                problem(4, Error, "Type mismatch"),
                problem(4, Warning, "Unused variable"),
            ],
        }]);
    let snap = app.a11y_snapshot();
    assert_eq!(snap.focus, "Problems, 2 errors, 1 warning");
    assert_eq!(
        snap.item.as_deref(),
        Some("app.py line 4: Undefined name `totl` (ruff)")
    );
    // #1540: a diagnostic with a rule announces it as the row shows it.
    let mut coded = problem(0, Error, "`os` imported but unused");
    coded.code = Some(crate::lsp::manager::DiagnosticCode {
        value: String::from("F401"),
        source: Some(String::from("Ruff")),
        href: None,
    });
    app.problems
        .set_groups(vec![crate::widgets::problems::ProblemGroup {
            path: tmp.path().join("app.py"),
            name: "app.py".into(),
            rel_dir: String::new(),
            items: vec![coded],
        }]);
    assert_eq!(
        app.a11y_snapshot().item.as_deref(),
        Some("app.py line 1: `os` imported but unused (Ruff(F401))")
    );
}

/// #1488: a watcher that clears the screen (`tsc --watch`, `cargo watch -c`)
/// erases its own output mark, so its finish reports no output. That finish
/// never reached the build scan, the one-shot skip meant for it stayed set,
/// and it swallowed the NEXT command's scan instead: PROBLEMS kept the
/// watcher's stale cycle and dropped the new build's errors.
#[test]
fn a_build_after_a_screen_clearing_watcher_reaches_problems() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let pane = app.run_project_task(long_task("tsc --watch")).unwrap();
    let cwd = tmp.path().to_path_buf();
    let stale = "main.ts(1,7): error TS2322: Type 'string' is not assignable to type 'number'.\n";
    let fresh = "main.ts(2,7): error TS2322: Type 'number' is not assignable to type 'string'.\n";
    // The watcher's last cycle, published mid-run.
    assert!(app.apply_build_scan(pane, Some(&cwd), "tsc --watch", stale));
    app.watch_published_panes.insert(pane);
    // Ctrl+C: the watcher's own finish, its output erased by the clears.
    finish_pane_command(&mut app, pane, Some(130), 5_000);
    // The next build in the same pane.
    assert!(
        app.apply_build_scan(pane, Some(&cwd), "tsc", fresh),
        "the build after the watcher is scanned"
    );
    let groups = app.problems.groups().to_vec();
    assert_eq!(groups.len(), 1, "{groups:?}");
    let lines: Vec<u32> = groups[0].items.iter().map(|d| d.line).collect();
    assert_eq!(
        lines,
        vec![1],
        "the build's line 2 error (0-based 1), not the watcher's line 1"
    );
}

/// #1594: a user matcher named `go` is not one of the loose built-in rows,
/// so its rows are kept even for a file not on disk.
#[test]
fn a_custom_matcher_named_go_keeps_rows_for_missing_files() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.matchers = std::sync::Arc::new(crate::problem_matchers::MatcherSet::from_json(
        r##"[ { "name": "go",
               "pattern": "^(?P<file>\\S+):(?P<line>\\d+):(?P<col>\\d+) (?P<severity>\\w+) (?P<message>.+)$",
               "applies_to": "mygo*" } ]"##,
    ));
    let out = "gen/missing.go:3:1 error generated file absent\n";
    assert!(app.apply_build_scan(0, Some(tmp.path()), "mygo build", out));
    let groups = app.problems.groups().to_vec();
    let g = groups
        .iter()
        .find(|g| g.path == tmp.path().join("gen/missing.go"))
        .expect("a user matcher's row must not need an existing file");
    assert_eq!(g.items[0].source, "go");
}

/// #1594: a `go build` error and a flake8 row land in PROBLEMS for files
/// that exist; the same shapes naming no file are not problems.
#[test]
fn go_and_lint_rows_reach_problems_only_for_real_files() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("main.go"), "package main\n").unwrap();
    std::fs::write(tmp.path().join("app.py"), "import os\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let out = "./main.go:4:6: declared and not used: unused\n\
               app.py:1:1: F401 'os' imported but unused\n\
               notes.go:9:9: just some text\n\
               ghost.py:3:1: E999 not a real file\n\
               app.py:2: error: Incompatible types in assignment\n";
    assert!(app.apply_build_scan(3, Some(tmp.path()), "go build ./... ; flake8 app.py", out));
    let mut rows: Vec<(String, u32, String)> = app
        .problems
        .groups()
        .iter()
        .flat_map(|g| {
            let name = g.path.file_name().unwrap().to_string_lossy().into_owned();
            g.items
                .iter()
                .map(move |i| (name.clone(), i.line, i.source.clone()))
        })
        .collect();
    rows.sort();
    assert_eq!(
        rows,
        [
            (String::from("app.py"), 0, String::from("lint")),
            (String::from("app.py"), 1, String::from("no-column")),
            (String::from("main.go"), 3, String::from("go")),
        ]
    );
}

/// Seed the build-diagnostic store the way a finished build does.
fn seed_build_rows(app: &mut App, rows: &[(&std::path::Path, u32, u32, &str)]) {
    use crate::lsp::manager::DiagnosticSeverity;
    for (path, line, col, msg) in rows {
        app.build_diagnostics
            .entry(path.to_path_buf())
            .or_default()
            .push((
                1,
                crate::widgets::problems::ProblemItem {
                    line: *line,
                    col: *col,
                    col_utf16: false,
                    severity: DiagnosticSeverity::Warning,
                    message: (*msg).to_string(),
                    source: String::from("build"),
                    code: None,
                    related: Vec::new(),
                },
            ));
    }
    app.rebuild_problems();
}

#[test]
fn go_to_next_and_previous_problem_walk_the_build_messages_across_files_and_wrap() {
    use crate::widgets::command_palette::Command;
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.c");
    let b = tmp.path().join("b.c");
    std::fs::write(&a, "int a;\nint b;\nint c;\n").unwrap();
    std::fs::write(&b, "int d;\nint e;\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    seed_build_rows(
        &mut app,
        &[(&a, 0, 4, "one"), (&a, 2, 1, "two"), (&b, 1, 2, "three")],
    );
    let next = Command::from_id("next_problem").expect("next_problem id");
    let prev = Command::from_id("previous_problem").expect("previous_problem id");

    // Nothing open: the first entry.
    app.run_command(next);
    assert_eq!(app.editor.path.as_deref(), Some(a.as_path()));
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (0, 4));
    assert!(app.status.contains("Problem 1/3"), "{}", app.status);
    assert!(app.status.contains("one"), "{}", app.status);
    // On an entry: the next one, then across the file boundary, then wrap.
    app.run_command(next);
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (2, 1));
    app.run_command(next);
    assert_eq!(app.editor.path.as_deref(), Some(b.as_path()));
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (1, 2));
    app.run_command(next);
    assert_eq!(
        app.editor.path.as_deref(),
        Some(a.as_path()),
        "wraps to the first"
    );
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (0, 4));
    // And back, wrapping to the last.
    app.run_command(prev);
    assert_eq!(
        app.editor.path.as_deref(),
        Some(b.as_path()),
        "wraps to the last"
    );
    app.run_command(prev);
    assert_eq!(app.editor.path.as_deref(), Some(a.as_path()));
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (2, 1));
}

#[test]
fn go_to_next_problem_between_entries_and_with_none() {
    use crate::widgets::command_palette::Command;
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.c");
    std::fs::write(&a, "int a;\nint b;\nint c;\nint d;\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let next = Command::from_id("next_problem").unwrap();
    app.run_command(next);
    assert_eq!(app.status, "No problems");
    seed_build_rows(&mut app, &[(&a, 1, 0, "x"), (&a, 3, 0, "y")]);
    app.editor.open_pinned(&a).unwrap();
    app.editor.cursor_row = 2;
    app.editor.cursor_col = 0;
    app.run_command(next);
    assert_eq!(app.editor.cursor_row, 3, "the first entry after the caret");
    app.editor.cursor_row = 0;
    app.run_command(Command::from_id("previous_problem").unwrap());
    assert_eq!(
        app.editor.cursor_row, 3,
        "before the first wraps to the last"
    );
}

/// An entry past its line's end leaves the caret clamped short of it, and
/// entries can share a position: repeating Next Problem still walks every
/// entry instead of picking the same one again.
#[test]
fn go_to_next_problem_walks_past_an_entry_beyond_its_line_and_shared_positions() {
    use crate::widgets::command_palette::Command;
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.c");
    std::fs::write(&a, "int a;\nint b;\nint c;\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    seed_build_rows(
        &mut app,
        &[
            (&a, 0, 50, "past the end"),
            (&a, 2, 1, "first here"),
            (&a, 2, 1, "second here"),
        ],
    );
    let next = Command::from_id("next_problem").unwrap();
    app.run_command(next);
    assert!(app.status.contains("past the end"), "{}", app.status);
    assert_eq!(app.editor.cursor_row, 0);
    app.run_command(next);
    assert!(app.status.contains("first here"), "{}", app.status);
    app.run_command(next);
    assert!(app.status.contains("second here"), "{}", app.status);
    app.run_command(next);
    assert!(app.status.contains("past the end"), "wraps: {}", app.status);
}

/// Repeated Next Problem visits every entry once per round, whichever file
/// is open: an LSP row's UTF-16 column and a build row's character column
/// order differently on a line with astral characters, and the walk's order
/// must not change when that file opens, or a step from the remembered
/// entry passes over the rows that moved.
#[test]
fn go_to_next_problem_visits_every_entry_once_around_mixed_columns() {
    use crate::lsp::manager::DiagnosticSeverity;
    use crate::widgets::command_palette::Command;
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.c");
    let b = tmp.path().join("b.c");
    std::fs::write(&a, "\u{1f600}\u{1f600}abc\n").unwrap();
    std::fs::write(&b, "int b;\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let row = |col: u32, col_utf16: bool, msg: &str| {
        (
            1,
            crate::widgets::problems::ProblemItem {
                line: 0,
                col,
                col_utf16,
                severity: DiagnosticSeverity::Warning,
                message: msg.to_string(),
                source: String::from("build"),
                code: None,
                related: Vec::new(),
            },
        )
    };
    // In a.c, `b` is character 3 and UTF-16 column 4 is character 2.
    app.build_diagnostics
        .entry(a.clone())
        .or_default()
        .extend([row(3, false, "at b"), row(4, true, "at a")]);
    app.build_diagnostics
        .entry(b.clone())
        .or_default()
        .push(row(0, false, "in b.c"));
    app.rebuild_problems();
    let next = Command::from_id("next_problem").unwrap();
    let mut seen = Vec::new();
    for _ in 0..3 {
        app.run_command(next);
        seen.push(app.status.clone());
    }
    for msg in ["at a", "at b", "in b.c"] {
        assert_eq!(
            seen.iter().filter(|s| s.contains(msg)).count(),
            1,
            "{msg} once in a round: {seen:?}"
        );
    }
}

/// An entry whose file no longer opens is passed over instead of holding
/// every repeat of Next Problem on itself; when no entry opens, the failure
/// is reported.
#[test]
fn go_to_next_problem_passes_over_an_entry_whose_file_is_gone() {
    use crate::widgets::command_palette::Command;
    let tmp = tempfile::tempdir().unwrap();
    let gone = tmp.path().join("a_gone.c");
    let b = tmp.path().join("b.c");
    std::fs::write(&b, "int b;\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    seed_build_rows(&mut app, &[(&gone, 0, 1, "lost"), (&b, 0, 4, "found")]);
    let next = Command::from_id("next_problem").unwrap();
    app.run_command(next);
    assert_eq!(
        app.editor.path.as_deref(),
        Some(b.as_path()),
        "{}",
        app.status
    );
    assert!(app.status.contains("found"), "{}", app.status);
    std::fs::remove_file(&b).unwrap();
    let mut alone = App::new(tmp.path().to_path_buf()).unwrap();
    seed_build_rows(&mut alone, &[(&gone, 0, 1, "lost")]);
    alone.run_command(next);
    assert!(alone.status.starts_with("Open failed"), "{}", alone.status);
}

/// A watch task's batch is installed without a finished command's scan, and
/// still gets the `build_column_unit` conversion: a gcc display column on a
/// tabbed line lands on the character it names.
#[test]
fn a_watch_batch_gets_the_build_column_conversion() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("t.c"), "{\n\t\t\tint u;\n}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let row = crate::build_matchers::BuildDiag {
        file: String::from("t.c"),
        line: 1,
        // Three tabs at stop 8 put `u` on display column 28.
        col: 28,
        severity: crate::lsp::manager::DiagnosticSeverity::Warning,
        message: String::from("unused"),
        source: String::from("build"),
        needs_file: false,
    };
    app.install_build_diags(
        7,
        Some(tmp.path()),
        vec![row],
        crate::build_matchers::DEFAULT_TABSTOP,
    );
    let rows = &app.build_diagnostics[&tmp.path().join("t.c")];
    assert_eq!(rows.len(), 1);
    assert_eq!(rows[0].1.col, 7, "display column 28 is the `u`, char 7");
}

/// With the bottom panel hidden, the spot where a PROBLEMS row was drawn is
/// the editor's: a right-click there opens the editor's menu, not the hidden
/// problem's.
#[test]
fn a_hidden_problems_panel_takes_no_right_click() {
    use crate::lsp::manager::DiagnosticSeverity;
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("hello.rs");
    let text: String = (0..60).map(|i| format!("fn f{i}() {{}}\n")).collect();
    std::fs::write(&file, &text).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&file).unwrap();
    let mut by_server = std::collections::HashMap::new();
    by_server.insert(
        String::from("rustc"),
        vec![crate::lsp::manager::Diagnostic {
            start_line: 2,
            start_char: 3,
            end_line: 2,
            end_char: 6,
            severity: DiagnosticSeverity::Warning,
            message: String::from("function `f2` is never used"),
            tags: Default::default(),
            code: None,
            origin: None,
        }],
    );
    app.lsp.diagnostics.insert(file.clone(), by_server);
    app.rebuild_problems();
    app.bottom_panel_tab = BottomPanelTab::Problems;
    app.focus_pane(Pane::Editor);
    let _ = draw_buffer(&mut app, 140, 50);
    let list = app.problems.last_area;
    // Right of the line numbers the editor draws once it fills the spot.
    let (x, y) = (list.x + 30, list.y + 2);
    assert!(
        app.problems.diagnostic_at(y).is_some(),
        "a problem row is there"
    );
    app.show_terminal = false;
    let _ = draw_buffer(&mut app, 140, 50);
    assert!(
        rect_contains(app.editor.last_area, x, y),
        "the editor now covers the spot"
    );
    app.handle_mouse(mouse(
        crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Right),
        x,
        y,
    ));
    let labels: Vec<String> = app
        .context_menu
        .as_ref()
        .map(|m| {
            menu_labels(&m.items)
                .into_iter()
                .map(String::from)
                .collect()
        })
        .unwrap_or_default();
    assert!(
        !labels
            .iter()
            .any(|l| l.contains("Navigator") && l.contains("Fix")),
        "the hidden problem's menu opened: {labels:?}"
    );
    assert!(
        labels.iter().any(|l| l.contains("Command Palette")),
        "the editor's menu opens there: {labels:?}"
    );
}

/// #2848: PROBLEMS draws a scrollbar once its rows outgrow the panel, and
/// the bar answers the mouse as every other one does: a press on the track
/// jumps the list there, and dragging the thumb keeps it under the pointer.
#[test]
fn pressing_and_dragging_the_problems_scrollbar_scrolls_the_list() {
    use crate::lsp::manager::DiagnosticSeverity;
    use crate::widgets::problems::ProblemHit;
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("many.rs");
    std::fs::write(&file, "fn a() {}\n".repeat(120)).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let diagnostics = (0..120)
        .map(|line| crate::lsp::manager::Diagnostic {
            start_line: line,
            start_char: 3,
            end_line: line,
            end_char: 4,
            severity: DiagnosticSeverity::Warning,
            message: format!("warning on line {line}"),
            tags: Default::default(),
            code: None,
            origin: None,
        })
        .collect();
    let mut by_server = std::collections::HashMap::new();
    by_server.insert(String::from("rustc"), diagnostics);
    app.lsp.diagnostics.insert(file.clone(), by_server);
    app.rebuild_problems();
    app.bottom_panel_tab = BottomPanelTab::Problems;

    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let bar = app.problems.last_scrollbar;
    assert!(
        bar.width > 0 && bar.height > 2,
        "120 problems in the panel must draw a scrollbar"
    );
    let top_line = |app: &App| match app.problems.hit_at(bar.y) {
        Some(ProblemHit::Diagnostic { line, .. }) => Some(line),
        _ => None,
    };
    assert!(
        matches!(app.problems.hit_at(bar.y), Some(ProblemHit::Header(_))),
        "the list starts at the file's header"
    );

    // A press near the track's foot jumps the list toward its end.
    let foot = bar.y + bar.height - 1;
    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), bar.x, foot));
    term.draw(|f| app.render(f)).unwrap();
    let jumped = top_line(&app);
    assert!(
        jumped.is_some_and(|l| l > 20),
        "a press on the scrollbar's foot must jump the list down, but its top row is line {jumped:?}"
    );

    // Dragging the thumb back to the top follows the pointer up.
    app.handle_mouse(mouse(MouseEventKind::Drag(MouseButton::Left), bar.x, bar.y));
    term.draw(|f| app.render(f)).unwrap();
    assert!(
        matches!(app.problems.hit_at(bar.y), Some(ProblemHit::Header(_))),
        "dragging the thumb to the track's top must bring the header back"
    );
    app.handle_mouse(mouse(MouseEventKind::Up(MouseButton::Left), bar.x, bar.y));
    assert!(app.gesture.is_none(), "the release ends the drag");
}

/// #2863: a scrollbar drag belongs to the bar it started on. Press OUTPUT's
/// bar, switch the panel to PROBLEMS from the keyboard with the button still
/// held (Ctrl+Shift+M), and drag: PROBLEMS must not scroll. The press used
/// to record only the panel, and each drag scrolled whichever list the panel
/// showed by then.
#[test]
fn a_drag_begun_on_the_output_scrollbar_leaves_problems_alone_after_a_tab_switch() {
    use crate::lsp::manager::DiagnosticSeverity;
    use crate::widgets::problems::ProblemHit;
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("many.rs");
    std::fs::write(&file, "fn a() {}\n".repeat(120)).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let diagnostics = (0..120)
        .map(|line| crate::lsp::manager::Diagnostic {
            start_line: line,
            start_char: 3,
            end_line: line,
            end_char: 4,
            severity: DiagnosticSeverity::Warning,
            message: format!("warning on line {line}"),
            tags: Default::default(),
            code: None,
            origin: None,
        })
        .collect();
    let mut by_server = std::collections::HashMap::new();
    by_server.insert(String::from("rustc"), diagnostics);
    app.lsp.diagnostics.insert(file.clone(), by_server);
    app.rebuild_problems();
    // The bus is process-wide, so the channel carries a name no other test
    // uses.
    let channel = "Tab Switch Drag 2863";
    for i in 0..200 {
        crate::output::push(
            channel,
            crate::output::OutputLevel::Info,
            &format!("log line {i:03}"),
        );
    }
    app.output.sync();
    assert!(app.output.select_by_name(channel));
    app.bottom_panel_tab = BottomPanelTab::Output;

    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let bar = app.output.last_scrollbar;
    assert!(bar.width > 0 && bar.height > 2, "OUTPUT draws a scrollbar");
    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), bar.x, bar.y));

    // Ctrl+Shift+M with the button still held.
    app.set_bottom_panel_tab(BottomPanelTab::Problems);
    term.draw(|f| app.render(f)).unwrap();
    let problems_bar = app.problems.last_scrollbar;
    assert!(problems_bar.width > 0, "PROBLEMS draws a scrollbar");
    assert!(
        matches!(
            app.problems.hit_at(problems_bar.y),
            Some(ProblemHit::Header(_))
        ),
        "PROBLEMS opens at its first file's header"
    );

    let foot = bar.y + bar.height - 1;
    app.handle_mouse(mouse(MouseEventKind::Drag(MouseButton::Left), bar.x, foot));
    term.draw(|f| app.render(f)).unwrap();
    assert!(
        matches!(
            app.problems.hit_at(problems_bar.y),
            Some(ProblemHit::Header(_))
        ),
        "a drag begun on OUTPUT's bar must not scroll PROBLEMS"
    );
    app.handle_mouse(mouse(MouseEventKind::Up(MouseButton::Left), bar.x, foot));
}

/// #2903: a whole-project check still running at a workspace switch is
/// let go. Its rows describe the old project: kept, they landed in the new
/// workspace's PROBLEMS when the check finished, and until then a check of
/// the new workspace was refused as already running.
#[cfg(unix)]
#[test]
fn a_workspace_switch_lets_go_of_the_old_projects_check() {
    let tmp = tempfile::tempdir().unwrap();
    let (a, b) = (tmp.path().join("a"), tmp.path().join("b"));
    std::fs::create_dir_all(a.join("src")).unwrap();
    std::fs::create_dir_all(&b).unwrap();
    std::fs::write(a.join("src/x.ts"), "let x: number = 's';\n").unwrap();
    let mut app = App::new(a.clone()).unwrap();
    // The check has finished on its thread but not landed yet.
    app.queue_project_check_result_for_test(
        &a,
        "src/x.ts(1,5): error TS2322: Type 'string' is not assignable to type 'number'.\n",
        "",
        false,
    );

    app.change_workspace_root(b);
    assert!(app.project_check.is_none(), "the old project's check");
    app.drain_project_check();
    app.rebuild_problems();
    assert_eq!(app.problems.total_count(), 0, "{}", app.status);
    assert!(app.status.starts_with("Workspace root:"), "{}", app.status);
}

/// #2903 review: letting go of the old project's check at a workspace
/// switch stops its checker. Kept running, the old project's compile went on
/// beside the new one's, one more for each switch.
#[cfg(target_os = "linux")]
#[test]
fn a_workspace_switch_stops_the_old_projects_checker() {
    use std::os::unix::fs::PermissionsExt as _;
    let a = tempfile::tempdir().unwrap();
    let b = tempfile::tempdir().unwrap();
    std::fs::write(
        a.path().join("tsconfig.json"),
        r#"{ "files": ["main.ts"] }"#,
    )
    .unwrap();
    std::fs::write(a.path().join("main.ts"), "let n = 1;\n").unwrap();
    let bin = a.path().join("node_modules/.bin");
    std::fs::create_dir_all(&bin).unwrap();
    // A checker that says where it is, then compiles for half a minute.
    std::fs::write(
        bin.join("tsc"),
        "#!/bin/sh\necho $$ > pid.tmp && mv pid.tmp pid\nexec sleep 30\n",
    )
    .unwrap();
    std::fs::set_permissions(bin.join("tsc"), std::fs::Permissions::from_mode(0o755)).unwrap();
    let mut app = App::new(a.path().to_path_buf()).unwrap();
    app.run_command(crate::widgets::command_palette::Command::ProblemsCheckProject);
    assert!(app.project_check.is_some(), "{}", app.status);
    let pid_file = a.path().join("pid");
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
    while !pid_file.exists() {
        assert!(
            std::time::Instant::now() < deadline,
            "the checker never started"
        );
        std::thread::sleep(std::time::Duration::from_millis(10));
    }
    let pid: i32 = std::fs::read_to_string(&pid_file)
        .unwrap()
        .trim()
        .parse()
        .unwrap();

    app.change_workspace_root(b.path().to_path_buf());
    let running = |pid: i32| {
        std::fs::read_to_string(format!("/proc/{pid}/stat"))
            .ok()
            .and_then(|stat| {
                let after = stat.rsplit_once(')')?.1.to_string();
                after.split_whitespace().next().map(|state| state != "Z")
            })
            .unwrap_or(false)
    };
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
    while running(pid) && std::time::Instant::now() < deadline {
        std::thread::sleep(std::time::Duration::from_millis(10));
    }
    assert!(
        !running(pid),
        "the old project's checker is still compiling"
    );
}

/// #2896: after a workspace switch PROBLEMS and its badge list nothing from
/// the old workspace, as after Restart Language Servers, instead of keeping its
/// build and language-server problems until a server of the new root reports.
#[test]
fn a_workspace_switch_empties_problems_of_the_old_workspace() {
    let a = tempfile::tempdir().unwrap();
    let b = tempfile::tempdir().unwrap();
    let file = a.path().join("t.c");
    std::fs::write(&file, "int u;\n").unwrap();
    let mut app = App::new(a.path().to_path_buf()).unwrap();
    let row = crate::build_matchers::BuildDiag {
        file: String::from("t.c"),
        line: 1,
        col: 5,
        severity: crate::lsp::manager::DiagnosticSeverity::Warning,
        message: String::from("unused"),
        source: String::from("build"),
        needs_file: false,
    };
    app.install_build_diags(
        7,
        Some(a.path()),
        vec![row],
        crate::build_matchers::DEFAULT_TABSTOP,
    );
    let mut by_server = std::collections::HashMap::new();
    by_server.insert(
        String::from("clangd"),
        vec![crate::lsp::manager::Diagnostic {
            start_line: 0,
            start_char: 4,
            end_line: 0,
            end_char: 5,
            severity: crate::lsp::manager::DiagnosticSeverity::Warning,
            message: String::from("unused variable"),
            tags: Default::default(),
            code: None,
            origin: None,
        }],
    );
    app.lsp.diagnostics.insert(file, by_server);
    app.rebuild_problems();
    app.refresh_problems_badge();
    assert_eq!(app.problems.total_count(), 2);

    app.change_workspace_root(b.path().to_path_buf());

    assert_eq!(
        app.problems.total_count(),
        0,
        "PROBLEMS lists nothing from the workspace that was left"
    );
    assert_eq!(app.problems_badge_count, 0, "and its badge counts nothing");
}