fresh-editor 0.1.86

A lightweight, fast terminal-based text editor with LSP support and TypeScript plugins
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
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
//! Plugin-related tests

use crate::common::fake_lsp::FakeLspServer;
use crate::common::fixtures::TestFixture;
use crate::common::harness::{copy_plugin, copy_plugin_lib, EditorTestHarness};
use crate::common::tracing::init_tracing_from_env;
use crossterm::event::{KeyCode, KeyModifiers};
use fresh::config::Config;
use fresh::services::lsp::LspServerConfig;
use fresh::services::process_limits::ProcessLimits;
use std::fs;
use std::time::Duration;

/// Test that render-line hook receives args properly
#[test]
fn test_render_line_hook_with_args() {
    // Create a temporary project directory
    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    // Create plugins directory
    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();

    // Create a simple plugin that captures render-line hook args
    let test_plugin = r###"
const editor = getEditor();
// Test plugin to verify render-line hook receives args
let line_count = 0;
let found_marker = false;

globalThis.onRenderLine = function(args: {
    buffer_id: number;
    line_number: number;
    byte_start: number;
    byte_end: number;
    content: string;
}): boolean {
    editor.debug("render-line hook called!");
    // Verify args are present
    if (args && args.buffer_id !== undefined && args.line_number !== undefined && args.content !== undefined) {
        line_count = line_count + 1;
        editor.debug(`Line ${args.line_number}: ${args.content}`);

        // Look for "TEST_MARKER" in the content
        if (args.content.includes("TEST_MARKER")) {
            found_marker = true;
            editor.debug("Found TEST_MARKER!");
            editor.setStatus(`Found TEST_MARKER on line ${args.line_number} at byte ${args.byte_start}`);
        }
    } else {
        editor.debug("ERROR: args is nil or missing fields!");
    }
    return true;
};

editor.on("render_line", "onRenderLine");

globalThis.test_show_count = function(): void {
    editor.setStatus(`Rendered ${line_count} lines, found=${found_marker}`);
    line_count = 0;  // Reset counter
    found_marker = false;
};

editor.registerCommand(
    "Test: Show Line Count",
    "Show how many lines were rendered",
    "test_show_count",
    "normal"
);

editor.setStatus("Test plugin loaded!");
"###;

    let test_plugin_path = plugins_dir.join("test_render_hook.ts");
    fs::write(&test_plugin_path, test_plugin).unwrap();

    // Create test file with marker
    let test_file_content = "Line 1\nLine 2\nTEST_MARKER line\nLine 4\n";
    let fixture = TestFixture::new("test_render.txt", test_file_content).unwrap();

    // Create harness with the project directory
    let mut harness =
        EditorTestHarness::with_config_and_working_dir(80, 24, Default::default(), project_root)
            .unwrap();

    // Open the test file - this should trigger render-line hooks
    harness.open_file(&fixture.path).unwrap();
    harness.render().unwrap();

    // Check that the test file is visible
    harness.assert_screen_contains("TEST_MARKER");

    // Run the "Show Line Count" command to verify hooks executed
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.type_text("Test: Show Line Count").unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Check the rendered screen content - should still contain the test content
    harness.assert_screen_contains("TEST_MARKER");

    // The plugin should have detected the marker via render-line hooks
    // We verify this by checking that the screen was rendered successfully
}

/// Test TODO Highlighter plugin - loads plugin, enables it, and checks highlighting
#[test]
fn test_todo_highlighter_plugin() {
    // Create a temporary project directory
    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    // Create plugins directory and copy the TODO highlighter plugin
    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();

    copy_plugin(&plugins_dir, "todo_highlighter");

    // Create test file with TODO comments
    let test_file_content = r#"// This is a test file for the TODO Highlighter plugin

// TODO: Implement user authentication
// FIXME: Memory leak in connection pool
// HACK: Temporary workaround for parser bug
// NOTE: This function is performance-critical
// XXX: Needs review before production
// BUG: Off-by-one error in loop counter

# Python-style comments
# TODO: Add type hints to all functions
# FIXME: Handle edge case when list is empty

Regular text without keywords should not be highlighted:
TODO FIXME HACK NOTE XXX BUG (not in comments)
"#;

    let fixture = TestFixture::new("test_todo.txt", test_file_content).unwrap();

    // Create harness with the project directory (so plugins load)
    let mut harness =
        EditorTestHarness::with_config_and_working_dir(80, 24, Default::default(), project_root)
            .unwrap();

    // Open the test file
    harness.open_file(&fixture.path).unwrap();
    harness.render().unwrap();

    // Check that file content is visible
    harness.assert_screen_contains("TODO: Implement user authentication");

    // Open command palette
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();

    // Type "TODO Highlighter: Enable" command
    harness.type_text("TODO Highlighter: Enable").unwrap();

    // Wait for command to appear in palette before executing
    harness
        .wait_until(|h| h.screen_to_string().contains("TODO Highlighter: Enable"))
        .unwrap();

    // Execute the command
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();

    // Wait for plugin to apply highlighting to at least one TODO keyword
    // The plugin needs to:
    // 1. Process the RefreshLines command from the channel
    // 2. Clear seen_lines and set plugin_render_requested
    // 3. Re-render to trigger lines_changed hook
    // 4. Process addOverlay commands from the hook
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            let lines: Vec<&str> = screen.lines().collect();

            // Find the position of "TODO" on screen and check if it's highlighted
            for (y, line) in lines.iter().enumerate() {
                if let Some(x) = line.find("TODO") {
                    // Check if this TODO is in a comment (should have "//" before it)
                    if line[..x].contains("//") {
                        // Check the style of the 'T' in "TODO"
                        if let Some(style) = h.get_cell_style(x as u16, y as u16) {
                            // Check if foreground color is an actual RGB color (overlays set foreground, not background)
                            // TODO keywords should be yellow (255, 200, 50)
                            if let Some(fg) = style.fg {
                                // Only count as highlighted if it's an actual RGB color
                                if matches!(fg, ratatui::style::Color::Rgb(_, _, _)) {
                                    return true;
                                }
                            }
                        }
                    }
                }
            }
            false
        })
        .expect("Expected to find at least one highlighted TODO keyword");

    // Print screen for debugging
    let screen = harness.screen_to_string();
    println!("Screen after enabling TODO highlighter:\n{}", screen);
}

