fresh-editor 0.3.8

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
//! Tests for the package manager plugin and package loading from packages directory.

#![cfg(feature = "plugins")]

use crate::common::git_test_helper::{DirGuard, GitTestRepo};
use crate::common::harness::{copy_plugin, copy_plugin_lib, EditorTestHarness};
use crate::common::tracing::init_tracing_from_env;
use crossterm::event::{KeyCode, KeyModifiers};
use std::fs;

/// Test that plugins in the packages/ subdirectory are discovered and loaded.
#[test]
fn test_plugin_loading_from_packages_directory() {
    // Create a git repo with the typical project structure
    let repo = GitTestRepo::new();
    repo.setup_typical_project();

    // Create the plugins directory structure
    let plugins_dir = repo.path.join("plugins");
    fs::create_dir_all(&plugins_dir).unwrap();
    copy_plugin_lib(&plugins_dir);

    // Create packages subdirectory with a test plugin
    let packages_dir = plugins_dir.join("packages");
    fs::create_dir_all(&packages_dir).unwrap();

    // Create a minimal test plugin in packages/test-plugin/
    let test_plugin_dir = packages_dir.join("test-plugin");
    fs::create_dir_all(&test_plugin_dir).unwrap();

    // Write the plugin's main.ts
    fs::write(
        test_plugin_dir.join("main.ts"),
        r#"
/// <reference path="../../lib/fresh.d.ts" />
const editor = getEditor();

globalThis.test_pkg_plugin_hello = function(): void {
    editor.setStatus("Hello from packages plugin!");
};

editor.registerCommand(
    "test_pkg_plugin_hello",
    "Test Package Plugin: Hello",
    "test_pkg_plugin_hello",
    null
);

editor.debug("Test package plugin loaded!");
"#,
    )
    .unwrap();

    // Write package.json manifest
    fs::write(
        test_plugin_dir.join("package.json"),
        r#"{
    "name": "test-plugin",
    "version": "1.0.0",
    "description": "A test plugin for package loading",
    "type": "plugin",
    "fresh": {
        "entry": "main.ts"
    }
}"#,
    )
    .unwrap();

    // Change to repo directory
    let original_dir = repo.change_to_repo_dir();
    let _guard = DirGuard::new(original_dir);

    // Create editor with the project directory
    let mut harness = EditorTestHarness::with_config_and_working_dir(
        100,
        30,
        Default::default(),
        repo.path.clone(),
    )
    .unwrap();

    // Open command palette and search for our test command
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.wait_for_prompt().unwrap();

    // Type the test plugin command
    harness.type_text("Test Package Plugin").unwrap();

    // Wait for the command to appear in suggestions (semantic wait)
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("Test Package Plugin") || screen.contains("Hello")
        })
        .unwrap();

    let screen = harness.screen_to_string();
    assert!(
        screen.contains("Test Package Plugin") || screen.contains("Hello"),
        "Plugin from packages directory should be loaded. Screen: {}",
        screen
    );
}

/// Test the package manager plugin's list command.
#[test]
fn test_pkg_list_installed_empty() {
    let repo = GitTestRepo::new();
    repo.setup_typical_project();

    // Setup plugins directory with the package manager
    let plugins_dir = repo.path.join("plugins");
    fs::create_dir_all(&plugins_dir).unwrap();
    copy_plugin_lib(&plugins_dir);
    copy_plugin(&plugins_dir, "pkg");

    // Change to repo directory
    let original_dir = repo.change_to_repo_dir();
    let _guard = DirGuard::new(original_dir);

    let mut harness = EditorTestHarness::with_config_and_working_dir(
        100,
        30,
        Default::default(),
        repo.path.clone(),
    )
    .unwrap();

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

    // Search for pkg command - wait for it to appear
    harness.type_text("Package: Packages").unwrap();
    harness
        .wait_until(|h| h.screen_to_string().contains("Package: Packages"))
        .unwrap();

    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();

    // Wait for status message showing no packages
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("No packages") || screen.contains("Installed")
        })
        .unwrap();

    let screen = harness.screen_to_string();
    assert!(
        screen.contains("No packages") || screen.contains("Installed"),
        "Should show package list status. Screen: {}",
        screen
    );
}

/// Test installing a plugin from a local git repository.
#[test]
#[cfg_attr(windows, ignore)] // file:// URLs don't work reliably on Windows
fn test_pkg_install_from_local_git_url() {
    // Create a "remote" repo to serve as the package source
    let package_repo = GitTestRepo::new();

    // Create a simple plugin in the package repo
    fs::write(
        package_repo.path.join("main.ts"),
        r#"
/// <reference path="./lib/fresh.d.ts" />
const editor = getEditor();
editor.registerCommand("sample_cmd", "Sample: Command", "sample_cmd", null);
globalThis.sample_cmd = function() { editor.setStatus("Sample plugin works!"); };
"#,
    )
    .unwrap();

    fs::write(
        package_repo.path.join("package.json"),
        r#"{
    "name": "sample-plugin",
    "version": "1.0.0",
    "type": "plugin",
    "fresh": { "entry": "main.ts" }
}"#,
    )
    .unwrap();

    // Commit the plugin to make it a valid git repo for cloning
    package_repo.git_add_all();
    package_repo.git_commit("Initial plugin");

    // Create the main project repo
    let repo = GitTestRepo::new();
    repo.setup_typical_project();

    let plugins_dir = repo.path.join("plugins");
    fs::create_dir_all(&plugins_dir).unwrap();
    copy_plugin_lib(&plugins_dir);
    copy_plugin(&plugins_dir, "pkg");

    // Create the packages directory (simulating ~/.config/fresh/plugins/packages)
    let packages_dir = plugins_dir.join("packages");
    fs::create_dir_all(&packages_dir).unwrap();

    let original_dir = repo.change_to_repo_dir();
    let _guard = DirGuard::new(original_dir);

    let mut harness = EditorTestHarness::with_config_and_working_dir(
        120,
        35,
        Default::default(),
        repo.path.clone(),
    )
    .unwrap();

    // Open command palette and install from URL
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.wait_for_prompt().unwrap();

    harness.type_text("pkg: Install from URL").unwrap();
    harness
        .wait_until(|h| h.screen_to_string().contains("Install from URL"))
        .unwrap();

    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();

    // Wait for the URL prompt to appear
    harness
        .wait_until(|h| h.screen_to_string().contains("Git URL or local path"))
        .unwrap();

    // Enter the local git repo path as the URL
    let local_url = format!("file://{}", package_repo.path.display());
    harness.type_text(&local_url).unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();

    // Wait for git clone to complete - look for any status change
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("Installed")
                || screen.contains("Failed")
                || screen.contains("already")
                || screen.contains("Installing")
        })
        .unwrap();

    let screen = harness.screen_to_string();

    // Check that either installation succeeded or we got an expected status
    // Note: The actual cloning might fail in test environment, but the flow should work
    assert!(
        screen.contains("Install")
            || screen.contains("sample")
            || screen.contains("Git URL or local path")
            || screen.contains("Failed"),
        "Should show install progress or result. Screen: {}",
        screen
    );
}

