fresh-editor 0.3.12

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
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
//! LSP Manager - manages multiple language servers using async I/O
//!
//! This module provides a manager for multiple LSP servers that:
//! - Spawns one server per language
//! - Uses async LspHandle for non-blocking I/O
//! - Routes requests to appropriate servers
//! - Configured via config.json

use crate::services::async_bridge::AsyncBridge;
use crate::services::lsp::async_handler::LspHandle;
use crate::types::{FeatureFilter, LspFeature, LspServerConfig};
use lsp_types::{SemanticTokensLegend, Uri};
use std::collections::HashMap;
use std::collections::HashSet;
use std::path::Path;
use std::time::{Duration, Instant};

/// Consume and discard a `Result` from a fire-and-forget operation.
///
/// Use for best-effort cleanup where failure is expected and non-actionable,
/// e.g. shutting down an LSP server that may have already exited.
fn fire_and_forget<E: std::fmt::Debug>(result: Result<(), E>) {
    if let Err(e) = result {
        tracing::trace!(error = ?e, "fire-and-forget operation failed");
    }
}

/// Which languages an LSP server handles.
///
/// Empty means the server is universal (accepts all languages).
/// Non-empty lists only the accepted languages.
#[derive(Debug, Clone)]
pub struct LanguageScope(Vec<String>);

impl LanguageScope {
    /// Universal scope — accepts all languages.
    pub fn all() -> Self {
        Self(Vec::new())
    }

    /// Scope for a single language.
    pub fn single(language: impl Into<String>) -> Self {
        Self(vec![language.into()])
    }

    /// Whether this scope accepts documents of the given language.
    pub fn accepts(&self, language: &str) -> bool {
        self.0.is_empty() || self.0.iter().any(|l| l == language)
    }

    /// Whether this is a universal scope (accepts all languages).
    pub fn is_universal(&self) -> bool {
        self.0.is_empty()
    }

    /// The language list. Empty means all.
    pub fn languages(&self) -> &[String] {
        &self.0
    }

    /// A display label for logging and status messages.
    pub fn label(&self) -> &str {
        self.0.first().map(|s| s.as_str()).unwrap_or("universal")
    }
}

/// Result of attempting to spawn an LSP server
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LspSpawnResult {
    /// Server was spawned or already running
    Spawned,
    /// Server is not configured for auto-start
    /// The server can still be started manually via command palette
    NotAutoStart,
    /// No LSP server is configured for this language
    NotConfigured,
    /// Every configured server for this language has `enabled: false`.
    /// This is a deliberate user opt-out, not a failure — callers
    /// should stay silent (or log at debug level) rather than warning.
    Disabled,
    /// Server spawn failed (missing runtime, cooldown, or spawn error).
    Failed,
}

/// Constants for restart behavior
const MAX_RESTARTS_IN_WINDOW: usize = 5;
const RESTART_WINDOW_SECS: u64 = 180; // 3 minutes
const RESTART_BACKOFF_BASE_MS: u64 = 1000; // 1s, 2s, 4s, 8s...

/// Outcome of consulting the spawn gate for a language.
///
/// The gate is the single throttle point for process spawns — every
/// path that ultimately forks an LSP child (user activity via
/// `try_spawn` → `force_spawn`, scheduled restarts via
/// `process_pending_restarts`, crash recovery, manual restarts) goes
/// through it. Previously, only `handle_server_crash` tracked restart
/// attempts, which meant a fast-crashing server respawned on every
/// edit via `force_spawn` and flooded the log (see #1612).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SpawnDecision {
    /// A handle already exists — return the existing one, don't spawn.
    Existing,
    /// Spawn is permitted; the attempt has been recorded.
    Allow,
    /// A restart is already scheduled via exponential backoff — do
    /// not double-spawn. The scheduled restart will fire later.
    PendingBackoff,
    /// The language hit the crash cap and is in cooldown until the
    /// user manually re-enables it.
    CooledDown,
}

/// Convert a directory path to an LSP `file://` URI without the `url` crate.
fn path_to_uri(path: &Path) -> Option<Uri> {
    let abs = if path.is_absolute() {
        path.to_path_buf()
    } else {
        std::env::current_dir().ok()?.join(path)
    };
    // Percent-encode each path component for RFC 3986 compliance
    let encoded: String = abs
        .components()
        .filter_map(|c| match c {
            std::path::Component::RootDir => None, // handled by leading '/' in Normal
            std::path::Component::Normal(s) => {
                let s = s.to_str()?;
                let mut out = String::with_capacity(s.len() + 1);
                out.push('/');
                for b in s.bytes() {
                    if b.is_ascii_alphanumeric()
                        || matches!(
                            b,
                            b'-' | b'.'
                                | b'_'
                                | b'~'
                                | b'@'
                                | b'!'
                                | b'$'
                                | b'&'
                                | b'\''
                                | b'('
                                | b')'
                                | b'+'
                                | b','
                                | b';'
                                | b'='
                        )
                    {
                        out.push(b as char);
                    } else {
                        out.push_str(&format!("%{:02X}", b));
                    }
                }
                Some(out)
            }
            _ => None,
        })
        .collect();
    format!("file://{}", encoded).parse().ok()
}

/// Detect workspace root by walking upward from a file looking for marker files/directories.
///
/// Returns the first directory containing any of the markers, or the file's parent
/// directory if no marker is found.
pub fn detect_workspace_root(file_path: &Path, root_markers: &[String]) -> std::path::PathBuf {
    let file_dir = file_path.parent().unwrap_or(file_path).to_path_buf();

    if root_markers.is_empty() {
        return file_dir;
    }

    let mut dir = Some(file_dir.as_path());
    while let Some(d) = dir {
        for marker in root_markers {
            if d.join(marker).exists() {
                return d.to_path_buf();
            }
        }
        dir = d.parent();
    }

    file_dir
}

/// Summary of capabilities reported by an LSP server during initialization.
///
/// This is extracted from `ServerCapabilities` in the `initialize` response
/// and stored per-server so that requests are only sent to servers that
/// actually support them. Follows the LSP 3.17 specification.
///
#[derive(Debug, Clone, Default)]
pub struct ServerCapabilitySummary {
    /// Whether capabilities have been received from the server.
    /// When false, `has_capability()` defers to the handle's readiness state.
    pub initialized: bool,
    pub hover: bool,
    pub completion: bool,
    pub completion_resolve: bool,
    pub completion_trigger_characters: Vec<String>,
    pub definition: bool,
    pub references: bool,
    pub document_formatting: bool,
    pub document_range_formatting: bool,
    pub rename: bool,
    pub signature_help: bool,
    pub inlay_hints: bool,
    pub folding_ranges: bool,
    pub semantic_tokens_full: bool,
    pub semantic_tokens_full_delta: bool,
    pub semantic_tokens_range: bool,
    pub semantic_tokens_legend: Option<SemanticTokensLegend>,
    pub document_highlight: bool,
    pub code_action: bool,
    pub code_action_resolve: bool,
    pub document_symbols: bool,
    pub workspace_symbols: bool,
    pub diagnostics: bool,
}

impl ServerCapabilitySummary {
    /// Apply a single dynamic capability registration
    /// (`client/registerCapability`) or unregistration
    /// (`client/unregisterCapability`) by toggling the matching capability
    /// flag. `register == false` clears the flag (and any derived state such
    /// as completion trigger characters or the semantic-tokens legend).
    ///
    /// Many servers advertise little or nothing in their `initialize` result
    /// and register providers dynamically afterwards; without this the feature
    /// stays gated off (`has_capability` → false) for the whole session.
    ///
    /// Returns `true` if `method` is one we recognize and gate a feature on,
    /// so the caller knows whether to re-issue requests for already-open
    /// buffers. Unknown methods (e.g. `workspace/didChangeWatchedFiles`, which
    /// is handled separately) return `false`.
    pub fn apply_dynamic_registration(
        &mut self,
        method: &str,
        register_options: Option<&serde_json::Value>,
        register: bool,
    ) -> bool {
        use lsp_types::SemanticTokensFullOptions;

        match method {
            "textDocument/hover" => self.hover = register,
            "textDocument/completion" => {
                self.completion = register;
                if register {
                    if let Some(opts) = register_options {
                        if let Some(chars) =
                            opts.get("triggerCharacters").and_then(|v| v.as_array())
                        {
                            self.completion_trigger_characters = chars
                                .iter()
                                .filter_map(|v| v.as_str().map(str::to_string))
                                .collect();
                        }
                        if let Some(resolve) = opts
                            .get("resolveProvider")
                            .and_then(serde_json::Value::as_bool)
                        {
                            self.completion_resolve = resolve;
                        }
                    }
                } else {
                    self.completion_trigger_characters.clear();
                    self.completion_resolve = false;
                }
            }
            "textDocument/definition" => self.definition = register,
            "textDocument/references" => self.references = register,
            "textDocument/formatting" => self.document_formatting = register,
            "textDocument/rangeFormatting" => self.document_range_formatting = register,
            "textDocument/rename" => self.rename = register,
            "textDocument/signatureHelp" => self.signature_help = register,
            "textDocument/inlayHint" => self.inlay_hints = register,
            "textDocument/foldingRange" => self.folding_ranges = register,
            "textDocument/documentHighlight" => self.document_highlight = register,
            "textDocument/codeAction" => {
                self.code_action = register;
                if register {
                    if let Some(resolve) = register_options
                        .and_then(|opts| opts.get("resolveProvider"))
                        .and_then(serde_json::Value::as_bool)
                    {
                        self.code_action_resolve = resolve;
                    }
                } else {
                    self.code_action_resolve = false;
                }
            }
            "textDocument/documentSymbol" => self.document_symbols = register,
            "workspace/symbol" => self.workspace_symbols = register,
            "textDocument/diagnostic" => self.diagnostics = register,
            "textDocument/semanticTokens" => {
                if register {
                    // Registration options carry the legend and full/range
                    // flags. They are `SemanticTokensRegistrationOptions`, but
                    // its extra fields (documentSelector, id) are ignored by
                    // serde, so parsing the embedded `SemanticTokensOptions`
                    // succeeds.
                    match register_options.and_then(|opts| {
                        serde_json::from_value::<lsp_types::SemanticTokensOptions>(opts.clone())
                            .ok()
                    }) {
                        Some(opts) => {
                            self.semantic_tokens_legend = Some(opts.legend);
                            match opts.full {
                                Some(SemanticTokensFullOptions::Bool(v)) => {
                                    self.semantic_tokens_full = v;
                                    self.semantic_tokens_full_delta = false;
                                }
                                Some(SemanticTokensFullOptions::Delta { delta }) => {
                                    self.semantic_tokens_full = true;
                                    self.semantic_tokens_full_delta = delta.unwrap_or(false);
                                }
                                None => {
                                    self.semantic_tokens_full = false;
                                    self.semantic_tokens_full_delta = false;
                                }
                            }
                            self.semantic_tokens_range = opts.range.unwrap_or(false);
                        }
                        // No parseable options: assume full support so the
                        // feature isn't silently dropped, but a legend is
                        // required to decode tokens, so leave it as-is.
                        None => self.semantic_tokens_full = true,
                    }
                } else {
                    self.semantic_tokens_full = false;
                    self.semantic_tokens_full_delta = false;
                    self.semantic_tokens_range = false;
                    self.semantic_tokens_legend = None;
                }
            }
            _ => return false,
        }
        true
    }
}