/// Test TODO Highlighter disable command
#[test]
fn test_todo_highlighter_disable() {
    // Create a temporary project directory
    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    // Create plugins directory and copy the TODO highlighter plugin
    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();

    copy_plugin(&plugins_dir, "todo_highlighter");

    // Create test file with TODO comments
    let test_file_content = "// TODO: Test comment\n";
    let fixture = TestFixture::new("test_todo.txt", test_file_content).unwrap();

    // Create harness with the project directory (so plugins load)
    let mut harness =
        EditorTestHarness::with_config_and_working_dir(80, 24, Default::default(), project_root)
            .unwrap();

    // Open the test file
    harness.open_file(&fixture.path).unwrap();
    harness.render().unwrap();

    // Enable highlighting first
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.type_text("TODO Highlighter: Enable").unwrap();
    harness
        .wait_until(|h| h.screen_to_string().contains("TODO Highlighter: Enable"))
        .unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Now disable it
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.type_text("TODO Highlighter: Disable").unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Verify the content is still visible after disabling
    harness.assert_screen_contains("TODO: Test comment");

    // The test passes if we can execute disable without error
    // Highlighting should be removed but we don't check for it explicitly
    // since removing overlays doesn't leave visible traces to assert on
}

/// Test TODO Highlighter toggle command
#[test]
fn test_todo_highlighter_toggle() {
    // Create a temporary project directory
    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    // Create plugins directory and copy the TODO highlighter plugin
    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();

    copy_plugin(&plugins_dir, "todo_highlighter");

    // Create test file with TODO comments
    let test_file_content = "// TODO: Test comment\n";
    let fixture = TestFixture::new("test_todo.txt", test_file_content).unwrap();

    // Create harness with the project directory (so plugins load)
    let mut harness =
        EditorTestHarness::with_config_and_working_dir(80, 24, Default::default(), project_root)
            .unwrap();

    // Open the test file
    harness.open_file(&fixture.path).unwrap();
    harness.render().unwrap();

    // Toggle on
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.type_text("TODO Highlighter: Toggle").unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();

    // Wait for plugin to process and apply highlight overlay using semantic waiting
    // The plugin needs async cycles to process RefreshLines and addOverlay commands
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            let lines: Vec<&str> = screen.lines().collect();

            for (y, line) in lines.iter().enumerate() {
                if let Some(x) = line.find("TODO") {
                    if line[..x].contains("//") {
                        if let Some(style) = h.get_cell_style(x as u16, y as u16) {
                            // Check if it's highlighted with an RGB color
                            if let Some(fg) = style.fg {
                                if matches!(fg, ratatui::style::Color::Rgb(_, _, _)) {
                                    return true;
                                }
                            }
                        }
                    }
                }
            }
            false
        })
        .expect("Expected TODO to be highlighted after toggle on");

    // Toggle off
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.type_text("TODO Highlighter: Toggle").unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Verify content is still visible after toggling off
    harness.assert_screen_contains("TODO: Test comment");
}