/// Test that the Install Plugin command works with an empty registry.
/// This tests the async command flow and status updates.
#[test]
fn test_pkg_install_plugin_empty_registry() {
    use fresh::config_io::DirectoryContext;
    use tempfile::TempDir;

    init_tracing_from_env();

    // Create temp directories for test isolation
    let temp_dir = TempDir::new().unwrap();
    let dir_context = DirectoryContext::for_testing(temp_dir.path());

    let repo = GitTestRepo::new();
    repo.setup_typical_project();

    // Setup plugins directory in the working directory (for the pkg plugin to load)
    let plugins_dir = repo.path.join("plugins");
    fs::create_dir_all(&plugins_dir).unwrap();
    copy_plugin_lib(&plugins_dir);
    copy_plugin(&plugins_dir, "pkg");

    // Create an empty index in the CONFIG directory (not the working directory!)
    // The pkg plugin uses getConfigDir() which points to dir_context.config_dir
    let config_plugins_dir = dir_context.config_dir.join("plugins");
    fs::create_dir_all(&config_plugins_dir).unwrap();
    let packages_dir = config_plugins_dir.join("packages");
    fs::create_dir_all(&packages_dir).unwrap();
    let index_dir = packages_dir.join(".index");
    fs::create_dir_all(&index_dir).unwrap();

    // Create a fake registry source directory that matches the hash for the default registry
    // djb2("https://github.com/sinelaw/fresh-plugins-registry") = 193934da
    let fake_registry_dir = index_dir.join("193934da");
    fs::create_dir_all(&fake_registry_dir).unwrap();
    // Write an empty plugins.json so the registry is considered synced
    fs::write(
        fake_registry_dir.join("plugins.json"),
        r#"{"schema_version": 1, "updated": "2024-01-01", "packages": {}}"#,
    )
    .unwrap();
    // Initialize a real git repo (no remote) so `git pull` exits immediately
    std::process::Command::new("git")
        .args(["init"])
        .current_dir(&fake_registry_dir)
        .output()
        .expect("Failed to git init fake registry");
    std::process::Command::new("git")
        .args(["add", "."])
        .current_dir(&fake_registry_dir)
        .output()
        .expect("Failed to git add in fake registry");
    std::process::Command::new("git")
        .args(["commit", "-m", "init"])
        .current_dir(&fake_registry_dir)
        .output()
        .expect("Failed to git commit in fake registry");

    // Change to repo directory
    let original_dir = repo.change_to_repo_dir();
    let _guard = DirGuard::new(original_dir);

    let mut harness = EditorTestHarness::with_shared_dir_context(
        100,
        30,
        Default::default(),
        repo.path.clone(),
        dir_context,
    )
    .unwrap();

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

    // Open the package manager UI
    harness.type_text("Package: Packages").unwrap();
    harness
        .wait_until(|h| h.screen_to_string().contains("Package: Packages"))
        .unwrap();

    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();

    // Wait for package manager UI to appear - may show syncing or empty state
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            // Package manager UI opened or showing empty/syncing state
            screen.contains("Packages") || screen.contains("Syncing")
        })
        .unwrap();

    let screen = harness.screen_to_string();
    // With empty registry, the package manager should show the UI (even if no packages available)
    assert!(
        screen.contains("Packages") || screen.contains("Syncing"),
        "Should show package manager UI or syncing status. Screen: {}",
        screen
    );
}