/// A named LSP handle with feature filter metadata and per-server capabilities.
/// Wraps an LspHandle with the server's display name, feature routing filter,
/// and the capabilities reported by this specific server during initialization.
pub struct ServerHandle {
    /// Display name for this server (e.g., "rust-analyzer", "eslint")
    pub name: String,
    /// The underlying LSP handle
    pub handle: LspHandle,
    /// Feature filter controlling which LSP features this server handles
    pub feature_filter: FeatureFilter,
    /// Capabilities reported by this server during initialization.
    pub capabilities: ServerCapabilitySummary,
}

impl ServerHandle {
    /// Check if this server has the actual capability for a feature.
    ///
    /// Checks the server's reported capabilities (from the `initialize` response).
    /// Before initialization completes (capabilities not yet received), returns
    /// `false` — the main loop must not route feature requests to servers whose
    /// capabilities are unknown. Callers handle `None` from `handle_for_feature_mut`
    /// by relying on existing retry mechanisms (render-cycle polling, timer retries,
    /// or explicit re-requests from the `LspInitialized` handler).
    pub fn has_capability(&self, feature: LspFeature) -> bool {
        if !self.capabilities.initialized {
            return false;
        }
        match feature {
            LspFeature::Hover => self.capabilities.hover,
            LspFeature::Completion => self.capabilities.completion,
            LspFeature::Definition => self.capabilities.definition,
            LspFeature::References => self.capabilities.references,
            LspFeature::Format => {
                self.capabilities.document_formatting || self.capabilities.document_range_formatting
            }
            LspFeature::Rename => self.capabilities.rename,
            LspFeature::SignatureHelp => self.capabilities.signature_help,
            LspFeature::InlayHints => self.capabilities.inlay_hints,
            LspFeature::FoldingRange => self.capabilities.folding_ranges,
            LspFeature::SemanticTokens => {
                self.capabilities.semantic_tokens_full || self.capabilities.semantic_tokens_range
            }
            LspFeature::DocumentHighlight => self.capabilities.document_highlight,
            LspFeature::CodeAction => self.capabilities.code_action,
            LspFeature::DocumentSymbols => self.capabilities.document_symbols,
            LspFeature::WorkspaceSymbols => self.capabilities.workspace_symbols,
            LspFeature::Diagnostics => self.capabilities.diagnostics,
        }
    }
}

/// Manager for multiple language servers (async version)
pub struct LspManager {
    /// Window that owns this manager. Set at construction time (one
    /// `LspManager` per `Window`). Threaded into every async response
    /// the manager's tasks emit so the editor's dispatcher can route
    /// LSP responses back to the right window's pending-request maps
    /// without a global registry.
    window_id: fresh_core::WindowId,

    /// All running LSP server handles. Each handle's `LanguageScope` determines
    /// which languages it serves. Universal servers have `LanguageScope::all()`.
    handles: Vec<ServerHandle>,

    /// Configuration for each language (supports multiple servers per language)
    config: HashMap<String, Vec<LspServerConfig>>,

    /// Universal (global) LSP server configs — spawned once per project.
    universal_configs: Vec<LspServerConfig>,

    /// Default root URI for workspace (used if no per-language root is set)
    root_uri: Option<Uri>,

    /// Per-language root URIs (allows plugins to specify project roots)
    per_language_root_uris: HashMap<String, Uri>,

    /// Tokio runtime reference
    runtime: Option<tokio::runtime::Handle>,

    /// Async bridge for communication
    async_bridge: Option<AsyncBridge>,

    /// Long-running stdio spawner from the active authority. Used by
    /// `force_spawn` and friends to route LSP child processes through
    /// the right backend (local Command, `docker exec -i`, SSH). Set
    /// by `set_long_running_spawner` from `Editor::set_boot_authority`
    /// before any LSP spawn can happen.
    long_running_spawner: Option<std::sync::Arc<dyn crate::services::remote::LongRunningSpawner>>,

    /// Active authority's Workspace Trust handle. LSP servers load and execute
    /// project-controlled code at startup (analyzers/source-generators for C#,
    /// `build.rs`/proc-macros for Rust, `compile_commands` for clangd, …), so
    /// auto-start is gated on this: an untrusted workspace doesn't auto-start
    /// servers. `None` (tests / not yet wired) means "allow".
    workspace_trust: Option<std::sync::Arc<crate::services::workspace_trust::WorkspaceTrust>>,

    /// Active authority's host↔remote workspace mapping. When set
    /// (devcontainer attach), [`Self::resolve_root_uri`] applies it to
    /// the marker-walked workspace root so an in-container LSP sees
    /// `file:///workspaces/proj` rather than the on-host temp path.
    path_translation: Option<crate::services::authority::PathTranslation>,

    /// Restart attempt timestamps per language (for tracking restart frequency)
    restart_attempts: HashMap<String, Vec<Instant>>,

    /// Languages currently in restart cooldown (gave up after too many restarts)
    restart_cooldown: HashSet<String>,

    /// Scheduled restart times (language -> when to restart)
    pending_restarts: HashMap<String, Instant>,

    /// Languages that have been manually started by the user
    /// If a language is in this set, it will spawn even if auto_start=false in config
    allowed_languages: HashSet<String>,

    /// Languages that have been explicitly disabled/stopped by the user
    /// These will not auto-restart until user manually restarts them
    disabled_languages: HashSet<String>,
}

impl LspManager {
    /// Window that owns this manager.
    pub fn window_id(&self) -> fresh_core::WindowId {
        self.window_id
    }

    /// Create a new LSP manager owned by the given window.
    pub fn new(window_id: fresh_core::WindowId, root_uri: Option<Uri>) -> Self {
        Self {
            window_id,
            handles: Vec::new(),
            config: HashMap::new(),
            universal_configs: Vec::new(),
            root_uri,
            per_language_root_uris: HashMap::new(),
            runtime: None,
            async_bridge: None,
            long_running_spawner: None,
            workspace_trust: None,
            path_translation: None,
            restart_attempts: HashMap::new(),
            restart_cooldown: HashSet::new(),
            pending_restarts: HashMap::new(),
            allowed_languages: HashSet::new(),
            disabled_languages: HashSet::new(),
        }
    }

    /// Wire the long-running spawner from the active `Authority`.
    ///
    /// Called from `Editor::set_boot_authority` so every LSP server
    /// spawned after this point runs under the right backend — local
    /// host, `docker exec -i` for containers, or SSH-tunneled.
    /// Authority transitions destroy and rebuild the editor (and
    /// therefore `LspManager`), so this is a one-shot wiring call per
    /// editor instance.
    pub fn set_long_running_spawner(
        &mut self,
        spawner: std::sync::Arc<dyn crate::services::remote::LongRunningSpawner>,
    ) {
        self.long_running_spawner = Some(spawner);
    }

    /// Install the active authority's Workspace Trust handle. Called from
    /// `set_boot_authority` alongside the spawner setter so trust gating is in
    /// place before any LSP auto-start.
    pub fn set_workspace_trust(
        &mut self,
        trust: std::sync::Arc<crate::services::workspace_trust::WorkspaceTrust>,
    ) {
        self.workspace_trust = Some(trust);
    }

    /// Whether LSP servers may auto-start: only in a Trusted workspace (or
    /// when trust isn't wired, e.g. tests). Untrusted workspaces don't
    /// auto-start servers because starting one runs project-controlled code.
    fn lsp_autostart_allowed(&self) -> bool {
        use crate::services::workspace_trust::TrustLevel;
        self.workspace_trust
            .as_ref()
            .map(|t| t.level() == TrustLevel::Trusted)
            .unwrap_or(true)
    }

    /// Install the active authority's host↔remote path mapping. The
    /// editor calls this from `set_boot_authority` alongside the
    /// spawner setter so URI translation is in place before any LSP
    /// spawns under the new authority.
    pub fn set_path_translation(
        &mut self,
        translation: Option<crate::services::authority::PathTranslation>,
    ) {
        self.path_translation = translation;
    }

    /// Blocking variant of the authority-routed command probe used by
    /// the LSP status popup (which runs on the main thread and needs a
    /// synchronous answer). Blocks on the tokio runtime to drive the
    /// async trait method; the local spawner resolves immediately via
    /// `which::which`, the docker spawner runs a short
    /// `docker exec <id> sh -c 'command -v <cmd>'`.
    ///
    /// Falls back to the module-level host probe when the spawner or
    /// runtime hasn't been wired yet (e.g. during early editor boot
    /// before `set_boot_authority` runs). The fallback is only
    /// reachable in test harnesses and a vanishingly small window
    /// around startup, so routing through the authority is the
    /// effective behavior in production.
    pub fn command_exists_via_authority(&self, command: &str) -> bool {
        if command.is_empty() {
            return false;
        }
        let (Some(runtime), Some(spawner)) =
            (self.runtime.as_ref(), self.long_running_spawner.as_ref())
        else {
            return crate::services::lsp::command_exists(command);
        };
        runtime.block_on(spawner.command_exists(command))
    }

    /// Check if a language has been manually enabled (allowing spawn even if auto_start=false)
    pub fn is_language_allowed(&self, language: &str) -> bool {
        self.allowed_languages.contains(language)
    }

    /// Allow a language to spawn LSP server (used by manual start command)
    pub fn allow_language(&mut self, language: &str) {
        self.allowed_languages.insert(language.to_string());
        tracing::info!("LSP language '{}' manually enabled", language);
    }

    /// Get the set of manually enabled languages
    pub fn allowed_languages(&self) -> &HashSet<String> {
        &self.allowed_languages
    }

    /// Get the configurations for a specific language (one or more servers).
    pub fn get_configs(&self, language: &str) -> Option<&[LspServerConfig]> {
        self.config.get(language).map(|v| v.as_slice())
    }

    /// Get the primary (first) configuration for a specific language.
    pub fn get_config(&self, language: &str) -> Option<&LspServerConfig> {
        self.config.get(language).and_then(|v| v.first())
    }

    /// Store capabilities on the specific server handle identified by server_name.
    pub fn set_server_capabilities(
        &mut self,
        _language: &str,
        server_name: &str,
        mut capabilities: ServerCapabilitySummary,
    ) {
        capabilities.initialized = true;

        if let Some(sh) = self.handles.iter_mut().find(|sh| sh.name == server_name) {
            sh.capabilities = capabilities;
        }
    }

    /// Apply dynamic capability (un)registrations to the named server's stored
    /// capabilities. Each entry is `(method, register_options)`. Returns `true`
    /// if any recognized feature flag changed, so the caller can re-issue
    /// requests for buffers that opened before the registration arrived.
    ///
    /// Per the LSP spec a server only sends `client/registerCapability` after
    /// it has received our `initialized` notification — i.e. after the
    /// `initialize` result was processed and `set_server_capabilities` ran — so
    /// these merge on top of the static summary rather than racing it.
    pub fn apply_dynamic_capabilities(
        &mut self,
        server_name: &str,
        register: bool,
        registrations: &[(String, Option<serde_json::Value>)],
    ) -> bool {
        let Some(sh) = self.handles.iter_mut().find(|sh| sh.name == server_name) else {
            return false;
        };
        let mut changed = false;
        for (method, options) in registrations {
            if sh
                .capabilities
                .apply_dynamic_registration(method, options.as_ref(), register)
            {
                changed = true;
            }
        }
        changed
    }

    /// Get the semantic token legend for a language from the first eligible server.
    pub fn semantic_tokens_legend(&self, language: &str) -> Option<&SemanticTokensLegend> {
        self.get_handles(language).into_iter().find_map(|sh| {
            if sh.feature_filter.allows(LspFeature::SemanticTokens)
                && sh.has_capability(LspFeature::SemanticTokens)
            {
                sh.capabilities.semantic_tokens_legend.as_ref()
            } else {
                None
            }
        })
    }