/// Test TODO Highlighter updates when buffer content changes
///
/// This test documents a known limitation: overlays don't update positions
/// when the buffer is modified. When text is inserted before an overlay,
/// the overlay stays at its original byte position instead of shifting.
#[test]
#[ignore = "Overlays don't update positions when buffer changes - needs overlay position tracking fix"]
fn test_todo_highlighter_updates_on_edit() {
    // Enable tracing for debugging
    use tracing_subscriber::{fmt, EnvFilter};
    let _ = fmt()
        .with_env_filter(
            EnvFilter::from_default_env().add_directive("fresh=trace".parse().unwrap()),
        )
        .with_test_writer()
        .try_init();

    // Create a temporary project directory
    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    // Create plugins directory and copy the TODO highlighter plugin
    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();

    copy_plugin(&plugins_dir, "todo_highlighter");

    // Create test file with TODO comment at the start
    let test_file_content = "// TODO: Original comment\n";
    let fixture = TestFixture::new("test_todo.txt", test_file_content).unwrap();

    // Create harness with the project directory (so plugins load)
    let mut harness =
        EditorTestHarness::with_config_and_working_dir(80, 24, Default::default(), project_root)
            .unwrap();

    // Open the test file
    harness.open_file(&fixture.path).unwrap();
    harness.render().unwrap();

    // Enable highlighting
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.type_text("TODO Highlighter: Enable").unwrap();
    harness
        .wait_until(|h| h.screen_to_string().contains("TODO Highlighter: Enable"))
        .unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Verify the original TODO is highlighted
    let screen_before = harness.screen_to_string();
    println!("Screen before edit:\n{}", screen_before);

    let lines: Vec<&str> = screen_before.lines().collect();
    let mut found_original_todo = false;

    for (y, line) in lines.iter().enumerate() {
        if line.contains("TODO: Original") {
            if let Some(x) = line.find("TODO") {
                if let Some(style) = harness.get_cell_style(x as u16, y as u16) {
                    if let Some(bg) = style.bg {
                        // Check it's not just Reset/White, should be a real color
                        println!("Found TODO at ({}, {}) with background: {:?}", x, y, bg);
                        found_original_todo = true;
                        break;
                    }
                }
            }
        }
    }

    assert!(
        found_original_todo,
        "Expected to find highlighted 'TODO: Original' before edit"
    );

    // Go to the beginning of the file
    harness
        .send_key(KeyCode::Home, KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Insert a new line at the top: "// FIXME: New comment\n"
    harness.type_text("// FIXME: New comment\n").unwrap();
    harness.render().unwrap();

    let screen_after = harness.screen_to_string();
    println!("Screen after adding FIXME:\n{}", screen_after);

    // The buffer should now be:
    // Line 1: // FIXME: New comment
    // Line 2: // TODO: Original comment

    // Check that FIXME is highlighted
    let lines: Vec<&str> = screen_after.lines().collect();
    let mut found_fixme = false;
    let mut found_todo_on_line_2 = false;

    for (y, line) in lines.iter().enumerate() {
        if line.contains("FIXME: New") {
            if let Some(x) = line.find("FIXME") {
                if let Some(style) = harness.get_cell_style(x as u16, y as u16) {
                    if let Some(bg) = style.bg {
                        println!("Found FIXME at ({}, {}) with background: {:?}", x, y, bg);
                        found_fixme = true;
                    }
                }
            }
        }
        if line.contains("TODO: Original") {
            if let Some(x) = line.find("TODO") {
                if let Some(style) = harness.get_cell_style(x as u16, y as u16) {
                    if let Some(bg) = style.bg {
                        println!(
                            "Found TODO on line 2 at ({}, {}) with background: {:?}",
                            x, y, bg
                        );
                        // Check if it's an actual RGB color (orange), not just Reset
                        if matches!(bg, ratatui::style::Color::Rgb(_, _, _)) {
                            found_todo_on_line_2 = true;
                        }
                    }
                }
            }
        }
    }

    // Bug: FIXME gets highlighted because it happens to be at the byte position where TODO was
    // But TODO should ALSO be highlighted, not just have Reset background
    assert!(
        found_fixme,
        "Expected to find highlighted FIXME after inserting new line"
    );

    // This assertion will FAIL, demonstrating the bug - TODO highlight doesn't update
    assert!(
        found_todo_on_line_2,
        "BUG REPRODUCED: TODO on line 2 is not highlighted! The old overlay at byte 3-7 \
         now highlights FIXME (which happens to be at those bytes), but TODO moved to a \
         new byte position and didn't get a new overlay. Overlays need to update when buffer changes!"
    );
}

/// Test TODO Highlighter updates correctly when deleting text
#[test]
fn test_todo_highlighter_updates_on_delete() {
    // Create a temporary project directory
    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    // Create plugins directory and copy the TODO highlighter plugin
    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();

    copy_plugin(&plugins_dir, "todo_highlighter");

    // Create test file with TODO on second line
    let test_file_content = "// FIXME: Delete this line\n// TODO: Keep this one\n";
    let fixture = TestFixture::new("test_todo.txt", test_file_content).unwrap();

    // Create harness with the project directory (so plugins load)
    let mut harness =
        EditorTestHarness::with_config_and_working_dir(80, 24, Default::default(), project_root)
            .unwrap();

    // Open the test file
    harness.open_file(&fixture.path).unwrap();
    harness.render().unwrap();

    // Enable highlighting
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.type_text("TODO Highlighter: Enable").unwrap();
    harness
        .wait_until(|h| h.screen_to_string().contains("TODO Highlighter: Enable"))
        .unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Need an extra render to trigger the render-line hooks after enabling
    harness.render().unwrap();

    // Verify both keywords are highlighted initially
    let screen_before = harness.screen_to_string();
    println!("Screen before delete:\n{}", screen_before);

    let mut found_fixme_before = false;
    let mut found_todo_before = false;

    for (y, line) in screen_before.lines().enumerate() {
        if line.contains("FIXME") && line[..line.find("FIXME").unwrap()].contains("//") {
            if let Some(x) = line.find("FIXME") {
                if let Some(style) = harness.get_cell_style(x as u16, y as u16) {
                    if let Some(bg) = style.bg {
                        println!(
                            "Found FIXME highlighted at ({}, {}) before delete with bg: {:?}",
                            x, y, bg
                        );
                        found_fixme_before = true;
                    }
                }
            }
        }
        if line.contains("TODO") && line[..line.find("TODO").unwrap()].contains("//") {
            if let Some(x) = line.find("TODO") {
                if let Some(style) = harness.get_cell_style(x as u16, y as u16) {
                    if let Some(bg) = style.bg {
                        println!(
                            "Found TODO highlighted at ({}, {}) before delete with bg: {:?}",
                            x, y, bg
                        );
                        found_todo_before = true;
                    }
                }
            }
        }
    }

    assert!(found_fixme_before, "FIXME should be highlighted initially");
    assert!(found_todo_before, "TODO should be highlighted initially");

    // Now delete the first line (FIXME line)
    // Go to beginning
    harness
        .send_key(KeyCode::Home, KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Select the entire first line
    harness.send_key(KeyCode::End, KeyModifiers::SHIFT).unwrap();
    harness
        .send_key(KeyCode::Right, KeyModifiers::SHIFT)
        .unwrap(); // Include the newline
    harness.render().unwrap();

    // Delete the selection
    harness
        .send_key(KeyCode::Backspace, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    let screen_after = harness.screen_to_string();
    println!("Screen after deleting FIXME line:\n{}", screen_after);

    // The buffer should now only contain: "// TODO: Keep this one\n"
    // TODO should still be highlighted (now on line 1)

    let mut found_todo_after = false;

    for (y, line) in screen_after.lines().enumerate() {
        if line.contains("TODO") && line[..line.find("TODO").unwrap()].contains("//") {
            if let Some(x) = line.find("TODO") {
                if let Some(style) = harness.get_cell_style(x as u16, y as u16) {
                    if let Some(bg) = style.bg {
                        println!(
                            "Found TODO at ({}, {}) after delete with background: {:?}",
                            x, y, bg
                        );
                        found_todo_after = true;
                    }
                }
            }
        }
    }

    assert!(
        found_todo_after,
        "BUG: TODO should still be highlighted after deleting the line above it! \
         Instead, the highlight either disappeared or shifted to the wrong position."
    );
}

/// Test diagnostics panel plugin loads and creates a virtual buffer split
/// This verifies the full implementation with LSP-like diagnostics display
#[test]
#[cfg_attr(windows, ignore)] // Uses bash script for fake LSP server
fn test_diagnostics_panel_plugin_loads() {
    use crate::common::fake_lsp::FakeLspServer;
    init_tracing_from_env();

    // Create a fake LSP server that sends diagnostics
    let _fake_server = FakeLspServer::spawn_many_diagnostics(3).unwrap();

    // Create a temporary project directory
    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().to_path_buf();

    // Create plugins directory and copy the diagnostics panel plugin
    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();
    copy_plugin(&plugins_dir, "diagnostics_panel");
    copy_plugin_lib(&plugins_dir); // Copy lib/ for results-panel.ts import

    // Create a simple test file in the project directory (not via TestFixture!)
    let test_file_content = "fn main() {\n    println!(\"test\");\n}\n";
    let test_file = project_root.join("test_diagnostics.rs");
    fs::write(&test_file, test_file_content).unwrap();

    // Configure editor to use the fake LSP server that sends diagnostics
    let mut config = fresh::config::Config::default();
    config.lsp.insert(
        "rust".to_string(),
        fresh::services::lsp::LspServerConfig {
            command: FakeLspServer::many_diagnostics_script_path()
                .to_string_lossy()
                .to_string(),
            args: vec![],
            enabled: true,
            auto_start: true,
            process_limits: fresh::services::process_limits::ProcessLimits::default(),
            initialization_options: None,
        },
    );

    // Create harness with the project directory and LSP config
    let mut harness =
        EditorTestHarness::with_config_and_working_dir(80, 24, config, project_root).unwrap();

    // Open the test file - this should trigger plugin loading and LSP
    harness.open_file(&test_file).unwrap();
    harness.render().unwrap();

    // Check that file content is visible
    harness.assert_screen_contains("fn main()");

    // Wait for LSP to send diagnostics (the fake server sends them on didOpen/didChange)
    // We wait for diagnostic overlays to appear since the status bar E: count may be
    // truncated on narrow terminals (the test uses 80 columns)
    harness
        .wait_until(|h| {
            // Check if diagnostic overlays have been applied
            let overlays = h.editor().active_state().overlays.all();
            let diagnostic_ns = fresh::services::lsp::diagnostics::lsp_diagnostic_namespace();
            overlays
                .iter()
                .any(|o| o.namespace.as_ref() == Some(&diagnostic_ns))
        })
        .unwrap();

    // The plugin should have loaded successfully without Lua errors
    // If the Lua scoping is wrong (update_panel_content not defined before create_panel calls it),
    // the plugin would fail to load with: "attempt to call a nil value (global 'update_panel_content')"

    // The plugin sets a status message on successful load
    // Look for evidence that the plugin loaded by checking the screen
    let screen = harness.screen_to_string();
    println!("Screen after plugin load:\n{}", screen);

    // Now try to execute the "Show Diagnostics Panel" command
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Type to search for the command
    harness.type_text("Show Diagnostics Panel").unwrap();
    harness.render().unwrap();

    let palette_screen = harness.screen_to_string();
    println!("Command palette screen:\n{}", palette_screen);

    // The command should be visible in the palette (registered by the plugin)
    // If the plugin failed to load due to Lua errors, this command wouldn't be registered
    assert!(
        palette_screen.contains("Show Diagnostics Panel")
            || palette_screen.contains("diagnostics")
            || palette_screen.contains("Diagnostics"),
        "The 'Show Diagnostics Panel' command should be registered by the plugin. \
         If the plugin had Lua scoping errors, it wouldn't load and the command wouldn't exist."
    );

    // Execute the command
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Wait for the async panel creation to complete
    // The panel shows "Diagnostics" header when open
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("*Diagnostics*") || screen.contains("Diagnostics (")
        })
        .unwrap();

    let final_screen = harness.screen_to_string();
    println!("Final screen after executing command:\n{}", final_screen);

    // Verify the diagnostics panel content is displayed in a horizontal split
    assert!(
        final_screen.contains("Diagnostics"),
        "Expected to see 'Diagnostics' header in the panel"
    );
    assert!(
        final_screen.contains("[E]") || final_screen.contains("[W]"),
        "Expected to see severity icons like [E] or [W] in the diagnostics"
    );
    // The plugin uses background highlighting for selection, not a '>' marker
    assert!(
        final_screen.contains("*Diagnostics*"),
        "Expected to see buffer name '*Diagnostics*' in status bar"
    );
    // Verify horizontal split view (separator line should be visible)
    assert!(
        final_screen.contains("───") || final_screen.contains("---"),
        "Expected to see horizontal split separator"
    );
    // The original code buffer should still be visible above the diagnostics
    assert!(
        final_screen.contains("fn main()"),
        "Expected to see original code buffer in upper split"
    );
}

/// Test editor <-> plugin message queue architecture
///
/// This test exercises the complete bidirectional message flow:
/// 1. Editor sends action request to plugin thread (fire-and-forget)
/// 2. Plugin executes action and sends commands back via command queue
/// 3. Editor polls command queue with try_recv (non-blocking)
/// 4. Plugin awaits async response for buffer ID
///
/// This ensures no deadlocks occur in the message passing architecture.
#[test]
fn test_plugin_message_queue_architecture() {
    // Create a temporary project directory
    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    // Create plugins directory
    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();

    // Create a test plugin that exercises the message queue:
    // 1. Registers a command (tests command registration via plugin commands)
    // 2. When executed, creates a virtual buffer in split (tests async response)
    // 3. Uses the returned buffer ID to set status (tests async result propagation)
    let test_plugin = r#"
const editor = getEditor();
// Test plugin for message queue architecture
// This plugin exercises the bidirectional message flow

// Register a command that will create a virtual buffer
editor.registerCommand(
    "Test: Create Virtual Buffer",
    "Create a virtual buffer and verify buffer ID is returned",
    "test_create_virtual_buffer",
    "normal"
);

// Counter to track executions
let executionCount = 0;

globalThis.test_create_virtual_buffer = async function(): Promise<void> {
    executionCount++;
    editor.setStatus(`Starting execution ${executionCount}...`);

    // Create entries for the virtual buffer
    const entries = [
        {
            text: `Test entry ${executionCount}\n`,
            properties: {
                index: executionCount,
            },
        },
    ];

    try {
        // This is the critical async operation that tests:
        // 1. Plugin sends CreateVirtualBufferInSplit command
        // 2. Editor creates buffer and sends response
        // 3. Plugin receives buffer ID via async channel
        const bufferId = await editor.createVirtualBufferInSplit({
            name: "*Test Buffer*",
            mode: "normal",
            read_only: true,
            entries: entries,
            ratio: 0.5,
            panel_id: "test-panel",
            show_line_numbers: false,
            show_cursors: true,
        });

        // Verify we got a valid buffer ID
        if (typeof bufferId === 'number' && bufferId > 0) {
            editor.setStatus(`Success: Created buffer ID ${bufferId}`);
        } else {
            editor.setStatus(`Error: Invalid buffer ID: ${bufferId}`);
        }
    } catch (error) {
        const msg = error instanceof Error ? error.message : String(error);
        editor.setStatus(`Error: ${msg}`);
    }
};

editor.setStatus("Message queue test plugin loaded!");
"#;

    let test_plugin_path = plugins_dir.join("test_message_queue.ts");
    fs::write(&test_plugin_path, test_plugin).unwrap();

    // Create a simple test file
    let test_file_content = "Test file content\nLine 2\nLine 3\n";
    let fixture = TestFixture::new("test_file.txt", test_file_content).unwrap();

    // Create harness with the project directory (so plugins load)
    let mut harness =
        EditorTestHarness::with_config_and_working_dir(80, 24, Default::default(), project_root)
            .unwrap();

    // Open the test file - this should trigger plugin loading
    harness.open_file(&fixture.path).unwrap();
    harness.render().unwrap();

    // Verify file content is visible
    harness.assert_screen_contains("Test file content");

    // Verify plugin loaded by checking for the status message
    let screen = harness.screen_to_string();
    println!("Screen after plugin load:\n{}", screen);

    // Now execute the command that creates a virtual buffer
    // This exercises the full message queue flow
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Type the command name
    harness.type_text("Test: Create Virtual Buffer").unwrap();
    harness.render().unwrap();

    // Verify command appears in palette (proves command registration worked)
    let palette_screen = harness.screen_to_string();
    println!("Command palette screen:\n{}", palette_screen);
    assert!(
        palette_screen.contains("Create Virtual Buffer"),
        "Command should be registered and visible in palette"
    );

    // Execute the command
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();

    // Wait for the async operation to complete by checking for visible buffer content
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("*Test Buffer*") || screen.contains("Test entry")
        })
        .unwrap();

    let final_screen = harness.screen_to_string();
    println!("Final screen after command execution:\n{}", final_screen);

    // Verify the async operation completed successfully by checking for visible content
    // Note: We check for the buffer content rather than status message,
    // because status messages may have timing issues with async processing
    assert!(
        final_screen.contains("*Test Buffer*") || final_screen.contains("Test entry"),
        "Expected to see the virtual buffer content. \
         The split should show either the buffer name or entry content. \
         Got screen:\n{}",
        final_screen
    );

    // Verify the original file content is still visible (split view working)
    assert!(
        final_screen.contains("Test file content"),
        "Expected original file content to still be visible in split view"
    );
}