/// Test that Install Plugin auto-syncs a stale registry before showing results.
/// This test simulates a scenario where the registry was previously synced but
/// is now out of date. The Install Plugin command should automatically pull
/// the latest registry data before showing available plugins.
///
/// Without the fix (always calling syncRegistry), this test would fail because
/// the stale empty registry would be used without attempting to update.
#[test]
fn test_pkg_install_plugin_auto_syncs_stale_registry() {
    use fresh::config_io::DirectoryContext;
    use tempfile::TempDir;

    init_tracing_from_env();

    // Create temp directories for test isolation
    let temp_dir = TempDir::new().unwrap();
    let dir_context = DirectoryContext::for_testing(temp_dir.path());

    // Step 1: Create a "remote" registry repository - starts EMPTY
    let registry_repo = GitTestRepo::new();
    fs::write(
        registry_repo.path.join("plugins.json"),
        r#"{"schema_version": 1, "updated": "2024-01-01", "packages": {}}"#,
    )
    .unwrap();
    registry_repo.git_add_all();
    registry_repo.git_commit("Initial empty registry");

    // Set up the project
    let repo = GitTestRepo::new();
    repo.setup_typical_project();

    // Setup plugins directory with the pkg plugin
    let plugins_dir = repo.path.join("plugins");
    fs::create_dir_all(&plugins_dir).unwrap();
    copy_plugin_lib(&plugins_dir);
    copy_plugin(&plugins_dir, "pkg");

    // Create the index directory structure in CONFIG directory
    let config_plugins_dir = dir_context.config_dir.join("plugins");
    fs::create_dir_all(&config_plugins_dir).unwrap();
    let packages_dir = config_plugins_dir.join("packages");
    fs::create_dir_all(&packages_dir).unwrap();
    let index_dir = packages_dir.join(".index");
    fs::create_dir_all(&index_dir).unwrap();

    // Step 2: Clone the registry (simulates first sync when registry was empty)
    let registry_index_dir = index_dir.join("193934da");
    std::process::Command::new("git")
        .args([
            "clone",
            registry_repo.path.to_str().unwrap(),
            registry_index_dir.to_str().unwrap(),
        ])
        .output()
        .expect("Failed to clone registry");

    // Verify the cloned registry is empty
    let cloned_content = fs::read_to_string(registry_index_dir.join("plugins.json")).unwrap();
    assert!(
        cloned_content.contains(r#""packages": {}"#),
        "Cloned registry should be empty initially"
    );

    // Step 3: Update the "remote" registry with a new plugin (simulates registry update)
    fs::write(
        registry_repo.path.join("plugins.json"),
        r#"{
            "schema_version": 1,
            "updated": "2026-01-25T00:00:00Z",
            "packages": {
                "test-plugin": {
                    "description": "A test plugin for auto-sync verification",
                    "repository": "https://example.com/test-plugin"
                }
            }
        }"#,
    )
    .unwrap();
    registry_repo.git_add_all();
    registry_repo.git_commit("Add test plugin to registry");

    // At this point:
    // - Remote registry has "test-plugin"
    // - Local clone (index) still has empty registry
    // - Without auto-sync: would show "No plugins"
    // - With auto-sync: git pull runs, shows "test-plugin"

    // Change to repo directory
    let original_dir = repo.change_to_repo_dir();
    let _guard = DirGuard::new(original_dir);

    let mut harness = EditorTestHarness::with_shared_dir_context(
        120,
        35,
        Default::default(),
        repo.path.clone(),
        dir_context,
    )
    .unwrap();

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

    // Open the package manager UI (which now auto-syncs on open)
    harness.type_text("Package: Packages").unwrap();
    harness
        .wait_until(|h| h.screen_to_string().contains("Package: Packages"))
        .unwrap();

    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();

    // Wait for the package manager UI - with auto-sync it should pull the updated registry
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            // Package manager opened, may show syncing or already have plugin list
            screen.contains("test-plugin")
                || screen.contains("Packages")
                || screen.contains("Syncing")
                || screen.contains("Updating")
        })
        .unwrap();

    let screen = harness.screen_to_string();

    // With auto-sync on open: syncRegistry() is called, git pull runs
    // The package manager should show syncing activity or already have the plugin
    assert!(
        screen.contains("test-plugin")
            || screen.contains("Syncing")
            || screen.contains("Updating")
            || screen.contains("Packages"),
        "Package manager should auto-sync on open. Screen: {}",
        screen
    );
}

/// Test package manager UI flows:
/// - Split-view layout with list on left, details on right
/// - Tab navigation through all focusable buttons
/// - Filter activation
/// - Package selection with arrow keys
#[test]
fn test_pkg_manager_ui_split_view_and_tab_navigation() {
    use fresh::config_io::DirectoryContext;
    use tempfile::TempDir;

    init_tracing_from_env();

    // Create temp directories for test isolation
    let temp_dir = TempDir::new().unwrap();
    let dir_context = DirectoryContext::for_testing(temp_dir.path());

    let repo = GitTestRepo::new();
    repo.setup_typical_project();

    // Setup plugins directory with the pkg plugin
    let plugins_dir = repo.path.join("plugins");
    fs::create_dir_all(&plugins_dir).unwrap();
    copy_plugin_lib(&plugins_dir);
    copy_plugin(&plugins_dir, "pkg");

    // Create registry structure in config dir
    let config_plugins_dir = dir_context.config_dir.join("plugins");
    fs::create_dir_all(&config_plugins_dir).unwrap();
    let packages_dir = config_plugins_dir.join("packages");
    fs::create_dir_all(&packages_dir).unwrap();
    let index_dir = packages_dir.join(".index");
    fs::create_dir_all(&index_dir).unwrap();

    // Create fake registry with test packages
    let fake_registry_dir = index_dir.join("193934da");
    fs::create_dir_all(&fake_registry_dir).unwrap();
    fs::write(
        fake_registry_dir.join("plugins.json"),
        r#"{
            "schema_version": 1,
            "updated": "2026-01-01T00:00:00Z",
            "packages": {
                "test-plugin-alpha": {
                    "description": "Test plugin Alpha for UI testing",
                    "repository": "https://github.com/test/plugin-alpha",
                    "author": "Test Author",
                    "license": "MIT"
                },
                "test-plugin-beta": {
                    "description": "Test plugin Beta for UI testing",
                    "repository": "https://github.com/test/plugin-beta",
                    "author": "Test Author",
                    "license": "MIT"
                }
            }
        }"#,
    )
    .unwrap();
    // Initialize a real git repo (no remote) so `git pull` exits immediately
    std::process::Command::new("git")
        .args(["init"])
        .current_dir(&fake_registry_dir)
        .output()
        .expect("Failed to git init fake registry");
    std::process::Command::new("git")
        .args(["add", "."])
        .current_dir(&fake_registry_dir)
        .output()
        .expect("Failed to git add in fake registry");
    std::process::Command::new("git")
        .args(["commit", "-m", "init"])
        .current_dir(&fake_registry_dir)
        .output()
        .expect("Failed to git commit in fake registry");

    // Change to repo directory
    let original_dir = repo.change_to_repo_dir();
    let _guard = DirGuard::new(original_dir);

    let mut harness = EditorTestHarness::with_shared_dir_context(
        100,
        30,
        Default::default(),
        repo.path.clone(),
        dir_context,
    )
    .unwrap();

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

    harness.type_text("Package: Packages").unwrap();
    harness
        .wait_until(|h| h.screen_to_string().contains("Package: Packages"))
        .unwrap();

    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();

    // Wait for package manager UI to appear and loading to complete.
    // `AVAILABLE` appears once the registry sync finishes, and the footer
    // panel's help text (which contains "Tab") is populated by the same
    // updatePkgManagerView() pass — but on slow runners the footer render
    // can land a frame or two after the list. Wait for both.
    harness
        .wait_until(|h| {
            let s = h.screen_to_string();
            s.contains("AVAILABLE") && s.contains("Tab")
        })
        .unwrap();

    let screen = harness.screen_to_string();
    println!("Package manager initial state:\n{}", screen);

    // Verify split-view layout elements
    assert!(
        screen.contains("Packages"),
        "Should show 'Packages' header. Screen:\n{}",
        screen
    );
    assert!(
        screen.contains("All") && screen.contains("Installed"),
        "Should show filter buttons. Screen:\n{}",
        screen
    );
    assert!(
        screen.contains("│"),
        "Should have vertical divider for split view. Screen:\n{}",
        screen
    );
    assert!(
        screen.contains("Tab"),
        "Should show Tab in help text. Screen:\n{}",
        screen
    );

    // Verify available packages appear in the list (already checked in wait_until)
    assert!(
        screen.contains("AVAILABLE"),
        "Should show AVAILABLE section with registry packages. Screen:\n{}",
        screen
    );

    // Test Tab navigation - press Tab and check that focus changes
    // (indicated by help text changing or visual elements changing)
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();
    let screen_after_tab1 = harness.screen_to_string();
    println!("After Tab 1:\n{}", screen_after_tab1);

    // Tab through all focusable elements (typically: list -> action -> filters -> sync -> search -> back to list)
    for i in 2..=8 {
        harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
        harness.render().unwrap();
        println!("After Tab {}:", i);
    }

    // After cycling, we should be back to a navigable state
    let screen_after_cycle = harness.screen_to_string();
    println!("After full Tab cycle:\n{}", screen_after_cycle);

    // Verify the UI is still functional
    assert!(
        screen_after_cycle.contains("Packages"),
        "Should still show Packages header after Tab cycle"
    );

    // Test Escape to close - may need multiple presses depending on focus state
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();

    // Wait for package manager to close (semantic waiting per README guidelines)
    harness
        .wait_until(|h| !h.screen_to_string().contains("*Packages*"))
        .unwrap();

    let screen_after_close = harness.screen_to_string();
    println!("After Escape:\n{}", screen_after_close);
}