    /// Check if any eligible server for the language supports full semantic tokens.
    pub fn semantic_tokens_full_supported(&self, language: &str) -> bool {
        self.get_handles(language).iter().any(|sh| {
            sh.feature_filter.allows(LspFeature::SemanticTokens)
                && sh.capabilities.semantic_tokens_full
        })
    }

    /// Check if any eligible server for the language supports full semantic token deltas.
    pub fn semantic_tokens_full_delta_supported(&self, language: &str) -> bool {
        self.get_handles(language).iter().any(|sh| {
            sh.feature_filter.allows(LspFeature::SemanticTokens)
                && sh.capabilities.semantic_tokens_full_delta
        })
    }

    /// Check if any eligible server for the language supports range semantic tokens.
    pub fn semantic_tokens_range_supported(&self, language: &str) -> bool {
        self.get_handles(language).iter().any(|sh| {
            sh.feature_filter.allows(LspFeature::SemanticTokens)
                && sh.capabilities.semantic_tokens_range
        })
    }

    /// Check if any eligible server for the language supports folding ranges.
    pub fn folding_ranges_supported(&self, language: &str) -> bool {
        self.get_handles(language).iter().any(|sh| {
            sh.feature_filter.allows(LspFeature::FoldingRange) && sh.capabilities.folding_ranges
        })
    }

    /// Check if a character is a completion trigger for any running language server.
    pub fn is_completion_trigger_char(&self, ch: char, language: &str) -> bool {
        let ch_str = ch.to_string();
        self.get_handles(language).iter().any(|sh| {
            sh.feature_filter.allows(LspFeature::Completion)
                && sh
                    .capabilities
                    .completion_trigger_characters
                    .contains(&ch_str)
        })
    }

    /// Try to spawn an LSP server, checking auto_start configuration
    ///
    /// This is the main entry point for spawning LSP servers on file open.
    /// It returns:
    /// - `LspSpawnResult::Spawned` if the server was spawned or already running
    /// - `LspSpawnResult::NotAutoStart` if auto_start is false and not manually allowed
    /// - `LspSpawnResult::NotConfigured` if no LSP server is configured for the language
    /// - `LspSpawnResult::Disabled` if every configured server has `enabled: false`
    /// - `LspSpawnResult::Failed` if spawn failed (missing runtime, cooldown, etc.)
    ///
    /// The `file_path` is used for workspace root detection via `root_markers`.
    ///
    /// IMPORTANT: Callers should only call this when there is at least one buffer
    /// with a matching language. Do not call for languages with no open files.
    pub fn try_spawn(&mut self, language: &str, file_path: Option<&Path>) -> LspSpawnResult {
        // If handles already exist for this language, just ensure universals are running too
        if self
            .handles
            .iter()
            .any(|sh| sh.handle.scope().accepts(language))
        {
            self.ensure_universal_servers_running(file_path);
            return LspSpawnResult::Spawned;
        }

        // Check if we have runtime and bridge
        if self.runtime.is_none() || self.async_bridge.is_none() {
            return LspSpawnResult::Failed;
        }

        // Workspace Trust gate: starting an LSP server loads/executes
        // project-controlled code (C# analyzers, Rust build scripts/proc-macros,
        // clangd's compile_commands, …). In an untrusted workspace, don't
        // auto-start — unless the user has explicitly enabled this language
        // (manual start is an explicit, informed action). The trust prompt on
        // open lets the user enable everything by trusting the folder.
        if !self.lsp_autostart_allowed() && !self.allowed_languages.contains(language) {
            tracing::info!(
                "LSP for '{}' not auto-started: workspace is not trusted \
                 (trust the folder to enable language servers)",
                language
            );
            return LspSpawnResult::NotAutoStart;
        }

        // Always try to start universal servers (they manage their own auto_start check)
        self.ensure_universal_servers_running(file_path);

        // Check if language is configured
        let configs = match self.config.get(language) {
            Some(configs) if !configs.is_empty() => configs,
            _ => {
                // No per-language config, but universal servers may be running
                if self
                    .handles
                    .iter()
                    .any(|sh| sh.handle.scope().is_universal())
                {
                    return LspSpawnResult::Spawned;
                }
                return LspSpawnResult::NotConfigured;
            }
        };

        // Check if any per-language config is enabled
        if !configs.iter().any(|c| c.enabled) {
            if self
                .handles
                .iter()
                .any(|sh| sh.handle.scope().is_universal())
            {
                return LspSpawnResult::Spawned;
            }
            return LspSpawnResult::Disabled;
        }

        // Check if auto_start is enabled (on any per-language config) or language was manually allowed
        let any_auto_start = configs.iter().any(|c| c.auto_start && c.enabled);
        if !any_auto_start && !self.allowed_languages.contains(language) {
            if self
                .handles
                .iter()
                .any(|sh| sh.handle.scope().is_universal())
            {
                return LspSpawnResult::Spawned;
            }
            return LspSpawnResult::NotAutoStart;
        }

        // Spawn per-language servers
        let spawned = self.force_spawn(language, file_path).is_some();

        if spawned
            || self
                .handles
                .iter()
                .any(|sh| sh.handle.scope().is_universal())
        {
            LspSpawnResult::Spawned
        } else {
            LspSpawnResult::Failed
        }
    }

    /// Set the Tokio runtime and async bridge
    ///
    /// Must be called before spawning any servers
    pub fn set_runtime(&mut self, runtime: tokio::runtime::Handle, async_bridge: AsyncBridge) {
        self.runtime = Some(runtime);
        self.async_bridge = Some(async_bridge);
    }

    /// Set configuration for a language (single server).
    pub fn set_language_config(&mut self, language: String, config: LspServerConfig) {
        self.config.insert(language, vec![config]);
    }

    /// Set configurations for a language (one or more servers).
    pub fn set_language_configs(&mut self, language: String, configs: Vec<LspServerConfig>) {
        self.config.insert(language, configs);
    }

    /// Append additional server configs to an existing language entry.
    pub fn append_language_configs(&mut self, language: String, configs: Vec<LspServerConfig>) {
        self.config.entry(language).or_default().extend(configs);
    }

    /// Set universal (global) LSP server configs.
    ///
    /// Universal servers are spawned once per project and shared across all
    /// languages, rather than being duplicated into each language's config list.
    pub fn set_universal_configs(&mut self, configs: Vec<LspServerConfig>) {
        self.universal_configs = configs;
    }

    /// Return the list of currently configured language keys.
    pub fn configured_languages(&self) -> Vec<String> {
        self.config.keys().cloned().collect()
    }

    /// Set a new root URI for the workspace
    ///
    /// This should be called after shutting down all servers when switching projects.
    /// Servers spawned after this will use the new root URI.
    pub fn set_root_uri(&mut self, root_uri: Option<Uri>) {
        self.root_uri = root_uri;
    }

    /// Set a language-specific root URI
    ///
    /// This allows plugins to specify project roots for specific languages.
    /// For example, a C# plugin can set the root to the directory containing .csproj.
    /// Returns true if an existing server was restarted with the new root.
    pub fn set_language_root_uri(&mut self, language: &str, uri: Uri) -> bool {
        tracing::info!("Setting root URI for {}: {}", language, uri.as_str());
        self.per_language_root_uris
            .insert(language.to_string(), uri.clone());

        // If there's an existing server for this language, restart it with the new root
        if self
            .handles
            .iter()
            .any(|sh| sh.handle.scope().accepts(language))
        {
            tracing::info!(
                "Restarting {} LSP server with new root: {}",
                language,
                uri.as_str()
            );
            self.shutdown_server(language);
            // The server will be respawned on next request with the new root
            return true;
        }
        false
    }

    /// Resolve the root URI for a language, using root_markers for detection.
    ///
    /// Priority:
    /// 1. Plugin-set per-language root (per_language_root_uris)
    /// 2. Walk upward from file_path using config's root_markers
    /// 3. File's parent directory
    pub fn resolve_root_uri(&self, language: &str, file_path: Option<&Path>) -> Option<Uri> {
        // 1. Plugin-set root takes priority
        if let Some(uri) = self.per_language_root_uris.get(language) {
            return Some(uri.clone());
        }

        // 2. Use root_markers to detect workspace root from file path.
        //    Walks the host filesystem; on a container authority that
        //    yields a host path, which would confuse an in-container
        //    LSP. Translate before encoding to a URI.
        if let Some(path) = file_path {
            let markers = self
                .config
                .get(language)
                .and_then(|configs| configs.first())
                .map(|c| c.root_markers.as_slice())
                .unwrap_or(&[]);
            let root = detect_workspace_root(path, markers);
            let mapped = self
                .path_translation
                .as_ref()
                .and_then(|t| t.host_to_remote(&root))
                .unwrap_or(root);
            if let Some(uri) = path_to_uri(&mapped) {
                return Some(uri);
            }
        }

        // 3. No file path available — use the global root_uri
        self.root_uri.clone()
    }

    /// Get the effective root URI for a language (legacy, without file-based detection)
    ///
    /// Returns the language-specific root if set, otherwise the default root.
    pub fn get_effective_root_uri(&self, language: &str) -> Option<Uri> {
        self.resolve_root_uri(language, None)
    }

    /// Reset the manager for a new project
    ///
    /// This shuts down all servers and clears state, preparing for a fresh start.
    /// The configuration is preserved but servers will need to be respawned.
    pub fn reset_for_new_project(&mut self, new_root_uri: Option<Uri>) {
        // Shutdown all servers
        self.shutdown_all();

        // Update root URI
        self.root_uri = new_root_uri;

        // Clear restart tracking state (fresh start)
        self.restart_attempts.clear();
        self.restart_cooldown.clear();
        self.pending_restarts.clear();

        // Keep allowed_languages and disabled_languages as user preferences
        // Keep config as it's not project-specific

        tracing::info!(
            "LSP manager reset for new project: {:?}",
            self.root_uri.as_ref().map(|u| u.as_str())
        );
    }

    /// Get the primary (first) existing LSP handle for a language (no spawning).
    /// Checks language-specific handles first, then universal handles.
    pub fn get_handle(&self, language: &str) -> Option<&LspHandle> {
        self.handles
            .iter()
            .find(|sh| sh.handle.scope().accepts(language))
            .map(|sh| &sh.handle)
    }

    /// Get the primary (first) mutable existing LSP handle for a language (no spawning).
    /// Checks language-specific handles first, then universal handles.
    pub fn get_handle_mut(&mut self, language: &str) -> Option<&mut LspHandle> {
        self.handles
            .iter_mut()
            .find(|sh| sh.handle.scope().accepts(language))
            .map(|sh| &mut sh.handle)
    }

    /// Get all handles that accept a language (both language-specific and universal).
    pub fn get_handles(&self, language: &str) -> Vec<&ServerHandle> {
        self.handles
            .iter()
            .filter(|sh| sh.handle.scope().accepts(language))
            .collect()
    }

    /// Get all mutable handles that accept a language (both language-specific and universal).
    pub fn get_handles_mut(&mut self, language: &str) -> Vec<&mut ServerHandle> {
        self.handles
            .iter_mut()
            .filter(|sh| sh.handle.scope().accepts(language))
            .collect()
    }

    /// Get the language scope for a server by name.
    ///
    /// Returns `None` if the server is not found.
    pub fn server_scope(&self, server_name: &str) -> Option<&LanguageScope> {
        self.handles
            .iter()
            .find(|sh| sh.name == server_name)
            .map(|sh| sh.handle.scope())
    }

    /// Check if any handles (language-specific or universal) exist for a language.
    pub fn has_handles(&self, language: &str) -> bool {
        self.handles
            .iter()
            .any(|sh| sh.handle.scope().accepts(language))
    }