/// Test that multiple plugin actions can be queued without deadlock
#[test]
fn test_plugin_multiple_actions_no_deadlock() {
    // Create a temporary project directory
    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    // Create plugins directory
    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();

    // Create a plugin with multiple commands that all set status
    let test_plugin = r#"
const editor = getEditor();
// Test plugin for multiple concurrent actions

editor.registerCommand("Action A", "Set status to A", "action_a", null);
editor.registerCommand("Action B", "Set status to B", "action_b", null);
editor.registerCommand("Action C", "Set status to C", "action_c", null);

globalThis.action_a = function(): void {
    editor.setStatus("Status: A executed");
};

globalThis.action_b = function(): void {
    editor.setStatus("Status: B executed");
};

globalThis.action_c = function(): void {
    editor.setStatus("Status: C executed");
};

editor.setStatus("Multi-action plugin loaded");
"#;

    let test_plugin_path = plugins_dir.join("test_multi_action.ts");
    fs::write(&test_plugin_path, test_plugin).unwrap();

    // Create a simple test file
    let test_file_content = "Test content\n";
    let fixture = TestFixture::new("test.txt", test_file_content).unwrap();

    // Create harness
    let mut harness =
        EditorTestHarness::with_config_and_working_dir(80, 24, Default::default(), project_root)
            .unwrap();

    // Open file and load plugins
    harness.open_file(&fixture.path).unwrap();
    harness.render().unwrap();

    // Execute multiple commands in sequence rapidly
    // This tests that the message queue handles multiple actions correctly
    // The main assertion is that the commands execute without deadlock or hanging
    let start = std::time::Instant::now();

    for action_name in ["Action A", "Action B", "Action C"] {
        // Open command palette
        harness
            .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
            .unwrap();
        harness.render().unwrap();

        // Type and execute command
        harness.type_text(action_name).unwrap();
        harness
            .send_key(KeyCode::Enter, KeyModifiers::NONE)
            .unwrap();

        // Process async and render a few times to let the action execute
        for _ in 0..3 {
            harness.process_async_and_render().unwrap();
            harness.sleep(Duration::from_millis(20));
        }
    }

    let elapsed = start.elapsed();

    // The key assertion: all commands should execute quickly without deadlock
    // If there's a deadlock or blocking issue, this would timeout
    assert!(
        elapsed < Duration::from_secs(2),
        "Multiple actions should complete without deadlock. Took {:?}",
        elapsed
    );

    // Verify the editor is still responsive
    let screen = harness.screen_to_string();
    assert!(
        screen.contains("Test content"),
        "Editor should still show content after multiple actions. Got:\n{}",
        screen
    );
}