/// Test installing a plugin from a monorepo with subpath (e.g., repo#packages/my-plugin).
/// This verifies that only the specific subdirectory is installed, not the entire repo,
/// and that the package.json is at the correct location so version can be read.
#[test]
#[cfg_attr(windows, ignore)] // file:// URLs don't work reliably on Windows
fn test_pkg_install_from_monorepo_with_subpath() {
    use fresh::config_io::DirectoryContext;
    use tempfile::TempDir;

    init_tracing_from_env();

    // Create temp directories for test isolation
    let temp_dir = TempDir::new().unwrap();
    let dir_context = DirectoryContext::for_testing(temp_dir.path());

    // Create a "remote" monorepo with multiple plugins
    let monorepo = GitTestRepo::new();

    // Create plugin-alpha in subdirectory
    let alpha_dir = monorepo.path.join("plugin-alpha");
    fs::create_dir_all(&alpha_dir).unwrap();
    fs::write(
        alpha_dir.join("main.ts"),
        r#"
/// <reference path="./lib/fresh.d.ts" />
const editor = getEditor();
editor.registerCommand("alpha_cmd", "Alpha: Command", "alpha_cmd", null);
globalThis.alpha_cmd = function() { editor.setStatus("Alpha plugin works!"); };
"#,
    )
    .unwrap();
    fs::write(
        alpha_dir.join("package.json"),
        r#"{
    "name": "plugin-alpha",
    "version": "2.0.0",
    "description": "Alpha plugin from monorepo",
    "type": "plugin",
    "fresh": { "entry": "main.ts" }
}"#,
    )
    .unwrap();

    // Create plugin-beta in another subdirectory
    let beta_dir = monorepo.path.join("plugin-beta");
    fs::create_dir_all(&beta_dir).unwrap();
    fs::write(
        beta_dir.join("main.ts"),
        r#"
/// <reference path="./lib/fresh.d.ts" />
const editor = getEditor();
editor.registerCommand("beta_cmd", "Beta: Command", "beta_cmd", null);
globalThis.beta_cmd = function() { editor.setStatus("Beta plugin works!"); };
"#,
    )
    .unwrap();
    fs::write(
        beta_dir.join("package.json"),
        r#"{
    "name": "plugin-beta",
    "version": "3.0.0",
    "description": "Beta plugin from monorepo",
    "type": "plugin",
    "fresh": { "entry": "main.ts" }
}"#,
    )
    .unwrap();

    // Add a root file to distinguish from subdirectory
    fs::write(monorepo.path.join("README.md"), "# Monorepo").unwrap();

    // Commit the monorepo
    monorepo.git_add_all();
    monorepo.git_commit("Initial monorepo with plugins");

    // Create the main project repo
    let repo = GitTestRepo::new();
    repo.setup_typical_project();

    let plugins_dir = repo.path.join("plugins");
    fs::create_dir_all(&plugins_dir).unwrap();
    copy_plugin_lib(&plugins_dir);
    copy_plugin(&plugins_dir, "pkg");

    // Create the packages directory in config dir
    let config_plugins_dir = dir_context.config_dir.join("plugins");
    fs::create_dir_all(&config_plugins_dir).unwrap();
    let packages_dir = config_plugins_dir.join("packages");
    fs::create_dir_all(&packages_dir).unwrap();

    // Create empty registry so sync doesn't interfere
    let index_dir = packages_dir.join(".index");
    fs::create_dir_all(&index_dir).unwrap();
    let fake_registry_dir = index_dir.join("193934da");
    fs::create_dir_all(&fake_registry_dir).unwrap();
    fs::write(
        fake_registry_dir.join("plugins.json"),
        r#"{"schema_version": 1, "updated": "2024-01-01", "packages": {}}"#,
    )
    .unwrap();
    // Initialize a real git repo (no remote) so `git pull` exits immediately
    std::process::Command::new("git")
        .args(["init"])
        .current_dir(&fake_registry_dir)
        .output()
        .expect("Failed to git init fake registry");
    std::process::Command::new("git")
        .args(["add", "."])
        .current_dir(&fake_registry_dir)
        .output()
        .expect("Failed to git add in fake registry");
    std::process::Command::new("git")
        .args(["commit", "-m", "init"])
        .current_dir(&fake_registry_dir)
        .output()
        .expect("Failed to git commit in fake registry");

    let original_dir = repo.change_to_repo_dir();
    let _guard = DirGuard::new(original_dir);

    let mut harness = EditorTestHarness::with_shared_dir_context(
        120,
        35,
        Default::default(),
        repo.path.clone(),
        dir_context.clone(),
    )
    .unwrap();

    // Open command palette and install from URL with subpath
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.wait_for_prompt().unwrap();

    harness.type_text("pkg: Install from URL").unwrap();
    harness
        .wait_until(|h| h.screen_to_string().contains("Install from URL"))
        .unwrap();

    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();

    // Wait for the URL prompt
    harness
        .wait_until(|h| h.screen_to_string().contains("Git URL or local path"))
        .unwrap();

    // Enter monorepo URL with subpath fragment (note: # for subpath)
    let monorepo_url = format!("file://{}#plugin-alpha", monorepo.path.display());
    harness.type_text(&monorepo_url).unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();

    // Wait for installation to complete
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("Installed")
                || screen.contains("Failed")
                || screen.contains("already")
                || screen.contains("activated")
        })
        .unwrap();

    let screen = harness.screen_to_string();
    println!("After monorepo install:\n{}", screen);

    // Verify the plugin directory structure is correct
    let installed_plugin_dir = packages_dir.join("plugin-alpha");

    // Check that the package.json exists at the root of the installed plugin
    let package_json_path = installed_plugin_dir.join("package.json");
    assert!(
        package_json_path.exists(),
        "package.json should be at the root of installed plugin directory. \
         Expected: {:?}, Directory contents: {:?}",
        package_json_path,
        fs::read_dir(&installed_plugin_dir)
            .map(|entries| entries
                .filter_map(|e| e.ok())
                .map(|e| e.file_name())
                .collect::<Vec<_>>())
            .unwrap_or_default()
    );

    // Verify it's the correct package.json (from subdirectory, not a root one)
    let package_json_content = fs::read_to_string(&package_json_path).unwrap();
    assert!(
        package_json_content.contains("\"version\": \"2.0.0\""),
        "package.json should have version 2.0.0 from plugin-alpha. Content: {}",
        package_json_content
    );
    assert!(
        package_json_content.contains("plugin-alpha"),
        "package.json should be for plugin-alpha. Content: {}",
        package_json_content
    );

    // Check that main.ts exists
    let main_ts_path = installed_plugin_dir.join("main.ts");
    assert!(
        main_ts_path.exists(),
        "main.ts should exist at root of installed plugin. Path: {:?}",
        main_ts_path
    );

    // Verify the monorepo root files are NOT present (README.md, plugin-beta directory)
    let readme_path = installed_plugin_dir.join("README.md");
    assert!(
        !readme_path.exists(),
        "README.md from monorepo root should NOT be in installed plugin. \
         The entire monorepo was cloned instead of just the subdirectory."
    );

    let beta_in_alpha = installed_plugin_dir.join("plugin-beta");
    assert!(
        !beta_in_alpha.exists(),
        "plugin-beta directory should NOT be in installed plugin-alpha. \
         The entire monorepo was cloned instead of just the subdirectory."
    );
}