    /// Count all handles that accept a language.
    pub fn handle_count(&self, language: &str) -> usize {
        self.handles
            .iter()
            .filter(|sh| sh.handle.scope().accepts(language))
            .count()
    }

    /// Check if a server with the given name exists.
    pub fn has_server_named(&self, server_name: &str) -> bool {
        self.handles.iter().any(|sh| sh.name == server_name)
    }

    /// Get the first handle for a language that allows a given feature (for exclusive features).
    /// For capability-gated features (semantic tokens, folding ranges), this also checks
    /// that the server actually reported the capability during initialization.
    /// Checks per-language handles first, then universal handles.
    /// Returns `None` if no handle matches.
    pub fn handle_for_feature(&self, language: &str, feature: LspFeature) -> Option<&ServerHandle> {
        self.handles
            .iter()
            .filter(|sh| sh.handle.scope().accepts(language))
            .find(|sh| sh.feature_filter.allows(feature) && sh.has_capability(feature))
    }

    /// Get the first mutable handle for a language that allows a given feature.
    /// For capability-gated features, this also checks the server's actual capabilities.
    /// Checks per-language handles first, then universal handles.
    pub fn handle_for_feature_mut(
        &mut self,
        language: &str,
        feature: LspFeature,
    ) -> Option<&mut ServerHandle> {
        self.handles
            .iter_mut()
            .filter(|sh| sh.handle.scope().accepts(language))
            .find(|sh| sh.feature_filter.allows(feature) && sh.has_capability(feature))
    }

    /// Get all handles for a language that allow a given feature (for merged features).
    /// Like `handle_for_feature`, also checks per-server capabilities.
    /// Includes both per-language and universal handles.
    pub fn handles_for_feature(&self, language: &str, feature: LspFeature) -> Vec<&ServerHandle> {
        self.handles
            .iter()
            .filter(|sh| sh.handle.scope().accepts(language))
            .filter(|sh| sh.feature_filter.allows(feature) && sh.has_capability(feature))
            .collect()
    }

    /// Get all mutable handles for a language that allow a given feature.
    /// Like `handle_for_feature_mut`, also checks per-server capabilities.
    /// Includes both per-language and universal handles.
    pub fn handles_for_feature_mut(
        &mut self,
        language: &str,
        feature: LspFeature,
    ) -> Vec<&mut ServerHandle> {
        self.handles
            .iter_mut()
            .filter(|sh| sh.handle.scope().accepts(language))
            .filter(|sh| sh.feature_filter.allows(feature) && sh.has_capability(feature))
            .collect()
    }

    /// Consult the spawn throttle for `language` and, on `Allow`, record
    /// the attempt.
    ///
    /// This is the single source of truth for "are we allowed to spawn
    /// another LSP child right now?" — every path that actually spawns
    /// must call it.  The caller should propagate the decision (return
    /// None / refuse to spawn) on anything other than `Allow`.
    fn spawn_decision(&mut self, language: &str) -> SpawnDecision {
        if self
            .handles
            .iter()
            .any(|sh| sh.handle.scope().accepts(language))
        {
            return SpawnDecision::Existing;
        }
        if self.restart_cooldown.contains(language) {
            return SpawnDecision::CooledDown;
        }
        if self.pending_restarts.contains_key(language) {
            return SpawnDecision::PendingBackoff;
        }

        let now = Instant::now();
        let window = Duration::from_secs(RESTART_WINDOW_SECS);
        let attempts = self
            .restart_attempts
            .entry(language.to_string())
            .or_default();
        attempts.retain(|t| now.duration_since(*t) < window);

        if attempts.len() >= MAX_RESTARTS_IN_WINDOW {
            self.restart_cooldown.insert(language.to_string());
            tracing::warn!(
                "LSP server for {} has spawned {} times in {} minutes, entering cooldown",
                language,
                MAX_RESTARTS_IN_WINDOW,
                RESTART_WINDOW_SECS / 60
            );
            return SpawnDecision::CooledDown;
        }

        attempts.push(now);
        SpawnDecision::Allow
    }

    /// Force spawn LSP server(s) for a language.
    ///
    /// Spawns servers configured for the language, filtered as follows:
    /// - If the language is in `allowed_languages` (the user explicitly
    ///   started or approved this language via a manual command), spawns
    ///   every configured server regardless of its `enabled` / `auto_start`
    ///   flags. This is the "manual" path used by the command palette's
    ///   Start / Restart LSP commands and the LSP confirmation popup.
    /// - Otherwise (the auto-start path, reached via `try_spawn` on buffer
    ///   load or by crash recovery), spawns only servers that have both
    ///   `enabled=true` AND `auto_start=true`. Each config's own
    ///   `auto_start` flag is honoured individually, so configuring one
    ///   auto-start server alongside an opt-in manual server no longer
    ///   drags the manual one along for the ride.
    ///
    /// Returns a mutable reference to the primary (first) handle if any
    /// were spawned. The `file_path` is used for workspace root detection
    /// via `root_markers`.
    pub fn force_spawn(
        &mut self,
        language: &str,
        file_path: Option<&Path>,
    ) -> Option<&mut LspHandle> {
        tracing::debug!("force_spawn called for language: {}", language);

        // Return existing handle if available
        if self
            .handles
            .iter()
            .any(|sh| sh.handle.scope().accepts(language))
        {
            tracing::debug!("force_spawn: returning existing handle for {}", language);
            return self
                .handles
                .iter_mut()
                .find(|sh| sh.handle.scope().accepts(language))
                .map(|sh| &mut sh.handle);
        }

        // Check if language was explicitly disabled by user (via stop command)
        if self.disabled_languages.contains(language) {
            tracing::debug!(
                "LSP for {} is disabled, not spawning (use manual restart to re-enable)",
                language
            );
            return None;
        }

        // Get configs for this language
        let configs = match self.config.get(language) {
            Some(configs) if !configs.is_empty() => configs.clone(),
            _ => {
                tracing::warn!(
                    "force_spawn: no config found for language '{}', available configs: {:?}",
                    language,
                    self.config.keys().collect::<Vec<_>>()
                );
                return None;
            }
        };

        // Consult the spawn gate. This is the single point that enforces
        // the restart throttle across *all* spawn entry points — user
        // activity (try_spawn), scheduled backoff, manual restart. See
        // #1612: previously only handle_server_crash tracked attempts,
        // so a fast-crashing server got respawned on every edit.
        match self.spawn_decision(language) {
            SpawnDecision::Existing => {
                // Existing-handle case is already short-circuited above,
                // but handle it defensively.
                return self
                    .handles
                    .iter_mut()
                    .find(|sh| sh.handle.scope().accepts(language))
                    .map(|sh| &mut sh.handle);
            }
            SpawnDecision::CooledDown => {
                tracing::debug!(
                    "force_spawn: {} is in cooldown, refusing spawn (use Restart LSP command)",
                    language
                );
                return None;
            }
            SpawnDecision::PendingBackoff => {
                tracing::debug!(
                    "force_spawn: {} has a pending restart scheduled, not double-spawning",
                    language
                );
                return None;
            }
            SpawnDecision::Allow => {}
        }

        // Check we have runtime, bridge, and the authority's spawner.
        // All three are wired at editor construction; a missing one is
        // a configuration error worth surfacing rather than silently
        // degrading to a host-only spawn.
        let runtime = match self.runtime.as_ref() {
            Some(r) => r.clone(),
            None => {
                tracing::error!("force_spawn: no tokio runtime available for {}", language);
                return None;
            }
        };
        let async_bridge = match self.async_bridge.as_ref() {
            Some(b) => b.clone(),
            None => {
                tracing::error!("force_spawn: no async bridge available for {}", language);
                return None;
            }
        };
        // Default to the local spawner when nothing's been wired. The
        // editor's `set_boot_authority` wires this as part of normal
        // construction; tests and other call sites that construct an
        // LspManager directly without going through Editor get the
        // pre-Phase-L behavior (host-only spawn) automatically. Passing
        // through the warning keeps the failure loud enough to catch
        // regressions in Editor-side wiring.
        let long_running_spawner = match self.long_running_spawner.as_ref() {
            Some(s) => s.clone(),
            None => {
                tracing::warn!(
                    "force_spawn: long-running spawner not wired for {} — \
                     falling back to host-local spawn (normal for tests \
                     that skip set_boot_authority)",
                    language
                );
                std::sync::Arc::new(crate::services::remote::LocalLongRunningSpawner::new(
                    std::sync::Arc::new(crate::services::env_provider::EnvProvider::inactive()),
                    std::sync::Arc::new(
                        crate::services::workspace_trust::WorkspaceTrust::permissive(),
                    ),
                ))
            }
        };

        let mut spawned_handles = Vec::new();
        let manually_allowed = self.allowed_languages.contains(language);

        for config in &configs {
            if manually_allowed {
                // User explicitly started this language via command palette:
                // spawn every configured server, even if individually
                // disabled or marked not-auto-start.
            } else {
                // Auto-start path: only spawn servers that the user has
                // opted into both via `enabled=true` AND `auto_start=true`.
                // This honours each config's flags independently so that
                // e.g. configuring rust-auto (auto_start=true) alongside
                // rust-manual (auto_start=false) does not spawn both.
                if !config.enabled || !config.auto_start {
                    continue;
                }
            }

            if config.command.is_empty() {
                tracing::warn!(
                    "force_spawn: LSP command is empty for {} server '{}'",
                    language,
                    config.display_name()
                );
                continue;
            }

            let server_name = config.display_name();
            tracing::info!(
                "Spawning LSP server '{}' for language: {}",
                server_name,
                language
            );

            match LspHandle::spawn(
                &runtime,
                &config.command,
                &config.args,
                config.env.clone(),
                LanguageScope::single(language),
                server_name.clone(),
                &async_bridge,
                config.process_limits.clone(),
                config.language_id_overrides.clone(),
                long_running_spawner.clone(),
            ) {
                Ok(handle) => {
                    let effective_root = self.resolve_root_uri(language, file_path);
                    if let Err(e) =
                        handle.initialize(effective_root, config.initialization_options.clone())
                    {
                        tracing::error!(
                            "Failed to send initialize command for {} ({}): {}",
                            language,
                            server_name,
                            e
                        );
                        continue;
                    }

                    tracing::info!(
                        "LSP initialization started for {} ({}), will be ready asynchronously",
                        language,
                        server_name
                    );

                    spawned_handles.push(ServerHandle {
                        name: server_name,
                        handle,
                        feature_filter: config.feature_filter(),
                        capabilities: ServerCapabilitySummary::default(),
                    });
                }
                Err(e) => {
                    tracing::error!(
                        "Failed to spawn LSP handle for {} ({}): {}",
                        language,
                        server_name,
                        e
                    );
                }
            }
        }

        if spawned_handles.is_empty() {
            return None;
        }

        self.handles.extend(spawned_handles);
        self.handles
            .iter_mut()
            .rev()
            .find(|sh| sh.handle.scope().accepts(language))
            .map(|sh| &mut sh.handle)
    }