/// Test that plugin action execution is non-blocking
///
/// This verifies that the editor doesn't hang when executing a plugin action
/// even if the action takes time. The fire-and-forget pattern should allow
/// the editor to continue processing events.
#[test]
fn test_plugin_action_nonblocking() {
    // Create a temporary project directory
    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    // Create plugins directory
    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();

    // Create a plugin that does some work
    let test_plugin = r#"
const editor = getEditor();
// Test plugin to verify non-blocking action execution

editor.registerCommand(
    "Slow Action",
    "An action that does some computation",
    "slow_action",
    "normal"
);

globalThis.slow_action = function(): void {
    // Simulate some work (this is synchronous but should not block editor)
    let sum = 0;
    for (let i = 0; i < 1000; i++) {
        sum += i;
    }
    editor.setStatus(`Completed: sum = ${sum}`);
};

editor.setStatus("Nonblocking test plugin loaded");
"#;

    let test_plugin_path = plugins_dir.join("test_nonblocking.ts");
    fs::write(&test_plugin_path, test_plugin).unwrap();

    // Create a simple test file
    let test_file_content = "Test\n";
    let fixture = TestFixture::new("test.txt", test_file_content).unwrap();

    // Create harness
    let mut harness =
        EditorTestHarness::with_config_and_working_dir(80, 24, Default::default(), project_root)
            .unwrap();

    // Open file
    harness.open_file(&fixture.path).unwrap();
    harness.render().unwrap();

    // Execute the slow action
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();
    harness.type_text("Slow Action").unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();

    // The key test: we should be able to render without blocking while action runs
    let start = std::time::Instant::now();

    // Process several render cycles - this verifies the editor isn't blocked
    for _ in 0..5 {
        harness.process_async_and_render().unwrap();
        harness.sleep(Duration::from_millis(50));
    }

    let elapsed = start.elapsed();

    // If the action was blocking, renders would stall
    // The action execution is async, so renders complete immediately
    assert!(
        elapsed < Duration::from_secs(1),
        "Rendering should complete quickly even with action running. Took {:?}",
        elapsed
    );

    // Verify the screen is still responsive (command palette closed)
    let screen = harness.screen_to_string();
    assert!(
        screen.contains("Test"),
        "Editor should show file content. Got:\n{}",
        screen
    );
}

/// Performance test for TODO highlighter with cursor movement
/// Run with: RUST_LOG=trace cargo test test_todo_highlighter_cursor_perf -- --nocapture
#[test]
fn test_todo_highlighter_cursor_perf() {
    // Initialize tracing subscriber for performance analysis
    let _ = tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::from_default_env()
                .add_directive("fresh=trace".parse().unwrap()),
        )
        .with_test_writer()
        .try_init();

    // Create a temporary project directory
    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    // Create plugins directory and copy the TODO highlighter plugin
    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();

    copy_plugin(&plugins_dir, "todo_highlighter");

    // Create a larger test file with many lines and TODO comments
    let mut test_content = String::new();
    for i in 0..100 {
        if i % 5 == 0 {
            test_content.push_str(&format!("// TODO: Task number {}\n", i));
        } else if i % 7 == 0 {
            test_content.push_str(&format!("// FIXME: Issue number {}\n", i));
        } else {
            test_content.push_str(&format!("Line {} of test content\n", i));
        }
    }
    let fixture = TestFixture::new("test_perf.txt", &test_content).unwrap();

    // Create harness with the project directory
    let mut harness =
        EditorTestHarness::with_config_and_working_dir(80, 40, Default::default(), project_root)
            .unwrap();

    // Open the test file
    harness.open_file(&fixture.path).unwrap();
    harness.render().unwrap();

    // Enable TODO Highlighter
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.type_text("TODO Highlighter: Enable").unwrap();
    harness
        .wait_until(|h| h.screen_to_string().contains("TODO Highlighter: Enable"))
        .unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Measure cursor movement performance
    let num_moves = 20;

    println!("\n=== TODO Highlighter Cursor Movement Performance Test ===");
    println!("Moving cursor down {} times...", num_moves);

    let down_start = std::time::Instant::now();
    for _ in 0..num_moves {
        harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
        harness.render().unwrap();
    }
    let down_elapsed = down_start.elapsed();

    println!("Moving cursor up {} times...", num_moves);

    let up_start = std::time::Instant::now();
    for _ in 0..num_moves {
        harness.send_key(KeyCode::Up, KeyModifiers::NONE).unwrap();
        harness.render().unwrap();
    }
    let up_elapsed = up_start.elapsed();

    println!("\n=== Results ===");
    println!(
        "Down: {:?} total, {:?} per move",
        down_elapsed,
        down_elapsed / num_moves
    );
    println!(
        "Up: {:?} total, {:?} per move",
        up_elapsed,
        up_elapsed / num_moves
    );
    println!("Total: {:?}", down_elapsed + up_elapsed);
    println!("================\n");

    // No assertion on timing - this is for data collection
    // The trace logs will show where time is spent
}