/// Test installing a bundle package from a local path.
/// A bundle contains multiple languages and plugins in a single package.
/// This test verifies:
/// - Bundle installs to the bundles/packages directory
/// - Languages from the bundle are registered (grammars)
/// - Plugins from the bundle are loaded and their commands available
#[test]
#[cfg_attr(windows, ignore)] // file:// URLs don't work reliably on Windows
fn test_pkg_install_bundle_from_local_path() {
    use fresh::config_io::DirectoryContext;
    use tempfile::TempDir;

    init_tracing_from_env();

    // Create temp directories for test isolation
    let temp_dir = TempDir::new().unwrap();
    let dir_context = DirectoryContext::for_testing(temp_dir.path());

    // Create a local bundle package with 2 languages and 1 plugin
    // Note: We create it inside a subdirectory named "test-bundle" so the package
    // manager extracts the correct name from the path
    let bundle_temp = TempDir::new().unwrap();
    let bundle_dir = bundle_temp.path().join("test-bundle");
    fs::create_dir_all(&bundle_dir).unwrap();

    // Create the grammars directory
    let grammars_dir = bundle_dir.join("grammars");
    fs::create_dir_all(&grammars_dir).unwrap();

    // Create a minimal sublime-syntax grammar for "testlang1"
    fs::write(
        grammars_dir.join("TestLang1.sublime-syntax"),
        r#"%YAML 1.2
---
name: TestLang1
file_extensions: [tl1]
scope: source.testlang1
contexts:
  main:
    - match: '#.*'
      scope: comment.line
"#,
    )
    .unwrap();

    // Create a minimal sublime-syntax grammar for "testlang2"
    fs::write(
        grammars_dir.join("TestLang2.sublime-syntax"),
        r#"%YAML 1.2
---
name: TestLang2
file_extensions: [tl2]
scope: source.testlang2
contexts:
  main:
    - match: '//.*'
      scope: comment.line
"#,
    )
    .unwrap();

    // Create the plugins directory
    let plugins_dir = bundle_dir.join("plugins");
    fs::create_dir_all(&plugins_dir).unwrap();

    // Create first plugin that registers a command
    // Note: registerCommand(id, displayName, functionName, keybinding)
    fs::write(
        plugins_dir.join("test-helper.ts"),
        r#"
/// <reference path="./lib/fresh.d.ts" />
const editor = getEditor();

globalThis.bundle_test_cmd = function(): void {
    editor.setStatus("Bundle test command executed!");
};

editor.registerCommand(
    "bundle_test_cmd",
    "Bundle Test: Command",
    "bundle_test_cmd",
    null
);

editor.debug("Bundle test plugin 1 loaded!");
"#,
    )
    .unwrap();

    // Create second plugin that registers another command
    fs::write(
        plugins_dir.join("another-helper.ts"),
        r#"
/// <reference path="./lib/fresh.d.ts" />
const editor = getEditor();

globalThis.bundle_another_cmd = function(): void {
    editor.setStatus("Bundle another command executed!");
};

editor.registerCommand(
    "bundle_another_cmd",
    "Bundle Another: Command",
    "bundle_another_cmd",
    null
);

editor.debug("Bundle test plugin 2 loaded!");
"#,
    )
    .unwrap();

    // Create the themes directory
    let themes_dir = bundle_dir.join("themes");
    fs::create_dir_all(&themes_dir).unwrap();

    // Create first theme (dark variant)
    // Note: Using r##"..."## because JSON contains "#" color codes
    fs::write(
        themes_dir.join("bundle-dark.json"),
        r##"{
    "name": "Bundle Dark Theme",
    "variant": "dark",
    "colors": {
        "editor.background": "#1e1e1e",
        "editor.foreground": "#d4d4d4"
    }
}"##,
    )
    .unwrap();

    // Create second theme (light variant)
    fs::write(
        themes_dir.join("bundle-light.json"),
        r##"{
    "name": "Bundle Light Theme",
    "variant": "light",
    "colors": {
        "editor.background": "#ffffff",
        "editor.foreground": "#000000"
    }
}"##,
    )
    .unwrap();

    // Create the bundle's package.json manifest
    // Note: Using r##"..."## because the content contains "#" which would close r#"..."#
    fs::write(
        bundle_dir.join("package.json"),
        r##"{
    "name": "test-bundle",
    "version": "1.0.0",
    "description": "Test bundle with languages, plugins, and themes",
    "type": "bundle",
    "fresh": {
        "languages": [
            {
                "id": "testlang1",
                "grammar": {
                    "file": "grammars/TestLang1.sublime-syntax",
                    "extensions": ["tl1"]
                },
                "language": {
                    "commentPrefix": "#",
                    "tabSize": 2
                }
            },
            {
                "id": "testlang2",
                "grammar": {
                    "file": "grammars/TestLang2.sublime-syntax",
                    "extensions": ["tl2"]
                },
                "language": {
                    "commentPrefix": "//",
                    "tabSize": 4
                }
            }
        ],
        "plugins": [
            { "entry": "plugins/test-helper.ts" },
            { "entry": "plugins/another-helper.ts" }
        ],
        "themes": [
            { "file": "themes/bundle-dark.json", "name": "Bundle Dark Theme", "variant": "dark" },
            { "file": "themes/bundle-light.json", "name": "Bundle Light Theme", "variant": "light" }
        ]
    }
}"##,
    )
    .unwrap();

    // Create the main project repo
    let repo = GitTestRepo::new();
    repo.setup_typical_project();

    // Setup plugins directory with the package manager
    let project_plugins_dir = repo.path.join("plugins");
    fs::create_dir_all(&project_plugins_dir).unwrap();
    copy_plugin_lib(&project_plugins_dir);
    copy_plugin(&project_plugins_dir, "pkg");

    // Also copy lib to bundle plugins dir so the plugin can find fresh.d.ts
    let bundle_plugins_lib_dir = plugins_dir.join("lib");
    fs::create_dir_all(&bundle_plugins_lib_dir).unwrap();
    fs::copy(
        project_plugins_dir.join("lib").join("fresh.d.ts"),
        bundle_plugins_lib_dir.join("fresh.d.ts"),
    )
    .unwrap();

    // Create empty registry structure so sync doesn't interfere
    let config_plugins_dir = dir_context.config_dir.join("plugins");
    fs::create_dir_all(&config_plugins_dir).unwrap();
    let packages_dir = config_plugins_dir.join("packages");
    fs::create_dir_all(&packages_dir).unwrap();
    let index_dir = packages_dir.join(".index");
    fs::create_dir_all(&index_dir).unwrap();
    let fake_registry_dir = index_dir.join("193934da");
    fs::create_dir_all(&fake_registry_dir).unwrap();
    fs::write(
        fake_registry_dir.join("plugins.json"),
        r#"{"schema_version": 1, "updated": "2024-01-01", "packages": {}}"#,
    )
    .unwrap();
    // Initialize a real git repo (no remote) so `git pull` exits immediately
    std::process::Command::new("git")
        .args(["init"])
        .current_dir(&fake_registry_dir)
        .output()
        .expect("Failed to git init fake registry");
    std::process::Command::new("git")
        .args(["add", "."])
        .current_dir(&fake_registry_dir)
        .output()
        .expect("Failed to git add in fake registry");
    std::process::Command::new("git")
        .args(["commit", "-m", "init"])
        .current_dir(&fake_registry_dir)
        .output()
        .expect("Failed to git commit in fake registry");

    // Create the bundles directory structure
    let bundles_packages_dir = dir_context.config_dir.join("bundles").join("packages");
    fs::create_dir_all(&bundles_packages_dir).unwrap();

    let original_dir = repo.change_to_repo_dir();
    let _guard = DirGuard::new(original_dir);

    let mut harness = EditorTestHarness::with_shared_dir_context(
        120,
        35,
        Default::default(),
        repo.path.clone(),
        dir_context.clone(),
    )
    .unwrap();

    // Open command palette and install from URL
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.wait_for_prompt().unwrap();

    harness.type_text("pkg: Install from URL").unwrap();
    harness
        .wait_until(|h| h.screen_to_string().contains("Install from URL"))
        .unwrap();

    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();

    // Wait for the URL prompt to appear
    harness
        .wait_until(|h| h.screen_to_string().contains("Git URL or local path"))
        .unwrap();

    // Enter the local bundle directory path (not git, just a local path)
    let bundle_path = bundle_dir.display().to_string();
    harness.type_text(&bundle_path).unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();

    // Wait for installation to complete
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("Installed bundle")
                || screen.contains("Failed")
                || screen.contains("already")
        })
        .unwrap();

    let screen = harness.screen_to_string();
    println!("After bundle install:\n{}", screen);

    // Verify the bundle was installed to bundles/packages directory
    let installed_bundle_dir = bundles_packages_dir.join("test-bundle");
    assert!(
        installed_bundle_dir.exists(),
        "Bundle should be installed in bundles/packages directory. Path: {:?}",
        installed_bundle_dir
    );

    // Verify package.json exists
    let package_json_path = installed_bundle_dir.join("package.json");
    assert!(
        package_json_path.exists(),
        "package.json should exist in installed bundle"
    );

    // Verify the package type is bundle
    let package_json_content = fs::read_to_string(&package_json_path).unwrap();
    assert!(
        package_json_content.contains("\"type\": \"bundle\""),
        "package.json should have type 'bundle'. Content: {}",
        package_json_content
    );

    // Verify grammar files were copied
    let grammar1_path = installed_bundle_dir
        .join("grammars")
        .join("TestLang1.sublime-syntax");
    assert!(
        grammar1_path.exists(),
        "Grammar file for testlang1 should exist"
    );
    let grammar2_path = installed_bundle_dir
        .join("grammars")
        .join("TestLang2.sublime-syntax");
    assert!(
        grammar2_path.exists(),
        "Grammar file for testlang2 should exist"
    );

    // === Test 1: Verify bundled plugin command is available and works ===
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.wait_for_prompt().unwrap();

    harness.type_text("Bundle Test").unwrap();

    // Wait for the command to appear (semantic wait)
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("Bundle Test: Command") || screen.contains("bundle_test_cmd")
        })
        .unwrap();

    let screen = harness.screen_to_string();
    assert!(
        screen.contains("Bundle Test: Command") || screen.contains("bundle_test_cmd"),
        "Bundle plugin command should be available in command palette. Screen: {}",
        screen
    );

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

    // Wait for the status message from the plugin command
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("Bundle test command executed!")
        })
        .unwrap();

    let screen = harness.screen_to_string();
    println!("After executing bundle command:\n{}", screen);
    assert!(
        screen.contains("Bundle test command executed!"),
        "Bundle plugin command should show status message when executed. Screen: {}",
        screen
    );

    // === Test 2: Verify bundled languages are available in "Set Language" ===
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.wait_for_prompt().unwrap();

    harness.type_text("Set Language").unwrap();
    harness
        .wait_until(|h| h.screen_to_string().contains("Set Language"))
        .unwrap();

    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();

    // Wait for language selection prompt
    harness
        .wait_until(|h| h.screen_to_string().contains("Language:"))
        .unwrap();

    // Type the name of our bundled language
    harness.type_text("testlang1").unwrap();

    // Wait for the bundled language to appear in the list
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            // The language should appear in the suggestions
            screen.contains("testlang1") || screen.to_lowercase().contains("testlang1")
        })
        .unwrap();

    let screen = harness.screen_to_string();
    println!("Set Language showing bundled language:\n{}", screen);
    assert!(
        screen.to_lowercase().contains("testlang1"),
        "Bundled language 'testlang1' should be available in Set Language. Screen: {}",
        screen
    );

    // Close the language selection
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // === Test 3: Verify second plugin command is available ===
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.wait_for_prompt().unwrap();

    harness.type_text("Bundle Another").unwrap();

    // Wait for the second command to appear
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("Bundle Another: Command") || screen.contains("bundle_another_cmd")
        })
        .unwrap();

    let screen = harness.screen_to_string();
    println!("Second plugin command in palette:\n{}", screen);
    assert!(
        screen.contains("Bundle Another: Command") || screen.contains("bundle_another_cmd"),
        "Second bundle plugin command should be available. Screen: {}",
        screen
    );

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

    harness
        .wait_until(|h| {
            h.screen_to_string()
                .contains("Bundle another command executed!")
        })
        .unwrap();

    let screen = harness.screen_to_string();
    println!("After executing second plugin command:\n{}", screen);

    // === Test 4: Verify bundled themes are available in "Select Theme" ===
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.wait_for_prompt().unwrap();

    harness.type_text("Select Theme").unwrap();
    harness
        .wait_until(|h| h.screen_to_string().contains("Select Theme"))
        .unwrap();

    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();

    // Wait for theme selection - the finder shows themes
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            // Look for any theme-related content or the finder
            screen.contains("Bundle Dark") || screen.contains("Theme") || screen.contains("dark")
        })
        .unwrap();

    // Type to filter for our bundled theme
    harness.type_text("Bundle").unwrap();

    // Wait for the bundled theme to appear
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("Bundle Dark") || screen.to_lowercase().contains("bundle")
        })
        .unwrap();

    let screen = harness.screen_to_string();
    println!("Select Theme showing bundled theme:\n{}", screen);
    assert!(
        screen.to_lowercase().contains("bundle"),
        "Bundled theme should be available in theme selection. Screen: {}",
        screen
    );

    // Close the theme selection
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // === Test 5: Verify bundle shows up in package manager with installed status ===
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.wait_for_prompt().unwrap();

    harness.type_text("Package: Packages").unwrap();
    harness
        .wait_until(|h| h.screen_to_string().contains("Package: Packages"))
        .unwrap();

    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();

    // Wait for package manager UI to load and show installed bundles
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("INSTALLED") && screen.contains("test-bundle")
        })
        .unwrap();

    let screen = harness.screen_to_string();
    println!("Package manager showing bundle:\n{}", screen);

    assert!(
        screen.contains("test-bundle"),
        "Package manager should show the installed bundle. Screen: {}",
        screen
    );
}