    /// Spawn universal LSP servers if they aren't already running.
    ///
    /// Called from `try_spawn` — universal servers are spawned once and shared
    /// across all languages. Only servers with `enabled=true` and
    /// `auto_start=true` are started automatically.
    fn ensure_universal_servers_running(&mut self, file_path: Option<&Path>) {
        if self
            .handles
            .iter()
            .any(|sh| sh.handle.scope().is_universal())
            || self.universal_configs.is_empty()
        {
            return;
        }

        let runtime = match self.runtime.as_ref() {
            Some(r) => r.clone(),
            None => return,
        };
        let async_bridge = match self.async_bridge.as_ref() {
            Some(b) => b.clone(),
            None => return,
        };
        let long_running_spawner =
            self.long_running_spawner
                .as_ref()
                .cloned()
                .unwrap_or_else(|| {
                    std::sync::Arc::new(crate::services::remote::LocalLongRunningSpawner::new(
                        std::sync::Arc::new(crate::services::env_provider::EnvProvider::inactive()),
                        std::sync::Arc::new(
                            crate::services::workspace_trust::WorkspaceTrust::permissive(),
                        ),
                    ))
                });

        let mut spawned = Vec::new();
        for config in &self.universal_configs {
            if !config.enabled || !config.auto_start {
                continue;
            }
            if config.command.is_empty() {
                continue;
            }

            let server_name = config.display_name();
            tracing::info!("Spawning universal LSP server '{}'", server_name);

            match LspHandle::spawn(
                &runtime,
                &config.command,
                &config.args,
                config.env.clone(),
                LanguageScope::all(),
                server_name.clone(),
                &async_bridge,
                config.process_limits.clone(),
                config.language_id_overrides.clone(),
                long_running_spawner.clone(),
            ) {
                Ok(handle) => {
                    let effective_root = file_path
                        .and_then(|p| {
                            let root = detect_workspace_root(p, &config.root_markers);
                            path_to_uri(&root)
                        })
                        .or_else(|| self.root_uri.clone());
                    if let Err(e) =
                        handle.initialize(effective_root, config.initialization_options.clone())
                    {
                        tracing::error!(
                            "Failed to initialize universal LSP server '{}': {}",
                            server_name,
                            e
                        );
                        continue;
                    }
                    tracing::info!(
                        "Universal LSP server '{}' initialization started",
                        server_name
                    );
                    spawned.push(ServerHandle {
                        name: server_name,
                        handle,
                        feature_filter: config.feature_filter(),
                        capabilities: ServerCapabilitySummary::default(),
                    });
                }
                Err(e) => {
                    tracing::error!(
                        "Failed to spawn universal LSP server '{}': {}",
                        server_name,
                        e
                    );
                }
            }
        }

        self.handles.extend(spawned);
    }

    /// Handle a server crash by scheduling a restart with exponential backoff
    ///
    /// Returns a message describing the action taken (for UI notification)
    pub fn handle_server_crash(&mut self, language: &str, server_name: &str) -> String {
        // Check if the crashed server is a universal handle
        if self
            .handles
            .iter()
            .any(|sh| sh.name == server_name && sh.handle.scope().is_universal())
        {
            // Drain all universal handles and shut them down
            let universals: Vec<ServerHandle> = {
                let mut drained = Vec::new();
                let mut i = 0;
                while i < self.handles.len() {
                    if self.handles[i].handle.scope().is_universal() {
                        drained.push(self.handles.remove(i));
                    } else {
                        i += 1;
                    }
                }
                drained
            };
            for sh in universals {
                fire_and_forget(sh.handle.shutdown());
            }
            // Universal servers will be re-spawned on next try_spawn call
            return "Universal LSP server crashed. It will restart on next file open.".to_string();
        }

        // Remove all handles that accept this language (but not universal ones)
        {
            let mut i = 0;
            while i < self.handles.len() {
                if !self.handles[i].handle.scope().is_universal()
                    && self.handles[i].handle.scope().accepts(language)
                {
                    let sh = self.handles.remove(i);
                    fire_and_forget(sh.handle.shutdown());
                } else {
                    i += 1;
                }
            }
        }

        // Check if server was explicitly disabled by user (via stop command)
        // Don't auto-restart disabled servers
        if self.disabled_languages.contains(language) {
            return format!(
                "LSP server for {} stopped. Use 'Restart LSP Server' command to start it again.",
                language
            );
        }

        // Check if we're in cooldown
        if self.restart_cooldown.contains(language) {
            return format!(
                "LSP server for {} crashed. Too many restarts - use 'Restart LSP Server' command to retry.",
                language
            );
        }

        // Attempt-counting and the cap are owned by `spawn_decision`
        // (called at every real spawn site). Here we only schedule the
        // next restart with exponential backoff; the gate will decide
        // whether it actually proceeds when the pending restart fires.
        let now = Instant::now();
        let attempt_number = self
            .restart_attempts
            .get(language)
            .map(|v| v.len())
            .unwrap_or(0);

        let delay_ms = RESTART_BACKOFF_BASE_MS * (1 << attempt_number); // 1s, 2s, 4s, 8s
        let restart_time = now + Duration::from_millis(delay_ms);

        self.pending_restarts
            .insert(language.to_string(), restart_time);

        tracing::info!(
            "LSP server for {} crashed (attempt {}/{}), will restart in {}ms",
            language,
            attempt_number + 1,
            MAX_RESTARTS_IN_WINDOW,
            delay_ms
        );

        format!(
            "LSP server for {} crashed (attempt {}/{}), restarting in {}s...",
            language,
            attempt_number + 1,
            MAX_RESTARTS_IN_WINDOW,
            delay_ms / 1000
        )
    }

    /// Check and process any pending restarts that are due
    ///
    /// Returns list of (language, success, message) for each restart attempted
    pub fn process_pending_restarts(&mut self) -> Vec<(String, bool, String)> {
        let now = Instant::now();
        let mut results = Vec::new();

        // Find restarts that are due
        let due_restarts: Vec<String> = self
            .pending_restarts
            .iter()
            .filter(|(_, time)| **time <= now)
            .map(|(lang, _)| lang.clone())
            .collect();

        for language in due_restarts {
            self.pending_restarts.remove(&language);

            // Attempt to spawn the server (bypassing auto_start for
            // crash recovery). The attempt is recorded by the spawn
            // gate inside force_spawn — no need to push here.
            if self.force_spawn(&language, None).is_some() {
                let message = format!("LSP server for {} restarted successfully", language);
                tracing::info!("{}", message);
                results.push((language, true, message));
            } else {
                let message = format!("Failed to restart LSP server for {}", language);
                tracing::error!("{}", message);
                results.push((language, false, message));
            }
        }

        results
    }

    /// Check if a language server is in restart cooldown
    pub fn is_in_cooldown(&self, language: &str) -> bool {
        self.restart_cooldown.contains(language)
    }

    /// Check if a language server has a pending restart
    pub fn has_pending_restart(&self, language: &str) -> bool {
        self.pending_restarts.contains_key(language)
    }

    /// Clear cooldown for a language and allow manual restart
    pub fn clear_cooldown(&mut self, language: &str) {
        self.restart_cooldown.remove(language);
        self.restart_attempts.remove(language);
        self.pending_restarts.remove(language);
        tracing::info!("Cleared restart cooldown for {}", language);
    }

    /// Manually restart/start a language server (bypasses cooldown and auto_start check)
    ///
    /// This is used both to restart a crashed server and to manually start a server
    /// that has auto_start=false in its configuration.
    ///
    /// Returns (success, message) tuple
    pub fn manual_restart(&mut self, language: &str, file_path: Option<&Path>) -> (bool, String) {
        // Clear any existing state
        self.clear_cooldown(language);

        // Re-enable the language (remove from disabled set)
        self.disabled_languages.remove(language);

        // Add to allowed languages so it stays active even if auto_start=false
        self.allowed_languages.insert(language.to_string());

        // Remove existing handles for this language (non-universal)
        {
            let mut i = 0;
            while i < self.handles.len() {
                if !self.handles[i].handle.scope().is_universal()
                    && self.handles[i].handle.scope().accepts(language)
                {
                    let sh = self.handles.remove(i);
                    fire_and_forget(sh.handle.shutdown());
                } else {
                    i += 1;
                }
            }
        }

        // Spawn new server (bypassing auto_start for user-initiated restart)
        if self.force_spawn(language, file_path).is_some() {
            let message = format!("LSP server for {} started", language);
            tracing::info!("{}", message);
            (true, message)
        } else {
            let message = format!("Failed to start LSP server for {}", language);
            tracing::error!("{}", message);
            (false, message)
        }
    }

    /// Restart a single server by name for a specific language.
    ///
    /// Shuts down just that server and re-spawns it from config.
    /// Returns (success, message) tuple.
    pub fn manual_restart_server(
        &mut self,
        language: &str,
        server_name: &str,
        file_path: Option<&Path>,
    ) -> (bool, String) {
        self.clear_cooldown(language);
        self.disabled_languages.remove(language);
        self.allowed_languages.insert(language.to_string());

        // Find and shut down just the named server
        if let Some(idx) = self.handles.iter().position(|sh| sh.name == server_name) {
            let sh = self.handles.remove(idx);
            fire_and_forget(sh.handle.shutdown());
        }

        // Find the matching config (check per-language first, then universal)
        let is_universal = self
            .universal_configs
            .iter()
            .any(|c| c.display_name() == server_name);
        let config = if is_universal {
            self.universal_configs
                .iter()
                .find(|c| c.display_name() == server_name)
                .cloned()
        } else {
            self.config
                .get(language)
                .and_then(|configs| configs.iter().find(|c| c.display_name() == server_name))
                .cloned()
        };

        let Some(config) = config else {
            let message = format!(
                "No config found for server '{}' ({})",
                server_name, language
            );
            tracing::error!("{}", message);
            return (false, message);
        };

        if config.command.is_empty() {
            let message = format!(
                "LSP command is empty for {} server '{}'",
                language, server_name
            );
            tracing::error!("{}", message);
            return (false, message);
        }

        let runtime = match self.runtime.as_ref() {
            Some(r) => r.clone(),
            None => return (false, "No tokio runtime available".to_string()),
        };
        let async_bridge = match self.async_bridge.as_ref() {
            Some(b) => b.clone(),
            None => return (false, "No async bridge available".to_string()),
        };
        let long_running_spawner =
            self.long_running_spawner
                .as_ref()
                .cloned()
                .unwrap_or_else(|| {
                    std::sync::Arc::new(crate::services::remote::LocalLongRunningSpawner::new(
                        std::sync::Arc::new(crate::services::env_provider::EnvProvider::inactive()),
                        std::sync::Arc::new(
                            crate::services::workspace_trust::WorkspaceTrust::permissive(),
                        ),
                    ))
                });

        let scope = if is_universal {
            LanguageScope::all()
        } else {
            LanguageScope::single(language)
        };

        match LspHandle::spawn(
            &runtime,
            &config.command,
            &config.args,
            config.env.clone(),
            scope,
            server_name.to_string(),
            &async_bridge,
            config.process_limits.clone(),
            config.language_id_overrides.clone(),
            long_running_spawner,
        ) {
            Ok(handle) => {
                let effective_root = if is_universal {
                    file_path
                        .and_then(|p| {
                            let root = detect_workspace_root(p, &config.root_markers);
                            path_to_uri(&root)
                        })
                        .or_else(|| self.root_uri.clone())
                } else {
                    self.resolve_root_uri(language, file_path)
                };
                if let Err(e) =
                    handle.initialize(effective_root, config.initialization_options.clone())
                {
                    let message = format!(
                        "Failed to initialize LSP server '{}' for {}: {}",
                        server_name, language, e
                    );
                    tracing::error!("{}", message);
                    return (false, message);
                }

                let sh = ServerHandle {
                    name: server_name.to_string(),
                    handle,
                    feature_filter: config.feature_filter(),
                    capabilities: ServerCapabilitySummary::default(),
                };

                self.handles.push(sh);

                let message = format!("LSP server '{}' for {} started", server_name, language);
                tracing::info!("{}", message);
                (true, message)
            }
            Err(e) => {
                let message = format!(
                    "Failed to start LSP server '{}' for {}: {}",
                    server_name, language, e
                );
                tracing::error!("{}", message);
                (false, message)
            }
        }
    }