/// Test Color Highlighter plugin - loads plugin, enables it, and checks for color swatches
#[test]
#[ignore]
fn test_color_highlighter_plugin() {
    // Create a temporary project directory
    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    // Create plugins directory and copy the color highlighter plugin
    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();
    copy_plugin(&plugins_dir, "color_highlighter");

    // Create test file with various color formats
    let test_file_content = r###"// Test file for Color Highlighter
// CSS hex colors
let red = "#ff0000";
let green = "#0f0";
let blue = "#0000ff";
let transparent = "#ff000080";

// CSS rgb/rgba
background: rgb(255, 128, 0);
color: rgba(0, 255, 128, 0.5);

// CSS hsl/hsla
hsl(120, 100%, 50%);
hsla(240, 100%, 50%, 0.8);

// Rust colors
Color::Rgb(255, 255, 0)
Color::Rgb(128, 0, 255)
"###;

    let fixture = TestFixture::new("test_colors.txt", test_file_content).unwrap();

    // Create harness with the project directory (so plugins load)
    let mut harness =
        EditorTestHarness::with_config_and_working_dir(80, 24, Default::default(), project_root)
            .unwrap();

    // Open the test file
    harness.open_file(&fixture.path).unwrap();
    harness.render().unwrap();

    // Check that file content is visible
    harness.assert_screen_contains("#ff0000");

    // Open command palette
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();

    // Type "Color Highlighter: Enable" command
    harness.type_text("Color Highlighter: Enable").unwrap();

    // Wait for command to appear in palette before executing
    harness
        .wait_until(|h| h.screen_to_string().contains("Color Highlighter: Enable"))
        .unwrap();

    // Execute the command
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Need extra renders to trigger the render-line hooks after enabling
    harness.render().unwrap();
    harness.render().unwrap();

    let screen = harness.screen_to_string();
    println!("Screen after enabling Color highlighter:\n{}", screen);

    // Check that color swatches (â–ˆ) appear in the output
    // The plugin adds "â–ˆ " before each color code
    let swatch_count = screen.matches('â–ˆ').count();
    println!("Found {} color swatches", swatch_count);

    // We should have at least some color swatches visible
    // (the file has many colors, some should be in the viewport)
    assert!(
        swatch_count > 0,
        "Expected to find color swatch characters (â–ˆ) after enabling Color Highlighter. \
         This indicates virtual text is being rendered."
    );

    // Check that color swatches have foreground colors set
    // Find a swatch and check its style
    let lines: Vec<&str> = screen.lines().collect();
    let mut found_colored_swatch = false;

    for (y, line) in lines.iter().enumerate() {
        // Find swatch using char indices to handle multi-byte chars correctly
        for (char_idx, ch) in line.char_indices() {
            if ch == 'â–ˆ' {
                // Use character position, not byte position
                let x = line[..char_idx].chars().count();
                // Bounds check - skip if outside screen
                if x >= 80 {
                    continue;
                }
                if let Some(style) = harness.get_cell_style(x as u16, y as u16) {
                    // Check if foreground color is set (should be the color being highlighted)
                    if let Some(fg) = style.fg {
                        println!(
                            "Found swatch at ({}, {}) with foreground color: {:?}",
                            x, y, fg
                        );
                        // Check if it's an actual RGB color
                        if matches!(fg, ratatui::style::Color::Rgb(_, _, _)) {
                            found_colored_swatch = true;
                            break;
                        }
                    }
                }
            }
        }
        if found_colored_swatch {
            break;
        }
    }

    assert!(
        found_colored_swatch,
        "Expected to find at least one color swatch with RGB foreground color"
    );
}

/// Test Color Highlighter disable command
#[test]
fn test_color_highlighter_disable() {
    // Create a temporary project directory
    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    // Create plugins directory and copy the color highlighter plugin
    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();
    copy_plugin(&plugins_dir, "color_highlighter");

    // Create test file with a color
    let test_file_content = "let color = \"#ff0000\";\n";
    let fixture = TestFixture::new("test_colors.txt", test_file_content).unwrap();

    // Create harness with the project directory (so plugins load)
    let mut harness =
        EditorTestHarness::with_config_and_working_dir(80, 24, Default::default(), project_root)
            .unwrap();

    // Open the test file
    harness.open_file(&fixture.path).unwrap();
    harness.render().unwrap();

    // Enable highlighting first
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.type_text("Color Highlighter: Enable").unwrap();
    harness
        .wait_until(|h| h.screen_to_string().contains("Color Highlighter: Enable"))
        .unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();

    // Helper function to count color swatches (excludes scrollbar at position 79)
    fn count_color_swatches(screen: &str) -> usize {
        screen
            .lines()
            .flat_map(|line| {
                line.char_indices().filter(|&(char_idx, ch)| {
                    if ch != 'â–ˆ' {
                        return false;
                    }
                    // Calculate character position (not byte position)
                    let x = line[..char_idx].chars().count();
                    // Exclude scrollbar (at position 79, the last visible column)
                    x < 79
                })
            })
            .count()
    }

    // Wait for swatches to appear (plugin needs time to process)
    harness
        .wait_until(|h| count_color_swatches(&h.screen_to_string()) > 0)
        .unwrap();

    let screen_enabled = harness.screen_to_string();
    let swatches_enabled = count_color_swatches(&screen_enabled);

    // Now disable it
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.type_text("Color Highlighter: Disable").unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();

    // Wait for swatches to be removed
    harness
        .wait_until(|h| count_color_swatches(&h.screen_to_string()) < swatches_enabled)
        .unwrap();

    // Verify the content is still visible after disabling
    harness.assert_screen_contains("#ff0000");

    // Swatches should be removed
    let screen_disabled = harness.screen_to_string();
    let swatches_disabled = count_color_swatches(&screen_disabled);

    assert!(
        swatches_disabled < swatches_enabled,
        "Expected fewer swatches after disabling. Before: {}, After: {}",
        swatches_enabled,
        swatches_disabled
    );
}