/// Test that uninstalling a plugin removes its commands from the command palette.
/// This verifies that commands registered by a plugin are properly unregistered
/// when the plugin is unloaded, not just showing untranslated keys.
#[test]
#[cfg_attr(windows, ignore)]
fn test_uninstall_plugin_removes_commands() {
    use fresh::config_io::DirectoryContext;
    use tempfile::TempDir;

    init_tracing_from_env();

    let temp_dir = TempDir::new().unwrap();
    let dir_context = DirectoryContext::for_testing(temp_dir.path());

    let repo = GitTestRepo::new();
    repo.setup_typical_project();

    // Setup plugins directory
    let plugins_dir = repo.path.join("plugins");
    fs::create_dir_all(&plugins_dir).unwrap();
    copy_plugin_lib(&plugins_dir);
    copy_plugin(&plugins_dir, "pkg");

    // Create fake registry so syncRegistry doesn't try to hit the network
    let packages_dir = dir_context.config_dir.join("plugins").join("packages");
    fs::create_dir_all(&packages_dir).unwrap();
    let index_dir = packages_dir.join(".index");
    fs::create_dir_all(&index_dir).unwrap();

    // Create a fake registry as a proper git repo so that syncRegistry's
    // `git pull --ff-only` fails fast ("no remote") instead of hanging on
    // a broken .git directory (which can timeout on macOS CI).
    let fake_registry_dir = index_dir.join("193934da");
    fs::create_dir_all(&fake_registry_dir).unwrap();
    fs::write(
        fake_registry_dir.join("plugins.json"),
        r#"{"schema_version": 1, "updated": "2024-01-01", "packages": {}}"#,
    )
    .unwrap();
    fs::write(
        fake_registry_dir.join("themes.json"),
        r#"{"schema_version": 1, "updated": "2024-01-01", "packages": {}}"#,
    )
    .unwrap();
    // Initialize a real git repo (no remote) so `git pull` exits immediately
    std::process::Command::new("git")
        .args(["init"])
        .current_dir(&fake_registry_dir)
        .output()
        .expect("Failed to git init fake registry");
    std::process::Command::new("git")
        .args(["add", "."])
        .current_dir(&fake_registry_dir)
        .output()
        .expect("Failed to git add in fake registry");
    std::process::Command::new("git")
        .args(["commit", "-m", "init"])
        .current_dir(&fake_registry_dir)
        .output()
        .expect("Failed to git commit in fake registry");

    // Create a test plugin that registers a command
    let test_plugin_dir = packages_dir.join("uninstall-test-plugin");
    fs::create_dir_all(&test_plugin_dir).unwrap();

    fs::write(
        test_plugin_dir.join("main.ts"),
        r#"
/// <reference path="../../../plugins/lib/fresh.d.ts" />
const editor = getEditor();
editor.registerCommand("Uninstall Test: Hello", "Test command for uninstall", "uninstall_test_hello", null);
globalThis.uninstall_test_hello = function() { editor.setStatus("Hello from uninstall test!"); };
"#,
    )
    .unwrap();

    fs::write(
        test_plugin_dir.join("package.json"),
        r#"{
    "name": "uninstall-test-plugin",
    "version": "1.0.0",
    "type": "plugin",
    "fresh": { "entry": "main.ts" }
}"#,
    )
    .unwrap();

    let original_dir = repo.change_to_repo_dir();
    let _guard = DirGuard::new(original_dir);

    let mut harness = EditorTestHarness::with_shared_dir_context(
        120,
        30,
        Default::default(),
        repo.path.clone(),
        dir_context,
    )
    .unwrap();

    // Step 1: Open Quick Open
    eprintln!("[TEST] Step 1: Opening Quick Open (Ctrl+P)");
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.wait_for_prompt().unwrap();
    eprintln!(
        "[TEST] Step 1: Prompt opened. Screen:\n{}",
        harness.screen_to_string()
    );

    // Step 2: Type and verify command exists
    eprintln!("[TEST] Step 2: Typing 'Uninstall Test'");
    harness.type_text("Uninstall Test").unwrap();
    harness
        .wait_until(|h| h.screen_to_string().contains("Uninstall Test: Hello"))
        .unwrap();
    eprintln!(
        "[TEST] Step 2: Command found. Screen:\n{}",
        harness.screen_to_string()
    );

    let screen = harness.screen_to_string();
    assert!(
        screen.contains("Uninstall Test: Hello"),
        "Command should be available before uninstall. Screen: {}",
        screen
    );

    // Step 3: Close Quick Open
    eprintln!("[TEST] Step 3: Closing Quick Open (Esc)");
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.wait_for_prompt_closed().unwrap();
    eprintln!(
        "[TEST] Step 3: Prompt closed. Screen:\n{}",
        harness.screen_to_string()
    );

    // Step 4: Open Quick Open again for package manager
    eprintln!("[TEST] Step 4: Opening Quick Open for package manager (Ctrl+P)");
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.wait_for_prompt().unwrap();
    eprintln!(
        "[TEST] Step 4: Prompt opened. Screen:\n{}",
        harness.screen_to_string()
    );

    // Step 5: Type and select Package: Packages
    eprintln!("[TEST] Step 5: Typing 'Package: Packages'");
    harness.type_text("Package: Packages").unwrap();
    harness
        .wait_until(|h| h.screen_to_string().contains("Package: Packages"))
        .unwrap();
    eprintln!(
        "[TEST] Step 5: Package command found. Screen:\n{}",
        harness.screen_to_string()
    );

    eprintln!("[TEST] Step 5b: Pressing Enter to open package manager");
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();

    // Step 6: Wait for package manager UI to finish loading and show the plugin
    eprintln!("[TEST] Step 6: Waiting for package manager to load with plugin visible");
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("*Packages*") && screen.contains("uninstall-test")
        })
        .unwrap();
    eprintln!(
        "[TEST] Step 6: Package manager loaded. Screen:\n{}",
        harness.screen_to_string()
    );

    // Step 7: Wait for the Uninstall button to appear in the detail pane
    eprintln!("[TEST] Step 7: Waiting for Uninstall button");
    harness
        .wait_until(|h| h.screen_to_string().contains("Uninstall"))
        .unwrap();
    eprintln!(
        "[TEST] Step 7: Uninstall button visible. Screen:\n{}",
        harness.screen_to_string()
    );

    // Step 8: Tab to Uninstall button and press Enter
    eprintln!("[TEST] Step 8: Pressing Tab to focus Uninstall button");
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();
    eprintln!(
        "[TEST] Step 8: After Tab. Screen:\n{}",
        harness.screen_to_string()
    );

    eprintln!("[TEST] Step 8b: Pressing Enter to uninstall");
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();
    eprintln!(
        "[TEST] Step 8b: After Enter. Screen:\n{}",
        harness.screen_to_string()
    );

    // Step 9: Wait for uninstall to complete
    eprintln!("[TEST] Step 9: Waiting for uninstall to complete (Removed or plugin gone)");
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("Removed") || !screen.contains("uninstall-test")
        })
        .unwrap();
    eprintln!(
        "[TEST] Step 9: Uninstall complete. Screen:\n{}",
        harness.screen_to_string()
    );

    // Step 10: Close package manager
    eprintln!("[TEST] Step 10: Closing package manager (Esc)");
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness
        .wait_until(|h| !h.screen_to_string().contains("*Packages*"))
        .unwrap();
    eprintln!(
        "[TEST] Step 10: Package manager closed. Screen:\n{}",
        harness.screen_to_string()
    );

    // Step 11: Verify command is gone
    eprintln!("[TEST] Step 11: Opening Quick Open to verify command removal (Ctrl+P)");
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.wait_for_prompt().unwrap();
    eprintln!(
        "[TEST] Step 11: Prompt opened. Screen:\n{}",
        harness.screen_to_string()
    );

    eprintln!("[TEST] Step 11b: Typing 'Uninstall Test'");
    harness.type_text("Uninstall Test").unwrap();
    harness
        .wait_until(|h| h.screen_to_string().contains(">Uninstall Test"))
        .unwrap();
    eprintln!(
        "[TEST] Step 11b: Search results shown. Screen:\n{}",
        harness.screen_to_string()
    );

    let screen = harness.screen_to_string();
    // The command should be gone - it should NOT appear as a suggestion
    assert!(
        !screen.contains("Uninstall Test: Hello") && !screen.contains("uninstall_test_hello"),
        "Command should be removed after uninstall, not show untranslated keys. Screen: {}",
        screen
    );
}