    /// Get the number of recent restart attempts for a language
    pub fn restart_attempt_count(&self, language: &str) -> usize {
        let now = Instant::now();
        let window = Duration::from_secs(RESTART_WINDOW_SECS);
        self.restart_attempts
            .get(language)
            .map(|attempts| {
                attempts
                    .iter()
                    .filter(|t| now.duration_since(**t) < window)
                    .count()
            })
            .unwrap_or(0)
    }

    /// Get a list of currently running LSP server language labels (deduplicated).
    pub fn running_servers(&self) -> Vec<String> {
        let mut labels: Vec<String> = self
            .handles
            .iter()
            .map(|sh| sh.handle.scope().label().to_string())
            .collect();
        labels.sort();
        labels.dedup();
        labels
    }

    /// Get the names of all running servers for a given language
    pub fn server_names_for_language(&self, language: &str) -> Vec<String> {
        self.handles
            .iter()
            .filter(|sh| sh.handle.scope().accepts(language))
            .map(|sh| sh.name.clone())
            .collect()
    }

    /// Check if any LSP server for a language is running and ready to serve requests
    pub fn is_server_ready(&self, language: &str) -> bool {
        self.handles
            .iter()
            .filter(|sh| sh.handle.scope().accepts(language))
            .any(|sh| sh.handle.state().can_send_requests())
    }

    /// Shutdown a single server by name for a specific language.
    ///
    /// Returns true if the server was found and shut down.
    /// If this was the last server for the language, marks the language as disabled.
    pub fn shutdown_server_by_name(&mut self, language: &str, server_name: &str) -> bool {
        let Some(idx) = self.handles.iter().position(|sh| sh.name == server_name) else {
            tracing::warn!(
                "No running LSP server named '{}' found for {}",
                server_name,
                language
            );
            return false;
        };

        let sh = self.handles.remove(idx);
        tracing::info!(
            "Shutting down LSP server '{}' for {} (disabled until manual restart)",
            sh.name,
            language
        );
        fire_and_forget(sh.handle.shutdown());

        // If no more non-universal handles remain for this language, mark it disabled
        let has_remaining = self
            .handles
            .iter()
            .any(|sh| !sh.handle.scope().is_universal() && sh.handle.scope().accepts(language));
        if !has_remaining {
            self.disabled_languages.insert(language.to_string());
            self.pending_restarts.remove(language);
            self.restart_cooldown.remove(language);
            self.allowed_languages.remove(language);
        }

        true
    }

    /// Shutdown all servers for a specific language.
    ///
    /// This marks the language as disabled, preventing auto-restart until the user
    /// explicitly restarts it using the restart command.
    pub fn shutdown_server(&mut self, language: &str) -> bool {
        let mut found = false;
        let mut i = 0;
        while i < self.handles.len() {
            if !self.handles[i].handle.scope().is_universal()
                && self.handles[i].handle.scope().accepts(language)
            {
                let sh = self.handles.remove(i);
                tracing::info!(
                    "Shutting down LSP server '{}' for {} (disabled until manual restart)",
                    sh.name,
                    language
                );
                fire_and_forget(sh.handle.shutdown());
                found = true;
            } else {
                i += 1;
            }
        }

        if found {
            self.disabled_languages.insert(language.to_string());
            self.pending_restarts.remove(language);
            self.restart_cooldown.remove(language);
            self.allowed_languages.remove(language);
        } else {
            tracing::warn!("No running LSP server found for {}", language);
        }

        found
    }

    /// Shutdown all language servers (including universal servers)
    pub fn shutdown_all(&mut self) {
        for sh in &self.handles {
            tracing::info!(
                "Shutting down LSP server '{}' ({})",
                sh.name,
                sh.handle.scope().label()
            );
            fire_and_forget(sh.handle.shutdown());
        }
        self.handles.clear();
    }
}

impl Drop for LspManager {
    fn drop(&mut self) {
        self.shutdown_all();
    }
}

/// Helper function to detect language from file path using the config's languages section.
///
/// Priority order matches `GrammarRegistry::find_by_path`:
/// 1. Exact filename match against `filenames` (highest priority)
/// 2. Glob pattern match against `filenames` entries containing wildcards
/// 3. File extension match against `extensions` (lowest config-based priority)
///
/// Kept separate from `find_by_path` because this returns the user's
/// config **key** (`[languages.mylang]` → `"mylang"`) rather than the
/// catalog entry's `language_id`, which is needed for LSP routing when a
/// user aliases an existing grammar.
pub fn detect_language(
    path: &std::path::Path,
    languages: &std::collections::HashMap<String, crate::config::LanguageConfig>,
) -> Option<String> {
    let detected = detect_language_by_config(path, languages);

    // `.h` headers: the default config maps the extension to C, but in C++
    // projects the header is still C++ and must route to clangd in C++ mode.
    // If the detected language is `c`, the file is `.h`, and the surrounding
    // tree smells like C++ (sibling C++ sources or an ancestor
    // `compile_commands.json`), promote to `cpp` so the LSP binding is right.
    if detected.as_deref() == Some("c")
        && path.extension().and_then(|e| e.to_str()) == Some("h")
        && languages.contains_key("cpp")
        && header_in_cpp_tree(path)
    {
        return Some("cpp".to_string());
    }

    detected
}

/// Pure config/path-based language detection without filesystem probing.
fn detect_language_by_config(
    path: &std::path::Path,
    languages: &std::collections::HashMap<String, crate::config::LanguageConfig>,
) -> Option<String> {
    use crate::primitives::glob_match::{
        filename_glob_matches, is_glob_pattern, is_path_pattern, path_glob_matches,
    };

    if let Some(filename) = path.file_name().and_then(|f| f.to_str()) {
        // 1. Exact filename match (highest priority)
        for (language_name, lang_config) in languages {
            if lang_config
                .filenames
                .iter()
                .any(|f| !is_glob_pattern(f) && f == filename)
            {
                return Some(language_name.clone());
            }
        }

        // 2. Glob pattern match
        // Path patterns (containing `/`) match against the full path;
        // filename-only patterns match against just the filename.
        let path_str = path.to_str().unwrap_or("");
        for (language_name, lang_config) in languages {
            if lang_config.filenames.iter().any(|f| {
                if !is_glob_pattern(f) {
                    return false;
                }
                if is_path_pattern(f) {
                    path_glob_matches(f, path_str)
                } else {
                    filename_glob_matches(f, filename)
                }
            }) {
                return Some(language_name.clone());
            }
        }
    }

    // 3. Extension match (lowest priority among config-based detection)
    if let Some(extension) = path.extension().and_then(|e| e.to_str()) {
        for (language_name, lang_config) in languages {
            if lang_config.extensions.iter().any(|ext| ext == extension) {
                return Some(language_name.clone());
            }
        }
    }

    None
}

/// Filesystem probe: does this header sit inside something that looks like
/// a C++ project? Two signals, both conservative:
///
///   * The file's own directory contains any C++ source or C++-specific
///     header (`.cc`, `.cpp`, `.cxx`, `.C`, `.c++`, `.hpp`, `.hh`, `.hxx`).
///     Decisive — if the siblings are C++, the header is too.
///   * An ancestor up to 10 levels deep contains a `compile_commands.json`
///     whose content carries a C++ marker. The mere presence of the file
///     is not enough: CMake emits `compile_commands.json` for pure-C
///     builds as well, so we peek inside and only promote when the
///     payload mentions a C++-specific compiler, flag, or source
///     extension (`c++`, `.cpp`, `.cc`, `.cxx`, `.C` ). This still covers
///     the fmt / Chromium / LLVM / Qt-style layouts where the header
///     lives deep under `include/` while sources sit in `src/` at the
///     project root.
///
/// Bounded by depth (10), by a single shallow `read_dir` at the start,
/// and by a capped 1 MiB read of `compile_commands.json`, so the cost is
/// a handful of `stat`s plus at most one bounded read on file open.
/// Silent on any I/O error — if we can't see the filesystem we fall back
/// to the default config answer (C), which is the pre-fix behavior.
///
/// NOTE(remote-fs): Uses `std::fs` directly, matching the pre-existing
/// `detect_workspace_root` in this module. On SSH sessions the probe
/// sees the local filesystem, so the promotion silently becomes a no-op
/// (returns `false`, falls back to `c`). Fixing this requires threading
/// `&dyn FileSystem` through `detect_language` and
/// `DetectedLanguage::from_path` — a cross-cutting refactor that should
/// be done alongside the same fix for `detect_workspace_root`.
fn header_in_cpp_tree(path: &std::path::Path) -> bool {
    let Some(start_dir) = path.parent() else {
        return false;
    };

    // 1. Sibling scan in the header's own directory.
    if let Ok(entries) = std::fs::read_dir(start_dir) {
        for entry in entries.flatten() {
            let p = entry.path();
            let Some(ext) = p.extension().and_then(|e| e.to_str()) else {
                continue;
            };
            if matches!(
                ext,
                "cc" | "cpp" | "cxx" | "C" | "c++" | "hpp" | "hh" | "hxx"
            ) {
                return true;
            }
        }
    }

    // 2. Walk ancestors for compile_commands.json, and only promote if
    //    the file actually carries a C++ marker — CMake emits it for
    //    pure-C builds too.
    let mut current = Some(start_dir);
    let mut depth = 0u32;
    while let Some(dir) = current {
        let cc = dir.join("compile_commands.json");
        if cc.is_file() && compile_commands_has_cpp_marker(&cc) {
            return true;
        }
        if depth >= 10 {
            break;
        }
        depth += 1;
        current = dir.parent();
    }

    false
}