/// Test Color Highlighter toggle command
#[test]
fn test_color_highlighter_toggle() {
    // Create a temporary project directory
    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    // Create plugins directory and copy the color highlighter plugin
    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();
    copy_plugin(&plugins_dir, "color_highlighter");

    // Create test file with a color
    let test_file_content = "rgb(128, 64, 255)\n";
    let fixture = TestFixture::new("test_colors.txt", test_file_content).unwrap();

    // Create harness with the project directory (so plugins load)
    let mut harness =
        EditorTestHarness::with_config_and_working_dir(80, 24, Default::default(), project_root)
            .unwrap();

    // Open the test file
    harness.open_file(&fixture.path).unwrap();
    harness.render().unwrap();

    // Helper function to count color swatches (excludes scrollbar at position 79)
    fn count_color_swatches(screen: &str) -> usize {
        screen
            .lines()
            .flat_map(|line| {
                line.char_indices().filter(|&(char_idx, ch)| {
                    if ch != 'â–ˆ' {
                        return false;
                    }
                    let x = line[..char_idx].chars().count();
                    x < 79
                })
            })
            .count()
    }

    // Toggle on
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.type_text("Color Highlighter: Toggle").unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();

    // Wait for swatches to appear
    harness
        .wait_until(|h| count_color_swatches(&h.screen_to_string()) > 0)
        .unwrap();

    let screen_on = harness.screen_to_string();
    let swatches_on = count_color_swatches(&screen_on);

    // Toggle off
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.type_text("Color Highlighter: Toggle").unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();

    // Wait for swatches to be removed
    harness
        .wait_until(|h| count_color_swatches(&h.screen_to_string()) < swatches_on)
        .unwrap();

    // Verify content is still visible after toggling off
    harness.assert_screen_contains("rgb(128, 64, 255)");
}

/// Ensure the clangd plugin reacts to file-status notifications
#[test]
#[ignore]
fn test_clangd_plugin_file_status_notification() -> anyhow::Result<()> {
    init_tracing_from_env();
    let _fake_server = FakeLspServer::spawn()?;

    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();
    copy_plugin(&plugins_dir, "clangd_support");
    copy_plugin_lib(&plugins_dir);

    let src_dir = project_root.join("src");
    fs::create_dir_all(&src_dir).unwrap();
    let source_file = src_dir.join("main.cpp");
    fs::write(&source_file, "int main() { return 0; }\n").unwrap();

    let mut config = Config::default();
    config.lsp.insert(
        "cpp".to_string(),
        LspServerConfig {
            command: FakeLspServer::script_path().to_string_lossy().to_string(),
            args: vec![],
            enabled: true,
            auto_start: true,
            process_limits: ProcessLimits::default(),
            initialization_options: None,
        },
    );

    let mut harness =
        EditorTestHarness::with_config_and_working_dir(120, 30, config, project_root.clone())
            .unwrap();

    harness.open_file(&source_file)?;
    harness.render()?;
    for _ in 0..10 {
        harness.sleep(Duration::from_millis(100));
        let _ = harness.editor_mut().process_async_messages();
        harness.render()?;
    }

    let mut seen_status = false;
    for _ in 0..20 {
        harness.sleep(Duration::from_millis(50));
        let _ = harness.editor_mut().process_async_messages();
        harness.render()?;
        if let Some(msg) = harness.editor().get_status_message() {
            if msg == "Clangd file status: ready" {
                seen_status = true;
                break;
            }
        }
    }

    assert!(
        seen_status,
        "Expected clangd file status notification to set the plugin status"
    );

    Ok(())
}

/// Ensure the clangd plugin uses editor.sendLspRequest successfully
#[test]
#[cfg_attr(windows, ignore)] // Uses bash script for fake LSP server
fn test_clangd_plugin_switch_source_header() -> anyhow::Result<()> {
    init_tracing_from_env();
    let _fake_server = FakeLspServer::spawn()?;

    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();
    copy_plugin(&plugins_dir, "clangd_support");
    copy_plugin_lib(&plugins_dir);

    let src_dir = project_root.join("src");
    fs::create_dir_all(&src_dir).unwrap();
    let source_file = src_dir.join("main.cpp");
    fs::write(&source_file, "int main() { return 0; }\n").unwrap();
    let header_file = src_dir.join("main.h");
    fs::write(&header_file, "// header content\n").unwrap();

    let mut config = Config::default();
    config.lsp.insert(
        "cpp".to_string(),
        LspServerConfig {
            command: FakeLspServer::script_path().to_string_lossy().to_string(),
            args: vec![],
            enabled: true,
            auto_start: true,
            process_limits: ProcessLimits::default(),
            initialization_options: None,
        },
    );

    let mut harness =
        EditorTestHarness::with_config_and_working_dir(120, 30, config, project_root.clone())
            .unwrap();

    harness.open_file(&source_file)?;
    harness.render()?;

    // Open command palette and run the switch command
    // Wait for the command to appear (meaning plugin is loaded)
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.type_text("Clangd: Switch Source/Header").unwrap();
    harness.wait_until(|h| h.screen_to_string().contains("Switch Source/Header"))?;
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();

    // Wait for the header file content to appear
    harness.wait_until(|h| h.screen_to_string().contains("header content"))?;

    let screen = harness.screen_to_string();
    assert!(
        screen.contains("header content"),
        "Expected header file to be visible, got:\n{}",
        screen
    );

    Ok(())
}

/// Test that plugin commands show the plugin name as source in command palette
#[test]
fn test_plugin_command_source_in_palette() {
    // Initialize tracing and signal handlers for debugging
    init_tracing_from_env();
    fresh::services::signal_handler::install_signal_handlers();

    // Create a temporary project directory
    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    // Create plugins directory
    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();

    // Create a simple plugin that registers a command
    // IMPORTANT: description must NOT contain "test_source_plugin" so we can verify
    // that the source column shows it (not the description)
    let test_plugin = r#"
const editor = getEditor();
// Simple test plugin to verify command source is shown correctly
editor.registerCommand(
    "Test Source Plugin Command",
    "A special command for testing",
    "test_source_action",
    null
);

editor.setStatus("Test source plugin loaded!");
"#;

    let test_plugin_path = plugins_dir.join("test_source_plugin.ts");
    fs::write(&test_plugin_path, test_plugin).unwrap();

    // Create a test file
    let fixture = TestFixture::new("test.txt", "Test content\n").unwrap();

    // Create harness with the project directory
    let mut harness =
        EditorTestHarness::with_config_and_working_dir(120, 30, Default::default(), project_root)
            .unwrap();

    // Open the test file
    harness.open_file(&fixture.path).unwrap();
    harness.render().unwrap();

    // Wait for plugins to load
    for _ in 0..5 {
        harness.process_async_and_render().unwrap();
        harness.sleep(Duration::from_millis(50));
    }

    // Open command palette
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Search for our plugin command
    harness.type_text("Test Source Plugin").unwrap();

    // Process to update suggestions
    for _ in 0..3 {
        harness.process_async_and_render().unwrap();
        harness.sleep(Duration::from_millis(50));
    }

    let screen = harness.screen_to_string();
    println!("Screen showing command palette:\n{}", screen);

    // Verify the command appears
    assert!(
        screen.contains("Test Source Plugin Command"),
        "Plugin command should appear in palette. Got:\n{}",
        screen
    );

    // Verify the source shows the plugin name, NOT "builtin"
    // The source column should show "test_source_p..." (truncated filename without .ts)
    assert!(
        screen.contains("test_source_p"),
        "Command source should show plugin name 'test_source_p...', not 'builtin'. Got:\n{}",
        screen
    );
    // Also verify it does NOT show "builtin" for this command
    // (Since the command is on screen, if it showed "builtin" we'd see it)
    // Note: We can't easily check the specific line, but the fact that test_source_p
    // appears AND builtin commands show "builtin" confirms the feature works

    // Also verify that builtin commands still show "builtin"
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Open palette again and search for a builtin command
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();
    harness.type_text("Save File").unwrap();

    for _ in 0..3 {
        harness.process_async_and_render().unwrap();
        harness.sleep(Duration::from_millis(50));
    }

    let screen2 = harness.screen_to_string();
    println!("Screen showing Save File command:\n{}", screen2);

    // Save File should show "builtin" as source
    assert!(
        screen2.contains("builtin"),
        "Builtin command should show 'builtin' as source. Got:\n{}",
        screen2
    );
}

/// Test that diagnostics from fake LSP are stored and accessible via getAllDiagnostics API
#[test]
#[cfg_attr(windows, ignore)] // Uses bash script for fake LSP server
fn test_diagnostics_api_with_fake_lsp() -> anyhow::Result<()> {
    init_tracing_from_env();
    let _fake_server = FakeLspServer::spawn()?;

    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    // Create plugins directory and copy lib
    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();

    let lib_source_dir = std::env::current_dir().unwrap().join("plugins/lib");
    let lib_dest_dir = plugins_dir.join("lib");
    fs::create_dir(&lib_dest_dir).unwrap();
    for entry in fs::read_dir(&lib_source_dir).unwrap() {
        let entry = entry.unwrap();
        if entry.path().extension().map(|e| e == "ts").unwrap_or(false) {
            fs::copy(entry.path(), lib_dest_dir.join(entry.file_name())).unwrap();
        }
    }

    // Create a simple plugin that captures diagnostics via getAllDiagnostics
    let test_plugin = r#"/// <reference path="./lib/fresh.d.ts" />
const editor = getEditor();

// Test plugin to verify getAllDiagnostics API works with real LSP data
let diagnosticCount = 0;

globalThis.on_test_diagnostics_updated = function(data: { uri: string; count: number }): void {
    // When diagnostics update, query them and store count
    const allDiags = editor.getAllDiagnostics();
    diagnosticCount = allDiags.length;
    editor.setStatus(`Diagnostics received: ${diagnosticCount} total, URI count: ${data.count}`);
};

globalThis.get_diagnostic_count = function(): void {
    const allDiags = editor.getAllDiagnostics();
    diagnosticCount = allDiags.length;
    editor.setStatus(`Current diagnostics: ${diagnosticCount}`);
};

editor.on("diagnostics_updated", "on_test_diagnostics_updated");

editor.registerCommand(
    "Test: Get Diagnostic Count",
    "Report the number of diagnostics",
    "get_diagnostic_count",
    "normal"
);

editor.setStatus("Test diagnostics plugin loaded");
"#;

    fs::write(plugins_dir.join("test_diagnostics.ts"), test_plugin).unwrap();

    // Create a test Rust file
    let test_file = project_root.join("test.rs");
    fs::write(&test_file, "fn main() {\n    let x = 1;\n}\n").unwrap();

    // Configure fake LSP for Rust files
    let mut config = Config::default();
    config.lsp.insert(
        "rust".to_string(),
        LspServerConfig {
            command: FakeLspServer::script_path().to_string_lossy().to_string(),
            args: vec![],
            enabled: true,
            auto_start: true,
            process_limits: ProcessLimits::default(),
            initialization_options: None,
        },
    );

    let mut harness =
        EditorTestHarness::with_config_and_working_dir(100, 30, config, project_root.clone())
            .unwrap();

    // Open the test file - this will start LSP
    harness.open_file(&test_file)?;
    harness.render()?;

    // Wait for LSP to initialize and plugin to load
    for _ in 0..10 {
        harness.sleep(Duration::from_millis(100));
        let _ = harness.editor_mut().process_async_messages();
        harness.render()?;
    }

    // Save the file to trigger diagnostics from fake LSP
    harness
        .send_key(KeyCode::Char('s'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render()?;

    // Wait for diagnostics to be received and processed
    // Loop indefinitely - test framework timeout will catch actual failures
    loop {
        harness.sleep(Duration::from_millis(100));
        let _ = harness.editor_mut().process_async_messages();
        harness.render()?;

        // Check if diagnostics were stored
        let stored = harness.editor().get_stored_diagnostics();
        if !stored.is_empty() {
            println!("Diagnostics received: {:?}", stored);
            break;
        }
    }

    // Verify the diagnostics content
    let stored = harness.editor().get_stored_diagnostics();
    assert_eq!(stored.len(), 1, "Expected diagnostics for one file");

    // Get the diagnostics for our file
    // Note: On macOS, temp paths like /var/folders/... get canonicalized to /private/var/folders/...
    // so we need to canonicalize the path before constructing the URI
    let canonical_path = test_file
        .canonicalize()
        .unwrap_or_else(|_| test_file.clone());
    let file_uri = format!("file://{}", canonical_path.to_string_lossy());
    let diags = stored
        .get(&file_uri)
        .expect("Should have diagnostics for test file");
    assert_eq!(diags.len(), 1, "Expected exactly one diagnostic");

    // Verify the diagnostic content matches what fake LSP sends
    let diag = &diags[0];
    assert_eq!(
        diag.message, "Test error from fake LSP",
        "Diagnostic message should match fake LSP"
    );
    assert_eq!(
        diag.severity,
        Some(lsp_types::DiagnosticSeverity::ERROR),
        "Diagnostic severity should be error"
    );

    // Verify the plugin's diagnostics_updated hook was called
    // by checking if the status message shows diagnostics count
    if let Some(status) = harness.editor().get_status_message() {
        println!("Status message: {}", status);
        // The hook should have set status with "Diagnostics received"
        if status.contains("Diagnostics received") {
            println!("Plugin hook was triggered successfully");
        }
    }

    Ok(())
}