/// Returns true when `compile_commands.json` contains a C++ marker —
/// either the literal substring `c++` (covers `-std=c++17`, `clang++`,
/// `g++`, the `c++` compiler name) or a C++ source extension in a
/// context where it cannot be confused with an adjacent header path
/// (`.cpp`, `.cc`, `.cxx`). Reads at most 1 MiB so multi-megabyte
/// compile DBs from large monorepos don't block file open; a valid CMake
/// entry fits comfortably in that window.
fn compile_commands_has_cpp_marker(path: &std::path::Path) -> bool {
    use std::io::Read;
    const MAX_READ: u64 = 1_048_576;

    let Ok(file) = std::fs::File::open(path) else {
        return false;
    };
    let mut buf = Vec::with_capacity(64 * 1024);
    if file.take(MAX_READ).read_to_end(&mut buf).is_err() {
        return false;
    }
    let Ok(text) = std::str::from_utf8(&buf) else {
        return false;
    };

    // Strongest single marker: literal "c++" appears in -std=c++NN,
    // clang++, g++, and the "c++" compiler name — never in a pure-C
    // compilation invocation.
    if text.contains("c++") {
        return true;
    }
    // Secondary markers: any mention of a C++ source extension in the
    // compile DB implies at least one C++ translation unit in the tree.
    text.contains(".cpp") || text.contains(".cxx") || text.contains(".cc\"")
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::Path;

    #[test]
    fn test_lsp_manager_new() {
        let root_uri: Option<Uri> = "file:///test".parse().ok();
        let manager = LspManager::new(fresh_core::WindowId(1), root_uri.clone());

        // Manager should start with no handles
        assert_eq!(manager.handles.len(), 0);
        assert_eq!(manager.config.len(), 0);
        assert!(manager.root_uri.is_some());
        assert!(manager.runtime.is_none());
        assert!(manager.async_bridge.is_none());
    }

    #[test]
    fn test_lsp_manager_set_language_config() {
        let mut manager = LspManager::new(fresh_core::WindowId(1), None);

        let config = LspServerConfig {
            enabled: true,
            command: "rust-analyzer".to_string(),
            args: vec![],
            process_limits: crate::services::process_limits::ProcessLimits::unlimited(),
            auto_start: false,
            initialization_options: None,
            env: Default::default(),
            language_id_overrides: Default::default(),
            name: None,
            only_features: None,
            except_features: None,
            root_markers: Default::default(),
        };

        manager.set_language_config("rust".to_string(), config);

        assert_eq!(manager.config.len(), 1);
        assert!(manager.config.contains_key("rust"));
        assert!(manager.config.get("rust").unwrap().first().unwrap().enabled);
    }

    #[test]
    fn test_lsp_manager_force_spawn_no_runtime() {
        let mut manager = LspManager::new(fresh_core::WindowId(1), None);

        // Add config for rust
        manager.set_language_config(
            "rust".to_string(),
            LspServerConfig {
                enabled: true,
                command: "rust-analyzer".to_string(),
                args: vec![],
                process_limits: crate::services::process_limits::ProcessLimits::unlimited(),
                auto_start: false,
                initialization_options: None,
                env: Default::default(),
                language_id_overrides: Default::default(),
                name: None,
                only_features: None,
                except_features: None,
                root_markers: Default::default(),
            },
        );

        // force_spawn should return None without runtime
        let result = manager.force_spawn("rust", None);
        assert!(result.is_none());
    }

    #[test]
    fn test_lsp_manager_force_spawn_no_config() {
        let rt = tokio::runtime::Runtime::new().unwrap();
        let mut manager = LspManager::new(fresh_core::WindowId(1), None);
        let async_bridge = AsyncBridge::new();

        manager.set_runtime(rt.handle().clone(), async_bridge);

        // force_spawn should return None for unconfigured language
        let result = manager.force_spawn("rust", None);
        assert!(result.is_none());
    }

    #[test]
    fn test_lsp_manager_force_spawn_disabled_language() {
        let rt = tokio::runtime::Runtime::new().unwrap();
        let mut manager = LspManager::new(fresh_core::WindowId(1), None);
        let async_bridge = AsyncBridge::new();

        manager.set_runtime(rt.handle().clone(), async_bridge);

        // Add disabled config (command is optional when disabled)
        manager.set_language_config(
            "rust".to_string(),
            LspServerConfig {
                enabled: false,
                command: String::new(), // command not required when disabled
                args: vec![],
                process_limits: crate::services::process_limits::ProcessLimits::unlimited(),
                auto_start: false,
                initialization_options: None,
                env: Default::default(),
                language_id_overrides: Default::default(),
                name: None,
                only_features: None,
                except_features: None,
                root_markers: Default::default(),
            },
        );

        // force_spawn should return None for disabled language
        let result = manager.force_spawn("rust", None);
        assert!(result.is_none());
    }

    // try_spawn must distinguish "user disabled it" (enabled=false for
    // every configured server) from real spawn failures. Opening a file
    // of a deliberately-disabled language should return `Disabled`, not
    // `Failed`, so callers can log at debug level instead of warning on
    // every file open.
    #[test]
    fn test_lsp_manager_try_spawn_returns_disabled_when_all_configs_disabled() {
        let rt = tokio::runtime::Runtime::new().unwrap();
        let mut manager = LspManager::new(fresh_core::WindowId(1), None);
        let async_bridge = AsyncBridge::new();
        manager.set_runtime(rt.handle().clone(), async_bridge);

        manager.set_language_config(
            "rust".to_string(),
            LspServerConfig {
                enabled: false,
                command: String::new(),
                args: vec![],
                process_limits: crate::services::process_limits::ProcessLimits::unlimited(),
                auto_start: false,
                initialization_options: None,
                env: Default::default(),
                language_id_overrides: Default::default(),
                name: None,
                only_features: None,
                except_features: None,
                root_markers: Default::default(),
            },
        );

        assert_eq!(manager.try_spawn("rust", None), LspSpawnResult::Disabled);
    }

    #[test]
    fn test_lsp_manager_shutdown_all() {
        let mut manager = LspManager::new(fresh_core::WindowId(1), None);

        // shutdown_all should not panic even with no handles
        manager.shutdown_all();
        assert_eq!(manager.handles.len(), 0);
    }

    fn test_languages() -> std::collections::HashMap<String, crate::config::LanguageConfig> {
        let mut languages = std::collections::HashMap::new();
        languages.insert(
            "rust".to_string(),
            crate::config::LanguageConfig {
                extensions: vec!["rs".to_string()],
                filenames: vec![],
                grammar: "rust".to_string(),
                comment_prefix: Some("//".to_string()),
                auto_indent: true,
                auto_close: None,
                auto_surround: None,
                textmate_grammar: None,
                show_whitespace_tabs: false,
                line_wrap: None,
                wrap_column: None,
                page_view: None,
                page_width: None,
                use_tabs: None,
                tab_size: None,
                formatter: None,
                format_on_save: false,
                on_save: vec![],
                word_characters: None,
            },
        );
        languages.insert(
            "javascript".to_string(),
            crate::config::LanguageConfig {
                extensions: vec!["js".to_string(), "jsx".to_string()],
                filenames: vec![],
                grammar: "javascript".to_string(),
                comment_prefix: Some("//".to_string()),
                auto_indent: true,
                auto_close: None,
                auto_surround: None,
                textmate_grammar: None,
                show_whitespace_tabs: false,
                line_wrap: None,
                wrap_column: None,
                page_view: None,
                page_width: None,
                use_tabs: None,
                tab_size: None,
                formatter: None,
                format_on_save: false,
                on_save: vec![],
                word_characters: None,
            },
        );
        languages.insert(
            "csharp".to_string(),
            crate::config::LanguageConfig {
                extensions: vec!["cs".to_string()],
                filenames: vec![],
                grammar: "c_sharp".to_string(),
                comment_prefix: Some("//".to_string()),
                auto_indent: true,
                auto_close: None,
                auto_surround: None,
                textmate_grammar: None,
                show_whitespace_tabs: false,
                line_wrap: None,
                wrap_column: None,
                page_view: None,
                page_width: None,
                use_tabs: None,
                tab_size: None,
                formatter: None,
                format_on_save: false,
                on_save: vec![],
                word_characters: None,
            },
        );
        languages
    }

    #[test]
    fn test_detect_language_from_config() {
        let languages = test_languages();

        // Test configured languages
        assert_eq!(
            detect_language(Path::new("main.rs"), &languages),
            Some("rust".to_string())
        );
        assert_eq!(
            detect_language(Path::new("index.js"), &languages),
            Some("javascript".to_string())
        );
        assert_eq!(
            detect_language(Path::new("App.jsx"), &languages),
            Some("javascript".to_string())
        );
        assert_eq!(
            detect_language(Path::new("Program.cs"), &languages),
            Some("csharp".to_string())
        );

        // Test unconfigured extensions return None
        assert_eq!(detect_language(Path::new("main.py"), &languages), None);
        assert_eq!(detect_language(Path::new("file.xyz"), &languages), None);
        assert_eq!(detect_language(Path::new("file"), &languages), None);
    }

    #[test]
    fn test_detect_language_no_extension() {
        let languages = test_languages();
        assert_eq!(detect_language(Path::new("README"), &languages), None);
        assert_eq!(detect_language(Path::new("Makefile"), &languages), None);
    }

    #[test]
    fn test_detect_language_path_glob() {
        let mut languages = test_languages();
        languages.insert(
            "shell".to_string(),
            crate::config::LanguageConfig {
                extensions: vec!["sh".to_string()],
                filenames: vec!["/etc/**/rc.*".to_string(), "*rc".to_string()],
                grammar: "bash".to_string(),
                comment_prefix: Some("#".to_string()),
                auto_indent: true,
                auto_close: None,
                auto_surround: None,
                textmate_grammar: None,
                show_whitespace_tabs: false,
                line_wrap: None,
                wrap_column: None,
                page_view: None,
                page_width: None,
                use_tabs: None,
                tab_size: None,
                formatter: None,
                format_on_save: false,
                on_save: vec![],
                word_characters: None,
            },
        );

        // Path glob: /etc/**/rc.* should match
        assert_eq!(
            detect_language(Path::new("/etc/rc.conf"), &languages),
            Some("shell".to_string())
        );
        assert_eq!(
            detect_language(Path::new("/etc/init/rc.local"), &languages),
            Some("shell".to_string())
        );
        // Path glob should NOT match different root
        assert_eq!(detect_language(Path::new("/var/rc.conf"), &languages), None);

        // Filename glob: *rc should still work
        assert_eq!(
            detect_language(Path::new("lfrc"), &languages),
            Some("shell".to_string())
        );
    }

    #[test]
    fn test_detect_workspace_root_finds_marker_in_parent() {
        let tmp = tempfile::tempdir().unwrap();
        let project = tmp.path().join("myproject");
        let src = project.join("src");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::write(project.join("Cargo.toml"), "").unwrap();
        let file = src.join("main.rs");
        std::fs::write(&file, "").unwrap();

        let root = detect_workspace_root(&file, &["Cargo.toml".to_string(), ".git".to_string()]);
        assert_eq!(root, project);
    }

    #[test]
    fn test_detect_workspace_root_finds_marker_two_levels_up() {
        let tmp = tempfile::tempdir().unwrap();
        let project = tmp.path().join("myproject");
        let deep = project.join("src").join("nested");
        std::fs::create_dir_all(&deep).unwrap();
        std::fs::write(project.join("Cargo.toml"), "").unwrap();
        let file = deep.join("lib.rs");
        std::fs::write(&file, "").unwrap();

        let root = detect_workspace_root(&file, &["Cargo.toml".to_string()]);
        assert_eq!(root, project);
    }

    #[test]
    fn test_detect_workspace_root_no_marker_returns_parent() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("somedir");
        std::fs::create_dir_all(&dir).unwrap();
        let file = dir.join("file.txt");
        std::fs::write(&file, "").unwrap();

        let root = detect_workspace_root(&file, &["nonexistent_marker".to_string()]);
        assert_eq!(root, dir);
    }

    #[test]
    fn test_detect_workspace_root_empty_markers_returns_parent() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("somedir");
        std::fs::create_dir_all(&dir).unwrap();
        let file = dir.join("file.txt");
        std::fs::write(&file, "").unwrap();

        let root = detect_workspace_root(&file, &[]);
        assert_eq!(root, dir);
    }

    #[test]
    fn test_detect_workspace_root_directory_marker() {
        let tmp = tempfile::tempdir().unwrap();
        let project = tmp.path().join("myproject");
        let src = project.join("src");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::create_dir_all(project.join(".git")).unwrap();
        let file = src.join("main.rs");
        std::fs::write(&file, "").unwrap();

        let root = detect_workspace_root(&file, &[".git".to_string()]);
        assert_eq!(root, project);
    }

    /// Returns a languages map mirroring the default config's `c` + `cpp`
    /// entries: `.h` maps to `c`, and `.cpp/.cc/.cxx/.hpp/.hh/.hxx` map to
    /// `cpp`. Matches `config.rs:3010` and `:3040-3047` so the promotion
    /// logic is exercised under realistic config.
    fn c_cpp_languages() -> std::collections::HashMap<String, crate::config::LanguageConfig> {
        use crate::config::LanguageConfig;
        let mut languages = std::collections::HashMap::new();
        let base = LanguageConfig {
            extensions: vec![],
            filenames: vec![],
            grammar: String::new(),
            comment_prefix: Some("//".to_string()),
            auto_indent: true,
            auto_close: None,
            auto_surround: None,
            textmate_grammar: None,
            show_whitespace_tabs: false,
            line_wrap: None,
            wrap_column: None,
            page_view: None,
            page_width: None,
            use_tabs: None,
            tab_size: None,
            formatter: None,
            format_on_save: false,
            on_save: vec![],
            word_characters: None,
        };
        languages.insert(
            "c".to_string(),
            LanguageConfig {
                extensions: vec!["c".to_string(), "h".to_string()],
                grammar: "c".to_string(),
                ..base.clone()
            },
        );
        languages.insert(
            "cpp".to_string(),
            LanguageConfig {
                extensions: vec![
                    "cpp".to_string(),
                    "cc".to_string(),
                    "cxx".to_string(),
                    "hpp".to_string(),
                    "hh".to_string(),
                    "hxx".to_string(),
                ],
                grammar: "cpp".to_string(),
                ..base
            },
        );
        languages
    }

    #[test]
    fn test_detect_language_h_stays_c_without_cpp_signals() {
        // No filesystem context — plain `Path::new("foo.h")` doesn't exist,
        // so sibling scan + compile_commands walk both return false and the
        // default-config answer (`c`) survives.
        let languages = c_cpp_languages();
        assert_eq!(
            detect_language(Path::new("foo.h"), &languages),
            Some("c".to_string())
        );
    }

    #[test]
    fn test_detect_language_h_promotes_to_cpp_with_sibling_cpp_source() {
        let tmp = tempfile::tempdir().unwrap();
        let project = tmp.path().join("proj");
        std::fs::create_dir_all(&project).unwrap();
        let header = project.join("widget.h");
        std::fs::write(&header, "").unwrap();
        // Sibling .cpp source — the decisive C++ signal.
        std::fs::write(project.join("widget.cpp"), "").unwrap();

        let languages = c_cpp_languages();
        assert_eq!(
            detect_language(&header, &languages),
            Some("cpp".to_string())
        );
    }

    #[test]
    fn test_detect_language_h_promotes_to_cpp_with_sibling_hpp() {
        let tmp = tempfile::tempdir().unwrap();
        let project = tmp.path().join("proj");
        std::fs::create_dir_all(&project).unwrap();
        let header = project.join("a.h");
        std::fs::write(&header, "").unwrap();
        // A `.hpp` sibling is also a C++-specific signal.
        std::fs::write(project.join("b.hpp"), "").unwrap();

        let languages = c_cpp_languages();
        assert_eq!(
            detect_language(&header, &languages),
            Some("cpp".to_string())
        );
    }

    #[test]
    fn test_detect_language_h_promotes_to_cpp_with_ancestor_compile_commands() {
        let tmp = tempfile::tempdir().unwrap();
        let project = tmp.path().join("proj");
        let include = project.join("include").join("fmt");
        std::fs::create_dir_all(&include).unwrap();
        // Compile DB two levels above the header — the fmt-style layout.
        // Realistic CMake output: the compile command references clang++
        // and a C++ source, which is the C++ marker we key on.
        std::fs::write(
            project.join("compile_commands.json"),
            r#"[{"directory":"/proj","command":"/usr/bin/clang++ -std=c++17 -c src/format.cc","file":"src/format.cc"}]"#,
        ).unwrap();
        let header = include.join("format.h");
        std::fs::write(&header, "").unwrap();

        let languages = c_cpp_languages();
        assert_eq!(
            detect_language(&header, &languages),
            Some("cpp".to_string())
        );
    }

    #[test]
    fn test_detect_language_h_stays_c_with_pure_c_compile_commands() {
        // A compile_commands.json generated for a pure-C project (gcc,
        // -std=c11, .c sources only) must NOT promote .h to cpp.
        let tmp = tempfile::tempdir().unwrap();
        let project = tmp.path().join("cproj");
        let include = project.join("include");
        std::fs::create_dir_all(&include).unwrap();
        std::fs::write(
            project.join("compile_commands.json"),
            r#"[{"directory":"/cproj","command":"/usr/bin/gcc -std=c11 -c src/lib.c","file":"src/lib.c"}]"#,
        )
        .unwrap();
        let header = include.join("lib.h");
        std::fs::write(&header, "").unwrap();

        let languages = c_cpp_languages();
        assert_eq!(detect_language(&header, &languages), Some("c".to_string()));
    }

    #[test]
    fn test_detect_language_h_stays_c_in_pure_c_tree() {
        let tmp = tempfile::tempdir().unwrap();
        let project = tmp.path().join("cproj");
        std::fs::create_dir_all(&project).unwrap();
        let header = project.join("lib.h");
        std::fs::write(&header, "").unwrap();
        // Only `.c` siblings — no C++ signal, no compile_commands.json.
        std::fs::write(project.join("lib.c"), "").unwrap();

        let languages = c_cpp_languages();
        assert_eq!(detect_language(&header, &languages), Some("c".to_string()));
    }

    #[test]
    fn test_detect_language_h_stays_c_with_empty_compile_commands() {
        // Empty / minimal compile_commands.json carries no C++ marker,
        // so we stay conservative and leave the header as C.
        let tmp = tempfile::tempdir().unwrap();
        let project = tmp.path().join("proj");
        std::fs::create_dir_all(&project).unwrap();
        std::fs::write(project.join("compile_commands.json"), "[]").unwrap();
        let header = project.join("foo.h");
        std::fs::write(&header, "").unwrap();

        let languages = c_cpp_languages();
        assert_eq!(detect_language(&header, &languages), Some("c".to_string()));
    }

    #[test]
    fn test_detect_language_h_promotes_on_cpp_std_flag_alone() {
        // `-std=c++20` with no other C++ extension is still conclusive.
        let tmp = tempfile::tempdir().unwrap();
        let project = tmp.path().join("proj");
        let include = project.join("include");
        std::fs::create_dir_all(&include).unwrap();
        std::fs::write(
            project.join("compile_commands.json"),
            // A contrived entry using the `.C` (capital) source extension
            // with the c++20 flag — tests that the "c++" substring alone
            // is sufficient even when our `.cpp/.cc/.cxx` scan would miss.
            r#"[{"directory":"/proj","command":"/usr/bin/clang -std=c++20 -c src/x.C","file":"src/x.C"}]"#,
        )
        .unwrap();
        let header = include.join("x.h");
        std::fs::write(&header, "").unwrap();

        let languages = c_cpp_languages();
        assert_eq!(
            detect_language(&header, &languages),
            Some("cpp".to_string())
        );
    }

    #[test]
    fn test_detect_language_c_source_never_promoted() {
        // `.c` files should stay `c` even in a C++ tree.
        let tmp = tempfile::tempdir().unwrap();
        let project = tmp.path().join("proj");
        std::fs::create_dir_all(&project).unwrap();
        let source = project.join("legacy.c");
        std::fs::write(&source, "").unwrap();
        std::fs::write(project.join("main.cpp"), "").unwrap();

        let languages = c_cpp_languages();
        assert_eq!(detect_language(&source, &languages), Some("c".to_string()));
    }

    #[test]
    fn test_detect_language_h_no_promotion_without_cpp_config() {
        // If the user hasn't configured `cpp`, we have nowhere to promote to
        // — stay with the base detection rather than inventing a language.
        let tmp = tempfile::tempdir().unwrap();
        let project = tmp.path().join("proj");
        std::fs::create_dir_all(&project).unwrap();
        let header = project.join("widget.h");
        std::fs::write(&header, "").unwrap();
        std::fs::write(project.join("widget.cpp"), "").unwrap();

        let mut languages = c_cpp_languages();
        languages.remove("cpp");
        assert_eq!(detect_language(&header, &languages), Some("c".to_string()));
    }

    #[test]
    fn test_path_to_uri_basic() {
        let uri = path_to_uri(Path::new("/tmp/test")).unwrap();
        assert_eq!(uri.as_str(), "file:///tmp/test");
    }

    #[test]
    fn test_path_to_uri_with_spaces() {
        let uri = path_to_uri(Path::new("/tmp/my project/src")).unwrap();
        assert_eq!(uri.as_str(), "file:///tmp/my%20project/src");
    }

    #[test]
    fn dynamic_registration_enables_then_disables_inlay_hints() {
        // A server that advertised no static inlayHintProvider but registers it
        // dynamically must end up with the capability enabled — and unregister
        // must turn it back off (sinelaw/fresh#2195 §1).
        let mut caps = ServerCapabilitySummary::default();
        assert!(!caps.inlay_hints);

        let recognized = caps.apply_dynamic_registration("textDocument/inlayHint", None, true);
        assert!(
            recognized,
            "inlayHint must be a recognized capability method"
        );
        assert!(
            caps.inlay_hints,
            "dynamic registration must enable inlay hints"
        );

        let recognized = caps.apply_dynamic_registration("textDocument/inlayHint", None, false);
        assert!(recognized);
        assert!(!caps.inlay_hints, "unregister must disable inlay hints");
    }

    #[test]
    fn dynamic_registration_ignores_unknown_methods() {
        // Methods we don't gate a feature on (e.g. file watching, handled
        // elsewhere) must report "not recognized" so the caller doesn't
        // needlessly re-issue feature requests.
        let mut caps = ServerCapabilitySummary::default();
        let recognized =
            caps.apply_dynamic_registration("workspace/didChangeWatchedFiles", None, true);
        assert!(!recognized);
    }

    #[test]
    fn dynamic_registration_parses_completion_options() {
        let mut caps = ServerCapabilitySummary::default();
        let opts = serde_json::json!({
            "triggerCharacters": [".", "::"],
            "resolveProvider": true,
        });
        let recognized =
            caps.apply_dynamic_registration("textDocument/completion", Some(&opts), true);
        assert!(recognized);
        assert!(caps.completion);
        assert!(caps.completion_resolve);
        assert_eq!(caps.completion_trigger_characters, vec![".", "::"]);

        // Unregister clears the derived state too.
        caps.apply_dynamic_registration("textDocument/completion", None, false);
        assert!(!caps.completion);
        assert!(!caps.completion_resolve);
        assert!(caps.completion_trigger_characters.is_empty());
    }

    #[test]
    fn dynamic_registration_parses_semantic_tokens_legend() {
        let mut caps = ServerCapabilitySummary::default();
        let opts = serde_json::json!({
            "legend": {
                "tokenTypes": ["namespace", "type"],
                "tokenModifiers": ["declaration"],
            },
            "full": { "delta": true },
            "range": true,
        });
        let recognized =
            caps.apply_dynamic_registration("textDocument/semanticTokens", Some(&opts), true);
        assert!(recognized);
        assert!(caps.semantic_tokens_full);
        assert!(caps.semantic_tokens_full_delta);
        assert!(caps.semantic_tokens_range);
        let legend = caps
            .semantic_tokens_legend
            .as_ref()
            .expect("legend must be parsed from registration options");
        assert_eq!(legend.token_types.len(), 2);

        caps.apply_dynamic_registration("textDocument/semanticTokens", None, false);
        assert!(!caps.semantic_tokens_full);
        assert!(caps.semantic_tokens_legend.is_none());
    }

    #[test]
    fn apply_dynamic_capabilities_reports_change_only_for_known_methods() {
        // The manager-level entry point returns whether any recognized feature
        // flag changed, which gates whether the dispatcher re-issues requests.
        let mut caps = ServerCapabilitySummary::default();
        let known = caps.apply_dynamic_registration("textDocument/hover", None, true);
        let unknown = caps.apply_dynamic_registration("some/unknownMethod", None, true);
        assert!(known);
        assert!(!unknown);
        assert!(caps.hover);
    }
}