croft-software 0.2.132

VSCode-style TUI written in Rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
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
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::Mutex as StdMutex;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc as std_mpsc;

use anyhow::Result;
use lsp_types::{
    ClientCapabilities, CodeActionCapabilityResolveSupport, CodeActionClientCapabilities,
    CodeActionKindLiteralSupport, CodeActionLiteralSupport, CodeActionOrCommand,
    CodeActionProviderCapability, CodeActionResponse, CompletionClientCapabilities,
    CompletionItemCapability, CompletionItemKind, CompletionItemKindCapability, CompletionResponse,
    DeclarationCapability, DiagnosticServerCapabilities, DocumentChangeOperation, DocumentChanges,
    DocumentSymbol, DocumentSymbolClientCapabilities, DocumentSymbolResponse,
    GotoDefinitionResponse, HoverContents, HoverProviderCapability,
    ImplementationProviderCapability, Location, MarkedString, MarkupKind, OneOf, Position,
    PublishDiagnosticsClientCapabilities, SemanticTokenModifier, SemanticTokenType,
    SemanticTokensClientCapabilities, SemanticTokensClientCapabilitiesRequests,
    SemanticTokensFullOptions, SemanticTokensRangeResult, SemanticTokensResult,
    SemanticTokensServerCapabilities, SemanticTokensWorkspaceClientCapabilities,
    ServerCapabilities, SymbolKind, TextDocumentClientCapabilities, TextEdit, TokenFormat,
    TypeDefinitionProviderCapability, Url, WindowClientCapabilities, WorkspaceClientCapabilities,
    WorkspaceEdit,
};
use tokio::sync::{Mutex as TokioMutex, mpsc as tokio_mpsc, oneshot};

use crate::lsp::client::LspClient;
use crate::lsp::config::{Language, ServerConfig};
use crate::lsp::log_file;
use crate::lsp::registry::ServerRegistry;
use crate::lsp::runtime::LspRuntime;
use crate::text_edit::TextSpanEdit;

#[derive(Debug, Clone, Default)]
pub struct CompletionItem {
    pub label: String,
    pub detail: Option<String>,
    pub insert_text: Option<String>,
    pub filter_text: Option<String>,
    pub kind: Option<CompletionItemKind>,
    /// The `insert_text` is a snippet body (`$1`/`$0` tab stops) rather than
    /// literal text: an LSP item with `insertTextFormat: Snippet`, or a user
    /// snippet injected into the popup. The app expands it through the editor's
    /// snippet engine on accept instead of inserting it verbatim.
    pub is_snippet: bool,
    /// The server's own edit for this item (`textEdit`; for an insert/
    /// replace edit, its insert range), UTF-16 columns. It can reach back
    /// before the typed word (TypeScript's `?.foo` replaces the `.`), which
    /// replacing the word alone got wrong.
    pub text_edit: Option<TextSpanEdit>,
    /// `additionalTextEdits`: an auto-import or `#include` elsewhere in the
    /// file, applied along with the item.
    pub additional_edits: Vec<TextSpanEdit>,
    /// The item's documentation, Markdown or plain text as the server sent
    /// it, for the popup's details pane (#1527).
    pub documentation: Option<String>,
    /// The item as the server listed it, `data` and all, when the server
    /// resolves items lazily and the list left its imports out (#928):
    /// vtsls sends an auto-import only from `completionItem/resolve`, which
    /// the accept sends this back for.
    pub resolve: Option<Arc<lsp_types::CompletionItem>>,
}

/// A completion reply. A `completionItem/resolve` reply is one too, its
/// single item the resolved one (#928).
#[derive(Debug)]
pub struct CompletionResult {
    pub request_id: u64,
    pub path: PathBuf,
    pub items: Vec<CompletionItem>,
    /// The server capped the list (`isIncomplete`): typing on must ask it
    /// again rather than only filter these items (#1529).
    pub is_incomplete: bool,
}

/// Why a completion is asked for, sent as the request's `context`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompletionTrigger {
    /// Ctrl+Space, or a word begun with quick suggestions on (#929).
    Invoked,
    /// A character the server lists in `triggerCharacters` was typed
    /// (#929): TypeScript's `"` and `/` in an import path, `.` for members.
    Character(char),
    /// Re-asking because the last list was incomplete (#1529).
    Incomplete,
}

/// The answer to one of rust-analyzer's own requests (#1626), raw; `Err`
/// says why there is none (no rust-analyzer for the file, or its error).
#[derive(Debug)]
pub struct RustAnalyzerResult {
    pub request_id: u64,
    pub request: crate::lsp::rust_analyzer::RaRequest,
    pub outcome: Result<serde_json::Value, String>,
}

#[derive(Debug)]
pub struct HoverResult {
    pub request_id: u64,
    pub text: Option<String>,
}

/// One callable signature for the Signature Help popup, normalised off the LSP
/// `SignatureInformation` so the widget never touches lsp-types. `active_param`
/// is the (start, end) char range within `label` to bold (the parameter the
/// caret currently sits in), already resolved against the active signature.
#[derive(Clone, Debug)]
pub struct SignatureInfo {
    pub label: String,
    pub active_param: Option<(usize, usize)>,
}

#[derive(Debug)]
pub struct SignatureHelpResult {
    pub request_id: u64,
    pub path: PathBuf,
    pub signatures: Vec<SignatureInfo>,
    pub active_signature: usize,
}

#[derive(Debug)]
pub struct DefinitionResult {
    pub request_id: u64,
    pub target: Option<(PathBuf, u32, u32)>,
}

/// The kind of an outline symbol, normalised off the LSP `SymbolKind` wire
/// enum so the Outline widget never depends on `lsp-types`. Mirrors VS Code's
/// symbol categories one-to-one; the widget maps each to a codicon + colour.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OutlineKind {
    File,
    Module,
    Namespace,
    Package,
    Class,
    Method,
    Property,
    Field,
    Constructor,
    Enum,
    Interface,
    Function,
    Variable,
    Constant,
    String,
    Number,
    Boolean,
    Array,
    Object,
    Key,
    Null,
    EnumMember,
    Struct,
    Event,
    Operator,
    TypeParameter,
}

impl OutlineKind {
    fn from_lsp(kind: SymbolKind) -> Self {
        match kind {
            SymbolKind::MODULE => Self::Module,
            SymbolKind::NAMESPACE => Self::Namespace,
            SymbolKind::PACKAGE => Self::Package,
            SymbolKind::CLASS => Self::Class,
            SymbolKind::METHOD => Self::Method,
            SymbolKind::PROPERTY => Self::Property,
            SymbolKind::FIELD => Self::Field,
            SymbolKind::CONSTRUCTOR => Self::Constructor,
            SymbolKind::ENUM => Self::Enum,
            SymbolKind::INTERFACE => Self::Interface,
            SymbolKind::FUNCTION => Self::Function,
            SymbolKind::VARIABLE => Self::Variable,
            SymbolKind::CONSTANT => Self::Constant,
            SymbolKind::STRING => Self::String,
            SymbolKind::NUMBER => Self::Number,
            SymbolKind::BOOLEAN => Self::Boolean,
            SymbolKind::ARRAY => Self::Array,
            SymbolKind::OBJECT => Self::Object,
            SymbolKind::KEY => Self::Key,
            SymbolKind::NULL => Self::Null,
            SymbolKind::ENUM_MEMBER => Self::EnumMember,
            SymbolKind::STRUCT => Self::Struct,
            SymbolKind::EVENT => Self::Event,
            SymbolKind::OPERATOR => Self::Operator,
            SymbolKind::TYPE_PARAMETER => Self::TypeParameter,
            // SymbolKind::FILE and any future/unknown kind fall back to File.
            _ => Self::File,
        }
    }
}

/// One row of the Outline, flattened from the server's symbol tree in document
/// order with a `depth` for indentation. `line`/`character` are the
/// `selectionRange` start (zero-based LSP UTF-16) — where the caret lands on
/// click — while `range_start_line`/`range_end_line` bound the whole construct
/// so the panel can highlight the symbol the editor caret currently sits in.
#[derive(Debug, Clone)]
pub struct OutlineSymbol {
    pub name: String,
    pub detail: Option<String>,
    pub kind: OutlineKind,
    pub depth: u16,
    pub line: u32,
    pub character: u32,
    pub range_start_line: u32,
    pub range_end_line: u32,
    /// The construct's start column on `range_start_line` and end column on
    /// `range_end_line` (#1221), so symbols sharing a line (a one-line
    /// interface's fields, a minified bundle's functions) are told apart.
    /// `0` / `u32::MAX` when only the lines are known.
    pub range_start_character: u32,
    pub range_end_character: u32,
}

/// The Outline for one document. Keyed by `path` (the latest batch wins, like
/// `SemanticTokensUpdate`); the app applies it only when `path` still matches
/// the active editor, so a reply for a file the user navigated away from is
/// dropped without needing a request id.
#[derive(Debug)]
pub struct DocumentSymbolsResult {
    pub path: PathBuf,
    /// Echo of the edit seq the request was issued at, so the app can drop a
    /// reply that answers an older buffer than the newest request.
    pub seq: u64,
    pub symbols: Vec<OutlineSymbol>,
}

#[derive(Debug)]
pub struct DeclarationResult {
    pub request_id: u64,
    pub target: Option<(PathBuf, u32, u32)>,
    /// True when no spawned server advertises a usable `declarationProvider`
    /// (e.g. vtsls, which sends `declarationProvider: false`). Lets the app
    /// say so plainly instead of silently doing nothing.
    pub unsupported: bool,
}

#[derive(Debug)]
pub struct TypeDefinitionResult {
    pub request_id: u64,
    pub target: Option<(PathBuf, u32, u32)>,
    /// True when no spawned server advertises a usable `typeDefinitionProvider`.
    /// Mirrors `DeclarationResult::unsupported` so the app can report it plainly
    /// rather than silently no-op.
    pub unsupported: bool,
}

#[derive(Debug)]
pub struct ImplementationResult {
    pub request_id: u64,
    /// Every implementation location the server returned. `textDocument/
    /// implementation` is the 1:many goto (one abstraction, several
    /// implementors), so all of them are carried through; the app jumps
    /// directly when there is one and shows a picker when there are several.
    pub targets: Vec<(PathBuf, u32, u32)>,
    /// True when no spawned server advertises a usable `implementationProvider`.
    pub unsupported: bool,
}

/// One `workspace/symbol` hit, mapped to croft's outline vocabulary.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WorkspaceSymbolItem {
    pub name: String,
    pub kind: OutlineKind,
    pub path: PathBuf,
    pub line: u32,
    pub character: u32,
    /// The enclosing symbol's name, for the dim qualifier in the picker row.
    pub container: Option<String>,
}

pub struct WorkspaceSymbolsResult {
    pub request_id: u64,
    pub symbols: Vec<WorkspaceSymbolItem>,
    /// True when no spawned server advertises a `workspaceSymbolProvider`.
    pub unsupported: bool,
}

#[derive(Debug)]
pub struct ReferencesResult {
    pub request_id: u64,
    /// Every reference location the server returned. `textDocument/references`
    /// is inherently 1:many (a symbol used in many places), so all of them are
    /// carried through; the app jumps directly when there is one and shows a
    /// picker when there are several, exactly like Go to Implementations.
    pub targets: Vec<(PathBuf, u32, u32)>,
    /// True when no spawned server advertises a usable `referencesProvider`.
    pub unsupported: bool,
}

#[derive(Debug)]
pub struct RenameResult {
    pub request_id: u64,
    /// `None` when the server declined or returned no edits. Otherwise the
    /// per-file, char-indexed spans to apply across the workspace.
    pub edits: Option<Vec<(PathBuf, Vec<TextSpanEdit>)>>,
}

/// One Explorer rename or move, as the servers see it (#610).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileRenameOp {
    pub old: PathBuf,
    pub new: PathBuf,
    pub is_dir: bool,
}

/// The servers' combined answer to `willRenameFiles` (#610). Always sent,
/// so the pending move never waits on a server that is not interested.
#[derive(Debug)]
pub struct WillRenameFilesResult {
    pub request_id: u64,
    /// Per-file, char-indexed spans to apply before the move.
    pub edits: Vec<(PathBuf, Vec<TextSpanEdit>)>,
}

/// A `textDocument/prepareRename` verdict (#254). Always answered — the
/// rename prompt is waiting on it. `unsupported` routes the app to the
/// plain word-under-cursor prompt; `error` carries the server's own
/// refusal (fail fast with ITS message, not a generic one); otherwise
/// `target` holds the validated UTF-16 range and optional placeholder,
/// and `None` means the server said "nothing renameable here".
#[derive(Debug)]
pub struct PrepareRenameResult {
    pub request_id: u64,
    pub unsupported: bool,
    pub error: Option<String>,
    /// `((start_line, start_char, end_line, end_char), placeholder)`.
    #[allow(clippy::type_complexity)]
    pub target: Option<((u32, u32, u32, u32), Option<String>)>,
}

/// A command to run after a code action's edits, via `workspace/executeCommand`
/// (LSP's `Command`). Carries the opaque command id and its arguments verbatim.
#[derive(Debug, Clone)]
pub struct CodeActionCommand {
    pub command: String,
    pub arguments: Vec<serde_json::Value>,
}

/// One selectable entry in the Quick Fix menu, normalised from an LSP
/// `CodeActionOrCommand` into croft's own char-indexed edit representation so
/// the app layer never touches `lsp_types`. Mirrors how [`RenameResult`] carries
/// already-normalised edits.
#[derive(Debug, Clone)]
pub struct CodeActionItem {
    pub title: String,
    /// The language server that produced this action. A `codeAction/resolve`
    /// for the action must go back to the same server, and the title is shown
    /// as-is (servers already prefix, e.g. "Ruff: Organize imports").
    pub server: String,
    /// Per-file, char-indexed spans to apply (empty when the action has no
    /// inline edit; it then runs `command` and/or must be resolved first).
    pub edits: Vec<(PathBuf, Vec<TextSpanEdit>)>,
    /// A command to run after the edits (or instead of them), if any.
    pub command: Option<CodeActionCommand>,
    /// True when the action carries `data` but neither an inline edit nor a
    /// command, so its edit must be fetched via `codeAction/resolve` first.
    pub needs_resolve: bool,
    /// The full original `CodeAction` serialized to JSON, kept only when
    /// `needs_resolve`. `codeAction/resolve` must round-trip the WHOLE action
    /// (ruff rejects a resolve missing `kind` with "No kind was given"), so we
    /// send this back verbatim rather than reconstructing from `title`+`data`.
    pub resolve_action: Option<serde_json::Value>,
    /// The server's "preferred" hint (VS Code's auto-fix target).
    pub is_preferred: bool,
}

#[derive(Debug)]
pub struct CodeActionResult {
    pub request_id: u64,
    /// The available actions. `None` means the request errored; `Some(vec![])`
    /// means the server ran but offered nothing here. The same shape is reused
    /// for a `codeAction/resolve` reply (a single, now-resolved item).
    pub items: Option<Vec<CodeActionItem>>,
    /// True when no spawned server advertises a usable `codeActionProvider`, so
    /// the app can say "no quick fixes available" distinctly from an empty list.
    pub unsupported: bool,
}

#[derive(Debug)]
pub struct FormatResult {
    pub request_id: u64,
    pub path: PathBuf,
    /// `None` when no server advertises `documentFormattingProvider`, the
    /// server declined, or it returned no edits. Otherwise the char-indexed
    /// spans to apply to the single formatted document. Unlike rename,
    /// `textDocument/formatting` only ever touches the requested file.
    pub edits: Option<Vec<TextSpanEdit>>,
    /// True when no spawned server advertises a usable
    /// `documentFormattingProvider`, so the app can tell "nothing to format"
    /// apart from "no formatter for this language".
    pub unsupported: bool,
    /// The server that answered, `None` when none did (#1511), so the app
    /// can attribute an empty reply to the formatter that sent it.
    pub server: Option<String>,
}

/// A fresh batch of semantic tokens for a document, pushed to the editor
/// to overlay on the tree-sitter highlights. Unlike the navigation
/// requests this carries no `request_id`: it is keyed by `path` + `seq`,
/// and the latest batch for the CURRENT text always wins. `data` is the raw relative-encoded LSP
/// array; the editor decodes it against its own buffer (where the text
/// lives) so UTF-16 columns convert to byte offsets correctly. `legend`
/// maps token-type indices to names.
#[derive(Debug)]
pub struct SemanticTokensUpdate {
    pub path: PathBuf,
    /// Echoes the edit sequence the request was fired for. The app drops a
    /// reply whose seq no longer matches the buffer — an external reload
    /// swaps the whole text while a request is still in the retry backoff,
    /// and decoding that batch over the new lines paints the old file's
    /// colours at the wrong offsets (and would poison the on-disk cache
    /// under the NEW content's key). Same guard as `InlayHintsUpdate`.
    pub seq: u64,
    /// Monotonic per-request stamp; the app drops a reply older than the
    /// newest one already applied for this path (see `semantic_generation`).
    pub generation: u64,
    pub data: Vec<u32>,
    pub legend: Arc<Vec<String>>,
    /// `true` for a whole-document `semanticTokens/full` batch, `false` for a
    /// viewport-only `semanticTokens/range` batch. The editor refuses to let a
    /// range batch overwrite a full one for the same file, so a range reply
    /// that arrives after the full document can never erase off-screen colour.
    pub is_full: bool,
}

/// One inlay hint from a language server (`textDocument/inlayHint`),
/// normalised off the LSP wire type: the label is already flattened
/// (label parts joined, padding folded in as spaces, newlines stripped)
/// so the editor splices it into the row verbatim. `character` is LSP
/// UTF-16; the editor converts it to a character column against its own
/// buffer, exactly as it does for diagnostics.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InlayHintItem {
    pub line: u32,
    pub character: u32,
    pub label: String,
}

/// A fresh, complete set of inlay hints for one document. `seq` echoes the
/// edit sequence the request was fired for; the app drops a reply whose seq
/// no longer matches the buffer (the hints were computed against old text).
#[derive(Debug)]
pub struct InlayHintsUpdate {
    pub path: PathBuf,
    pub seq: u64,
    pub hints: Vec<InlayHintItem>,
}

/// One server-resolved document link (#254): a UTF-16 range plus its
/// target URI string. Links the server left target-less are dropped at
/// normalisation (resolving them needs another round trip croft skips).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DocumentLinkItem {
    pub line: u32,
    pub character: u32,
    pub end_line: u32,
    pub end_character: u32,
    pub target: String,
}

/// One code lens (#608): the title the server gave it and the command it
/// runs, on a 0-based line.
#[derive(Debug, Clone, PartialEq)]
pub struct CodeLensItem {
    pub line: u32,
    pub title: String,
    pub command: Option<String>,
    pub arguments: Vec<serde_json::Value>,
    /// Whether the producing server lists the command in its
    /// `executeCommandProvider`, so croft can hand it back to run.
    pub server_side: bool,
}

/// A document's code lenses at one edit `seq` (#608).
#[derive(Debug)]
pub struct CodeLensUpdate {
    pub path: PathBuf,
    pub seq: u64,
    pub lenses: Vec<CodeLensItem>,
}

/// A fresh, complete link set for one document; same seq contract as
/// [`InlayHintsUpdate`].
#[derive(Debug)]
pub struct DocumentLinksUpdate {
    pub path: PathBuf,
    pub seq: u64,
    pub links: Vec<DocumentLinkItem>,
}

/// One server fold span (#254), 0-based inclusive line indexes matching
/// the editor's (header, end) fold model: collapsing hides
/// `start_line + 1 ..= end_line`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FoldingRangeItem {
    pub start_line: usize,
    pub end_line: usize,
    pub kind: FoldRangeKind,
}

/// The LSP folding-range kind, `Other` for servers that send none.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FoldRangeKind {
    Comment,
    Imports,
    Region,
    Other,
}

/// A complete fold-span set for one document; `seq` mirrors
/// [`InlayHintsUpdate`]'s staleness contract.
#[derive(Debug)]
pub struct FoldingRangesUpdate {
    pub path: PathBuf,
    pub seq: u64,
    pub ranges: Vec<FoldingRangeItem>,
}

/// One document color value (#254): the UTF-16 range of the literal and
/// its decoded RGB (alpha dropped — terminal cells can't blend). The
/// raw f32 channels ride along for the colorPresentation round trip.
#[derive(Debug, Clone, PartialEq)]
pub struct ColorItem {
    pub line: u32,
    pub character: u32,
    pub end_line: u32,
    pub end_character: u32,
    pub red: u8,
    pub green: u8,
    pub blue: u8,
    pub raw: (f32, f32, f32, f32),
}

/// A fresh, complete color set for one document; same seq contract as
/// [`InlayHintsUpdate`].
#[derive(Debug)]
pub struct DocumentColorsUpdate {
    pub path: PathBuf,
    pub seq: u64,
    pub colors: Vec<ColorItem>,
}

/// The alternative spellings of one color value (#254), each with the
/// char-indexed edits that rewrite the document to it. Answered for a
/// user-initiated picker, so every early-out replies (`presentations`
/// empty ⇒ nothing to offer).
#[derive(Debug)]
pub struct ColorPresentationsResult {
    pub request_id: u64,
    pub presentations: Vec<(String, Vec<TextSpanEdit>)>,
}

/// One row of a call-hierarchy answer: a caller (incoming) or callee
/// (outgoing), with the location the picker jumps to — the call expression
/// for incoming calls when the server reports one, the callee's definition
/// for outgoing. Positions are LSP UTF-16, like every navigation result.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CallSite {
    pub name: String,
    pub path: PathBuf,
    pub line: u32,
    pub character: u32,
}

/// Which hierarchy a [`CallHierarchyResult`] answers: calls either way, or
/// a type's supertypes / subtypes (#613), which share the picker.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HierarchyKind {
    IncomingCalls,
    OutgoingCalls,
    Supertypes,
    Subtypes,
}

impl HierarchyKind {
    /// How the status bar and picker name the rows.
    pub fn noun(self) -> &'static str {
        match self {
            HierarchyKind::IncomingCalls => "incoming calls",
            HierarchyKind::OutgoingCalls => "outgoing calls",
            HierarchyKind::Supertypes => "supertypes",
            HierarchyKind::Subtypes => "subtypes",
        }
    }
}

/// The callers or callees of the symbol at one caret position
/// (`prepareCallHierarchy` + `callHierarchy/incomingCalls|outgoingCalls`),
/// or the supertypes / subtypes of a type (#613), tagged with the request
/// id so stale replies drop.
#[derive(Debug)]
pub struct CallHierarchyResult {
    pub request_id: u64,
    pub kind: HierarchyKind,
    pub sites: Vec<CallSite>,
    /// True when no spawned server advertises the provider.
    pub unsupported: bool,
}

/// One occurrence of the symbol under the caret
/// (`textDocument/documentHighlight`), normalised off the LSP wire type.
/// Positions are LSP UTF-16; the editor converts them to character columns
/// against its own buffer, exactly as it does for diagnostics. `write` marks a
/// Write-kind highlight (VS Code tints those stronger than reads).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OccurrenceItem {
    pub start_line: u32,
    pub start_char: u32,
    pub end_line: u32,
    pub end_char: u32,
    pub write: bool,
}

/// The occurrences of the symbol at one caret position, tagged with the
/// request id so the app drops a reply the caret has since moved away from.
#[derive(Debug)]
pub struct DocumentHighlightsResult {
    pub request_id: u64,
    pub items: Vec<OccurrenceItem>,
}

/// One `textDocument/linkedEditingRange` answer (#254): the UTF-16
/// spans that rename together with the caret's, or empty when the caret
/// is not on a linked site. No `unsupported` flag — like occurrences,
/// the feature is a silent decoration that simply never activates for a
/// language without the provider.
#[derive(Debug)]
pub struct LinkedEditingResult {
    pub request_id: u64,
    /// `(start_line, start_char, end_line, end_char)` per span.
    pub ranges: Vec<(u32, u32, u32, u32)>,
}

/// One `textDocument/inlineCompletion` answer (LSP 3.18, #607): the
/// server's first suggestion, or `None` when it had nothing or failed.
#[derive(Debug)]
pub struct InlineCompletionResult {
    pub request_id: u64,
    pub item: Option<InlineItem>,
}

/// An inline completion as plain text, and the UTF-16 span
/// `(start_line, start_char, end_line, end_char)` it replaces when the
/// server gave one.
#[derive(Debug, PartialEq, Eq)]
pub struct InlineItem {
    pub text: String,
    pub range: Option<(u32, u32, u32, u32)>,
}

/// One `textDocument/selectionRange` answer (#254): a strictly-ordered
/// smallest-first chain of UTF-16 spans per requested position (the
/// server's parent links flattened), index-aligned with the request's
/// cursors. `unsupported` is true when the request could not be routed
/// (untracked doc, or no server advertises the provider) so the app can
/// fall back to tree-sitter ancestry immediately instead of waiting.
#[derive(Debug)]
pub struct SelectionRangesResult {
    pub request_id: u64,
    pub unsupported: bool,
    /// Per cursor: `(start_line, start_char, end_line, end_char)`.
    pub chains: Vec<Vec<(u32, u32, u32, u32)>>,
}

/// Severity of a diagnostic, normalised off the LSP `DiagnosticSeverity`
/// wire enum. Drives the underline colour the editor paints (VS Code: red
/// for errors, yellow for warnings, blue/teal for info & hints).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiagnosticSeverity {
    Error,
    Warning,
    Information,
    Hint,
}

/// One diagnostic from a language server, normalised off the LSP wire type.
/// Positions are LSP UTF-16 (`line`, `character`), zero-based; the editor
/// converts them to character columns against its own buffer, exactly as it
/// does for semantic tokens. A diagnostic can span several lines
/// (`start_line..=end_line`).
#[derive(Debug, Clone)]
pub struct Diagnostic {
    pub start_line: u32,
    pub start_char: u32,
    pub end_line: u32,
    pub end_char: u32,
    pub severity: DiagnosticSeverity,
    pub message: String,
    pub tags: DiagnosticTags,
    /// The rule the diagnostic reports (#1540): ruff's `F401`, ty's
    /// `invalid-argument-type`, TypeScript's `2322`.
    pub code: Option<DiagnosticCode>,
    /// The server that published it and its diagnostic as sent, `None` for
    /// one croft made itself.
    pub origin: Option<std::sync::Arc<DiagnosticOrigin>>,
}

/// Two diagnostics are the same finding when everything croft shows of them
/// matches. `origin` is left out: a server that reports one finding both
/// pushed and pulled may give each copy different `data`, and the copies
/// must still collapse into one row (`diagnostics_by_source`). The related
/// locations read from it are shown, though (#1523), so they count: a copy
/// that names them is never dropped for one that does not.
impl PartialEq for Diagnostic {
    fn eq(&self, other: &Self) -> bool {
        let Diagnostic {
            start_line,
            start_char,
            end_line,
            end_char,
            severity,
            message,
            tags,
            code,
            origin: _,
        } = self;
        (start_line, start_char, end_line, end_char)
            == (
                &other.start_line,
                &other.start_char,
                &other.end_line,
                &other.end_char,
            )
            && (severity, message, tags, code)
                == (&other.severity, &other.message, &other.tags, &other.code)
            && self.related() == other.related()
    }
}

/// A diagnostic exactly as a language server published it. A code-action
/// request hands it back to that server untouched: tsserver picks its fixes
/// by the error `code` and ruff reads its fix from `data`, so a diagnostic
/// rebuilt from croft's display fields got no quick fix at all (#1030).
#[derive(Debug, PartialEq)]
pub struct DiagnosticOrigin {
    pub server: String,
    pub wire: lsp_types::Diagnostic,
}

impl Diagnostic {
    /// The places the server points at to explain this diagnostic (#1523):
    /// rustc's "immutable borrow occurs here", TypeScript's "'foo' is
    /// declared here". Not stored on croft's diagnostic: built on demand
    /// from the server's own, kept in `origin`; one croft made itself has
    /// none.
    pub fn related(&self) -> Vec<RelatedLocation> {
        let Some(origin) = self.origin.as_deref() else {
            return Vec::new();
        };
        origin
            .wire
            .related_information
            .iter()
            .flatten()
            .filter_map(|r| {
                Some(RelatedLocation {
                    path: r.location.uri.to_file_path().ok()?,
                    line: r.location.range.start.line,
                    character: r.location.range.start.character,
                    message: r.message.clone(),
                })
            })
            .collect()
    }
}

/// One of a diagnostic's related locations (#1523): where its range starts,
/// zero-based with a UTF-16 column like the diagnostic's own position.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RelatedLocation {
    pub path: PathBuf,
    pub line: u32,
    pub character: u32,
    pub message: String,
}

impl RelatedLocation {
    /// `file(line, col): message`, one-based, as VS Code appends it to the
    /// diagnostic's hover, with the file relative to `root`.
    pub fn label(&self, root: &Path) -> String {
        let file = self.path.strip_prefix(root).unwrap_or(&self.path);
        format!(
            "{}({}, {}): {}",
            file.display(),
            self.line + 1,
            self.character + 1,
            one_line(&self.message)
        )
    }
}

/// `text` on one line, each line break (`\r\n`, `\n` or `\r`) a space: a
/// related location's message, which the hover and PROBLEMS show one
/// location to a line (#1523).
pub fn one_line(text: &str) -> String {
    text.replace("\r\n", " ").replace(['\r', '\n'], " ")
}

/// A diagnostic's rule code with the server's `source` and the rule's
/// documentation link, what a user needs to silence the rule or look it up
/// (#1540).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiagnosticCode {
    pub value: String,
    /// The diagnostic's own `source` (`Ruff`, `ty`, `ts`), if it named one.
    pub source: Option<String>,
    /// `codeDescription.href`, the rule's page.
    pub href: Option<String>,
}

impl DiagnosticCode {
    /// `source(code)` as VS Code writes it after the message, with `source`
    /// standing in when the diagnostic named none; just the code without
    /// either.
    pub fn label(&self, fallback_source: &str) -> String {
        let source = self.source.as_deref().unwrap_or(fallback_source);
        if source.is_empty() {
            self.value.clone()
        } else {
            format!("{source}({})", self.value)
        }
    }
}

/// The LSP `DiagnosticTag`s croft draws (#1522). Servers tag unused names
/// and unreachable code `Unnecessary`, which the editor fades instead of
/// underlining, and `Deprecated` API, which it strikes through.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct DiagnosticTags {
    pub unnecessary: bool,
    pub deprecated: bool,
}

impl DiagnosticTags {
    /// Whether the diagnostic carries a tag the editor draws on the text.
    pub fn any(self) -> bool {
        self.unnecessary || self.deprecated
    }
}

/// A fresh, COMPLETE set of diagnostics for one document from one server,
/// pushed via `textDocument/publishDiagnostics`. LSP always republishes the
/// whole list (an empty `diagnostics` means "all clear"), so each update
/// replaces the prior set for the same `(path, server)` pair. Keyed by
/// `server` too, so two servers analysing one file (e.g. ty + ruff) layer
/// their diagnostics instead of clobbering each other.
#[derive(Debug, Clone)]
pub struct DiagnosticsUpdate {
    pub path: PathBuf,
    pub server: String,
    pub diagnostics: Vec<Diagnostic>,
    /// The batch answers a pull (`textDocument/diagnostic` or
    /// `workspace/diagnostic`) rather than a `publishDiagnostics` push. A
    /// server can do both with different findings, rust-analyzer pulling
    /// its own analysis and pushing `cargo check`, so the two are kept
    /// apart and neither replaces the other (#1102).
    pub pulled: bool,
}

/// Marks the store entry holding what a server answered to a pull, beside
/// the entry of what it pushed (#1102). rust-analyzer answers a pull with
/// its own analysis and pushes the `cargo check` results; one entry per
/// server let each empty the other, so an open file showed no compile
/// errors. A server name never holds a NUL.
const PULLED_DIAGNOSTICS: &str = "\u{0}pulled";

/// The diagnostics store key for an update: its server's name, marked
/// when the update answers a pull.
pub fn diagnostics_store_key(u: &DiagnosticsUpdate) -> String {
    if u.pulled {
        format!("{}{PULLED_DIAGNOSTICS}", u.server)
    } else {
        u.server.clone()
    }
}

/// The server (or other source) a diagnostics store key names.
pub fn diagnostics_source(key: &str) -> &str {
    key.strip_suffix(PULLED_DIAGNOSTICS).unwrap_or(key)
}

/// One path's stored diagnostics, each with the source that reported it.
/// A server's pulled findings leave out any its push already carries, so a
/// server that reports the same finding both ways shows it once.
pub fn diagnostics_by_source(
    by_server: &std::collections::HashMap<String, Vec<Diagnostic>>,
) -> impl Iterator<Item = (&str, &Diagnostic)> {
    by_server.iter().flat_map(move |(key, diags)| {
        let source = diagnostics_source(key);
        let pushed = key
            .ends_with(PULLED_DIAGNOSTICS)
            .then(|| by_server.get(source))
            .flatten();
        diags
            .iter()
            .filter(move |d| !pushed.is_some_and(|p| p.contains(d)))
            .map(move |d| (source, d))
    })
}

/// Something a server tells the user rather than the editor: its work-done
/// progress and its `window/*` messages, in the order it sent them.
#[derive(Debug)]
pub struct ServerUpdate {
    pub server: String,
    pub event: ServerEvent,
}

#[derive(Debug)]
pub enum ServerEvent {
    /// A `$/progress` update: `Some(text)` while a task is running (Begin /
    /// Report) and `None` when it ends (End), so the app can show or clear
    /// the per-server status (e.g. "rust-analyzer: Indexing 112/340 33%").
    Progress(Option<String>),
    /// A `window/showMessage` the user should see (#1599): an error, a
    /// warning, or a note with a link in it, such as rust-analyzer's
    /// "Failed to load workspaces" or gopls's "open your browser to …".
    /// Other notes and every `window/logMessage` stay in OUTPUT.
    Message {
        /// Read by the tests, to prove the level is forwarded.
        #[cfg_attr(not(test), allow(dead_code))]
        level: lsp_types::MessageType,
        text: String,
    },
    /// A `window/showMessageRequest`: a question with `actions` to pick
    /// from. The pick, or `None` when the user dismisses it, goes back on
    /// `reply`; dropping `reply` answers `None` too.
    Question {
        text: String,
        actions: Vec<lsp_types::MessageActionItem>,
        reply: oneshot::Sender<Option<lsp_types::MessageActionItem>>,
    },
    /// A `window/showDocument`: open `uri` in a tab, or in the browser when
    /// `external`, with `selection` selected, moving keyboard focus to it
    /// only when `take_focus`. Whether it was shown goes back on `reply`;
    /// dropping `reply` answers "not shown".
    ShowDocument {
        uri: lsp_types::Url,
        external: bool,
        take_focus: bool,
        selection: Option<lsp_types::Range>,
        reply: oneshot::Sender<bool>,
    },
}

/// Whether a `window/showMessage` is worth interrupting the user for: an
/// error or a warning, or a note that points somewhere (gopls answers
/// "Browse documentation" with "open your browser to <url>"). Anything else
/// is chatter that OUTPUT keeps.
pub fn message_is_shown(level: lsp_types::MessageType, text: &str) -> bool {
    use lsp_types::MessageType as MT;
    level == MT::ERROR
        || level == MT::WARNING
        || (level == MT::INFO && (text.contains("https://") || text.contains("http://")))
}

enum Cmd {
    /// Gracefully shut every server down (LSP `shutdown`+`exit`, then await the
    /// child) and acknowledge on `done`. Sent by `LspManager`'s Drop so servers
    /// exit cleanly instead of being SIGKILLed by `kill_on_drop`.
    Shutdown {
        done: oneshot::Sender<()>,
    },
    OpenDoc {
        path: PathBuf,
        text: String,
    },
    /// Stop and start again the servers that serve `path` (#1621), leaving
    /// every other language's servers running.
    RestartServersFor {
        path: PathBuf,
    },
    /// Serve from `registry` from now on: the installed extensions or the
    /// disable set changed (#1842).
    ReplaceRegistry {
        registry: ServerRegistry,
    },
    /// Spawn the servers for every language whose project-root marker sits
    /// in the workspace root, before any file of theirs is opened (#27):
    /// rust-analyzer's cold indexing then overlaps with the user browsing
    /// the tree instead of starting at the first `.rs` open.
    PrewarmWorkspace,
    /// Replace the secondary workspace-root set (multi-root, #147): widens
    /// the project-root bound for future opens and prewarms roots that are
    /// new, so an added folder's servers start like a fresh workspace's.
    SetExtraRoots {
        roots: Vec<PathBuf>,
    },
    /// Pull whole-project diagnostics from every server that advertises
    /// `workspaceDiagnostics` (#533). Carries nothing: the previous result
    /// ids live with the client they were issued by.
    RequestWorkspaceDiagnostics,
    RequestSemanticTokens {
        path: PathBuf,
        seq: u64,
        generation: u64,
    },
    RequestSemanticTokensRange {
        path: PathBuf,
        start_line: u32,
        end: Position,
        seq: u64,
        generation: u64,
    },
    RequestInlayHints {
        path: PathBuf,
        end: Position,
        seq: u64,
    },
    RequestDocumentLinks {
        path: PathBuf,
        seq: u64,
    },
    RequestCodeLens {
        path: PathBuf,
        seq: u64,
    },
    RequestFoldingRanges {
        path: PathBuf,
        seq: u64,
    },
    RequestDocumentColors {
        path: PathBuf,
        seq: u64,
    },
    RequestColorPresentations {
        request_id: u64,
        path: PathBuf,
        color: (f32, f32, f32, f32),
        start: (u32, u32),
        end: (u32, u32),
    },
    ChangeDoc {
        path: PathBuf,
        text: String,
    },
    SaveDoc {
        path: PathBuf,
        text: String,
    },
    CloseDoc {
        path: PathBuf,
    },
    RequestCompletion {
        request_id: u64,
        path: PathBuf,
        line: u32,
        character: u32,
        trigger: CompletionTrigger,
    },
    ResolveCompletion {
        request_id: u64,
        path: PathBuf,
        item: Arc<lsp_types::CompletionItem>,
    },
    RequestSignatureHelp {
        request_id: u64,
        path: PathBuf,
        line: u32,
        character: u32,
    },
    RequestHover {
        request_id: u64,
        path: PathBuf,
        line: u32,
        character: u32,
    },
    RustAnalyzer {
        request_id: u64,
        path: PathBuf,
        request: crate::lsp::rust_analyzer::RaRequest,
        line: u32,
        character: u32,
    },
    RequestDefinition {
        request_id: u64,
        path: PathBuf,
        line: u32,
        character: u32,
    },
    RequestDocumentSymbols {
        path: PathBuf,
        seq: u64,
    },
    RequestDeclaration {
        request_id: u64,
        path: PathBuf,
        line: u32,
        character: u32,
    },
    RequestTypeDefinition {
        request_id: u64,
        path: PathBuf,
        line: u32,
        character: u32,
    },
    RequestImplementation {
        request_id: u64,
        path: PathBuf,
        line: u32,
        character: u32,
    },
    RequestWorkspaceSymbols {
        request_id: u64,
        query: String,
    },
    RequestReferences {
        request_id: u64,
        path: PathBuf,
        line: u32,
        character: u32,
    },
    RequestDocumentHighlights {
        request_id: u64,
        path: PathBuf,
        line: u32,
        character: u32,
    },
    RequestLinkedEditing {
        request_id: u64,
        path: PathBuf,
        line: u32,
        character: u32,
    },
    RequestInlineCompletion {
        request_id: u64,
        path: PathBuf,
        line: u32,
        character: u32,
    },
    RequestSelectionRanges {
        request_id: u64,
        path: PathBuf,
        positions: Vec<(u32, u32)>,
    },
    RequestCallHierarchy {
        request_id: u64,
        path: PathBuf,
        line: u32,
        character: u32,
        incoming: bool,
    },
    RequestTypeHierarchy {
        request_id: u64,
        path: PathBuf,
        line: u32,
        character: u32,
        supertypes: bool,
    },
    RequestRename {
        request_id: u64,
        path: PathBuf,
        line: u32,
        character: u32,
        new_name: String,
    },
    RequestPrepareRename {
        request_id: u64,
        path: PathBuf,
        line: u32,
        character: u32,
    },
    RequestWillRenameFiles {
        request_id: u64,
        renames: Vec<FileRenameOp>,
    },
    DidRenameFiles {
        renames: Vec<FileRenameOp>,
    },
    DidChangeWatchedFiles {
        changes: Vec<(PathBuf, lsp_types::FileChangeType)>,
    },
    RequestFormatting {
        request_id: u64,
        path: PathBuf,
        tab_size: u32,
        insert_spaces: bool,
    },
    RequestOnTypeFormatting {
        request_id: u64,
        path: PathBuf,
        line: u32,
        character: u32,
        ch: char,
        tab_size: u32,
        insert_spaces: bool,
    },
    RequestRangeFormatting {
        request_id: u64,
        path: PathBuf,
        start: (u32, u32),
        end: (u32, u32),
        tab_size: u32,
        insert_spaces: bool,
    },
    RequestCodeAction {
        request_id: u64,
        path: PathBuf,
        start_line: u32,
        start_char: u32,
        end_line: u32,
        end_char: u32,
        diagnostics: Vec<Diagnostic>,
    },
    ResolveCodeAction {
        request_id: u64,
        path: PathBuf,
        server: String,
        /// The full original `CodeAction` as JSON, sent back to the server intact.
        action: serde_json::Value,
    },
    ExecuteCommand {
        path: PathBuf,
        command: String,
        arguments: Vec<serde_json::Value>,
    },
}

/// Per-language support for the optional, capability-gated navigation methods,
/// published by the worker once a server has spawned and read synchronously by
/// the app at menu-build time. The app only shows "Go to Declaration" /
/// "Go to Type Definition" for languages whose server actually implements the
/// matching method (so Declaration is hidden for TypeScript, whose vtsls
/// advertises `declarationProvider: false`), mirroring VS Code.
#[derive(Default)]
struct LangCapabilitySupport {
    declaration: HashMap<Language, bool>,
    type_definition: HashMap<Language, bool>,
    implementation: HashMap<Language, bool>,
    references: HashMap<Language, bool>,
    formatting: HashMap<Language, bool>,
    code_action: HashMap<Language, bool>,
    call_hierarchy: HashMap<Language, bool>,
    /// The server instances, by (language, project root) as
    /// `request_inline_completion` picks them, one of whose running servers
    /// offers inline completions (#607).
    inline_completion: HashSet<ClientKey>,
    /// Whether a server for the language wants `willRenameFiles` (#610).
    will_rename: HashMap<Language, bool>,
    /// Concatenated on-type trigger characters per language (#254);
    /// a missing entry means "not probed yet".
    on_type_triggers: HashMap<Language, String>,
    /// The `triggerCharacters` of each server instance's completion server
    /// (#929), by (language, project root) as `request_completion` picks it;
    /// no entry while none of that instance's running servers completes.
    completion_triggers: HashMap<ClientKey, String>,
    /// The project root each open document's servers run at (#929), so a
    /// file's typed triggers are those of the server that answers it.
    document_roots: HashMap<PathBuf, PathBuf>,
    /// The servers reporting on each open document, by name (#851): the
    /// built-in Markdown lint stands down for a file only while rumdl
    /// reports on it. A document the app never opened here (one shown only
    /// in a split's other group) has no entry, and a server leaves the
    /// lists it was on when it is retired from document pulls or given up
    /// on after crashing.
    document_servers: HashMap<PathBuf, Vec<String>>,
    /// Every server open on each open document, by name (#1626), retired
    /// from document pulls or not: a server that let one diagnostic pull
    /// lapse still answers other requests, so this, not
    /// `document_servers`, says whether it serves the file.
    document_clients: HashMap<PathBuf, Vec<String>>,
}
type CapabilitySupport = Arc<StdMutex<LangCapabilitySupport>>;

/// The names of the servers `registry` registers, per language.
fn registered_servers_of(registry: &ServerRegistry) -> HashMap<Language, Vec<&'static str>> {
    registry
        .languages()
        .map(|lang| {
            let names = registry.for_language(lang).iter().map(|c| c.name).collect();
            (lang, names)
        })
        .collect()
}

pub struct LspManager {
    /// The servers registered per language once the disable set is
    /// applied (#1511), so the app can tell whether a server is in play.
    registered_servers: HashMap<Language, Vec<&'static str>>,
    /// Monotonic stamp handed to each semantic-token request. `seq`
    /// identifies CONTENT, not a request: `sync_lsp` and a server-driven
    /// refresh can have two full requests in flight at the same seq, and the
    /// retry loop emits an EMPTY batch after exhausting its backoff — so
    /// without an ordering stamp a late empty loser can blank a good overlay
    /// and be persisted to the content-keyed cache.
    semantic_generation: std::sync::atomic::AtomicU64,
    cmd_tx: tokio_mpsc::UnboundedSender<Cmd>,
    completion_rx: std_mpsc::Receiver<CompletionResult>,
    signature_help_rx: std_mpsc::Receiver<SignatureHelpResult>,
    hover_rx: std_mpsc::Receiver<HoverResult>,
    /// Test hook: a sender into `hover_rx`, so app tests can answer a
    /// hover request without a server.
    #[cfg(test)]
    hover_test_tx: std_mpsc::Sender<HoverResult>,
    rust_analyzer_rx: std_mpsc::Receiver<RustAnalyzerResult>,
    def_rx: std_mpsc::Receiver<DefinitionResult>,
    /// Test hooks: senders into the three jump channels, so app tests can
    /// answer a definition, declaration or type definition request
    /// without a server.
    #[cfg(test)]
    jump_test_tx: (
        std_mpsc::Sender<DefinitionResult>,
        std_mpsc::Sender<DeclarationResult>,
        std_mpsc::Sender<TypeDefinitionResult>,
    ),
    doc_symbols_rx: std_mpsc::Receiver<DocumentSymbolsResult>,
    decl_rx: std_mpsc::Receiver<DeclarationResult>,
    type_def_rx: std_mpsc::Receiver<TypeDefinitionResult>,
    impl_rx: std_mpsc::Receiver<ImplementationResult>,
    ref_rx: std_mpsc::Receiver<ReferencesResult>,
    doc_highlights_rx: std_mpsc::Receiver<DocumentHighlightsResult>,
    linked_editing_rx: std_mpsc::Receiver<LinkedEditingResult>,
    /// Test hook: a sender into `linked_editing_rx`, so app tests can
    /// answer a linkedEditingRange request without a server.
    #[cfg(test)]
    linked_editing_test_tx: std_mpsc::Sender<LinkedEditingResult>,
    inline_completion_rx: std_mpsc::Receiver<InlineCompletionResult>,
    /// Test hook: a sender into `inline_completion_rx`, so app tests can
    /// answer an inlineCompletion request without a server.
    #[cfg(test)]
    inline_completion_test_tx: std_mpsc::Sender<InlineCompletionResult>,
    /// Test hook: the text each document was last opened or changed with.
    #[cfg(test)]
    synced_texts: std::sync::Mutex<HashMap<PathBuf, String>>,
    selection_ranges_rx: std_mpsc::Receiver<SelectionRangesResult>,
    calls_rx: std_mpsc::Receiver<CallHierarchyResult>,
    ws_symbols_rx: std_mpsc::Receiver<WorkspaceSymbolsResult>,
    rename_rx: std_mpsc::Receiver<RenameResult>,
    prepare_rename_rx: std_mpsc::Receiver<PrepareRenameResult>,
    will_rename_files_rx: std_mpsc::Receiver<WillRenameFilesResult>,
    format_rx: std_mpsc::Receiver<FormatResult>,
    on_type_rx: std_mpsc::Receiver<FormatResult>,
    code_action_rx: std_mpsc::Receiver<CodeActionResult>,
    semantic_rx: std_mpsc::Receiver<SemanticTokensUpdate>,
    inlay_rx: std_mpsc::Receiver<InlayHintsUpdate>,
    links_rx: std_mpsc::Receiver<DocumentLinksUpdate>,
    code_lens_rx: std_mpsc::Receiver<CodeLensUpdate>,
    folding_rx: std_mpsc::Receiver<FoldingRangesUpdate>,
    colors_rx: std_mpsc::Receiver<DocumentColorsUpdate>,
    color_presentations_rx: std_mpsc::Receiver<ColorPresentationsResult>,
    diagnostics_rx: std_mpsc::Receiver<DiagnosticsUpdate>,
    /// Test hook: a sender into `diagnostics_rx`, so app tests can deliver
    /// a server's report without a server.
    #[cfg(test)]
    diagnostics_test_tx: std_mpsc::Sender<DiagnosticsUpdate>,
    progress_rx: std_mpsc::Receiver<ServerUpdate>,
    capability_support: CapabilitySupport,
    semantic_refresh: Arc<AtomicBool>,
    inlay_refresh: Arc<AtomicBool>,
    diagnostic_refresh: Arc<AtomicBool>,
    /// Set by the worker when it restarted a language server that exited
    /// (#694); see [`LspManager::take_servers_restarted`].
    servers_restarted: Arc<AtomicBool>,
    next_request_id: u64,
    /// Read by the app tests, to prove the servers follow a workspace change.
    #[cfg_attr(not(test), allow(dead_code))]
    workspace_root: PathBuf,
    _runtime: LspRuntime,
}

impl Drop for LspManager {
    fn drop(&mut self) {
        // Ask the worker to gracefully shut every server down, and block until
        // it acks. We run on the app's main thread (not inside the LSP runtime),
        // so block_on the runtime handle is valid. An overall cap keeps an
        // unresponsive server from hanging app exit; afterwards the fields drop
        // — `cmd_tx` closes the worker loop and `_runtime` joins the thread.
        let (done_tx, done_rx) = oneshot::channel();
        if self.cmd_tx.send(Cmd::Shutdown { done: done_tx }).is_ok() {
            let _ = self._runtime.handle().block_on(async {
                tokio::time::timeout(std::time::Duration::from_secs(3), done_rx).await
            });
        }
    }
}

/// Where a document ends, as an LSP position: the last line's index and its
/// length in UTF-16 units. A text ending in `\n` ends at the start of the
/// empty line after it. This is the end of a whole-document request range;
/// strict servers such as rust-analyzer reject any later end (#1490).
pub fn document_end(text: &str) -> Position {
    let line = text.matches('\n').count() as u32;
    let last = text.rsplit('\n').next().unwrap_or("");
    Position::new(line, last.encode_utf16().count() as u32)
}

/// The end of a range over a document's rows up to `end_row` (exclusive):
/// the start of that row, or the document's end when the range reaches it,
/// since a row past the last one is out of range (#1490).
pub fn rows_end(text: &str, end_row: u32) -> Position {
    let end = document_end(text);
    if end_row <= end.line {
        Position::new(end_row, 0)
    } else {
        end
    }
}

impl LspManager {
    pub fn new(workspace_root: PathBuf) -> Result<Self> {
        let runtime = LspRuntime::new()?;
        let (cmd_tx, cmd_rx) = tokio_mpsc::unbounded_channel();
        let (completion_tx, completion_rx) = std_mpsc::channel();
        let (signature_help_tx, signature_help_rx) = std_mpsc::channel();
        let (hover_tx, hover_rx) = std_mpsc::channel();
        #[cfg(test)]
        let hover_test_tx = hover_tx.clone();
        let (rust_analyzer_tx, rust_analyzer_rx) = std_mpsc::channel();
        let (def_tx, def_rx) = std_mpsc::channel();
        let (doc_symbols_tx, doc_symbols_rx) = std_mpsc::channel();
        let (decl_tx, decl_rx) = std_mpsc::channel();
        let (type_def_tx, type_def_rx) = std_mpsc::channel();
        #[cfg(test)]
        let jump_test_tx = (def_tx.clone(), decl_tx.clone(), type_def_tx.clone());
        let (impl_tx, impl_rx) = std_mpsc::channel();
        let (ref_tx, ref_rx) = std_mpsc::channel();
        let (doc_highlights_tx, doc_highlights_rx) = std_mpsc::channel();
        let (linked_editing_tx, linked_editing_rx) = std_mpsc::channel();
        #[cfg(test)]
        let linked_editing_test_tx = linked_editing_tx.clone();
        let (inline_completion_tx, inline_completion_rx) = std_mpsc::channel();
        #[cfg(test)]
        let inline_completion_test_tx = inline_completion_tx.clone();
        let (selection_ranges_tx, selection_ranges_rx) = std_mpsc::channel();
        let (calls_tx, calls_rx) = std_mpsc::channel();
        let (ws_symbols_tx, ws_symbols_rx) = std_mpsc::channel();
        let (rename_tx, rename_rx) = std_mpsc::channel();
        let (prepare_rename_tx, prepare_rename_rx) = std_mpsc::channel();
        let (will_rename_files_tx, will_rename_files_rx) = std_mpsc::channel();
        let (format_tx, format_rx) = std_mpsc::channel();
        let (on_type_tx, on_type_rx) = std_mpsc::channel();
        let (code_action_tx, code_action_rx) = std_mpsc::channel();
        let (semantic_tx, semantic_rx) = std_mpsc::channel();
        let (inlay_tx, inlay_rx) = std_mpsc::channel();
        let (links_tx, links_rx) = std_mpsc::channel();
        let (code_lens_tx, code_lens_rx) = std_mpsc::channel();
        let (folding_tx, folding_rx) = std_mpsc::channel();
        let (colors_tx, colors_rx) = std_mpsc::channel();
        let (color_presentations_tx, color_presentations_rx) = std_mpsc::channel();
        let (diagnostics_tx, diagnostics_rx) = std_mpsc::channel();
        #[cfg(test)]
        let diagnostics_test_tx = diagnostics_tx.clone();
        let (progress_tx, progress_rx) = std_mpsc::channel();
        let capability_support: CapabilitySupport =
            Arc::new(StdMutex::new(LangCapabilitySupport::default()));
        let semantic_refresh = Arc::new(AtomicBool::new(false));
        let inlay_refresh = Arc::new(AtomicBool::new(false));
        let diagnostic_refresh = Arc::new(AtomicBool::new(false));
        let servers_restarted = Arc::new(AtomicBool::new(false));
        let root = workspace_root.clone();
        // Load user-installed extensions (`~/.config/croft/extensions`) and merge
        // them with the bundled ones. The language table must be initialised
        // before the first file open resolves a language, and the registry must
        // see the same user servers, so both are built from one read here.
        let user_sources = crate::lsp::manifest::read_extension_sources(
            &crate::lsp::manifest::user_extensions_dir(),
        );
        let user_refs: Vec<&str> = user_sources.iter().map(String::as_str).collect();
        // The language table keeps every language identity (so file detection and
        // highlighting stay intact); only server registration honors the disable
        // set, so a disabled LSP extension stops spawning without losing its
        // language. The set is read from prefs at construction; a live add,
        // removal or toggle reaches a running manager through
        // `reload_extensions`.
        crate::lsp::languages::reload_with_user_sources(&user_refs);
        let disabled = crate::prefs::Prefs::load_or_default().disabled_extensions;
        let registry = ServerRegistry::with_user_extensions_filtered(&user_refs, &disabled);
        let registered_servers = registered_servers_of(&registry);
        runtime.handle().spawn(worker_loop(
            root,
            registry,
            cmd_rx,
            ResultSenders {
                completion: completion_tx,
                signature_help: signature_help_tx,
                hover: hover_tx,
                rust_analyzer: rust_analyzer_tx,
                definition: def_tx,
                document_symbols: doc_symbols_tx,
                declaration: decl_tx,
                type_definition: type_def_tx,
                implementation: impl_tx,
                references: ref_tx,
                document_highlights: doc_highlights_tx,
                linked_editing: linked_editing_tx,
                inline_completion: inline_completion_tx,
                selection_ranges: selection_ranges_tx,
                call_hierarchy: calls_tx,
                workspace_symbols: ws_symbols_tx,
                rename: rename_tx,
                prepare_rename: prepare_rename_tx,
                will_rename_files: will_rename_files_tx,
                formatting: format_tx,
                on_type_formatting: on_type_tx,
                code_action: code_action_tx,
                semantic_tokens: semantic_tx,
                inlay_hints: inlay_tx,
                document_links: links_tx,
                code_lens: code_lens_tx,
                folding_ranges: folding_tx,
                document_colors: colors_tx,
                color_presentations: color_presentations_tx,
                diagnostics: diagnostics_tx,
                progress: progress_tx,
            },
            capability_support.clone(),
            semantic_refresh.clone(),
            inlay_refresh.clone(),
            diagnostic_refresh.clone(),
            servers_restarted.clone(),
        ));
        Ok(Self {
            registered_servers,
            semantic_generation: std::sync::atomic::AtomicU64::new(0),
            cmd_tx,
            completion_rx,
            signature_help_rx,
            hover_rx,
            #[cfg(test)]
            hover_test_tx,
            rust_analyzer_rx,
            def_rx,
            #[cfg(test)]
            jump_test_tx,
            doc_symbols_rx,
            decl_rx,
            type_def_rx,
            impl_rx,
            ref_rx,
            doc_highlights_rx,
            linked_editing_rx,
            #[cfg(test)]
            linked_editing_test_tx,
            inline_completion_rx,
            #[cfg(test)]
            inline_completion_test_tx,
            #[cfg(test)]
            synced_texts: Default::default(),
            selection_ranges_rx,
            calls_rx,
            ws_symbols_rx,
            rename_rx,
            prepare_rename_rx,
            will_rename_files_rx,
            format_rx,
            on_type_rx,
            code_action_rx,
            semantic_rx,
            inlay_rx,
            links_rx,
            code_lens_rx,
            folding_rx,
            colors_rx,
            color_presentations_rx,
            diagnostics_rx,
            #[cfg(test)]
            diagnostics_test_tx,
            progress_rx,
            capability_support,
            semantic_refresh,
            inlay_refresh,
            diagnostic_refresh,
            servers_restarted,
            next_request_id: 1,
            workspace_root,
            _runtime: runtime,
        })
    }

    #[cfg_attr(not(test), allow(dead_code))]
    pub fn workspace_root(&self) -> &Path {
        &self.workspace_root
    }

    pub fn open_doc(&self, path: PathBuf, text: String) {
        #[cfg(test)]
        self.record_synced_text(&path, &text);
        let _ = self.cmd_tx.send(Cmd::OpenDoc { path, text });
    }

    /// Pre-warm the workspace's evident language servers (VS Code's
    /// `workspaceContains` activation). Inert under test: the suite builds
    /// hundreds of Apps in marker-bearing tempdirs and must never spawn a
    /// real rust-analyzer as a construction side effect.
    pub fn prewarm_workspace(&self) {
        if cfg!(test) {
            return;
        }
        let _ = self.cmd_tx.send(Cmd::PrewarmWorkspace);
    }

    /// Replace the secondary workspace-root set (multi-root, #147). Inert
    /// under `cfg(test)` like `prewarm_workspace`, for the same reason:
    /// test-built Apps must never spawn real servers.
    pub fn set_extra_roots(&self, roots: Vec<PathBuf>) {
        if cfg!(test) {
            return;
        }
        let _ = self.cmd_tx.send(Cmd::SetExtraRoots { roots });
    }

    pub fn change_doc(&self, path: PathBuf, text: String) {
        #[cfg(test)]
        self.record_synced_text(&path, &text);
        let _ = self.cmd_tx.send(Cmd::ChangeDoc { path, text });
    }

    /// Notify the servers a document was written to disk. rust-analyzer only
    /// re-runs its check-on-save (`cargo check`, the source of most Rust
    /// PROBLEMS entries) on `textDocument/didSave`.
    ///
    /// `text` is the buffer as saved, in the form `change_doc` sends it. Only
    /// a server whose `save` options ask for `includeText` receives it, and
    /// only a server that asked for saves at all is notified (#854).
    pub fn save_doc(&self, path: PathBuf, text: String) {
        let _ = self.cmd_tx.send(Cmd::SaveDoc { path, text });
    }

    pub fn close_doc(&self, path: PathBuf) {
        let _ = self.cmd_tx.send(Cmd::CloseDoc { path });
    }

    /// Restart the servers serving `path` (#1621): the user's "Language
    /// Servers: Restart for This File". The app re-opens its tabs when they
    /// are back, as after a crash restart.
    pub fn restart_servers_for(&self, path: PathBuf) {
        let _ = self.cmd_tx.send(Cmd::RestartServersFor { path });
    }

    /// Follow an extension added, removed, turned on or off (#1842):
    /// `user_sources` are the installed manifests now and `disabled` the
    /// disable set. Their languages resolve at once, and when that changes
    /// which servers a language registers, the worker swaps the new set in:
    /// that language's running servers stop, and the app re-opens its tabs,
    /// so the next of its files starts what is registered now. Every other
    /// language's servers keep running. Returns the servers no language
    /// registers any more.
    pub fn reload_extensions(
        &mut self,
        user_sources: &[&str],
        disabled: &std::collections::BTreeSet<String>,
    ) -> Vec<&'static str> {
        crate::lsp::languages::reload_with_user_sources(user_sources);
        let registry = ServerRegistry::with_user_extensions_filtered(user_sources, disabled);
        let registered = registered_servers_of(&registry);
        if registered == self.registered_servers {
            return Vec::new();
        }
        let kept: std::collections::HashSet<&str> =
            registered.values().flatten().copied().collect();
        let mut gone: Vec<&'static str> = self
            .registered_servers
            .values()
            .flatten()
            .copied()
            .filter(|name| !kept.contains(name))
            .collect();
        gone.sort_unstable();
        gone.dedup();
        self.registered_servers = registered;
        let _ = self.cmd_tx.send(Cmd::ReplaceRegistry { registry });
        gone
    }

    /// Ask for completions at a UTF-16 position, saying why: a re-ask as
    /// the user types into a list the server marked incomplete (#1529), or
    /// a typed trigger character (#929).
    pub fn request_completion(
        &mut self,
        path: PathBuf,
        line: u32,
        character: u32,
        trigger: CompletionTrigger,
    ) -> u64 {
        self.send_request(|request_id| Cmd::RequestCompletion {
            request_id,
            path,
            line,
            character,
            trigger,
        })
    }

    /// Allocate the next request id, send the command `make` builds around
    /// it, and return the id the reply will echo.
    fn send_request(&mut self, make: impl FnOnce(u64) -> Cmd) -> u64 {
        let id = self.next_request_id;
        self.next_request_id += 1;
        let _ = self.cmd_tx.send(make(id));
        id
    }

    /// Ask the completion server for the rest of an item it listed (#928).
    /// The reply comes through [`Self::drain_completion`] with this id, its
    /// one item the resolved one, or none when the server failed.
    pub fn request_completion_resolve(
        &mut self,
        path: PathBuf,
        item: Arc<lsp_types::CompletionItem>,
    ) -> u64 {
        self.send_request(|request_id| Cmd::ResolveCompletion {
            request_id,
            path,
            item,
        })
    }

    pub fn drain_completion(&self) -> Option<CompletionResult> {
        self.completion_rx.try_recv().ok()
    }

    pub fn request_signature_help(&mut self, path: PathBuf, line: u32, character: u32) -> u64 {
        self.send_request(|request_id| Cmd::RequestSignatureHelp {
            request_id,
            path,
            line,
            character,
        })
    }

    pub fn drain_signature_help(&self) -> Option<SignatureHelpResult> {
        self.signature_help_rx.try_recv().ok()
    }

    pub fn request_hover(&mut self, path: PathBuf, line: u32, character: u32) -> u64 {
        self.send_request(|request_id| Cmd::RequestHover {
            request_id,
            path,
            line,
            character,
        })
    }

    pub fn drain_hover(&self) -> Option<HoverResult> {
        self.hover_rx.try_recv().ok()
    }

    /// Test hook: deliver a hover reply as if a server had answered.
    #[cfg(test)]
    pub fn push_hover_for_test(&self, result: HoverResult) {
        self.hover_test_tx.send(result).expect("hover channel open");
    }

    /// Send one of rust-analyzer's own requests (#1626) for the caret at
    /// UTF-16 `(line, character)` in `path`; the answer arrives on
    /// [`LspManager::drain_rust_analyzer`] under the returned id.
    pub fn request_rust_analyzer(
        &mut self,
        path: PathBuf,
        request: crate::lsp::rust_analyzer::RaRequest,
        line: u32,
        character: u32,
    ) -> u64 {
        let id = self.next_request_id;
        self.next_request_id += 1;
        let _ = self.cmd_tx.send(Cmd::RustAnalyzer {
            request_id: id,
            path,
            request,
            line,
            character,
        });
        id
    }

    pub fn drain_rust_analyzer(&self) -> Option<RustAnalyzerResult> {
        self.rust_analyzer_rx.try_recv().ok()
    }

    /// Ask the server for the whole document's semantic tokens. Fire this
    /// on open and (debounced) after edits. The reply carries two stamps and
    /// the app needs both: `seq` identifies the document CONTENT the batch
    /// was computed against (so a reply that outlived an external reload is
    /// dropped), while `generation` orders overlapping requests for the same
    /// path (two can be in flight at one `seq`, and the retry loop emits an
    /// empty batch once its backoff runs out, so the loser must not win).
    /// A no-op for languages whose server advertises no
    /// `semanticTokensProvider`.
    pub fn request_semantic_tokens(&self, path: PathBuf, seq: u64) {
        let generation = self.next_semantic_generation();
        let _ = self.cmd_tx.send(Cmd::RequestSemanticTokens {
            path,
            seq,
            generation,
        });
    }

    fn next_semantic_generation(&self) -> u64 {
        self.semantic_generation
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed)
    }

    /// Ask the server for semantic tokens covering only `start_line` up to
    /// `end` (zero-based, end exclusive; see [`rows_end`]). Fire this on open
    /// with the editor's viewport so the visible code colours immediately,
    /// ahead of the whole-file request.
    pub fn request_semantic_tokens_range(
        &self,
        path: PathBuf,
        start_line: u32,
        end: Position,
        seq: u64,
    ) {
        let generation = self.next_semantic_generation();
        let _ = self.cmd_tx.send(Cmd::RequestSemanticTokensRange {
            path,
            start_line,
            end,
            seq,
            generation,
        });
    }

    pub fn drain_semantic_tokens(&self) -> Option<SemanticTokensUpdate> {
        self.semantic_rx.try_recv().ok()
    }

    /// Ask the server for the whole document's inlay hints. Fire-and-forget
    /// like the semantic-token requests; the reply lands in
    /// [`drain_inlay_hints`] tagged with `seq` so the app can drop a stale
    /// batch. A no-op when no spawned server advertises an `inlayHintProvider`.
    /// `end` is where the document ends ([`document_end`]).
    pub fn request_inlay_hints(&self, path: PathBuf, end: Position, seq: u64) {
        let _ = self.cmd_tx.send(Cmd::RequestInlayHints { path, end, seq });
    }

    pub fn drain_inlay_hints(&self) -> Option<InlayHintsUpdate> {
        self.inlay_rx.try_recv().ok()
    }

    /// Ask for the document's link set (#254); fire-and-forget on the
    /// open/change cadence, silent when no server advertises a
    /// documentLinkProvider.
    pub fn request_document_links(&self, path: PathBuf, seq: u64) {
        let _ = self.cmd_tx.send(Cmd::RequestDocumentLinks { path, seq });
    }

    pub fn drain_document_links(&self) -> Option<DocumentLinksUpdate> {
        self.links_rx.try_recv().ok()
    }

    /// Ask for the document's code lenses (#608); the reply carries `seq`.
    pub fn request_code_lens(&self, path: PathBuf, seq: u64) {
        let _ = self.cmd_tx.send(Cmd::RequestCodeLens { path, seq });
    }

    pub fn drain_code_lens(&self) -> Option<CodeLensUpdate> {
        self.code_lens_rx.try_recv().ok()
    }

    /// Ask the server for the document's fold spans (#254). Fire-and-forget
    /// on the same open/change cadence as inlay hints; the reply lands in
    /// [`drain_folding_ranges`] tagged with `seq`. A no-op when no spawned
    /// server advertises a `foldingRangeProvider`, which is what keeps the
    /// editor's indentation scan authoritative there.
    pub fn request_folding_ranges(&self, path: PathBuf, seq: u64) {
        let _ = self.cmd_tx.send(Cmd::RequestFoldingRanges { path, seq });
    }

    pub fn drain_folding_ranges(&self) -> Option<FoldingRangesUpdate> {
        self.folding_rx.try_recv().ok()
    }

    /// Ask for the document's color values (#254); same fire-and-forget
    /// seq contract as inlay hints, silent when no server advertises a
    /// colorProvider — the swatches simply never appear.
    pub fn request_document_colors(&self, path: PathBuf, seq: u64) {
        let _ = self.cmd_tx.send(Cmd::RequestDocumentColors { path, seq });
    }

    pub fn drain_document_colors(&self) -> Option<DocumentColorsUpdate> {
        self.colors_rx.try_recv().ok()
    }

    /// Ask for one color value's alternative spellings (#254); the reply
    /// always arrives (a picker is waiting on it).
    pub fn request_color_presentations(
        &mut self,
        path: PathBuf,
        color: (f32, f32, f32, f32),
        start: (u32, u32),
        end: (u32, u32),
    ) -> u64 {
        self.send_request(|request_id| Cmd::RequestColorPresentations {
            request_id,
            path,
            color,
            start,
            end,
        })
    }

    pub fn drain_color_presentations(&self) -> Option<ColorPresentationsResult> {
        self.color_presentations_rx.try_recv().ok()
    }

    /// Returns and clears the "a server asked us to re-request inlay hints"
    /// flag, set by any client that received `workspace/inlayHint/refresh`.
    /// Mirrors [`take_semantic_refresh`](Self::take_semantic_refresh).
    pub fn take_inlay_refresh(&self) -> bool {
        self.inlay_refresh.swap(false, Ordering::Relaxed)
    }

    /// Pop the next server-pushed diagnostics batch, if any. Each batch is the
    /// complete set for one `(path, server)` pair; the app keeps a per-file,
    /// per-server store so layering and "all clear" (empty batch) both work.
    /// A server no extension registers now (#1842) may still have reports
    /// queued or in flight from before it stopped: only its withdrawals
    /// come through, so nothing it says lands where nothing would clear it.
    pub fn drain_diagnostics(&self) -> Option<DiagnosticsUpdate> {
        loop {
            let u = self.diagnostics_rx.try_recv().ok()?;
            let registered = self
                .registered_servers
                .values()
                .any(|names| names.contains(&u.server.as_str()));
            if registered || u.diagnostics.is_empty() {
                return Some(u);
            }
        }
    }

    /// Test hook: deliver `update` as if a server had published it.
    #[cfg(test)]
    pub fn push_diagnostics_for_test(&self, update: DiagnosticsUpdate) {
        let _ = self.diagnostics_test_tx.send(update);
    }

    /// Pop the next server progress update or `window/*` message, if any.
    /// The app keeps a per-server progress map so the status bar can show or
    /// clear "Indexing…", and shows the messages.
    pub fn drain_server_update(&self) -> Option<ServerUpdate> {
        self.progress_rx.try_recv().ok()
    }

    /// Returns and clears the "a server asked us to re-pull semantic tokens"
    /// flag, set by any client that received `workspace/semanticTokens/refresh`
    /// (rust-analyzer does this once its analysis upgrades the token set). The
    /// app re-requests tokens for the visible editor(s) when this is true.
    pub fn take_semantic_refresh(&self) -> bool {
        self.semantic_refresh.swap(false, Ordering::Relaxed)
    }

    /// Returns and clears the "a language server was restarted" flag (#694).
    /// The restarted server knows no documents, so the app answers by
    /// re-opening every tab against it.
    pub fn take_servers_restarted(&self) -> bool {
        self.servers_restarted.swap(false, Ordering::Relaxed)
    }

    /// Returns and clears the "a server asked us to re-pull workspace
    /// diagnostics" flag, set by any client that received
    /// `workspace/diagnostic/refresh` (#533). Mirrors
    /// [`take_semantic_refresh`](Self::take_semantic_refresh).
    pub fn take_diagnostic_refresh(&self) -> bool {
        self.diagnostic_refresh.swap(false, Ordering::Relaxed)
    }

    /// Pull whole-project diagnostics (LSP 3.17 `workspace/diagnostic`) from
    /// every spawned server that advertises `workspaceDiagnostics` (#533).
    ///
    /// Fire-and-forget: reports land in [`drain_diagnostics`] as ordinary
    /// per-file batches, keyed by the same server name the PUSH path uses, so
    /// PROBLEMS shows a file no editor has open without a manual command.
    /// A no-op when no server advertises the capability - the request is
    /// never sent, so a server that pulls per document only is untouched.
    pub fn request_workspace_diagnostics(&self) {
        let _ = self.cmd_tx.send(Cmd::RequestWorkspaceDiagnostics);
    }

    pub fn request_definition(&mut self, path: PathBuf, line: u32, character: u32) -> u64 {
        self.send_request(|request_id| Cmd::RequestDefinition {
            request_id,
            path,
            line,
            character,
        })
    }

    pub fn drain_definition(&self) -> Option<DefinitionResult> {
        self.def_rx.try_recv().ok()
    }

    /// Test hook: deliver a definition reply as if a server had answered.
    #[cfg(test)]
    pub fn push_definition_for_test(&self, result: DefinitionResult) {
        let _ = self.jump_test_tx.0.send(result);
    }

    /// Test hook: deliver a declaration reply as if a server had answered.
    #[cfg(test)]
    pub fn push_declaration_for_test(&self, result: DeclarationResult) {
        let _ = self.jump_test_tx.1.send(result);
    }

    /// Test hook: deliver a type definition reply as if a server had
    /// answered.
    #[cfg(test)]
    pub fn push_type_definition_for_test(&self, result: TypeDefinitionResult) {
        let _ = self.jump_test_tx.2.send(result);
    }

    /// Ask the server for the document's symbol tree (the Outline). Fire on
    /// open, on the active editor tab changing, and (debounced) after edits;
    /// the freshest reply for the active file wins. `seq` is echoed back in
    /// the result so the app can drop a reply answering an older buffer than
    /// the newest request (a stale reply's shifted ranges made the
    /// breadcrumb's symbol crumb flicker while typing on a slow server).
    pub fn request_document_symbols(&self, path: PathBuf, seq: u64) {
        let _ = self.cmd_tx.send(Cmd::RequestDocumentSymbols { path, seq });
    }

    pub fn drain_document_symbols(&self) -> Option<DocumentSymbolsResult> {
        self.doc_symbols_rx.try_recv().ok()
    }

    pub fn request_declaration(&mut self, path: PathBuf, line: u32, character: u32) -> u64 {
        self.send_request(|request_id| Cmd::RequestDeclaration {
            request_id,
            path,
            line,
            character,
        })
    }

    pub fn drain_declaration(&self) -> Option<DeclarationResult> {
        self.decl_rx.try_recv().ok()
    }

    pub fn request_type_definition(&mut self, path: PathBuf, line: u32, character: u32) -> u64 {
        self.send_request(|request_id| Cmd::RequestTypeDefinition {
            request_id,
            path,
            line,
            character,
        })
    }

    pub fn drain_type_definition(&self) -> Option<TypeDefinitionResult> {
        self.type_def_rx.try_recv().ok()
    }

    pub fn request_implementation(&mut self, path: PathBuf, line: u32, character: u32) -> u64 {
        self.send_request(|request_id| Cmd::RequestImplementation {
            request_id,
            path,
            line,
            character,
        })
    }

    pub fn drain_implementation(&self) -> Option<ImplementationResult> {
        self.impl_rx.try_recv().ok()
    }

    pub fn request_references(&mut self, path: PathBuf, line: u32, character: u32) -> u64 {
        self.send_request(|request_id| Cmd::RequestReferences {
            request_id,
            path,
            line,
            character,
        })
    }

    /// Fire a `workspace/symbol` query at every running server that
    /// supports it; the merged reply arrives via
    /// [`Self::drain_workspace_symbols`] tagged with the returned id.
    pub fn request_workspace_symbols(&mut self, query: String) -> u64 {
        self.send_request(|request_id| Cmd::RequestWorkspaceSymbols { request_id, query })
    }

    pub fn drain_workspace_symbols(&self) -> Option<WorkspaceSymbolsResult> {
        self.ws_symbols_rx.try_recv().ok()
    }

    pub fn drain_references(&self) -> Option<ReferencesResult> {
        self.ref_rx.try_recv().ok()
    }

    /// Fire a `textDocument/documentHighlight` for the symbol at the caret;
    /// the reply arrives via [`Self::drain_document_highlights`] tagged with
    /// the returned id. Silent when no server supports the method — the app
    /// simply never gets a reply to paint.
    pub fn request_document_highlights(&mut self, path: PathBuf, line: u32, character: u32) -> u64 {
        self.send_request(|request_id| Cmd::RequestDocumentHighlights {
            request_id,
            path,
            line,
            character,
        })
    }

    pub fn drain_document_highlights(&self) -> Option<DocumentHighlightsResult> {
        self.doc_highlights_rx.try_recv().ok()
    }

    /// Ask which spans rename together with the caret's (#254). Same
    /// fire-and-forget id contract as occurrences; no reply arrives for
    /// a language without the provider.
    pub fn request_linked_editing(&mut self, path: PathBuf, line: u32, character: u32) -> u64 {
        self.send_request(|request_id| Cmd::RequestLinkedEditing {
            request_id,
            path,
            line,
            character,
        })
    }

    /// Ask for the Expand Selection chains at every cursor (#254): one
    /// request carries all positions, primary first. Returns the request
    /// id the reply will echo.
    pub fn request_selection_ranges(&mut self, path: PathBuf, positions: Vec<(u32, u32)>) -> u64 {
        self.send_request(|request_id| Cmd::RequestSelectionRanges {
            request_id,
            path,
            positions,
        })
    }

    pub fn drain_linked_editing(&self) -> Option<LinkedEditingResult> {
        self.linked_editing_rx.try_recv().ok()
    }

    /// Test hook: deliver `result` as if a server had answered.
    #[cfg(test)]
    pub fn push_linked_editing_for_test(&self, result: LinkedEditingResult) {
        let _ = self.linked_editing_test_tx.send(result);
    }

    /// Ask the server that offers inline completions for ghost text at the
    /// caret (#607). Returns the id the reply echoes; no reply arrives for a
    /// document no such server has.
    pub fn request_inline_completion(&mut self, path: PathBuf, line: u32, character: u32) -> u64 {
        self.send_request(|request_id| Cmd::RequestInlineCompletion {
            request_id,
            path,
            line,
            character,
        })
    }

    pub fn drain_inline_completion(&self) -> Option<InlineCompletionResult> {
        self.inline_completion_rx.try_recv().ok()
    }

    /// Test hook: deliver `result` as if a server had answered.
    #[cfg(test)]
    pub fn push_inline_completion_for_test(&self, result: InlineCompletionResult) {
        let _ = self.inline_completion_test_tx.send(result);
    }

    pub fn drain_selection_ranges(&self) -> Option<SelectionRangesResult> {
        self.selection_ranges_rx.try_recv().ok()
    }

    /// Fire a call-hierarchy expansion (callers when `incoming`, callees
    /// otherwise) for the symbol at the caret; the reply arrives via
    /// [`Self::drain_call_hierarchy`] tagged with the returned id.
    pub fn request_call_hierarchy(
        &mut self,
        path: PathBuf,
        line: u32,
        character: u32,
        incoming: bool,
    ) -> u64 {
        self.send_request(|request_id| Cmd::RequestCallHierarchy {
            request_id,
            path,
            line,
            character,
            incoming,
        })
    }

    pub fn drain_call_hierarchy(&self) -> Option<CallHierarchyResult> {
        self.calls_rx.try_recv().ok()
    }

    /// The supertypes or subtypes of the type at a position (#613); the
    /// reply arrives on the call-hierarchy drain with its [`HierarchyKind`].
    pub fn request_type_hierarchy(
        &mut self,
        path: PathBuf,
        line: u32,
        character: u32,
        supertypes: bool,
    ) -> u64 {
        self.send_request(|request_id| Cmd::RequestTypeHierarchy {
            request_id,
            path,
            line,
            character,
            supertypes,
        })
    }

    /// Whether any running server wants `willRenameFiles` (#610). When none
    /// does, an Explorer move runs at once instead of waiting on an answer
    /// that can only be empty.
    pub fn any_server_wants_file_renames(&self) -> bool {
        self.capability_support
            .lock()
            .is_ok_and(|s| s.will_rename.values().any(|w| *w))
    }

    /// Whether the server named `name` reports on the open document `path`
    /// (#851). Read synchronously by the app: the built-in Markdown lint
    /// stands down for a file rumdl, which covers its rules, reports on.
    pub fn document_reported_by(&self, path: &Path, name: &str) -> bool {
        self.capability_support.lock().is_ok_and(|s| {
            s.document_servers
                .get(path)
                .is_some_and(|names| names.iter().any(|n| n == name))
        })
    }

    /// Whether the server named `name` is registered for `lang`, i.e. no
    /// disabled extension removed it (#1511).
    pub fn server_registered(&self, lang: Language, name: &str) -> bool {
        self.registered_servers
            .get(&lang)
            .is_some_and(|names| names.contains(&name))
    }

    /// Test hook: replace the servers registered for `lang`, as a disabled
    /// or added extension would.
    #[cfg(test)]
    pub fn set_registered_servers_for_test(&mut self, lang: Language, names: &[&'static str]) {
        self.registered_servers.insert(lang, names.to_vec());
    }

    /// Whether the server named `name` is open on the document `path`
    /// (#1626), whether or not it still reports diagnostics on it.
    pub fn document_served_by(&self, path: &Path, name: &str) -> bool {
        self.capability_support.lock().is_ok_and(|s| {
            s.document_clients
                .get(path)
                .is_some_and(|names| names.iter().any(|n| n == name))
        })
    }

    /// Whether any running server has the open document `path` (#1566):
    /// one that does answers its completions, and word completion waits for
    /// that answer instead of opening on the document's words at once.
    pub fn document_has_server(&self, path: &Path) -> bool {
        self.capability_support.lock().is_ok_and(|s| {
            s.document_servers
                .get(path)
                .is_some_and(|names| !names.is_empty())
        })
    }

    /// Test hook: record `names` as the servers reporting on `path`, as an
    /// open would, without starting any.
    #[cfg(test)]
    pub fn set_document_servers_for_test(&self, path: &Path, names: &[&str]) {
        if let Ok(mut support) = self.capability_support.lock() {
            support.document_servers.insert(
                path.to_path_buf(),
                names.iter().map(|n| n.to_string()).collect(),
            );
        }
    }

    /// Test hook: record `names` as the servers open on `path` (#1626),
    /// without starting any or marking them as reporting on it.
    #[cfg(test)]
    pub fn set_document_clients_for_test(&self, path: &Path, names: &[&str]) {
        if let Ok(mut support) = self.capability_support.lock() {
            support.document_clients.insert(
                path.to_path_buf(),
                names.iter().map(|n| n.to_string()).collect(),
            );
        }
    }

    /// Test hook: the text the last open or change sent for `path`, as
    /// every server on it would read it.
    #[cfg(test)]
    pub fn synced_text_for_test(&self, path: &Path) -> Option<String> {
        self.synced_texts.lock().ok()?.get(path).cloned()
    }

    #[cfg(test)]
    fn record_synced_text(&self, path: &Path, text: &str) {
        if let Ok(mut texts) = self.synced_texts.lock() {
            texts.insert(path.to_path_buf(), text.to_string());
        }
    }

    /// Whether the server for `lang` implements call hierarchy. `None` means
    /// no server has reported yet. Drives the right-click menu rows.
    pub fn language_supports_call_hierarchy(&self, lang: Language) -> Option<bool> {
        self.language_supports(lang, |s| &s.call_hierarchy)
    }

    /// Whether a running server at `path`'s project root offers inline
    /// completions (#607), so the app asks it rather than a model.
    pub fn document_offers_inline_completion(&self, path: &Path) -> bool {
        let Some(lang) = path_to_language(path) else {
            return false;
        };
        self.capability_support.lock().is_ok_and(|support| {
            support
                .document_roots
                .get(path)
                .is_some_and(|root| support.inline_completion.contains(&(lang, root.clone())))
        })
    }

    /// Test hook: `path` is open at its directory, whose servers offer
    /// inline completions, unstarted.
    #[cfg(test)]
    pub fn set_inline_completion_for_test(&self, path: &Path) {
        let Some(lang) = path_to_language(path) else {
            return;
        };
        let root = path.parent().unwrap_or(path).to_path_buf();
        if let Ok(mut support) = self.capability_support.lock() {
            support
                .document_roots
                .insert(path.to_path_buf(), root.clone());
            support.inline_completion.insert((lang, root));
        }
    }

    /// Whether the server for `lang` implements `textDocument/declaration`.
    /// `None` means no server has reported yet (not spawned). Read synchronously
    /// by the app to decide whether to show the "Go to Declaration" menu item.
    pub fn language_supports_declaration(&self, lang: Language) -> Option<bool> {
        self.language_supports(lang, |s| &s.declaration)
    }

    /// Whether the server for `lang` implements `textDocument/typeDefinition`.
    /// `None` means no server has reported yet. Read synchronously by the app to
    /// decide whether to show the "Go to Type Definition" menu item.
    pub fn language_supports_type_definition(&self, lang: Language) -> Option<bool> {
        self.language_supports(lang, |s| &s.type_definition)
    }

    /// Whether the server for `lang` implements `textDocument/implementation`.
    /// `None` means no server has reported yet. Read synchronously by the app to
    /// decide whether to show the "Go to Implementations" menu item.
    pub fn language_supports_implementation(&self, lang: Language) -> Option<bool> {
        self.language_supports(lang, |s| &s.implementation)
    }

    /// Whether the server for `lang` implements `textDocument/references`.
    /// `None` means no server has reported yet. Read synchronously by the app to
    /// decide whether to show the "Go to References" menu item.
    pub fn language_supports_references(&self, lang: Language) -> Option<bool> {
        self.language_supports(lang, |s| &s.references)
    }

    pub fn request_rename(
        &mut self,
        path: PathBuf,
        line: u32,
        character: u32,
        new_name: String,
    ) -> u64 {
        self.send_request(|request_id| Cmd::RequestRename {
            request_id,
            path,
            line,
            character,
            new_name,
        })
    }

    /// Validate a rename position and fetch its placeholder (#254);
    /// the reply always arrives via [`Self::drain_prepare_rename`].
    pub fn request_prepare_rename(&mut self, path: PathBuf, line: u32, character: u32) -> u64 {
        self.send_request(|request_id| Cmd::RequestPrepareRename {
            request_id,
            path,
            line,
            character,
        })
    }

    pub fn drain_prepare_rename(&self) -> Option<PrepareRenameResult> {
        self.prepare_rename_rx.try_recv().ok()
    }

    pub fn drain_rename(&self) -> Option<RenameResult> {
        self.rename_rx.try_recv().ok()
    }

    /// Ask every interested server for its edit before `renames` happen
    /// (#610). Always answered, with no edits when no server cares, so the
    /// caller can wait on it.
    pub fn request_will_rename_files(&mut self, renames: Vec<FileRenameOp>) -> u64 {
        self.send_request(|request_id| Cmd::RequestWillRenameFiles {
            request_id,
            renames,
        })
    }

    pub fn drain_will_rename_files(&self) -> Option<WillRenameFilesResult> {
        self.will_rename_files_rx.try_recv().ok()
    }

    /// Tell interested servers that `renames` happened (#610).
    pub fn did_rename_files(&mut self, renames: Vec<FileRenameOp>) {
        let _ = self.cmd_tx.send(Cmd::DidRenameFiles { renames });
    }

    /// Tell the servers that watch them that files changed on disk (#908).
    /// A file gone by the time this is sent goes out as deleted.
    pub fn did_change_watched_files(&mut self, changes: Vec<(PathBuf, lsp_types::FileChangeType)>) {
        let _ = self.cmd_tx.send(Cmd::DidChangeWatchedFiles { changes });
    }

    pub fn request_formatting(&mut self, path: PathBuf, tab_size: u32, insert_spaces: bool) -> u64 {
        self.send_request(|request_id| Cmd::RequestFormatting {
            request_id,
            path,
            tab_size,
            insert_spaces,
        })
    }

    /// Fire `textDocument/onTypeFormatting` for the just-typed trigger
    /// character (#254). Silent for a language without the provider —
    /// on-type formatting is a background behavior, not a command.
    #[allow(clippy::too_many_arguments)]
    pub fn request_on_type_formatting(
        &mut self,
        path: PathBuf,
        line: u32,
        character: u32,
        ch: char,
        tab_size: u32,
        insert_spaces: bool,
    ) -> u64 {
        self.send_request(|request_id| Cmd::RequestOnTypeFormatting {
            request_id,
            path,
            line,
            character,
            ch,
            tab_size,
            insert_spaces,
        })
    }

    pub fn drain_on_type_formatting(&self) -> Option<FormatResult> {
        self.on_type_rx.try_recv().ok()
    }

    /// The on-type trigger characters some spawned server advertises for
    /// `lang` — `None` until a server for the language has been probed,
    /// or when none carries the provider. The app consults this before
    /// firing, so nothing is ever sent unadvertised.
    pub fn language_on_type_triggers(&self, lang: crate::lsp::Language) -> Option<String> {
        self.capability_support
            .lock()
            .ok()?
            .on_type_triggers
            .get(&lang)
            .cloned()
    }

    /// The characters that ask for completions as they are typed in
    /// `path` (#929): the `triggerCharacters` of the completion server at
    /// the file's project root, empty when it lists none. `None` while the
    /// file is open on no running server that completes, where nothing
    /// typed asks.
    pub fn completion_triggers(&self, path: &Path) -> Option<String> {
        let lang = path_to_language(path)?;
        let support = self.capability_support.lock().ok()?;
        let root = support.document_roots.get(path)?.clone();
        support.completion_triggers.get(&(lang, root)).cloned()
    }

    /// Test hook: `path` is open at its directory, whose completion server
    /// lists `triggers`, unstarted.
    #[cfg(test)]
    pub fn set_completion_triggers_for_test(&self, path: &Path, triggers: &str) {
        let Some(lang) = path_to_language(path) else {
            return;
        };
        let root = path.parent().unwrap_or(path).to_path_buf();
        if let Ok(mut support) = self.capability_support.lock() {
            support
                .document_roots
                .insert(path.to_path_buf(), root.clone());
            support
                .completion_triggers
                .insert((lang, root), triggers.to_string());
        }
    }

    /// Format only a UTF-16 span ("Format Selection", #254). Same reply
    /// channel and unsupported contract as whole-document formatting;
    /// the app tells the two apart by the returned id.
    pub fn request_range_formatting(
        &mut self,
        path: PathBuf,
        start: (u32, u32),
        end: (u32, u32),
        tab_size: u32,
        insert_spaces: bool,
    ) -> u64 {
        self.send_request(|request_id| Cmd::RequestRangeFormatting {
            request_id,
            path,
            start,
            end,
            tab_size,
            insert_spaces,
        })
    }

    pub fn drain_formatting(&self) -> Option<FormatResult> {
        self.format_rx.try_recv().ok()
    }

    /// Whether the server for `lang` implements `textDocument/formatting`.
    /// `None` means no server has reported yet. Read synchronously by the app
    /// to decide whether to offer "Format Document".
    pub fn language_supports_formatting(&self, lang: Language) -> Option<bool> {
        self.language_supports(lang, |s| &s.formatting)
    }

    /// Request the quick fixes / refactors available over a range (use the same
    /// position for start and end for a caret request). `diagnostics` are the
    /// app's diagnostics overlapping the range, forwarded as context so the
    /// server can attach fixes to them. Reply arrives via [`Self::drain_code_action`].
    #[allow(clippy::too_many_arguments)]
    pub fn request_code_action(
        &mut self,
        path: PathBuf,
        start_line: u32,
        start_char: u32,
        end_line: u32,
        end_char: u32,
        diagnostics: Vec<Diagnostic>,
    ) -> u64 {
        self.send_request(|request_id| Cmd::RequestCodeAction {
            request_id,
            path,
            start_line,
            start_char,
            end_line,
            end_char,
            diagnostics,
        })
    }

    /// Resolve an action that arrived without its edit (it carried only `data`).
    /// The reply reuses [`CodeActionResult`] with a single, now-resolved item.
    pub fn request_code_action_resolve(
        &mut self,
        path: PathBuf,
        server: String,
        action: serde_json::Value,
    ) -> u64 {
        self.send_request(|request_id| Cmd::ResolveCodeAction {
            request_id,
            path,
            server,
            action,
        })
    }

    /// Fire a `workspace/executeCommand` for a command-style code action. The
    /// server performs the effect; croft does not await a reply.
    pub fn execute_command(
        &mut self,
        path: PathBuf,
        command: String,
        arguments: Vec<serde_json::Value>,
    ) {
        let _ = self.cmd_tx.send(Cmd::ExecuteCommand {
            path,
            command,
            arguments,
        });
    }

    pub fn drain_code_action(&self) -> Option<CodeActionResult> {
        self.code_action_rx.try_recv().ok()
    }

    /// Whether the server for `lang` implements `textDocument/codeAction`.
    /// `None` means no server has reported yet.
    pub fn language_supports_code_action(&self, lang: Language) -> Option<bool> {
        self.language_supports(lang, |s| &s.code_action)
    }

    /// What the servers for `lang` reported in the per-language capability
    /// map `pick` names. `None` means no server has reported yet.
    fn language_supports(
        &self,
        lang: Language,
        pick: fn(&LangCapabilitySupport) -> &HashMap<Language, bool>,
    ) -> Option<bool> {
        pick(&*self.capability_support.lock().ok()?)
            .get(&lang)
            .copied()
    }
}

struct ManagedClient {
    name: String,
    client: Arc<TokioMutex<LspClient>>,
    supports_completion: bool,
    /// Its completion `triggerCharacters` (#929), as one string.
    completion_triggers: String,
    supports_signature_help: bool,
    /// Whether the server answers `workspace/diagnostic` (#533), read from
    /// the capability's inner `workspaceDiagnostics` flag rather than the
    /// outer `Option` - see `workspace_diagnostics_supported`.
    ///
    /// Written but not yet read: the request slice filters on it. Verified
    /// not to warn - a forced non-test rebuild under `-D warnings` with no
    /// `allow` is clean, because the field is written in a real constructor.
    supports_workspace_diagnostics: bool,
    /// The server's own `diagnosticProvider.identifier`, echoed back on every
    /// pull (#533). A server that registered more than one diagnostic source
    /// uses it to tell which one a previous result id belongs to, so sending
    /// `None` where it published an identifier throws its incrementality away.
    diagnostic_identifier: Option<String>,
    /// Result ids from this server's last pull (#533), behind the same async
    /// mutex the client is: a pull runs off the worker loop, so the cache has
    /// to outlive the borrow that started it.
    diagnostic_result_ids: Arc<TokioMutex<DiagnosticResultIds>>,
    /// Set once this server has let a `workspace/diagnostic` request expire,
    /// after which it is never pulled again for the life of the client.
    ///
    /// A request that times out cannot be cancelled: async-lsp assigns the id
    /// and parks the response sender in the mainloop's `outgoing` map, which
    /// is drained only by a response ARRIVING with that id (async-lsp 0.2.4
    /// `lib.rs:604`). A server that never answers therefore leaves one entry
    /// behind per request, forever. Since `workspace/diagnostic/refresh` is
    /// server-driven and unrated, a server that refreshes and then stalls
    /// would accrue one leak per refresh for the whole session. Asking it
    /// once and then stopping bounds the damage at exactly one.
    diagnostic_pull_stalled: Arc<AtomicBool>,
    /// Whether to send this server `textDocument/didSave`, and with the text
    /// or without it, read from its `textDocumentSync` (#854).
    save_notify: SaveNotify,
    /// Whether the server answers `textDocument/diagnostic` (#866), which
    /// advertising `diagnosticProvider` at all promises. croft declares the
    /// pull capability for the workspace pull (#533), and servers such as
    /// rumdl and the VS Code JSON, CSS and HTML servers then stop pushing,
    /// so for them a document pull is the only way diagnostics arrive.
    supports_document_diagnostics: bool,
    /// Set once this server lets a document pull expire; it is not asked
    /// again, for the reason `diagnostic_pull_stalled` gives.
    document_pull_stalled: Arc<AtomicBool>,
    /// Set once this server lets a prepareRename expire (#1677); later
    /// renames go straight to the word-under-cursor prompt, for the reason
    /// `diagnostic_pull_stalled` gives: an abandoned request leaks a
    /// mainloop entry, so one leak per client, not one per F2.
    prepare_rename_stalled: Arc<AtomicBool>,
    /// The newest pull generation per document (#866). A pull an edit has
    /// overtaken neither goes out nor, answered late, lands over a newer one.
    document_pull_generations: Arc<StdMutex<HashMap<PathBuf, u64>>>,
    supports_hover: bool,
    supports_definition: bool,
    supports_document_symbol: bool,
    supports_declaration: bool,
    supports_type_definition: bool,
    supports_implementation: bool,
    supports_references: bool,
    supports_document_highlight: bool,
    supports_linked_editing: bool,
    /// Offers `textDocument/inlineCompletion` (#607).
    supports_inline_completion: bool,
    supports_selection_range: bool,
    supports_call_hierarchy: bool,
    supports_type_hierarchy: bool,
    supports_workspace_symbols: bool,
    supports_rename: bool,
    supports_prepare_rename: bool,
    supports_formatting: bool,
    /// The server's on-type formatting trigger characters, when it
    /// advertises the provider (#254).
    on_type_triggers: Option<String>,
    supports_range_formatting: bool,
    supports_code_action: bool,
    /// The server's semantic-token legend (token-type names by index),
    /// captured at spawn. `None` when the server advertises no
    /// `semanticTokensProvider` with full-document support.
    semantic_legend: Option<Arc<Vec<String>>>,
    /// Whether the server's `semanticTokensProvider` also advertises range
    /// support. Used to prefer a purpose-built, incremental highlighter (e.g.
    /// ty, which answers in tens of ms even on a huge cold workspace and
    /// supports range) over one that only does full-document tokens after a
    /// slow whole-tree enumeration (e.g. basedpyright). See
    /// `request_semantic_tokens`.
    semantic_supports_range: bool,
    /// Whether the server advertises an `inlayHintProvider`
    /// (rust-analyzer, vtsls, gopls do; ruff does not).
    supports_inlay_hints: bool,
    supports_document_link: bool,
    /// `codeLensProvider` (#608), and whether it resolves lenses lazily.
    supports_code_lens: bool,
    code_lens_resolve: bool,
    /// The commands the server runs itself (`executeCommandProvider`).
    server_commands: Arc<Vec<String>>,
    supports_folding_range: bool,
    supports_document_color: bool,
    /// The paths this server wants `willRenameFiles` / `didRenameFiles`
    /// for (#610); `None` when it does not advertise the operation.
    will_rename: Option<Arc<crate::lsp::file_ops::FileOpFilters>>,
    did_rename: Option<Arc<crate::lsp::file_ops::FileOpFilters>>,
}

/// Servers are keyed by language AND the file's project root, not language
/// alone. A monorepo has one `.venv` (and `pyproject.toml`) per sub-project, so
/// a single server rooted at croft's workspace root can't resolve any of them.
/// Following Zed's model, croft runs a server instance per (language, project
/// root); each is rooted at the project so basedpyright/rust-analyzer/gopls
/// auto-detect that project's environment.
type ClientKey = (Language, PathBuf);

/// Why [`WorkerState::pick_server`] found no server to ask.
enum NoServer {
    /// The file is not open, or no server set exists for its language and
    /// root: the request is dropped without a reply (a hover gets an empty
    /// one).
    Unknown,
    /// Servers run for the file, but none carries the method.
    Unsupported,
}

struct WorkerState {
    workspace_root: PathBuf,
    /// Secondary workspace roots (multi-root, #147). Servers stay one
    /// instance per (language, project root); these only widen the bound
    /// `project_root_for_roots` walks within, so a file under a secondary root
    /// spawns its servers AT that root instead of falling back to the
    /// primary — the per-root-instance model every server supports.
    extra_roots: Vec<PathBuf>,
    registry: ServerRegistry,
    clients: HashMap<ClientKey, Vec<ManagedClient>>,
    docs: HashMap<PathBuf, DocState>,
    capability_support: CapabilitySupport,
    // Shared with every spawned client's router; a client sets it on a
    // `workspace/semanticTokens/refresh` and the app polls + clears it.
    semantic_refresh: Arc<AtomicBool>,
    // Same contract for `workspace/inlayHint/refresh`.
    inlay_refresh: Arc<AtomicBool>,
    // Same contract for `workspace/diagnostic/refresh` (#533); the app polls
    // it and asks for a fresh workspace pull.
    diagnostic_refresh: Arc<AtomicBool>,
    // Cloned into every spawned client's router so the server-pushed
    // `textDocument/publishDiagnostics` notifications reach the app.
    diagnostics_tx: std_mpsc::Sender<DiagnosticsUpdate>,
    // Cloned into every spawned client's router so server `$/progress`
    // notifications (rust-analyzer indexing, etc.) reach the status bar.
    progress_tx: std_mpsc::Sender<ServerUpdate>,
    restarts: ServerRestarts,
}

/// How often a (language, root)'s servers may be restarted after exiting,
/// and within what window (#694). A server that dies on every start would
/// otherwise respawn on every keystroke; past the limit croft leaves it
/// down and says so, as it did before restarts existed.
const MAX_RESTARTS: usize = 3;
const RESTART_WINDOW: std::time::Duration = std::time::Duration::from_secs(10 * 60);

/// Restart bookkeeping for servers that exited under a live workspace.
#[derive(Default)]
struct ServerRestarts {
    /// When each key's servers were last restarted, newest last.
    attempts: HashMap<ClientKey, Vec<std::time::Instant>>,
    /// Keys whose servers used up [`MAX_RESTARTS`]: left down until the
    /// workspace re-roots or croft restarts, so a crash loop cannot spin.
    gave_up: std::collections::HashSet<ClientKey>,
    /// Keys whose restart lost a server that ran before it, with the names
    /// of the servers that ran. The next pass restarts them as a set again: a
    /// non-empty list is never re-probed, and a lone missing server cannot be
    /// added to documents the others hold.
    incomplete: HashMap<ClientKey, Vec<String>>,
    /// Set by [`WorkerState::restart_dead_servers`] for the respawn it has
    /// already counted, so `ensure_clients` does not count it again: the
    /// servers that ran before it, which the respawn must bring back.
    respawn: Option<Vec<String>>,
    /// Raised after a restart; the app polls it to re-open its tabs.
    restarted: Arc<AtomicBool>,
}

impl ServerRestarts {
    fn reporting_to(restarted: Arc<AtomicBool>) -> Self {
        Self {
            restarted,
            ..Self::default()
        }
    }

    /// Record a restart of `key` at `now` if the budget allows one.
    fn try_restart(&mut self, key: &ClientKey, now: std::time::Instant) -> bool {
        let attempts = self.attempts.entry(key.clone()).or_default();
        attempts.retain(|t| now.duration_since(*t) < RESTART_WINDOW);
        if attempts.len() >= MAX_RESTARTS {
            self.gave_up.insert(key.clone());
            return false;
        }
        attempts.push(now);
        true
    }
}

struct DocState {
    language: Language,
    project_root: PathBuf,
    version: i32,
}

/// The reply channels the worker sends results back on, bundled so
/// `worker_loop` keeps a small argument list as request kinds grow.
struct ResultSenders {
    completion: std_mpsc::Sender<CompletionResult>,
    signature_help: std_mpsc::Sender<SignatureHelpResult>,
    hover: std_mpsc::Sender<HoverResult>,
    rust_analyzer: std_mpsc::Sender<RustAnalyzerResult>,
    definition: std_mpsc::Sender<DefinitionResult>,
    document_symbols: std_mpsc::Sender<DocumentSymbolsResult>,
    declaration: std_mpsc::Sender<DeclarationResult>,
    type_definition: std_mpsc::Sender<TypeDefinitionResult>,
    implementation: std_mpsc::Sender<ImplementationResult>,
    references: std_mpsc::Sender<ReferencesResult>,
    document_highlights: std_mpsc::Sender<DocumentHighlightsResult>,
    linked_editing: std_mpsc::Sender<LinkedEditingResult>,
    inline_completion: std_mpsc::Sender<InlineCompletionResult>,
    selection_ranges: std_mpsc::Sender<SelectionRangesResult>,
    call_hierarchy: std_mpsc::Sender<CallHierarchyResult>,
    workspace_symbols: std_mpsc::Sender<WorkspaceSymbolsResult>,
    rename: std_mpsc::Sender<RenameResult>,
    prepare_rename: std_mpsc::Sender<PrepareRenameResult>,
    will_rename_files: std_mpsc::Sender<WillRenameFilesResult>,
    formatting: std_mpsc::Sender<FormatResult>,
    on_type_formatting: std_mpsc::Sender<FormatResult>,
    code_action: std_mpsc::Sender<CodeActionResult>,
    semantic_tokens: std_mpsc::Sender<SemanticTokensUpdate>,
    inlay_hints: std_mpsc::Sender<InlayHintsUpdate>,
    document_links: std_mpsc::Sender<DocumentLinksUpdate>,
    code_lens: std_mpsc::Sender<CodeLensUpdate>,
    folding_ranges: std_mpsc::Sender<FoldingRangesUpdate>,
    document_colors: std_mpsc::Sender<DocumentColorsUpdate>,
    color_presentations: std_mpsc::Sender<ColorPresentationsResult>,
    diagnostics: std_mpsc::Sender<DiagnosticsUpdate>,
    progress: std_mpsc::Sender<ServerUpdate>,
}

// Every flag and channel here is an independent worker input, the same shape
// `LspClient::spawn` carries: bundling them behind one struct would add a
// layer of indirection without making any call site clearer. `ResultSenders`
// already bundles the part that grows per REQUEST KIND; these do not grow
// that way.
#[allow(clippy::too_many_arguments)]
async fn worker_loop(
    workspace_root: PathBuf,
    registry: ServerRegistry,
    mut cmd_rx: tokio_mpsc::UnboundedReceiver<Cmd>,
    tx: ResultSenders,
    capability_support: CapabilitySupport,
    semantic_refresh: Arc<AtomicBool>,
    inlay_refresh: Arc<AtomicBool>,
    diagnostic_refresh: Arc<AtomicBool>,
    servers_restarted: Arc<AtomicBool>,
) {
    let mut state = WorkerState {
        workspace_root,
        extra_roots: Vec::new(),
        registry,
        clients: HashMap::new(),
        docs: HashMap::new(),
        capability_support,
        semantic_refresh,
        inlay_refresh,
        diagnostic_refresh,
        diagnostics_tx: tx.diagnostics.clone(),
        progress_tx: tx.progress.clone(),
        restarts: ServerRestarts::reporting_to(servers_restarted),
    };
    while let Some(cmd) = cmd_rx.recv().await {
        // Before any command touches a server: one the kernel killed, or
        // that crashed, comes back here rather than staying down (#694).
        if !matches!(cmd, Cmd::Shutdown { .. }) {
            state.restart_dead_servers().await;
        }
        match cmd {
            Cmd::Shutdown { done } => {
                state.shutdown_all().await;
                let _ = done.send(());
                return;
            }
            Cmd::OpenDoc { path, text } => state.open_doc(path, text).await,
            Cmd::RestartServersFor { path } => state.restart_servers_for(&path).await,
            Cmd::ReplaceRegistry { registry } => state.replace_registry(registry).await,
            Cmd::PrewarmWorkspace => state.prewarm_workspace().await,
            Cmd::SetExtraRoots { roots } => {
                for root in &roots {
                    if !state.extra_roots.contains(root) {
                        state.prewarm_root(root.clone()).await;
                    }
                }
                // Retire clients whose project root lives under a REMOVED
                // workspace root and serves no open document (#148 review):
                // without this, repeated add/remove cycles accumulate live
                // server processes and workspace-symbol fan-outs keep
                // querying folders the user closed. A client still serving
                // an open doc survives — the file became out-of-workspace,
                // not closed.
                let removed: Vec<PathBuf> = state
                    .extra_roots
                    .iter()
                    .filter(|old_root| !roots.contains(old_root))
                    .cloned()
                    .collect();
                if !removed.is_empty() {
                    let doomed: Vec<ClientKey> = state
                        .clients
                        .keys()
                        .filter(|(_, project_root)| {
                            removed.iter().any(|r| project_root.starts_with(r))
                                && !state.docs.values().any(|d| &d.project_root == project_root)
                        })
                        .cloned()
                        .collect();
                    for key in doomed {
                        if let Some(clients) = state.clients.remove(&key) {
                            for managed in clients {
                                let mut client = managed.client.lock().await;
                                // Graceful LSP shutdown+exit; the transport's
                                // kill_on_drop reaps a server that ignores it.
                                // Bounded: a server that never answers
                                // `shutdown` must not wedge the worker loop.
                                let _ = tokio::time::timeout(
                                    std::time::Duration::from_secs(3),
                                    client.shutdown(),
                                )
                                .await;
                                log_file::log(&format!(
                                    "lsp retire: {} for removed workspace folder {}",
                                    managed.name,
                                    key.1.display()
                                ));
                            }
                        }
                    }
                }
                state.extra_roots = roots;
            }
            Cmd::RequestWorkspaceDiagnostics => state.request_workspace_diagnostics(),
            Cmd::RequestSemanticTokens {
                path,
                seq,
                generation,
            } => {
                state
                    .request_semantic_tokens(path, seq, generation, &tx.semantic_tokens)
                    .await
            }
            Cmd::RequestSemanticTokensRange {
                path,
                start_line,
                end,
                seq,
                generation,
            } => {
                state
                    .request_semantic_tokens_range(
                        path,
                        start_line,
                        end,
                        seq,
                        generation,
                        &tx.semantic_tokens,
                    )
                    .await
            }
            Cmd::RequestInlayHints { path, end, seq } => {
                state
                    .request_inlay_hints(path, end, seq, &tx.inlay_hints)
                    .await
            }
            Cmd::RequestCodeLens { path, seq } => {
                state.request_code_lens(path, seq, &tx.code_lens).await
            }
            Cmd::RequestDocumentLinks { path, seq } => {
                state
                    .request_document_links(path, seq, &tx.document_links)
                    .await
            }
            Cmd::RequestFoldingRanges { path, seq } => {
                state
                    .request_folding_ranges(path, seq, &tx.folding_ranges)
                    .await
            }
            Cmd::RequestDocumentColors { path, seq } => {
                state
                    .request_document_colors(path, seq, &tx.document_colors)
                    .await
            }
            Cmd::RequestColorPresentations {
                request_id,
                path,
                color,
                start,
                end,
            } => {
                state
                    .request_color_presentations(
                        request_id,
                        path,
                        color,
                        start,
                        end,
                        &tx.color_presentations,
                    )
                    .await
            }
            Cmd::ChangeDoc { path, text } => state.change_doc(path, text).await,
            Cmd::SaveDoc { path, text } => state.save_doc(path, text).await,
            Cmd::CloseDoc { path } => state.close_doc(path).await,
            Cmd::RequestCompletion {
                request_id,
                path,
                line,
                character,
                trigger,
            } => {
                state
                    .request_completion(request_id, path, line, character, trigger, &tx.completion)
                    .await
            }
            Cmd::ResolveCompletion {
                request_id,
                path,
                item,
            } => {
                state
                    .resolve_completion(request_id, path, item, &tx.completion)
                    .await
            }
            Cmd::RequestSignatureHelp {
                request_id,
                path,
                line,
                character,
            } => {
                state
                    .request_signature_help(request_id, path, line, character, &tx.signature_help)
                    .await
            }
            Cmd::RequestHover {
                request_id,
                path,
                line,
                character,
            } => {
                state
                    .request_hover(request_id, path, line, character, &tx.hover)
                    .await
            }
            Cmd::RustAnalyzer {
                request_id,
                path,
                request,
                line,
                character,
            } => {
                state
                    .request_rust_analyzer(
                        request_id,
                        path,
                        request,
                        (line, character),
                        &tx.rust_analyzer,
                    )
                    .await
            }
            Cmd::RequestDefinition {
                request_id,
                path,
                line,
                character,
            } => {
                state
                    .request_definition(request_id, path, line, character, &tx.definition)
                    .await
            }
            Cmd::RequestDocumentSymbols { path, seq } => {
                state
                    .request_document_symbols(path, seq, &tx.document_symbols)
                    .await
            }
            Cmd::RequestDeclaration {
                request_id,
                path,
                line,
                character,
            } => {
                state
                    .request_declaration(request_id, path, line, character, &tx.declaration)
                    .await
            }
            Cmd::RequestTypeDefinition {
                request_id,
                path,
                line,
                character,
            } => {
                state
                    .request_type_definition(request_id, path, line, character, &tx.type_definition)
                    .await
            }
            Cmd::RequestImplementation {
                request_id,
                path,
                line,
                character,
            } => {
                state
                    .request_implementation(request_id, path, line, character, &tx.implementation)
                    .await
            }
            Cmd::RequestWorkspaceSymbols { request_id, query } => {
                state
                    .request_workspace_symbols(request_id, query, &tx.workspace_symbols)
                    .await
            }
            Cmd::RequestReferences {
                request_id,
                path,
                line,
                character,
            } => {
                state
                    .request_references(request_id, path, line, character, &tx.references)
                    .await
            }
            Cmd::RequestDocumentHighlights {
                request_id,
                path,
                line,
                character,
            } => {
                state
                    .request_document_highlights(
                        request_id,
                        path,
                        line,
                        character,
                        &tx.document_highlights,
                    )
                    .await
            }
            Cmd::RequestLinkedEditing {
                request_id,
                path,
                line,
                character,
            } => {
                state
                    .request_linked_editing(request_id, path, line, character, &tx.linked_editing)
                    .await
            }
            Cmd::RequestInlineCompletion {
                request_id,
                path,
                line,
                character,
            } => {
                state
                    .request_inline_completion(
                        request_id,
                        path,
                        line,
                        character,
                        &tx.inline_completion,
                    )
                    .await
            }
            Cmd::RequestSelectionRanges {
                request_id,
                path,
                positions,
            } => {
                state
                    .request_selection_ranges(request_id, path, positions, &tx.selection_ranges)
                    .await
            }
            Cmd::RequestCallHierarchy {
                request_id,
                path,
                line,
                character,
                incoming,
            } => {
                state
                    .request_call_hierarchy(
                        request_id,
                        path,
                        line,
                        character,
                        incoming,
                        &tx.call_hierarchy,
                    )
                    .await
            }
            Cmd::RequestTypeHierarchy {
                request_id,
                path,
                line,
                character,
                supertypes,
            } => {
                state
                    .request_type_hierarchy(
                        request_id,
                        path,
                        line,
                        character,
                        supertypes,
                        &tx.call_hierarchy,
                    )
                    .await
            }
            Cmd::RequestRename {
                request_id,
                path,
                line,
                character,
                new_name,
            } => {
                state
                    .request_rename(request_id, path, line, character, new_name, &tx.rename)
                    .await
            }
            Cmd::RequestWillRenameFiles {
                request_id,
                renames,
            } => state.request_will_rename_files(request_id, renames, &tx.will_rename_files),
            Cmd::DidRenameFiles { renames } => state.did_rename_files(renames),
            Cmd::DidChangeWatchedFiles { changes } => state.did_change_watched_files(changes),
            Cmd::RequestPrepareRename {
                request_id,
                path,
                line,
                character,
            } => {
                state
                    .request_prepare_rename(request_id, path, line, character, &tx.prepare_rename)
                    .await
            }
            Cmd::RequestFormatting {
                request_id,
                path,
                tab_size,
                insert_spaces,
            } => {
                state
                    .request_formatting(request_id, path, tab_size, insert_spaces, &tx.formatting)
                    .await
            }
            Cmd::RequestOnTypeFormatting {
                request_id,
                path,
                line,
                character,
                ch,
                tab_size,
                insert_spaces,
            } => {
                state
                    .request_on_type_formatting(
                        request_id,
                        path,
                        line,
                        character,
                        ch,
                        tab_size,
                        insert_spaces,
                        &tx.on_type_formatting,
                    )
                    .await
            }
            Cmd::RequestRangeFormatting {
                request_id,
                path,
                start,
                end,
                tab_size,
                insert_spaces,
            } => {
                state
                    .request_range_formatting(
                        request_id,
                        path,
                        start,
                        end,
                        tab_size,
                        insert_spaces,
                        &tx.formatting,
                    )
                    .await
            }
            Cmd::RequestCodeAction {
                request_id,
                path,
                start_line,
                start_char,
                end_line,
                end_char,
                diagnostics,
            } => {
                state
                    .request_code_action(
                        request_id,
                        path,
                        start_line,
                        start_char,
                        end_line,
                        end_char,
                        diagnostics,
                        &tx.code_action,
                    )
                    .await
            }
            Cmd::ResolveCodeAction {
                request_id,
                path,
                server,
                action,
            } => {
                state
                    .resolve_code_action(request_id, path, server, action, &tx.code_action)
                    .await
            }
            Cmd::ExecuteCommand {
                path,
                command,
                arguments,
            } => state.execute_command(path, command, arguments).await,
        }
    }
}

impl WorkerState {
    /// Gracefully shut down every managed client concurrently. Each client's
    /// `shutdown` self-bounds its child-wait, so a single unresponsive server
    /// can't block the others. Clients are left in the map; their eventual Drop
    /// aborts the (now-finished) MainLoop and reaps the (now-exited) child.
    async fn shutdown_all(&mut self) {
        let clients: Vec<Arc<TokioMutex<LspClient>>> = self
            .clients
            .values()
            .flatten()
            .map(|m| m.client.clone())
            .collect();
        let mut tasks = Vec::with_capacity(clients.len());
        for client in clients {
            tasks.push(tokio::spawn(async move {
                let mut client = client.lock().await;
                let _ = tokio::time::timeout(std::time::Duration::from_secs(3), client.shutdown())
                    .await;
            }));
        }
        for t in tasks {
            let _ = t.await;
        }
    }

    /// Restart the servers of every (language, root) with a server that has
    /// exited (#694): killed by the OOM killer, which croft asks to pick
    /// language servers first, or crashed. Their documents are forgotten and
    /// the app is told to re-open its tabs, since a new server knows none of
    /// them. Past [`MAX_RESTARTS`] in [`RESTART_WINDOW`] the dead servers are
    /// dropped and left down instead.
    async fn restart_dead_servers(&mut self) {
        let dead: Vec<ClientKey> = self
            .clients
            .iter()
            .filter(|(key, clients)| {
                !self.restarts.gave_up.contains(*key)
                    && (self.restarts.incomplete.contains_key(*key)
                        || clients.iter().any(|managed| {
                            // A client in use is not a dead one; skip it rather
                            // than wait on the lock.
                            managed
                                .client
                                .try_lock()
                                .is_ok_and(|client| client.has_exited())
                        }))
            })
            .map(|(key, _)| key.clone())
            .collect();
        for key in dead {
            let Some(clients) = self.clients.remove(&key) else {
                continue;
            };
            let names: Vec<&str> = clients.iter().map(|c| c.name.as_str()).collect();
            // A server that never came up is not one the restart lost; a set
            // still short from the last restart keeps what it is missing.
            let expected = self
                .restarts
                .incomplete
                .get(&key)
                .cloned()
                .unwrap_or_else(|| names.iter().map(|n| n.to_string()).collect());
            if !self.restarts.try_restart(&key, std::time::Instant::now()) {
                let msg = format!(
                    "{} stopped {MAX_RESTARTS} times in 10 minutes; leaving it off until croft restarts or the workspace reopens",
                    names.join(", ")
                );
                log_file::log(&format!("lsp restart: {msg}"));
                crate::output::push("Language Servers", crate::output::OutputLevel::Error, &msg);
                // Keep the survivors; `gave_up` stops both this pass and the
                // empty-list re-probe from spawning the dead ones again.
                let alive: Vec<ManagedClient> = clients
                    .into_iter()
                    .filter(|m| m.client.try_lock().map_or(true, |c| !c.has_exited()))
                    .collect();
                // The dead ones report on nothing any more.
                if let Ok(mut support) = self.capability_support.lock() {
                    for (path, doc) in &self.docs {
                        if (doc.language, doc.project_root.clone()) != key {
                            continue;
                        }
                        if let Some(names) = support.document_servers.get_mut(path) {
                            names.retain(|n| alive.iter().any(|m| &m.name == n));
                        }
                        if let Some(names) = support.document_clients.get_mut(path) {
                            names.retain(|n| alive.iter().any(|m| &m.name == n));
                        }
                    }
                }
                self.restarts.incomplete.remove(&key);
                self.clients.insert(key, alive);
                continue;
            }
            let msg = format!("{} stopped; restarting", names.join(", "));
            log_file::log(&format!("lsp restart: {msg} for {}", key.1.display()));
            crate::output::push("Language Servers", crate::output::OutputLevel::Info, &msg);
            // The survivors go too: servers for one key are spawned and
            // opened as a set, and a half-restarted set would hold documents
            // the new server never saw.
            for managed in clients {
                let mut client = managed.client.lock().await;
                if !client.has_exited() {
                    let _ =
                        tokio::time::timeout(std::time::Duration::from_secs(3), client.shutdown())
                            .await;
                }
            }
            if let Ok(mut support) = self.capability_support.lock() {
                for (path, doc) in &self.docs {
                    if (doc.language, doc.project_root.clone()) == key {
                        support.document_servers.remove(path);
                        support.document_clients.remove(path);
                    }
                }
            }
            self.docs
                .retain(|_, doc| (doc.language, doc.project_root.clone()) != key);
            // Respawn as a re-probe, not a first attempt, so a set that comes
            // back short is marked incomplete and tried again.
            self.clients.insert(key.clone(), Vec::new());
            self.restarts.respawn = Some(expected);
            self.ensure_clients(key.0, &key.1).await;
            self.restarts.restarted.store(true, Ordering::Relaxed);
        }
    }

    /// Restart the servers serving `path` at the user's request (#1621): the
    /// (language, root) its document was opened under, else the one its
    /// language and project root would open it under, so the servers of
    /// other roots keep running. Unlike a crash restart this spends no
    /// budget and lifts a give-up, since the user asked for it.
    async fn restart_servers_for(&mut self, path: &Path) {
        let keys: Vec<ClientKey> = match self.docs.get(path) {
            Some(doc) => vec![(doc.language, doc.project_root.clone())],
            None => path_to_language(path)
                .map(|lang| {
                    (
                        lang,
                        project_root_for_roots(path, lang, &self.workspace_root, &self.extra_roots),
                    )
                })
                .filter(|key| self.clients.contains_key(key))
                .into_iter()
                .collect(),
        };
        if keys.is_empty() {
            crate::output::push(
                "Language Servers",
                crate::output::OutputLevel::Info,
                &format!("No language server serves {}", path.display()),
            );
            return;
        }
        for key in keys {
            self.restart_key(key).await;
        }
        self.restarts.restarted.store(true, Ordering::Relaxed);
    }

    /// Shut the servers of `key` down and start them again, forgetting its
    /// documents, which the new servers never saw.
    async fn restart_key(&mut self, key: ClientKey) {
        let names = self.retire_key(&key).await;
        let expected = self.restarts.incomplete.remove(&key).unwrap_or(names);
        self.clients.insert(key.clone(), Vec::new());
        if !expected.is_empty() {
            self.restarts.respawn = Some(expected.clone());
        }
        self.ensure_clients(key.0, &key.1).await;
        let msg = if expected.is_empty() {
            format!("Started the language servers for {}", key.1.display())
        } else {
            format!("Restarted {} for {}", expected.join(", "), key.1.display())
        };
        log_file::log(&format!("lsp restart: {msg}"));
        crate::output::push("Language Servers", crate::output::OutputLevel::Info, &msg);
    }

    /// Shut the servers of `key` down and forget them, its documents and
    /// its restart budget, returning the names of the servers that ran.
    async fn retire_key(&mut self, key: &ClientKey) -> Vec<String> {
        let clients = self.clients.remove(key).unwrap_or_default();
        let names: Vec<String> = clients.iter().map(|c| c.name.clone()).collect();
        // Withdraw what the old servers published or answered to a pull
        // (#1102) for their documents: a server that does not come back
        // would never clear it, and one that does reports again once the
        // app re-opens the tabs.
        for (path, doc) in &self.docs {
            if (doc.language, doc.project_root.clone()) != *key {
                continue;
            }
            for name in &names {
                for pulled in [false, true] {
                    let _ = self.diagnostics_tx.send(DiagnosticsUpdate {
                        path: path.clone(),
                        server: name.clone(),
                        diagnostics: Vec::new(),
                        pulled,
                    });
                }
            }
        }
        for managed in clients {
            let mut client = managed.client.lock().await;
            if !client.has_exited() {
                let _ = tokio::time::timeout(std::time::Duration::from_secs(3), client.shutdown())
                    .await;
            }
        }
        // Nothing serves its documents now, as after a crash; whatever
        // starts next says what it serves.
        if let Ok(mut support) = self.capability_support.lock() {
            for (path, doc) in &self.docs {
                if (doc.language, doc.project_root.clone()) == *key {
                    support.document_servers.remove(path);
                    support.document_clients.remove(path);
                }
            }
            support.completion_triggers.remove(key);
            support.inline_completion.remove(key);
        }
        self.docs
            .retain(|_, doc| (doc.language, doc.project_root.clone()) != *key);
        self.restarts.gave_up.remove(key);
        self.restarts.attempts.remove(key);
        names
    }

    /// Serve from `registry` from now on (#1842). A (language, root) whose
    /// servers it changes has the running ones shut down and is forgotten,
    /// so the next of its files starts what is registered now, as a first
    /// open does; the app re-opens its tabs for that. Every other key's
    /// servers keep running.
    async fn replace_registry(&mut self, registry: ServerRegistry) {
        let old = std::mem::replace(&mut self.registry, registry);
        // A file an added or removed extension maps to another language or
        // project root now leaves the servers of its old one, so the app's
        // re-open reaches the new one's as an open, not as a change.
        let moved: Vec<PathBuf> = self
            .docs
            .iter()
            .filter(|(path, doc)| {
                path_to_language(path).map(|lang| {
                    let root =
                        project_root_for_roots(path, lang, &self.workspace_root, &self.extra_roots);
                    (lang, root)
                }) != Some((doc.language, doc.project_root.clone()))
            })
            .map(|(path, _)| path.clone())
            .collect();
        for path in moved {
            self.close_doc(path).await;
        }
        let names = |r: &ServerRegistry, lang: Language| -> Vec<&'static str> {
            r.for_language(lang).iter().map(|c| c.name).collect()
        };
        let changed: Vec<ClientKey> = self
            .clients
            .keys()
            .filter(|(lang, _)| names(&old, *lang) != names(&self.registry, *lang))
            .cloned()
            .collect();
        for key in changed {
            let stopped = self.retire_key(&key).await;
            self.restarts.incomplete.remove(&key);
            if !stopped.is_empty() {
                let msg = format!(
                    "Stopped {} for {}: the extensions serving it changed",
                    stopped.join(", "),
                    key.1.display()
                );
                log_file::log(&format!("lsp registry: {msg}"));
                crate::output::push("Language Servers", crate::output::OutputLevel::Info, &msg);
            }
        }
        // Tabs the old registry served nothing for were never opened here,
        // so every tab goes out again, as after a restart.
        self.restarts.restarted.store(true, Ordering::Relaxed);
    }

    async fn ensure_clients(&mut self, lang: Language, root: &Path) -> &[ManagedClient] {
        // Re-probe when the cached list is empty: a server (e.g. the managed
        // vtsls) may have finished its background install since the first
        // attempt, so this is how TS LSP comes alive without a relaunch.
        // A non-empty list is stable and never re-probed.
        let key: ClientKey = (lang, root.to_path_buf());
        let first_attempt = !self.clients.contains_key(&key);
        // A key whose servers crash-looped stays down (#694): the empty-list
        // re-probe below would otherwise respawn them on every open.
        let empty = !first_attempt
            && self
                .clients
                .get(&key)
                .is_some_and(|clients| clients.is_empty());
        let respawn = self.restarts.respawn.take();
        let prepaid = respawn.is_some();
        let mut should_try = !self.restarts.gave_up.contains(&key) && (first_attempt || empty);
        // An empty list left by a restart whose respawn failed is re-probed
        // by every request. Each re-probe is another restart and spends the
        // same budget, so a server that never comes back stops being launched.
        if should_try
            && empty
            && !prepaid
            && self.restarts.attempts.contains_key(&key)
            && !self.restarts.try_restart(&key, std::time::Instant::now())
        {
            let msg = format!(
                "language servers for {} did not come back after {MAX_RESTARTS} restarts in 10 minutes; leaving them off until croft restarts or the workspace reopens",
                key.1.display()
            );
            log_file::log(&format!("lsp restart: {msg}"));
            crate::output::push("Language Servers", crate::output::OutputLevel::Error, &msg);
            should_try = false;
        }
        if should_try {
            // A launch's first frame comes first (see `startup_gate`): a file
            // restored at launch, or a restored extra root, otherwise starts
            // its servers, and the `rustup` that resolves rust-analyzer,
            // while that frame is still being drawn.
            crate::startup_gate::wait_async().await;
            let configs: Vec<ServerConfig> = self.registry.for_language(lang).to_vec();
            // Spawn every server for this root concurrently rather than awaiting
            // each in turn. The worker loop processes commands one at a time, so
            // a sequential spawn chain made the OpenDoc command (and the
            // semantic-token request queued right behind it) block on the SUM of
            // ty + basedpyright + ruff init handshakes. Concurrent spawn bounds
            // the cold-root stall to the SLOWEST single handshake instead.
            let resolved: Vec<(ServerConfig, Vec<PathBuf>)> = futures::future::join_all(
                configs
                    .iter()
                    .map(|config| resolve_for_root(config, root, first_attempt)),
            )
            .await
            .into_iter()
            .flatten()
            .collect();
            if first_attempt
                && resolved.is_empty()
                && let Some(note) =
                    missing_servers_note(lang, &configs, crate::lsp::install::missing_installer)
            {
                report_missing_servers_once(lang, &note);
            }
            let outcomes =
                futures::future::join_all(resolved.into_iter().map(|(config, extra_path)| {
                    let caps = build_client_capabilities();
                    let refresh = self.semantic_refresh.clone();
                    let inlay_refresh = self.inlay_refresh.clone();
                    let diagnostic_refresh = self.diagnostic_refresh.clone();
                    let diagnostics = self.diagnostics_tx.clone();
                    let progress = self.progress_tx.clone();
                    async move {
                        let result = LspClient::spawn(
                            &config,
                            root,
                            caps,
                            &extra_path,
                            refresh,
                            inlay_refresh,
                            diagnostic_refresh,
                            diagnostics,
                            progress,
                        )
                        .await;
                        (config, result)
                    }
                }))
                .await;
            let mut spawned: Vec<ManagedClient> = Vec::new();
            for (config, result) in outcomes {
                match result {
                    Ok(client) => {
                        let caps = client.capabilities();
                        // A capability that can be sent as a bare `false` (the
                        // bool-or-options shapes) must be read as its inner bool:
                        // `Option::is_some` treats `Some(false)` as supported,
                        // which made croft call `textDocument/declaration` on
                        // vtsls (which advertises `declarationProvider: false`)
                        // and get a -32601 "Unhandled method" back.
                        let supports = caps.completion_provider.is_some();
                        let completion_triggers = completion_triggers_of(caps);
                        let supports_signature_help =
                            signature_help_supported(&caps.signature_help_provider);
                        let supports_workspace_diagnostics =
                            workspace_diagnostics_supported(&caps.diagnostic_provider);
                        let supports_document_diagnostics = caps.diagnostic_provider.is_some();
                        let diagnostic_identifier =
                            diagnostic_identifier_of(&caps.diagnostic_provider);
                        let save_notify = save_notify_of(&caps.text_document_sync);
                        let supports_hover = hover_supported(&caps.hover_provider);
                        let supports_definition = one_of_supported(&caps.definition_provider);
                        let supports_document_symbol =
                            one_of_supported(&caps.document_symbol_provider);
                        let supports_declaration =
                            declaration_supported(&caps.declaration_provider);
                        let supports_type_definition =
                            type_definition_supported(&caps.type_definition_provider);
                        let supports_implementation =
                            implementation_supported(&caps.implementation_provider);
                        let supports_references = one_of_supported(&caps.references_provider);
                        let supports_document_highlight =
                            one_of_supported(&caps.document_highlight_provider);
                        let supports_linked_editing =
                            linked_editing_supported(&caps.linked_editing_range_provider);
                        let supports_inline_completion =
                            one_of_supported(&caps.inline_completion_provider);
                        let supports_selection_range =
                            selection_range_supported(&caps.selection_range_provider);
                        let supports_call_hierarchy =
                            call_hierarchy_supported(&caps.call_hierarchy_provider);
                        let supports_type_hierarchy = client.supports_type_hierarchy();
                        let supports_workspace_symbols =
                            one_of_supported(&caps.workspace_symbol_provider);
                        let supports_rename = one_of_supported(&caps.rename_provider);
                        let supports_prepare_rename =
                            prepare_rename_supported(&caps.rename_provider);
                        let supports_formatting =
                            one_of_supported(&caps.document_formatting_provider);
                        let on_type_triggers =
                            caps.document_on_type_formatting_provider.as_ref().map(|o| {
                                let mut t = o.first_trigger_character.clone();
                                for more in o.more_trigger_character.iter().flatten() {
                                    t.push_str(more);
                                }
                                t
                            });
                        let supports_range_formatting =
                            one_of_supported(&caps.document_range_formatting_provider);
                        let supports_code_action =
                            code_action_supported(&caps.code_action_provider);
                        let semantic_legend = semantic_legend_of(caps).map(Arc::new);
                        let semantic_supports_range = semantic_tokens_range_supported(caps);
                        let supports_inlay_hints = one_of_supported(&caps.inlay_hint_provider);
                        let supports_document_link = caps.document_link_provider.is_some();
                        let supports_code_lens = caps.code_lens_provider.is_some();
                        let code_lens_resolve = caps
                            .code_lens_provider
                            .as_ref()
                            .and_then(|o| o.resolve_provider)
                            .unwrap_or(false);
                        let server_commands = Arc::new(
                            caps.execute_command_provider
                                .as_ref()
                                .map(|o| o.commands.clone())
                                .unwrap_or_default(),
                        );
                        let supports_folding_range =
                            folding_range_supported(&caps.folding_range_provider);
                        let supports_document_color =
                            color_provider_supported(&caps.color_provider);
                        let file_ops = caps
                            .workspace
                            .as_ref()
                            .and_then(|w| w.file_operations.as_ref());
                        let compile = |reg: Option<
                            &lsp_types::FileOperationRegistrationOptions,
                        >| {
                            reg.map(|r| {
                                Arc::new(crate::lsp::file_ops::FileOpFilters::from_registration(r))
                            })
                        };
                        let will_rename = compile(file_ops.and_then(|f| f.will_rename.as_ref()));
                        let did_rename = compile(file_ops.and_then(|f| f.did_rename.as_ref()));
                        log_file::log(&format!(
                            "lsp[{}] spawned, root={} supports_completion={supports} supports_signature_help={supports_signature_help} supports_hover={supports_hover} supports_definition={supports_definition} supports_declaration={supports_declaration} supports_type_definition={supports_type_definition} supports_implementation={supports_implementation} supports_references={supports_references} supports_rename={supports_rename}",
                            config.name,
                            root.display()
                        ));
                        spawned.push(ManagedClient {
                            name: config.name.to_string(),
                            client: Arc::new(TokioMutex::new(client)),
                            supports_completion: supports,
                            completion_triggers,
                            supports_signature_help,
                            supports_workspace_diagnostics,
                            diagnostic_identifier,
                            diagnostic_result_ids: Arc::new(TokioMutex::new(
                                DiagnosticResultIds::default(),
                            )),
                            diagnostic_pull_stalled: Arc::new(AtomicBool::new(false)),
                            save_notify,
                            supports_document_diagnostics,
                            document_pull_stalled: Arc::new(AtomicBool::new(false)),
                            prepare_rename_stalled: Arc::new(AtomicBool::new(false)),
                            document_pull_generations: Arc::new(StdMutex::new(HashMap::new())),
                            supports_hover,
                            supports_definition,
                            supports_document_symbol,
                            supports_declaration,
                            supports_type_definition,
                            supports_implementation,
                            supports_references,
                            supports_document_highlight,
                            supports_linked_editing,
                            supports_inline_completion,
                            supports_selection_range,
                            supports_call_hierarchy,
                            supports_type_hierarchy,
                            supports_workspace_symbols,
                            supports_rename,
                            supports_prepare_rename,
                            supports_formatting,
                            on_type_triggers,
                            supports_range_formatting,
                            supports_code_action,
                            semantic_legend,
                            semantic_supports_range,
                            supports_inlay_hints,
                            supports_document_link,
                            supports_code_lens,
                            code_lens_resolve,
                            server_commands,
                            supports_folding_range,
                            supports_document_color,
                            will_rename,
                            did_rename,
                        });
                    }
                    Err(e) => {
                        log_file::log(&format!("lsp[{}] spawn failed: {e}", config.name));
                    }
                }
            }
            // Publish declaration / type-definition / implementation support for
            // this language so the app can show or hide the matching "Go to ..."
            // menu items synchronously. Written even when empty (value false) so
            // a missing entry means "not probed yet" rather than "unsupported".
            let supports_declaration = spawned.iter().any(|c| c.supports_declaration);
            let supports_type_definition = spawned.iter().any(|c| c.supports_type_definition);
            let supports_implementation = spawned.iter().any(|c| c.supports_implementation);
            let supports_references = spawned.iter().any(|c| c.supports_references);
            let supports_formatting = spawned.iter().any(|c| c.supports_formatting);
            let supports_code_action = spawned.iter().any(|c| c.supports_code_action);
            let supports_call_hierarchy = spawned.iter().any(|c| c.supports_call_hierarchy);
            if let Ok(mut support) = self.capability_support.lock() {
                support.declaration.insert(lang, supports_declaration);
                support
                    .type_definition
                    .insert(lang, supports_type_definition);
                support.implementation.insert(lang, supports_implementation);
                support.references.insert(lang, supports_references);
                support.formatting.insert(lang, supports_formatting);
                let triggers: String = spawned
                    .iter()
                    .filter_map(|c| c.on_type_triggers.as_deref())
                    .collect();
                // No entry when nothing advertises the provider — a missing
                // entry is the documented "no server carries it" answer.
                // Removed (not skipped) on the empty case so a re-probe of
                // the same language overwrites last-write-wins, like every
                // sibling capability map above.
                if triggers.is_empty() {
                    support.on_type_triggers.remove(&lang);
                } else {
                    support.on_type_triggers.insert(lang, triggers);
                }
                // The server `request_completion` picks: the first that
                // completes.
                match spawned.iter().find(|c| c.supports_completion) {
                    Some(c) => support
                        .completion_triggers
                        .insert(key.clone(), c.completion_triggers.clone()),
                    None => support.completion_triggers.remove(&key),
                };
                support.code_action.insert(lang, supports_code_action);
                support.call_hierarchy.insert(lang, supports_call_hierarchy);
                if spawned.iter().any(|c| c.supports_inline_completion) {
                    support.inline_completion.insert(key.clone());
                } else {
                    support.inline_completion.remove(&key);
                }
                support
                    .will_rename
                    .insert(lang, spawned.iter().any(|c| c.will_rename.is_some()));
            }
            // The first pull (#533). A server that answers workspace
            // diagnostics reports on files no editor has opened, and firing
            // here is what puts them in PROBLEMS without a manual command -
            // there is no other moment that covers a workspace whose files
            // are all still closed. Servers that do not advertise it drop out
            // in `workspace_pull_targets`, so this stays silent for them.
            spawn_workspace_pull(
                workspace_pull_targets(spawned.iter()),
                self.diagnostics_tx.clone(),
            );
            // An empty list that comes back is a restart as far as the app is
            // concerned: it sent its tabs while the list was empty, so these
            // servers have none of them (#694).
            if !first_attempt && !spawned.is_empty() {
                self.restarts.restarted.store(true, Ordering::Relaxed);
            }
            // A restart that lost a server which ran before it is retried as
            // a set by the next `restart_dead_servers` pass. One that never
            // came up is not a reason to restart the others.
            match respawn {
                Some(expected)
                    if !spawned.is_empty()
                        && expected
                            .iter()
                            .any(|name| !spawned.iter().any(|c| &c.name == name)) =>
                {
                    self.restarts.incomplete.insert(key.clone(), expected);
                }
                _ => {
                    self.restarts.incomplete.remove(&key);
                }
            }
            self.clients.insert(key.clone(), spawned);
        }
        self.clients.get(&key).map(Vec::as_slice).unwrap_or(&[])
    }

    /// The first server running for the open document `path` that `supports`
    /// a method, as its name and client. Re-probes first, so a server
    /// installed since the file was opened (e.g. the managed vtsls finishing
    /// its lazy background install) is picked up without reopening the file;
    /// cheap once the list is non-empty.
    async fn pick_server(
        &mut self,
        path: &Path,
        supports: fn(&ManagedClient) -> bool,
    ) -> Result<(String, Arc<TokioMutex<LspClient>>), NoServer> {
        let doc = self.docs.get(path).ok_or(NoServer::Unknown)?;
        let lang = doc.language;
        let root = doc.project_root.clone();
        self.ensure_clients(lang, &root).await;
        self.clients
            .get(&(lang, root))
            .ok_or(NoServer::Unknown)?
            .iter()
            .find(|c| supports(c))
            .map(|c| (c.name.clone(), c.client.clone()))
            .ok_or(NoServer::Unsupported)
    }

    /// Spawn (or begin provisioning) the servers for every language whose
    /// root marker is evident in the workspace root — exactly what the
    /// first `open_doc` of that language would do, minus the document.
    async fn prewarm_workspace(&mut self) {
        self.prewarm_root(self.workspace_root.clone()).await;
    }

    /// Prewarm one root: spawn the servers for every language whose
    /// marker sits at that root. Startup runs it on the primary; adding a
    /// workspace folder (#147) runs it on the new root so its servers
    /// come up like a fresh workspace's.
    async fn prewarm_root(&mut self, root: PathBuf) {
        for lang in crate::lsp::languages::languages_evident_in(&root) {
            let clients = self.ensure_clients(lang, &root).await;
            if !clients.is_empty() {
                log_file::log(&format!(
                    "lsp prewarm: {} server(s) up for {} at {}",
                    clients.len(),
                    lang.lsp_id(),
                    root.display()
                ));
            }
        }
    }

    async fn open_doc(&mut self, path: PathBuf, text: String) {
        // The app re-sends every tab after a restart (#694). A document whose
        // servers did not restart is still open there, and a second didOpen
        // would break the protocol, so it goes out as a full-text change.
        if self.docs.contains_key(&path) {
            self.change_doc(path, text).await;
            return;
        }
        let Some(lang) = path_to_language(&path) else {
            return;
        };
        let project_root =
            project_root_for_roots(&path, lang, &self.workspace_root, &self.extra_roots);
        let clients = self.ensure_clients(lang, &project_root).await;
        if clients.is_empty() {
            return;
        }
        let Ok(uri) = Url::from_file_path(&path) else {
            return;
        };
        let arcs: Vec<(String, Arc<TokioMutex<LspClient>>)> = clients
            .iter()
            .map(|c| (c.name.clone(), c.client.clone()))
            .collect();
        for (name, client_arc) in arcs {
            let mut client = client_arc.lock().await;
            if let Err(e) = client.did_open(uri.clone(), lang.lsp_id(), 0, text.clone()) {
                log_file::log(&format!("lsp[{name}] did_open failed: {e}"));
            }
        }
        // Pull-mode servers report only when asked (#866); ask at once, since
        // nothing is typed yet to debounce.
        let key: ClientKey = (lang, project_root.clone());
        let pulls = self
            .clients
            .get(&key)
            .map(|cs| document_pull_targets(cs.iter(), &path, &uri, &self.capability_support))
            .unwrap_or_default();
        spawn_document_pulls(
            pulls,
            self.diagnostics_tx.clone(),
            std::time::Duration::ZERO,
        );
        // Who reports on it (#851): every server open on it, less any retired
        // from document pulls, since those report nothing.
        let reporting: Vec<String> = self
            .clients
            .get(&key)
            .into_iter()
            .flatten()
            .filter(|c| !c.document_pull_stalled.load(Ordering::Relaxed))
            .map(|c| c.name.clone())
            .collect();
        let open_on: Vec<String> = self
            .clients
            .get(&key)
            .into_iter()
            .flatten()
            .map(|c| c.name.clone())
            .collect();
        if let Ok(mut support) = self.capability_support.lock() {
            support.document_servers.insert(path.clone(), reporting);
            support.document_clients.insert(path.clone(), open_on);
            support
                .document_roots
                .insert(path.clone(), project_root.clone());
        }
        self.docs.insert(
            path,
            DocState {
                language: lang,
                project_root,
                version: 0,
            },
        );
    }

    async fn change_doc(&mut self, path: PathBuf, text: String) {
        let Some(doc) = self.docs.get_mut(&path) else {
            return;
        };
        doc.version += 1;
        let version = doc.version;
        let key: ClientKey = (doc.language, doc.project_root.clone());
        let Ok(uri) = Url::from_file_path(&path) else {
            return;
        };
        let arcs: Vec<(String, Arc<TokioMutex<LspClient>>)> = match self.clients.get(&key) {
            Some(cs) => cs
                .iter()
                .map(|c| (c.name.clone(), c.client.clone()))
                .collect(),
            None => return,
        };
        for (name, client_arc) in arcs {
            let mut client = client_arc.lock().await;
            if let Err(e) = client.did_change_full(uri.clone(), version, text.clone()) {
                log_file::log(&format!("lsp[{name}] did_change failed: {e}"));
            }
        }
        let pulls = self
            .clients
            .get(&key)
            .map(|cs| document_pull_targets(cs.iter(), &path, &uri, &self.capability_support))
            .unwrap_or_default();
        spawn_document_pulls(pulls, self.diagnostics_tx.clone(), DOCUMENT_PULL_DEBOUNCE);
    }

    async fn save_doc(&mut self, path: PathBuf, text: String) {
        let Some(doc) = self.docs.get(&path) else {
            return;
        };
        let key: ClientKey = (doc.language, doc.project_root.clone());
        let Ok(uri) = Url::from_file_path(&path) else {
            return;
        };
        // Only the servers that asked for saves (#854): ruff advertises no
        // `save` and warns "no handler" on every notification it is sent.
        let arcs: Vec<(String, Arc<TokioMutex<LspClient>>, SaveNotify)> =
            match self.clients.get(&key) {
                Some(cs) => cs
                    .iter()
                    .filter(|c| c.save_notify != SaveNotify::Never)
                    .map(|c| (c.name.clone(), c.client.clone(), c.save_notify))
                    .collect(),
                None => return,
            };
        // The text is cloned only for a server that asks for it while another
        // still waits after it; the last one gets the buffer itself.
        let mut wanting = arcs
            .iter()
            .filter(|(_, _, notify)| *notify == SaveNotify::WithText)
            .count();
        let mut text = Some(text);
        for (name, client_arc, notify) in arcs {
            let text = if notify == SaveNotify::WithText {
                wanting -= 1;
                if wanting == 0 {
                    text.take()
                } else {
                    text.clone()
                }
            } else {
                None
            };
            let mut client = client_arc.lock().await;
            if let Err(e) = client.did_save(uri.clone(), text) {
                log_file::log(&format!("lsp[{name}] did_save failed: {e}"));
            }
        }
    }

    async fn close_doc(&mut self, path: PathBuf) {
        let Some(doc) = self.docs.remove(&path) else {
            return;
        };
        if let Ok(mut support) = self.capability_support.lock() {
            support.document_servers.remove(&path);
            support.document_clients.remove(&path);
            support.document_roots.remove(&path);
        }
        let Ok(uri) = Url::from_file_path(&path) else {
            return;
        };
        let key: ClientKey = (doc.language, doc.project_root.clone());
        let arcs: Vec<(String, Arc<TokioMutex<LspClient>>)> = match self.clients.get(&key) {
            Some(cs) => cs
                .iter()
                .map(|c| (c.name.clone(), c.client.clone()))
                .collect(),
            None => return,
        };
        for (name, client_arc) in arcs {
            let mut client = client_arc.lock().await;
            if let Err(e) = client.did_close(uri.clone()) {
                log_file::log(&format!("lsp[{name}] did_close failed: {e}"));
            }
        }
        // A pulled set describes an open buffer (#866): withdraw it, and
        // drop the generation so a pull still in flight stands down. A
        // server that also reports per workspace keeps covering the closed
        // file through that pull, so its rows stay.
        for managed in self.clients.get(&key).into_iter().flatten() {
            if !managed.supports_document_diagnostics {
                continue;
            }
            managed
                .document_pull_generations
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .remove(&path);
            if !managed.supports_workspace_diagnostics {
                let _ = self.diagnostics_tx.send(DiagnosticsUpdate {
                    path: path.clone(),
                    server: managed.name.clone(),
                    diagnostics: Vec::new(),
                    pulled: true,
                });
            }
        }
    }

    async fn request_completion(
        &mut self,
        request_id: u64,
        path: PathBuf,
        line: u32,
        character: u32,
        trigger: CompletionTrigger,
        tx: &std_mpsc::Sender<CompletionResult>,
    ) {
        let Some(doc) = self.docs.get(&path) else {
            return;
        };
        let lang = doc.language;
        let root = doc.project_root.clone();
        // Re-probe so a server installed since the file was opened (e.g. the
        // managed vtsls finishing its lazy background install) is picked up
        // without reopening the file. Cheap once the list is non-empty.
        self.ensure_clients(lang, &root).await;
        let Some(clients) = self.clients.get(&(lang, root)) else {
            return;
        };
        let picked = clients
            .iter()
            .find(|c| c.supports_completion)
            .map(|c| (c.name.clone(), c.client.clone()));
        let Some((server_name, client_arc)) = picked else {
            log_file::log(&format!(
                "completion request id={request_id} dropped: no client advertises completion_provider for {lang:?}"
            ));
            let _ = tx.send(CompletionResult {
                request_id,
                path,
                items: Vec::new(),
                is_incomplete: false,
            });
            return;
        };
        let Ok(uri) = Url::from_file_path(&path) else {
            return;
        };
        let tx = tx.clone();
        let path_clone = path.clone();
        log_file::log(&format!(
            "completion request id={request_id} server={server_name} path={} line={line} char={character} trigger={trigger:?}",
            path.display()
        ));
        tokio::spawn(async move {
            let (mut client, resolves) = {
                let client = client_arc.lock().await;
                let options = client.capabilities().completion_provider.as_ref();
                let resolves = options.and_then(|o| o.resolve_provider) == Some(true);
                (client.requests(), resolves)
            };
            let resp = client.completion(uri, line, character, trigger).await;
            drop(client);
            let convert = |item| listed_item(item, resolves);
            let (is_incomplete, items): (Option<bool>, Vec<CompletionItem>) = match resp {
                Ok(Some(CompletionResponse::Array(items))) => {
                    (None, items.into_iter().map(convert).collect())
                }
                Ok(Some(CompletionResponse::List(list))) => (
                    Some(list.is_incomplete),
                    list.items.into_iter().map(convert).collect(),
                ),
                Ok(None) => (None, Vec::new()),
                Err(e) => {
                    log_file::log(&format!("lsp[{server_name}] completion error: {e}"));
                    (None, Vec::new())
                }
            };
            let preview: Vec<&str> = items.iter().take(200).map(|i| i.label.as_str()).collect();
            let sample: Vec<String> = items
                .iter()
                .take(5)
                .map(|i| {
                    format!(
                        "{{label={:?} kind={:?} detail={:?} filter_text={:?} insert_text={:?}}}",
                        i.label, i.kind, i.detail, i.filter_text, i.insert_text
                    )
                })
                .collect();
            log_file::log(&format!(
                "completion response id={request_id} server={server_name} is_incomplete={is_incomplete:?} count={} labels={:?}",
                items.len(),
                preview
            ));
            if !sample.is_empty() {
                log_file::log(&format!(
                    "completion response id={request_id} server={server_name} sample={sample:?}"
                ));
            }
            let _ = tx.send(CompletionResult {
                request_id,
                path: path_clone,
                items,
                is_incomplete: is_incomplete == Some(true),
            });
        });
    }

    /// Send `completionItem/resolve` to the server `request_completion`
    /// asks, the one that listed the item (#928), and its answer back as a
    /// one-item completion reply, with no item when the server failed.
    async fn resolve_completion(
        &mut self,
        request_id: u64,
        path: PathBuf,
        item: Arc<lsp_types::CompletionItem>,
        tx: &std_mpsc::Sender<CompletionResult>,
    ) {
        let Ok((server_name, client_arc)) =
            self.pick_server(&path, |c| c.supports_completion).await
        else {
            return;
        };
        let tx = tx.clone();
        tokio::spawn(async move {
            let mut client = client_arc.lock().await.requests();
            let items = match client.completion_resolve((*item).clone()).await {
                Ok(item) => vec![into_item(item)],
                Err(e) => {
                    log_file::log(&format!(
                        "lsp[{server_name}] completion_resolve error: {e:#}"
                    ));
                    Vec::new()
                }
            };
            let _ = tx.send(CompletionResult {
                request_id,
                path,
                items,
                is_incomplete: false,
            });
        });
    }

    async fn request_signature_help(
        &mut self,
        request_id: u64,
        path: PathBuf,
        line: u32,
        character: u32,
        tx: &std_mpsc::Sender<SignatureHelpResult>,
    ) {
        let Some(doc) = self.docs.get(&path) else {
            return;
        };
        let lang = doc.language;
        let root = doc.project_root.clone();
        self.ensure_clients(lang, &root).await;
        let Some(clients) = self.clients.get(&(lang, root)) else {
            return;
        };
        // Every server that advertises the capability, in registration order.
        // Some servers (e.g. Astral's `ty`) advertise `signatureHelpProvider`
        // but return nothing, so we try each in turn and take the FIRST that
        // actually answers, rather than stopping at an empty stub.
        let candidates: Vec<(String, Arc<TokioMutex<LspClient>>)> = clients
            .iter()
            .filter(|c| c.supports_signature_help)
            .map(|c| (c.name.clone(), c.client.clone()))
            .collect();
        if candidates.is_empty() {
            log_file::log(&format!(
                "signatureHelp request id={request_id} dropped: no client advertises signature_help_provider for {lang:?}"
            ));
            let _ = tx.send(SignatureHelpResult {
                request_id,
                path,
                signatures: Vec::new(),
                active_signature: 0,
            });
            return;
        }
        let Ok(uri) = Url::from_file_path(&path) else {
            return;
        };
        let tx = tx.clone();
        let path_clone = path.clone();
        log_file::log(&format!(
            "signatureHelp request id={request_id} servers={:?} line={line} char={character}",
            candidates
                .iter()
                .map(|(n, _)| n.as_str())
                .collect::<Vec<_>>()
        ));
        tokio::spawn(async move {
            let mut signatures = Vec::new();
            let mut active_signature = 0;
            for (name, client_arc) in &candidates {
                let mut client = client_arc.lock().await.requests();
                let resp = client.signature_help(uri.clone(), line, character).await;
                drop(client);
                let (sigs, active) = match resp {
                    Ok(Some(help)) => normalise_signature_help(help),
                    Ok(None) => (Vec::new(), 0),
                    Err(e) => {
                        log_file::log(&format!("lsp[{name}] signatureHelp error: {e}"));
                        (Vec::new(), 0)
                    }
                };
                log_file::log(&format!(
                    "signatureHelp response id={request_id} server={name} count={}",
                    sigs.len()
                ));
                if !sigs.is_empty() {
                    signatures = sigs;
                    active_signature = active;
                    break;
                }
            }
            let _ = tx.send(SignatureHelpResult {
                request_id,
                path: path_clone,
                signatures,
                active_signature,
            });
        });
    }

    /// Send `request` to the rust-analyzer serving `path` (#1626). Every
    /// path answers: with no rust-analyzer for the file the reply says so,
    /// so the command that asked never waits on nothing.
    async fn request_rust_analyzer(
        &mut self,
        request_id: u64,
        path: PathBuf,
        request: crate::lsp::rust_analyzer::RaRequest,
        (line, character): (u32, u32),
        tx: &std_mpsc::Sender<RustAnalyzerResult>,
    ) {
        let answer = |outcome: Result<serde_json::Value, String>| RustAnalyzerResult {
            request_id,
            request,
            outcome,
        };
        let not_running = || {
            answer(Err(format!(
                "{} is not running for this file",
                crate::lsp::rust_analyzer::SERVER
            )))
        };
        let Some(doc) = self.docs.get(&path) else {
            let _ = tx.send(not_running());
            return;
        };
        let key = (doc.language, doc.project_root.clone());
        self.ensure_clients(key.0, &key.1).await;
        let picked = self.clients.get(&key).and_then(|clients| {
            clients
                .iter()
                .find(|c| c.name == crate::lsp::rust_analyzer::SERVER)
                .map(|c| c.client.clone())
        });
        let (Some(client_arc), Ok(uri)) = (picked, Url::from_file_path(&path)) else {
            let _ = tx.send(not_running());
            return;
        };
        let params = request.params(&uri, line, character);
        let tx = tx.clone();
        tokio::spawn(async move {
            let mut client = client_arc.lock().await.requests();
            let outcome = client
                .rust_analyzer(request, params)
                .await
                .map_err(|e| format!("{e:#}"));
            if let Err(e) = &outcome {
                log_file::log(&format!(
                    "lsp[rust-analyzer] {} error: {e}",
                    request.method()
                ));
            }
            let _ = tx.send(RustAnalyzerResult {
                request_id,
                request,
                outcome,
            });
        });
    }

    async fn request_hover(
        &mut self,
        request_id: u64,
        path: PathBuf,
        line: u32,
        character: u32,
        tx: &std_mpsc::Sender<HoverResult>,
    ) {
        // Every hover is answered, an empty answer when no server can give
        // one: the app holds a problem's message until the reply, and Show
        // Hover says when there is nothing (#1518).
        let none = || {
            let _ = tx.send(HoverResult {
                request_id,
                text: None,
            });
        };
        let (server_name, client_arc) = match self.pick_server(&path, |c| c.supports_hover).await {
            Ok(picked) => picked,
            Err(NoServer::Unsupported | NoServer::Unknown) => return none(),
        };
        let Ok(uri) = Url::from_file_path(&path) else {
            return none();
        };
        let tx = tx.clone();
        log_file::log(&format!(
            "hover request id={request_id} server={server_name} path={} line={line} char={character}",
            path.display()
        ));
        tokio::spawn(async move {
            let mut client = client_arc.lock().await.requests();
            let resp = client.hover(uri, line, character).await;
            drop(client);
            let text = match resp {
                Ok(Some(h)) => hover_text(&h.contents),
                Ok(None) => None,
                Err(e) => {
                    log_file::log(&format!("lsp[{server_name}] hover error: {e}"));
                    None
                }
            };
            log_file::log(&format!(
                "hover response id={request_id} server={server_name} has_text={}",
                text.is_some()
            ));
            let _ = tx.send(HoverResult { request_id, text });
        });
    }

    async fn request_semantic_tokens(
        &mut self,
        path: PathBuf,
        seq: u64,
        generation: u64,
        tx: &std_mpsc::Sender<SemanticTokensUpdate>,
    ) {
        let Some(doc) = self.docs.get(&path) else {
            return;
        };
        let lang = doc.language;
        let root = doc.project_root.clone();
        self.ensure_clients(lang, &root).await;
        let Some(clients) = self.clients.get(&(lang, root)) else {
            return;
        };
        // Prefer a range-capable semantic-token provider (ty answers in tens
        // of ms even on a huge cold workspace and is a purpose-built
        // incremental highlighter) over a full-only one (basedpyright, which
        // pays a slow whole-tree enumeration before its first response). Fall
        // back to any server with a legend so single-server languages and
        // setups without ty still get tokens.
        let pick = |c: &ManagedClient| {
            c.semantic_legend
                .clone()
                .map(|leg| (c.name.clone(), c.client.clone(), leg))
        };
        let picked = clients
            .iter()
            .filter(|c| c.semantic_supports_range)
            .find_map(&pick)
            .or_else(|| clients.iter().find_map(&pick));
        let Some((server_name, client_arc, legend)) = picked else {
            return;
        };
        let Ok(uri) = Url::from_file_path(&path) else {
            return;
        };
        let tx = tx.clone();
        let path_clone = path.clone();
        tokio::spawn(async move {
            // A server freshly spawned for a cold root can answer the very
            // first `semanticTokens/full` (fired microseconds after didOpen)
            // with an empty set before its analysis is ready, then have the
            // real tokens available a beat later. ty does NOT send
            // `workspace/semanticTokens/refresh` to prompt a re-pull (verified
            // empirically), and the doc-sync loop only re-requests on an edit,
            // so without this retry an unedited file would stay uncoloured for
            // seconds. Retry on empty with a short bounded backoff; stop at the
            // first non-empty batch (or after the last attempt, emitting empty
            // so a genuinely token-free file still resolves).
            const BACKOFF_MS: [u64; 5] = [0, 80, 160, 320, 640];
            let mut data: Vec<u32> = Vec::new();
            for (attempt, delay) in BACKOFF_MS.iter().enumerate() {
                if *delay > 0 {
                    tokio::time::sleep(std::time::Duration::from_millis(*delay)).await;
                }
                let mut client = client_arc.lock().await.requests();
                let resp = client.semantic_tokens_full(uri.clone()).await;
                drop(client);
                data = match resp {
                    Ok(Some(SemanticTokensResult::Tokens(t))) => flatten_semantic_tokens(&t.data),
                    Ok(Some(SemanticTokensResult::Partial(p))) => flatten_semantic_tokens(&p.data),
                    Ok(None) => Vec::new(),
                    Err(e) => {
                        log_file::log(&format!("lsp[{server_name}] semantic_tokens error: {e}"));
                        Vec::new()
                    }
                };
                if !data.is_empty() {
                    if attempt > 0 {
                        log_file::log(&format!(
                            "semantic_tokens server={server_name} resolved on retry #{attempt} for {}",
                            path_clone.display()
                        ));
                    }
                    break;
                }
            }
            log_file::log(&format!(
                "semantic_tokens response server={server_name} path={} tokens={}",
                path_clone.display(),
                data.len() / 5
            ));
            let _ = tx.send(SemanticTokensUpdate {
                path: path_clone,
                seq,
                generation,
                data,
                legend,
                is_full: true,
            });
        });
    }

    async fn request_inlay_hints(
        &mut self,
        path: PathBuf,
        end: Position,
        seq: u64,
        tx: &std_mpsc::Sender<InlayHintsUpdate>,
    ) {
        let Ok((server_name, client_arc)) =
            self.pick_server(&path, |c| c.supports_inlay_hints).await
        else {
            return;
        };
        let Ok(uri) = Url::from_file_path(&path) else {
            return;
        };
        let tx = tx.clone();
        tokio::spawn(async move {
            let mut client = client_arc.lock().await.requests();
            let resp = client.inlay_hints(uri, end).await;
            drop(client);
            let hints = match resp {
                Ok(Some(hints)) => hints.into_iter().map(normalise_inlay_hint).collect(),
                Ok(None) => Vec::new(),
                Err(e) => {
                    log_file::log(&format!("lsp[{server_name}] inlay_hints error: {e}"));
                    Vec::new()
                }
            };
            log_file::log(&format!(
                "inlay_hints response server={server_name} path={} hints={}",
                path.display(),
                hints.len()
            ));
            let _ = tx.send(InlayHintsUpdate { path, seq, hints });
        });
    }

    /// Document links (#254): fire-and-forget, seq-gated, silent when
    /// unsupported — Ctrl+click simply keeps meaning Go to Definition.
    async fn request_document_links(
        &mut self,
        path: PathBuf,
        seq: u64,
        tx: &std_mpsc::Sender<DocumentLinksUpdate>,
    ) {
        let Ok((server_name, client_arc)) =
            self.pick_server(&path, |c| c.supports_document_link).await
        else {
            return;
        };
        let Ok(uri) = Url::from_file_path(&path) else {
            return;
        };
        let tx = tx.clone();
        tokio::spawn(async move {
            let mut client = client_arc.lock().await.requests();
            let resp = client.document_links(uri).await;
            drop(client);
            let links = match resp {
                Ok(Some(ls)) => ls
                    .iter()
                    .filter_map(|l| {
                        let target = l.target.as_ref()?;
                        Some(DocumentLinkItem {
                            line: l.range.start.line,
                            character: l.range.start.character,
                            end_line: l.range.end.line,
                            end_character: l.range.end.character,
                            target: target.to_string(),
                        })
                    })
                    .collect(),
                Ok(None) => Vec::new(),
                Err(e) => {
                    log_file::log(&format!("lsp[{server_name}] documentLink error: {e:#}"));
                    Vec::new()
                }
            };
            let _ = tx.send(DocumentLinksUpdate { path, seq, links });
        });
    }

    /// Fetch the document's code lenses (#608), resolving the ones the
    /// server left without a command. Silent when no client advertises
    /// `codeLensProvider`.
    async fn request_code_lens(
        &mut self,
        path: PathBuf,
        seq: u64,
        tx: &std_mpsc::Sender<CodeLensUpdate>,
    ) {
        let Some(doc) = self.docs.get(&path) else {
            return;
        };
        let lang = doc.language;
        let root = doc.project_root.clone();
        self.ensure_clients(lang, &root).await;
        let Some(clients) = self.clients.get(&(lang, root)) else {
            return;
        };
        let picked = clients.iter().find(|c| c.supports_code_lens).map(|c| {
            (
                c.name.clone(),
                c.client.clone(),
                c.code_lens_resolve,
                c.server_commands.clone(),
            )
        });
        let Some((server_name, client_arc, resolve, server_commands)) = picked else {
            return;
        };
        let Ok(uri) = Url::from_file_path(&path) else {
            return;
        };
        let tx = tx.clone();
        tokio::spawn(async move {
            // Detached, and bounded: the worker loop's did-change for every
            // keystroke waits on this client's lock, so the lock is held only
            // to take a handle, and a server that never answers a resolve
            // costs at most the deadline (the #533 failure mode otherwise).
            let server = client_arc.lock().await.detached_server();
            let lenses = match tokio::time::timeout(
                CODE_LENS_TIMEOUT,
                LspClient::code_lens_on(server.clone(), uri),
            )
            .await
            {
                Ok(Ok(Some(ls))) => ls,
                Ok(Ok(None)) => Vec::new(),
                Ok(Err(e)) => {
                    log_file::log(&format!("lsp[{server_name}] codeLens error: {e:#}"));
                    return;
                }
                Err(_) => {
                    log_file::log(&format!("lsp[{server_name}] codeLens timed out"));
                    return;
                }
            };
            let deadline = tokio::time::Instant::now() + CODE_LENS_TIMEOUT;
            let mut out = Vec::new();
            for lens in lenses.into_iter().take(MAX_CODE_LENSES) {
                let lens = if lens.command.is_none() && resolve {
                    let left = deadline.saturating_duration_since(tokio::time::Instant::now());
                    if left.is_zero() {
                        break;
                    }
                    match tokio::time::timeout(
                        left,
                        LspClient::code_lens_resolve_on(server.clone(), lens),
                    )
                    .await
                    {
                        Ok(Ok(l)) => l,
                        Ok(Err(e)) => {
                            log_file::log(&format!(
                                "lsp[{server_name}] codeLens/resolve error: {e:#}"
                            ));
                            continue;
                        }
                        Err(_) => {
                            log_file::log(&format!(
                                "lsp[{server_name}] codeLens/resolve timed out; showing what resolved"
                            ));
                            break;
                        }
                    }
                } else {
                    lens
                };
                let Some(cmd) = lens.command else {
                    continue;
                };
                if cmd.title.trim().is_empty() {
                    continue;
                }
                out.push(CodeLensItem {
                    line: lens.range.start.line,
                    server_side: server_commands.contains(&cmd.command),
                    title: cmd.title,
                    command: (!cmd.command.is_empty()).then_some(cmd.command),
                    arguments: cmd.arguments.unwrap_or_default(),
                });
            }
            let _ = tx.send(CodeLensUpdate {
                path,
                seq,
                lenses: out,
            });
        });
    }

    /// Fetch the document's fold spans (#254). Silent when the path is
    /// untracked or no client advertises `foldingRangeProvider` — the app
    /// falls back to its indentation/region scan by never hearing back.
    async fn request_folding_ranges(
        &mut self,
        path: PathBuf,
        seq: u64,
        tx: &std_mpsc::Sender<FoldingRangesUpdate>,
    ) {
        let Ok((server_name, client_arc)) =
            self.pick_server(&path, |c| c.supports_folding_range).await
        else {
            return;
        };
        let Ok(uri) = Url::from_file_path(&path) else {
            return;
        };
        let tx = tx.clone();
        tokio::spawn(async move {
            let mut client = client_arc.lock().await.requests();
            let resp = client.folding_ranges(uri).await;
            drop(client);
            let ranges = match resp {
                Ok(Some(ranges)) => ranges
                    .into_iter()
                    .filter_map(normalise_folding_range)
                    .collect(),
                Ok(None) => Vec::new(),
                Err(e) => {
                    log_file::log(&format!("lsp[{server_name}] folding_ranges error: {e}"));
                    Vec::new()
                }
            };
            let _ = tx.send(FoldingRangesUpdate { path, seq, ranges });
        });
    }

    /// Document colors (#254): fire-and-forget, seq-gated, silent when
    /// unsupported — the swatch decoration simply never appears.
    async fn request_document_colors(
        &mut self,
        path: PathBuf,
        seq: u64,
        tx: &std_mpsc::Sender<DocumentColorsUpdate>,
    ) {
        let Ok((server_name, client_arc)) =
            self.pick_server(&path, |c| c.supports_document_color).await
        else {
            return;
        };
        let Ok(uri) = Url::from_file_path(&path) else {
            return;
        };
        let tx = tx.clone();
        tokio::spawn(async move {
            let mut client = client_arc.lock().await.requests();
            let resp = client.document_color(uri).await;
            drop(client);
            let colors = match resp {
                Ok(infos) => infos.iter().map(color_item).collect(),
                Err(e) => {
                    log_file::log(&format!("lsp[{server_name}] documentColor error: {e:#}"));
                    Vec::new()
                }
            };
            let _ = tx.send(DocumentColorsUpdate { path, seq, colors });
        });
    }

    /// Color presentations (#254): always answers — a picker is waiting.
    async fn request_color_presentations(
        &mut self,
        request_id: u64,
        path: PathBuf,
        color: (f32, f32, f32, f32),
        start: (u32, u32),
        end: (u32, u32),
        tx: &std_mpsc::Sender<ColorPresentationsResult>,
    ) {
        let empty = |tx: &std_mpsc::Sender<ColorPresentationsResult>| {
            let _ = tx.send(ColorPresentationsResult {
                request_id,
                presentations: Vec::new(),
            });
        };
        let Ok((server_name, client_arc)) =
            self.pick_server(&path, |c| c.supports_document_color).await
        else {
            empty(tx);
            return;
        };
        let Ok(uri) = Url::from_file_path(&path) else {
            empty(tx);
            return;
        };
        let lsp_color = lsp_types::Color {
            red: color.0,
            green: color.1,
            blue: color.2,
            alpha: color.3,
        };
        let tx = tx.clone();
        tokio::spawn(async move {
            let mut client = client_arc.lock().await.requests();
            let resp = client.color_presentations(uri, lsp_color, start, end).await;
            drop(client);
            let presentations = match resp {
                Ok(ps) => ps
                    .into_iter()
                    .map(|p| {
                        // A presentation without an explicit edit means
                        // "replace the color's range with the label".
                        let mut edits: Vec<TextSpanEdit> = Vec::new();
                        match &p.text_edit {
                            Some(te) => edits.push(text_edit_to_span(te)),
                            None => edits.push(TextSpanEdit {
                                start: (start.0 as usize, start.1 as usize),
                                end: (end.0 as usize, end.1 as usize),
                                new_text: p.label.clone(),
                                utf16: true,
                            }),
                        }
                        for te in p.additional_text_edits.iter().flatten() {
                            edits.push(text_edit_to_span(te));
                        }
                        (p.label, edits)
                    })
                    .collect(),
                Err(e) => {
                    log_file::log(&format!(
                        "lsp[{server_name}] colorPresentation error: {e:#}"
                    ));
                    Vec::new()
                }
            };
            let _ = tx.send(ColorPresentationsResult {
                request_id,
                presentations,
            });
        });
    }

    async fn request_semantic_tokens_range(
        &mut self,
        path: PathBuf,
        start_line: u32,
        end: Position,
        seq: u64,
        generation: u64,
        tx: &std_mpsc::Sender<SemanticTokensUpdate>,
    ) {
        let Some(doc) = self.docs.get(&path) else {
            return;
        };
        let lang = doc.language;
        let root = doc.project_root.clone();
        self.ensure_clients(lang, &root).await;
        let Some(clients) = self.clients.get(&(lang, root)) else {
            return;
        };
        // A range request only makes sense to a server that actually advertises
        // `semanticTokens/range`; there is no full-only fallback here because
        // the whole-document `request_semantic_tokens` covers those servers.
        let picked = clients
            .iter()
            .filter(|c| c.semantic_supports_range)
            .find_map(|c| {
                c.semantic_legend
                    .clone()
                    .map(|leg| (c.name.clone(), c.client.clone(), leg))
            });
        let Some((server_name, client_arc, legend)) = picked else {
            return;
        };
        let Ok(uri) = Url::from_file_path(&path) else {
            return;
        };
        let tx = tx.clone();
        let path_clone = path.clone();
        tokio::spawn(async move {
            let mut client = client_arc.lock().await.requests();
            let resp = client.semantic_tokens_range(uri, start_line, end).await;
            drop(client);
            let data: Vec<u32> = match resp {
                Ok(Some(SemanticTokensRangeResult::Tokens(t))) => flatten_semantic_tokens(&t.data),
                Ok(Some(SemanticTokensRangeResult::Partial(p))) => flatten_semantic_tokens(&p.data),
                Ok(None) => Vec::new(),
                Err(e) => {
                    log_file::log(&format!(
                        "lsp[{server_name}] semantic_tokens_range error: {e}"
                    ));
                    Vec::new()
                }
            };
            log_file::log(&format!(
                "semantic_tokens range response server={server_name} path={} lines={start_line}..{} tokens={}",
                path_clone.display(),
                end.line,
                data.len() / 5
            ));
            let _ = tx.send(SemanticTokensUpdate {
                path: path_clone,
                seq,
                generation,
                data,
                legend,
                is_full: false,
            });
        });
    }

    async fn request_definition(
        &mut self,
        request_id: u64,
        path: PathBuf,
        line: u32,
        character: u32,
        tx: &std_mpsc::Sender<DefinitionResult>,
    ) {
        let (server_name, client_arc) =
            match self.pick_server(&path, |c| c.supports_definition).await {
                Ok(picked) => picked,
                Err(NoServer::Unsupported) => {
                    let _ = tx.send(DefinitionResult {
                        request_id,
                        target: None,
                    });
                    return;
                }
                Err(NoServer::Unknown) => return,
            };
        let Ok(uri) = Url::from_file_path(&path) else {
            return;
        };
        let tx = tx.clone();
        log_file::log(&format!(
            "definition request id={request_id} server={server_name} path={} line={line} char={character}",
            path.display()
        ));
        tokio::spawn(async move {
            let mut client = client_arc.lock().await.requests();
            let resp = client.definition(uri, line, character).await;
            drop(client);
            let target = match resp {
                Ok(Some(r)) => def_location(&r),
                Ok(None) => None,
                Err(e) => {
                    log_file::log(&format!("lsp[{server_name}] definition error: {e:#}"));
                    None
                }
            };
            log_file::log(&format!(
                "definition response id={request_id} server={server_name} has_target={}",
                target.is_some()
            ));
            let _ = tx.send(DefinitionResult { request_id, target });
        });
    }

    async fn request_document_symbols(
        &mut self,
        path: PathBuf,
        seq: u64,
        tx: &std_mpsc::Sender<DocumentSymbolsResult>,
    ) {
        let (server_name, client_arc) = match self
            .pick_server(&path, |c| c.supports_document_symbol)
            .await
        {
            Ok(picked) => picked,
            Err(NoServer::Unsupported) => {
                // No symbol provider: send an empty outline so the panel shows
                // "No symbols" rather than a stale tree from a previous file.
                let _ = tx.send(DocumentSymbolsResult {
                    path,
                    seq,
                    symbols: Vec::new(),
                });
                return;
            }
            Err(NoServer::Unknown) => return,
        };
        let Ok(uri) = Url::from_file_path(&path) else {
            return;
        };
        let tx = tx.clone();
        let path_clone = path.clone();
        tokio::spawn(async move {
            let mut client = client_arc.lock().await.requests();
            let resp = client.document_symbol(uri).await;
            drop(client);
            let symbols = match resp {
                Ok(Some(r)) => flatten_symbols(r),
                Ok(None) => Vec::new(),
                Err(e) => {
                    log_file::log(&format!("lsp[{server_name}] document_symbol error: {e:#}"));
                    Vec::new()
                }
            };
            log_file::log(&format!(
                "document_symbol response server={server_name} count={}",
                symbols.len()
            ));
            let _ = tx.send(DocumentSymbolsResult {
                path: path_clone,
                seq,
                symbols,
            });
        });
    }

    async fn request_declaration(
        &mut self,
        request_id: u64,
        path: PathBuf,
        line: u32,
        character: u32,
        tx: &std_mpsc::Sender<DeclarationResult>,
    ) {
        let (server_name, client_arc) =
            match self.pick_server(&path, |c| c.supports_declaration).await {
                Ok(picked) => picked,
                Err(NoServer::Unsupported) => {
                    let _ = tx.send(DeclarationResult {
                        request_id,
                        target: None,
                        unsupported: true,
                    });
                    return;
                }
                Err(NoServer::Unknown) => return,
            };
        let Ok(uri) = Url::from_file_path(&path) else {
            return;
        };
        let tx = tx.clone();
        log_file::log(&format!(
            "declaration request id={request_id} server={server_name} path={} line={line} char={character}",
            path.display()
        ));
        tokio::spawn(async move {
            let mut client = client_arc.lock().await.requests();
            let resp = client.declaration(uri, line, character).await;
            drop(client);
            let target = match resp {
                Ok(Some(r)) => def_location(&r),
                Ok(None) => None,
                // `{e:#}` prints the full anyhow chain (the underlying JSON-RPC
                // error), not just the "declaration" context label.
                Err(e) => {
                    log_file::log(&format!("lsp[{server_name}] declaration error: {e:#}"));
                    None
                }
            };
            log_file::log(&format!(
                "declaration response id={request_id} server={server_name} has_target={}",
                target.is_some()
            ));
            let _ = tx.send(DeclarationResult {
                request_id,
                target,
                unsupported: false,
            });
        });
    }

    async fn request_type_definition(
        &mut self,
        request_id: u64,
        path: PathBuf,
        line: u32,
        character: u32,
        tx: &std_mpsc::Sender<TypeDefinitionResult>,
    ) {
        let (server_name, client_arc) = match self
            .pick_server(&path, |c| c.supports_type_definition)
            .await
        {
            Ok(picked) => picked,
            Err(NoServer::Unsupported) => {
                let _ = tx.send(TypeDefinitionResult {
                    request_id,
                    target: None,
                    unsupported: true,
                });
                return;
            }
            Err(NoServer::Unknown) => return,
        };
        let Ok(uri) = Url::from_file_path(&path) else {
            return;
        };
        let tx = tx.clone();
        log_file::log(&format!(
            "type_definition request id={request_id} server={server_name} path={} line={line} char={character}",
            path.display()
        ));
        tokio::spawn(async move {
            let mut client = client_arc.lock().await.requests();
            let resp = client.type_definition(uri, line, character).await;
            drop(client);
            let target = match resp {
                Ok(Some(r)) => def_location(&r),
                Ok(None) => None,
                // `{e:#}` prints the full anyhow chain (the underlying JSON-RPC
                // error), not just the "type_definition" context label.
                Err(e) => {
                    log_file::log(&format!("lsp[{server_name}] type_definition error: {e:#}"));
                    None
                }
            };
            log_file::log(&format!(
                "type_definition response id={request_id} server={server_name} has_target={}",
                target.is_some()
            ));
            let _ = tx.send(TypeDefinitionResult {
                request_id,
                target,
                unsupported: false,
            });
        });
    }

    async fn request_implementation(
        &mut self,
        request_id: u64,
        path: PathBuf,
        line: u32,
        character: u32,
        tx: &std_mpsc::Sender<ImplementationResult>,
    ) {
        let (server_name, client_arc) =
            match self.pick_server(&path, |c| c.supports_implementation).await {
                Ok(picked) => picked,
                Err(NoServer::Unsupported) => {
                    let _ = tx.send(ImplementationResult {
                        request_id,
                        targets: Vec::new(),
                        unsupported: true,
                    });
                    return;
                }
                Err(NoServer::Unknown) => return,
            };
        let Ok(uri) = Url::from_file_path(&path) else {
            return;
        };
        let tx = tx.clone();
        log_file::log(&format!(
            "implementation request id={request_id} server={server_name} path={} line={line} char={character}",
            path.display()
        ));
        tokio::spawn(async move {
            let mut client = client_arc.lock().await.requests();
            let resp = client.implementation(uri, line, character).await;
            drop(client);
            let targets = match resp {
                Ok(Some(r)) => def_locations(&r),
                Ok(None) => Vec::new(),
                // `{e:#}` prints the full anyhow chain (the underlying JSON-RPC
                // error), not just the "implementation" context label.
                Err(e) => {
                    log_file::log(&format!("lsp[{server_name}] implementation error: {e:#}"));
                    Vec::new()
                }
            };
            log_file::log(&format!(
                "implementation response id={request_id} server={server_name} count={}",
                targets.len()
            ));
            let _ = tx.send(ImplementationResult {
                request_id,
                targets,
                unsupported: false,
            });
        });
    }

    /// Pull whole-project diagnostics from every spawned server that
    /// advertises `workspaceDiagnostics` (#533), and every open document's
    /// from each server that answers `textDocument/diagnostic` (#866): a
    /// server's `workspace/diagnostic/refresh` asks the client to re-pull
    /// everything it holds. Fire-and-forget: the reports land on the
    /// diagnostics channel the push path already feeds.
    fn request_workspace_diagnostics(&self) {
        spawn_workspace_pull(
            workspace_pull_targets(self.clients.values().flatten()),
            self.diagnostics_tx.clone(),
        );
        for (path, doc) in &self.docs {
            let Ok(uri) = Url::from_file_path(path) else {
                continue;
            };
            let key: ClientKey = (doc.language, doc.project_root.clone());
            let pulls = self
                .clients
                .get(&key)
                .map(|cs| document_pull_targets(cs.iter(), path, &uri, &self.capability_support))
                .unwrap_or_default();
            spawn_document_pulls(
                pulls,
                self.diagnostics_tx.clone(),
                std::time::Duration::ZERO,
            );
        }
    }

    /// `workspace/symbol`: fan the query out to every running server that
    /// advertises the capability (across every language and root — VS Code
    /// merges all providers the same way) and send one merged reply.
    async fn request_workspace_symbols(
        &mut self,
        request_id: u64,
        query: String,
        tx: &std_mpsc::Sender<WorkspaceSymbolsResult>,
    ) {
        let picked: Vec<(String, Arc<TokioMutex<LspClient>>)> = self
            .clients
            .values()
            .flatten()
            .filter(|c| c.supports_workspace_symbols)
            .map(|c| (c.name.clone(), c.client.clone()))
            .collect();
        if picked.is_empty() {
            let _ = tx.send(WorkspaceSymbolsResult {
                request_id,
                symbols: Vec::new(),
                unsupported: true,
            });
            return;
        }
        let tx = tx.clone();
        log_file::log(&format!(
            "workspace symbols request id={request_id} servers={} query={query:?}",
            picked.len()
        ));
        tokio::spawn(async move {
            let mut symbols: Vec<WorkspaceSymbolItem> = Vec::new();
            for (server_name, client_arc) in picked {
                let mut client = client_arc.lock().await.requests();
                let resp = client.workspace_symbols(query.clone()).await;
                drop(client);
                match resp {
                    Ok(Some(r)) => symbols.extend(workspace_symbol_items(r)),
                    Ok(None) => {}
                    Err(e) => {
                        log_file::log(&format!(
                            "lsp[{server_name}] workspace symbols error: {e:#}"
                        ));
                    }
                }
            }
            log_file::log(&format!(
                "workspace symbols response id={request_id} count={}",
                symbols.len()
            ));
            let _ = tx.send(WorkspaceSymbolsResult {
                request_id,
                symbols,
                unsupported: false,
            });
        });
    }

    async fn request_references(
        &mut self,
        request_id: u64,
        path: PathBuf,
        line: u32,
        character: u32,
        tx: &std_mpsc::Sender<ReferencesResult>,
    ) {
        let (server_name, client_arc) =
            match self.pick_server(&path, |c| c.supports_references).await {
                Ok(picked) => picked,
                Err(NoServer::Unsupported) => {
                    let _ = tx.send(ReferencesResult {
                        request_id,
                        targets: Vec::new(),
                        unsupported: true,
                    });
                    return;
                }
                Err(NoServer::Unknown) => return,
            };
        let Ok(uri) = Url::from_file_path(&path) else {
            return;
        };
        let tx = tx.clone();
        log_file::log(&format!(
            "references request id={request_id} server={server_name} path={} line={line} char={character}",
            path.display()
        ));
        tokio::spawn(async move {
            let mut client = client_arc.lock().await.requests();
            let resp = client.references(uri, line, character).await;
            drop(client);
            let targets = match resp {
                Ok(Some(locs)) => reference_locations(&locs),
                Ok(None) => Vec::new(),
                // `{e:#}` prints the full anyhow chain (the underlying JSON-RPC
                // error), not just the "references" context label.
                Err(e) => {
                    log_file::log(&format!("lsp[{server_name}] references error: {e:#}"));
                    Vec::new()
                }
            };
            log_file::log(&format!(
                "references response id={request_id} server={server_name} count={}",
                targets.len()
            ));
            let _ = tx.send(ReferencesResult {
                request_id,
                targets,
                unsupported: false,
            });
        });
    }

    async fn request_document_highlights(
        &mut self,
        request_id: u64,
        path: PathBuf,
        line: u32,
        character: u32,
        tx: &std_mpsc::Sender<DocumentHighlightsResult>,
    ) {
        // No unsupported reply: occurrences are a silent background
        // decoration, so a language without the capability just never
        // paints (the app cleared the old set when the caret moved).
        let Ok((server_name, client_arc)) = self
            .pick_server(&path, |c| c.supports_document_highlight)
            .await
        else {
            return;
        };
        let Ok(uri) = Url::from_file_path(&path) else {
            return;
        };
        let tx = tx.clone();
        tokio::spawn(async move {
            let mut client = client_arc.lock().await.requests();
            let resp = client.document_highlight(uri, line, character).await;
            drop(client);
            let items = match resp {
                Ok(Some(hs)) => occurrence_items(hs),
                Ok(None) => Vec::new(),
                Err(e) => {
                    log_file::log(&format!(
                        "lsp[{server_name}] documentHighlight error: {e:#}"
                    ));
                    Vec::new()
                }
            };
            let _ = tx.send(DocumentHighlightsResult { request_id, items });
        });
    }

    /// Linked-editing spans at the caret (#254). Silent on every
    /// early-out like occurrences: the mirror is a background behavior
    /// that simply never engages for a language without the provider.
    async fn request_linked_editing(
        &mut self,
        request_id: u64,
        path: PathBuf,
        line: u32,
        character: u32,
        tx: &std_mpsc::Sender<LinkedEditingResult>,
    ) {
        let Ok((server_name, client_arc)) =
            self.pick_server(&path, |c| c.supports_linked_editing).await
        else {
            return;
        };
        let Ok(uri) = Url::from_file_path(&path) else {
            return;
        };
        let tx = tx.clone();
        tokio::spawn(async move {
            let mut client = client_arc.lock().await.requests();
            let resp = client.linked_editing_range(uri, line, character).await;
            drop(client);
            let ranges = match resp {
                Ok(Some(l)) => l
                    .ranges
                    .iter()
                    .map(|r| (r.start.line, r.start.character, r.end.line, r.end.character))
                    .collect(),
                Ok(None) => Vec::new(),
                Err(e) => {
                    log_file::log(&format!(
                        "lsp[{server_name}] linkedEditingRange error: {e:#}"
                    ));
                    Vec::new()
                }
            };
            let _ = tx.send(LinkedEditingResult { request_id, ranges });
        });
    }

    /// Inline completion at the caret (#607). Silent on every early-out,
    /// like linked editing: the app asks once per caret and edit, and a
    /// request left unanswered is simply replaced by the next one.
    async fn request_inline_completion(
        &mut self,
        request_id: u64,
        path: PathBuf,
        line: u32,
        character: u32,
        tx: &std_mpsc::Sender<InlineCompletionResult>,
    ) {
        let Ok((server_name, client_arc)) = self
            .pick_server(&path, |c| c.supports_inline_completion)
            .await
        else {
            return;
        };
        let Ok(uri) = Url::from_file_path(&path) else {
            return;
        };
        let tx = tx.clone();
        tokio::spawn(async move {
            let mut client = client_arc.lock().await.requests();
            let resp = client.inline_completion(uri, line, character).await;
            drop(client);
            let item = match resp {
                Ok(Some(answer)) => first_inline_item(answer),
                Ok(None) => None,
                Err(e) => {
                    log_file::log(&format!("lsp[{server_name}] inlineCompletion error: {e:#}"));
                    None
                }
            };
            let _ = tx.send(InlineCompletionResult { request_id, item });
        });
    }

    /// Expand Selection chains (#254). UNLIKE occurrences, every early-out
    /// answers with `unsupported: true` — the gesture is waiting on this
    /// reply, and an unsupported verdict is what tells the app to grow the
    /// selection from tree-sitter ancestry right now instead of never.
    async fn request_selection_ranges(
        &mut self,
        request_id: u64,
        path: PathBuf,
        positions: Vec<(u32, u32)>,
        tx: &std_mpsc::Sender<SelectionRangesResult>,
    ) {
        let unsupported = |tx: &std_mpsc::Sender<SelectionRangesResult>| {
            let _ = tx.send(SelectionRangesResult {
                request_id,
                unsupported: true,
                chains: Vec::new(),
            });
        };
        let Ok((server_name, client_arc)) = self
            .pick_server(&path, |c| c.supports_selection_range)
            .await
        else {
            unsupported(tx);
            return;
        };
        let Ok(uri) = Url::from_file_path(&path) else {
            unsupported(tx);
            return;
        };
        let lsp_positions: Vec<lsp_types::Position> = positions
            .iter()
            .map(|&(line, character)| lsp_types::Position { line, character })
            .collect();
        let tx = tx.clone();
        tokio::spawn(async move {
            let mut client = client_arc.lock().await.requests();
            let resp = client.selection_ranges(uri, lsp_positions).await;
            drop(client);
            let (unsupported, chains) = match resp {
                Ok(Some(ranges)) => (false, ranges.iter().map(flatten_selection_chain).collect()),
                // An empty answer is a real answer: nothing to grow to.
                Ok(None) => (false, Vec::new()),
                Err(e) => {
                    log_file::log(&format!("lsp[{server_name}] selectionRange error: {e:#}"));
                    // Treat a wire error like unsupported so the gesture
                    // still resolves via the tree-sitter fallback.
                    (true, Vec::new())
                }
            };
            let _ = tx.send(SelectionRangesResult {
                request_id,
                unsupported,
                chains,
            });
        });
    }

    /// The two-step call-hierarchy flow: `prepareCallHierarchy` resolves the
    /// symbol at the caret into an item, then `incomingCalls` / `outgoingCalls`
    /// expands one level of it. One level per request — invoking again at a
    /// picked site walks the next level, which keeps the UI croft's existing
    /// location picker instead of a new tree widget.
    async fn request_call_hierarchy(
        &mut self,
        request_id: u64,
        path: PathBuf,
        line: u32,
        character: u32,
        incoming: bool,
        tx: &std_mpsc::Sender<CallHierarchyResult>,
    ) {
        let kind = if incoming {
            HierarchyKind::IncomingCalls
        } else {
            HierarchyKind::OutgoingCalls
        };
        let (server_name, client_arc) =
            match self.pick_server(&path, |c| c.supports_call_hierarchy).await {
                Ok(picked) => picked,
                Err(NoServer::Unsupported) => {
                    let _ = tx.send(CallHierarchyResult {
                        request_id,
                        kind,
                        sites: Vec::new(),
                        unsupported: true,
                    });
                    return;
                }
                Err(NoServer::Unknown) => return,
            };
        let Ok(uri) = Url::from_file_path(&path) else {
            return;
        };
        let tx = tx.clone();
        tokio::spawn(async move {
            let mut client = client_arc.lock().await.requests();
            let item = match client.prepare_call_hierarchy(uri, line, character).await {
                Ok(Some(mut items)) if !items.is_empty() => items.remove(0),
                Ok(_) => {
                    drop(client);
                    let _ = tx.send(CallHierarchyResult {
                        request_id,
                        kind,
                        sites: Vec::new(),
                        unsupported: false,
                    });
                    return;
                }
                Err(e) => {
                    log_file::log(&format!(
                        "lsp[{server_name}] prepareCallHierarchy error: {e:#}"
                    ));
                    return;
                }
            };
            let sites = if incoming {
                match client.incoming_calls(item).await {
                    Ok(Some(calls)) => incoming_call_sites(calls),
                    Ok(None) => Vec::new(),
                    Err(e) => {
                        log_file::log(&format!("lsp[{server_name}] incomingCalls error: {e:#}"));
                        Vec::new()
                    }
                }
            } else {
                match client.outgoing_calls(item).await {
                    Ok(Some(calls)) => outgoing_call_sites(calls),
                    Ok(None) => Vec::new(),
                    Err(e) => {
                        log_file::log(&format!("lsp[{server_name}] outgoingCalls error: {e:#}"));
                        Vec::new()
                    }
                }
            };
            drop(client);
            let _ = tx.send(CallHierarchyResult {
                request_id,
                kind,
                sites,
                unsupported: false,
            });
        });
    }

    /// Type hierarchy (#613): prepare, then supertypes or subtypes, replied
    /// on the call-hierarchy channel so the app's picker serves both.
    async fn request_type_hierarchy(
        &mut self,
        request_id: u64,
        path: PathBuf,
        line: u32,
        character: u32,
        supertypes: bool,
        tx: &std_mpsc::Sender<CallHierarchyResult>,
    ) {
        let kind = if supertypes {
            HierarchyKind::Supertypes
        } else {
            HierarchyKind::Subtypes
        };
        let Some(doc) = self.docs.get(&path) else {
            return;
        };
        let lang = doc.language;
        let root = doc.project_root.clone();
        self.ensure_clients(lang, &root).await;
        let Some(clients) = self.clients.get(&(lang, root)) else {
            return;
        };
        let picked = clients
            .iter()
            .find(|c| c.supports_type_hierarchy)
            .map(|c| (c.name.clone(), c.client.clone()));
        let reply = move |sites: Vec<CallSite>, unsupported: bool| CallHierarchyResult {
            request_id,
            kind,
            sites,
            unsupported,
        };
        let Some((server_name, client_arc)) = picked else {
            let _ = tx.send(reply(Vec::new(), true));
            return;
        };
        let Ok(uri) = Url::from_file_path(&path) else {
            return;
        };
        let tx = tx.clone();
        tokio::spawn(async move {
            let mut client = client_arc.lock().await.requests();
            let item = match client.prepare_type_hierarchy(uri, line, character).await {
                Ok(Some(mut items)) if !items.is_empty() => items.remove(0),
                Ok(_) => {
                    drop(client);
                    let _ = tx.send(reply(Vec::new(), false));
                    return;
                }
                Err(e) => {
                    log_file::log(&format!(
                        "lsp[{server_name}] prepareTypeHierarchy error: {e:#}"
                    ));
                    return;
                }
            };
            let sites = match client.type_hierarchy(item, supertypes).await {
                Ok(Some(items)) => type_hierarchy_sites(items),
                Ok(None) => Vec::new(),
                Err(e) => {
                    log_file::log(&format!("lsp[{server_name}] {} error: {e:#}", kind.noun()));
                    Vec::new()
                }
            };
            drop(client);
            let _ = tx.send(reply(sites, false));
        });
    }

    #[allow(clippy::too_many_arguments)]
    async fn request_code_action(
        &mut self,
        request_id: u64,
        path: PathBuf,
        start_line: u32,
        start_char: u32,
        end_line: u32,
        end_char: u32,
        diagnostics: Vec<Diagnostic>,
        tx: &std_mpsc::Sender<CodeActionResult>,
    ) {
        let Some(doc) = self.docs.get(&path) else {
            return;
        };
        let lang = doc.language;
        let root = doc.project_root.clone();
        self.ensure_clients(lang, &root).await;
        let Some(clients) = self.clients.get(&(lang, root)) else {
            return;
        };
        // Aggregate across EVERY server that supports code actions, like VS Code:
        // for Python that is ty (type fixes), basedpyright (import fixes), and
        // ruff (lint quick-fixes + "Organize Imports" / "Fix all"). Picking only
        // the first server would silently drop ruff's source actions.
        let servers: Vec<(String, Arc<TokioMutex<LspClient>>)> = clients
            .iter()
            .filter(|c| c.supports_code_action)
            .map(|c| (c.name.clone(), c.client.clone()))
            .collect();
        if servers.is_empty() {
            let _ = tx.send(CodeActionResult {
                request_id,
                items: None,
                unsupported: true,
            });
            return;
        }
        let Ok(uri) = Url::from_file_path(&path) else {
            return;
        };
        let range = lsp_types::Range {
            start: lsp_types::Position {
                line: start_line,
                character: start_char,
            },
            end: lsp_types::Position {
                line: end_line,
                character: end_char,
            },
        };
        let tx = tx.clone();
        log_file::log(&format!(
            "code_action request id={request_id} servers={} path={} line={start_line}",
            servers.len(),
            path.display()
        ));
        tokio::spawn(async move {
            let mut combined: Vec<CodeActionItem> = Vec::new();
            let mut any_ran = false;
            for (server_name, client_arc) in servers {
                let diags = code_action_diagnostics(&diagnostics, &server_name);
                let mut client = client_arc.lock().await.requests();
                let resp = client.code_action(uri.clone(), range, diags).await;
                drop(client);
                match resp {
                    Ok(Some(r)) => {
                        any_ran = true;
                        combined.extend(code_action_items(&r, &server_name));
                    }
                    Ok(None) => any_ran = true,
                    Err(e) => {
                        log_file::log(&format!("lsp[{server_name}] code_action error: {e:#}"));
                    }
                }
            }
            // Preferred actions (e.g. the server's chosen auto-fix) float to the
            // top of the menu, matching VS Code's ordering.
            combined.sort_by_key(|i| !i.is_preferred);
            log_file::log(&format!(
                "code_action response id={request_id} count={} any_ran={any_ran}",
                combined.len()
            ));
            let _ = tx.send(CodeActionResult {
                request_id,
                // `None` only when every server errored; an empty Vec means a
                // server answered with nothing.
                items: if any_ran { Some(combined) } else { None },
                unsupported: false,
            });
        });
    }

    async fn resolve_code_action(
        &mut self,
        request_id: u64,
        path: PathBuf,
        server: String,
        action: serde_json::Value,
        tx: &std_mpsc::Sender<CodeActionResult>,
    ) {
        // Deserialize the original action back intact (kind/data/diagnostics all
        // preserved); a malformed payload simply yields no resolution.
        let Ok(action) = serde_json::from_value::<lsp_types::CodeAction>(action) else {
            let _ = tx.send(CodeActionResult {
                request_id,
                items: None,
                unsupported: false,
            });
            return;
        };
        let Some(doc) = self.docs.get(&path) else {
            return;
        };
        let lang = doc.language;
        let root = doc.project_root.clone();
        self.ensure_clients(lang, &root).await;
        let Some(clients) = self.clients.get(&(lang, root)) else {
            return;
        };
        // Resolve against the SAME server that produced the action; fall back to
        // any code-action server only if that one is gone.
        let picked = clients
            .iter()
            .find(|c| c.supports_code_action && c.name == server)
            .or_else(|| clients.iter().find(|c| c.supports_code_action))
            .map(|c| (c.name.clone(), c.client.clone()));
        let Some((server_name, client_arc)) = picked else {
            let _ = tx.send(CodeActionResult {
                request_id,
                items: None,
                unsupported: true,
            });
            return;
        };
        let tx = tx.clone();
        tokio::spawn(async move {
            let mut client = client_arc.lock().await.requests();
            let resolved = client.code_action_resolve(action).await;
            drop(client);
            let items = match resolved {
                Ok(a) => {
                    let one = vec![CodeActionOrCommand::CodeAction(a)];
                    Some(code_action_items(&one, &server_name))
                }
                Err(e) => {
                    log_file::log(&format!(
                        "lsp[{server_name}] code_action_resolve error: {e:#}"
                    ));
                    None
                }
            };
            let _ = tx.send(CodeActionResult {
                request_id,
                items,
                unsupported: false,
            });
        });
    }

    async fn execute_command(
        &mut self,
        path: PathBuf,
        command: String,
        arguments: Vec<serde_json::Value>,
    ) {
        let Ok((server_name, client_arc)) =
            self.pick_server(&path, |c| c.supports_code_action).await
        else {
            return;
        };
        tokio::spawn(async move {
            let mut client = client_arc.lock().await.requests();
            if let Err(e) = client.execute_command(command, arguments).await {
                log_file::log(&format!("lsp[{server_name}] execute_command error: {e:#}"));
            }
        });
    }

    async fn request_rename(
        &mut self,
        request_id: u64,
        path: PathBuf,
        line: u32,
        character: u32,
        new_name: String,
        tx: &std_mpsc::Sender<RenameResult>,
    ) {
        // Every early exit answers with no edits, so the caller's "Renaming
        // symbol" always resolves (#1193).
        let unanswerable = || {
            let _ = tx.send(RenameResult {
                request_id,
                edits: None,
            });
        };
        let Ok((server_name, client_arc)) = self.pick_server(&path, |c| c.supports_rename).await
        else {
            unanswerable();
            return;
        };
        let Ok(uri) = Url::from_file_path(&path) else {
            unanswerable();
            return;
        };
        let tx = tx.clone();
        log_file::log(&format!(
            "rename request id={request_id} server={server_name} path={} line={line} char={character} new_name={new_name}",
            path.display()
        ));
        tokio::spawn(async move {
            let mut client = client_arc.lock().await.requests();
            let resp = client.rename(uri, line, character, new_name).await;
            drop(client);
            let edits = match resp {
                Ok(Some(we)) => Some(workspace_edits(&we)),
                Ok(None) => None,
                Err(e) => {
                    log_file::log(&format!("lsp[{server_name}] rename error: {e}"));
                    None
                }
            };
            log_file::log(&format!(
                "rename response id={request_id} server={server_name} files={}",
                edits.as_ref().map(Vec::len).unwrap_or(0)
            ));
            let _ = tx.send(RenameResult { request_id, edits });
        });
    }

    /// The servers under a root that holds one of `renames` and whose
    /// filters accept it, paired with the renames each one asked about.
    fn file_op_clients(
        &self,
        renames: &[FileRenameOp],
        pick: impl Fn(&ManagedClient) -> Option<&Arc<crate::lsp::file_ops::FileOpFilters>>,
    ) -> Vec<(
        String,
        Arc<TokioMutex<LspClient>>,
        Vec<lsp_types::FileRename>,
    )> {
        let mut out = Vec::new();
        for ((_, root), clients) in &self.clients {
            for c in clients {
                let Some(filters) = pick(c) else {
                    continue;
                };
                let files: Vec<lsp_types::FileRename> = renames
                    .iter()
                    .filter(|r| r.old.starts_with(root) && filters.matches(&r.old, r.is_dir))
                    .filter_map(|r| {
                        Some(lsp_types::FileRename {
                            old_uri: Url::from_file_path(&r.old).ok()?.to_string(),
                            new_uri: Url::from_file_path(&r.new).ok()?.to_string(),
                        })
                    })
                    .collect();
                if !files.is_empty() {
                    out.push((c.name.clone(), c.client.clone(), files));
                }
            }
        }
        out
    }

    /// `willRenameFiles` fan-out (#610): every interested server, each with
    /// a deadline so a stalled one cannot hold the Explorer move hostage.
    fn request_will_rename_files(
        &mut self,
        request_id: u64,
        renames: Vec<FileRenameOp>,
        tx: &std_mpsc::Sender<WillRenameFilesResult>,
    ) {
        let targets = self.file_op_clients(&renames, |c| c.will_rename.as_ref());
        let tx = tx.clone();
        tokio::spawn(async move {
            let mut edits = Vec::new();
            for (name, client_arc, files) in targets {
                let resp = tokio::time::timeout(WILL_RENAME_TIMEOUT, async {
                    let mut requests = client_arc.lock().await.requests();
                    requests.will_rename_files(files).await
                })
                .await;
                match resp {
                    Ok(Ok(Some(we))) => edits.extend(workspace_edits(&we)),
                    Ok(Ok(None)) => {}
                    Ok(Err(e)) => log_file::log(&format!("lsp[{name}] willRenameFiles error: {e}")),
                    Err(_) => log_file::log(&format!("lsp[{name}] willRenameFiles timed out")),
                }
            }
            let _ = tx.send(WillRenameFilesResult { request_id, edits });
        });
    }

    fn did_rename_files(&mut self, renames: Vec<FileRenameOp>) {
        for (name, client_arc, files) in self.file_op_clients(&renames, |c| c.did_rename.as_ref()) {
            tokio::spawn(async move {
                if let Err(e) = client_arc.lock().await.did_rename_files(files) {
                    log_file::log(&format!("lsp[{name}] didRenameFiles error: {e}"));
                }
            });
        }
    }

    /// `workspace/didChangeWatchedFiles` fan-out (#908): each server gets
    /// the changes its watchers cover, less the documents it has open, which
    /// reach it through didChange. Existence is read here, off the UI
    /// thread, so a file that is gone by now goes out as deleted.
    fn did_change_watched_files(&mut self, changes: Vec<(PathBuf, lsp_types::FileChangeType)>) {
        let changes: Vec<_> = changes
            .into_iter()
            .map(|(path, typ)| match path.exists() {
                true => (path, typ),
                false => (path, lsp_types::FileChangeType::DELETED),
            })
            .collect();
        for ((lang, root), clients) in &self.clients {
            let closed: Arc<Vec<_>> = Arc::new(
                changes
                    .iter()
                    .filter(|(path, _)| {
                        !self
                            .docs
                            .get(path)
                            .is_some_and(|d| d.language == *lang && d.project_root == *root)
                    })
                    .cloned()
                    .collect(),
            );
            if closed.is_empty() {
                continue;
            }
            for c in clients {
                let (name, client, closed) = (c.name.clone(), c.client.clone(), closed.clone());
                tokio::spawn(async move {
                    if let Err(e) = client.lock().await.did_change_watched_files(&closed) {
                        log_file::log(&format!("lsp[{name}] didChangeWatchedFiles error: {e}"));
                    }
                });
            }
        }
    }

    /// Prepare-rename (#254): always answers, because the rename prompt
    /// is deferred on this verdict.
    async fn request_prepare_rename(
        &mut self,
        request_id: u64,
        path: PathBuf,
        line: u32,
        character: u32,
        tx: &std_mpsc::Sender<PrepareRenameResult>,
    ) {
        let unsupported = |tx: &std_mpsc::Sender<PrepareRenameResult>| {
            let _ = tx.send(PrepareRenameResult {
                request_id,
                unsupported: true,
                error: None,
                target: None,
            });
        };
        let Some(doc) = self.docs.get(&path) else {
            unsupported(tx);
            return;
        };
        let lang = doc.language;
        let root = doc.project_root.clone();
        self.ensure_clients(lang, &root).await;
        let Some(clients) = self.clients.get(&(lang, root)) else {
            unsupported(tx);
            return;
        };
        let picked = clients.iter().find(|c| c.supports_prepare_rename).map(|c| {
            (
                c.name.clone(),
                c.client.clone(),
                c.prepare_rename_stalled.clone(),
            )
        });
        let Some((server_name, client_arc, stalled)) = picked else {
            unsupported(tx);
            return;
        };
        let Ok(uri) = Url::from_file_path(&path) else {
            unsupported(tx);
            return;
        };
        spawn_prepare_rename(
            PrepareRenameAsk {
                request_id,
                server_name,
                client: client_arc,
                uri,
                line,
                character,
                stalled,
            },
            PREPARE_RENAME_TIMEOUT,
            tx,
        );
    }

    async fn request_formatting(
        &mut self,
        request_id: u64,
        path: PathBuf,
        tab_size: u32,
        insert_spaces: bool,
        tx: &std_mpsc::Sender<FormatResult>,
    ) {
        // Every bail below MUST still answer. The app defers the format-on-save
        // write until a reply lands, so a silent `return` strands the latch:
        // no write, no error, and the user believes the file was saved.
        let Some(doc) = self.docs.get(&path) else {
            answer_unsupported(tx, request_id, path);
            return;
        };
        let lang = doc.language;
        let root = doc.project_root.clone();
        // Re-probe so a formatter installed since the file opened is picked up
        // without reopening (mirrors `request_rename`).
        self.ensure_clients(lang, &root).await;
        let Some(clients) = self.clients.get(&(lang, root)) else {
            answer_unsupported(tx, request_id, path);
            return;
        };
        let picked = clients
            .iter()
            .find(|c| c.supports_formatting)
            .map(|c| (c.name.clone(), c.client.clone()));
        let Some((server_name, client_arc)) = picked else {
            let _ = tx.send(FormatResult {
                request_id,
                path,
                edits: None,
                unsupported: true,
                server: None,
            });
            return;
        };
        let Ok(uri) = Url::from_file_path(&path) else {
            answer_unsupported(tx, request_id, path);
            return;
        };
        let tx = tx.clone();
        let path_clone = path.clone();
        log_file::log(&format!(
            "formatting request id={request_id} server={server_name} path={} tab_size={tab_size} insert_spaces={insert_spaces}",
            path.display()
        ));
        tokio::spawn(async move {
            let mut client = client_arc.lock().await.requests();
            let resp = client.formatting(uri, tab_size, insert_spaces).await;
            drop(client);
            let edits = match resp {
                Ok(Some(tes)) => Some(tes.iter().map(text_edit_to_span).collect()),
                Ok(None) => None,
                Err(e) => {
                    log_file::log(&format!("lsp[{server_name}] formatting error: {e}"));
                    None
                }
            };
            log_file::log(&format!(
                "formatting response id={request_id} server={server_name} edits={}",
                edits.as_ref().map(Vec::len).unwrap_or(0)
            ));
            let _ = tx.send(FormatResult {
                request_id,
                path: path_clone,
                edits,
                unsupported: false,
                server: Some(server_name),
            });
        });
    }

    /// On-type formatting (#254): the server's reaction to one just-typed
    /// trigger character. Silent on every early-out — this is a
    /// background behavior with no status line waiting on it, and the
    /// app pre-checks the trigger set so an unroutable request means a
    /// race (doc closed), not a misconfiguration. This deliberately
    /// diverges from `request_formatting`'s "every bail must still
    /// answer" invariant: nothing blocks on this reply, so an unanswered
    /// bail costs nothing.
    #[allow(clippy::too_many_arguments)]
    async fn request_on_type_formatting(
        &mut self,
        request_id: u64,
        path: PathBuf,
        line: u32,
        character: u32,
        ch: char,
        tab_size: u32,
        insert_spaces: bool,
        tx: &std_mpsc::Sender<FormatResult>,
    ) {
        let Some(doc) = self.docs.get(&path) else {
            return;
        };
        let lang = doc.language;
        let root = doc.project_root.clone();
        self.ensure_clients(lang, &root).await;
        let Some(clients) = self.clients.get(&(lang, root)) else {
            return;
        };
        let picked = clients
            .iter()
            .find(|c| c.on_type_triggers.as_ref().is_some_and(|t| t.contains(ch)))
            .map(|c| (c.name.clone(), c.client.clone()));
        let Some((server_name, client_arc)) = picked else {
            return;
        };
        let Ok(uri) = Url::from_file_path(&path) else {
            return;
        };
        let tx = tx.clone();
        let path_clone = path.clone();
        tokio::spawn(async move {
            let mut client = client_arc.lock().await.requests();
            let resp = client
                .on_type_formatting(
                    uri,
                    line,
                    character,
                    ch.to_string(),
                    tab_size,
                    insert_spaces,
                )
                .await;
            drop(client);
            let edits = match resp {
                Ok(Some(tes)) => Some(tes.iter().map(text_edit_to_span).collect()),
                Ok(None) => None,
                Err(e) => {
                    log_file::log(&format!("lsp[{server_name}] onTypeFormatting error: {e}"));
                    None
                }
            };
            let _ = tx.send(FormatResult {
                request_id,
                path: path_clone,
                edits,
                unsupported: false,
                server: Some(server_name),
            });
        });
    }

    /// "Format Selection" (#254): `textDocument/rangeFormatting` over one
    /// UTF-16 span. Same always-answer contract as whole-document
    /// formatting — the app shows status off this reply.
    #[allow(clippy::too_many_arguments)]
    async fn request_range_formatting(
        &mut self,
        request_id: u64,
        path: PathBuf,
        start: (u32, u32),
        end: (u32, u32),
        tab_size: u32,
        insert_spaces: bool,
        tx: &std_mpsc::Sender<FormatResult>,
    ) {
        let Ok((server_name, client_arc)) = self
            .pick_server(&path, |c| c.supports_range_formatting)
            .await
        else {
            answer_unsupported(tx, request_id, path);
            return;
        };
        let Ok(uri) = Url::from_file_path(&path) else {
            answer_unsupported(tx, request_id, path);
            return;
        };
        let tx = tx.clone();
        let path_clone = path.clone();
        tokio::spawn(async move {
            let mut client = client_arc.lock().await.requests();
            let resp = client
                .range_formatting(uri, start.0, start.1, end.0, end.1, tab_size, insert_spaces)
                .await;
            drop(client);
            let edits = match resp {
                Ok(Some(tes)) => Some(tes.iter().map(text_edit_to_span).collect()),
                Ok(None) => None,
                Err(e) => {
                    log_file::log(&format!("lsp[{server_name}] range_formatting error: {e}"));
                    None
                }
            };
            let _ = tx.send(FormatResult {
                request_id,
                path: path_clone,
                edits,
                unsupported: false,
                server: Some(server_name),
            });
        });
    }
}

/// Normalise a `WorkspaceEdit` into per-file char-indexed spans. Handles both
/// the `changes` map and the `document_changes` form (edit operations only;
/// create/rename/delete file ops are ignored, which is correct for a symbol
/// rename). LSP positions are treated as char indices, matching how croft's
/// editor maps positions everywhere else.
fn workspace_edits(edit: &WorkspaceEdit) -> Vec<(PathBuf, Vec<TextSpanEdit>)> {
    let mut out: Vec<(PathBuf, Vec<TextSpanEdit>)> = Vec::new();
    if let Some(changes) = edit.changes.as_ref() {
        for (uri, edits) in changes {
            if let Ok(path) = uri.to_file_path() {
                out.push((path, edits.iter().map(text_edit_to_span).collect()));
            }
        }
    }
    if let Some(doc_changes) = edit.document_changes.as_ref() {
        match doc_changes {
            DocumentChanges::Edits(edits) => {
                for tde in edits {
                    if let Ok(path) = tde.text_document.uri.to_file_path() {
                        let spans = tde
                            .edits
                            .iter()
                            .map(|e| match e {
                                OneOf::Left(te) => text_edit_to_span(te),
                                OneOf::Right(ate) => text_edit_to_span(&ate.text_edit),
                            })
                            .collect();
                        out.push((path, spans));
                    }
                }
            }
            DocumentChanges::Operations(ops) => {
                for op in ops {
                    if let DocumentChangeOperation::Edit(tde) = op
                        && let Ok(path) = tde.text_document.uri.to_file_path()
                    {
                        let spans = tde
                            .edits
                            .iter()
                            .map(|e| match e {
                                OneOf::Left(te) => text_edit_to_span(te),
                                OneOf::Right(ate) => text_edit_to_span(&ate.text_edit),
                            })
                            .collect();
                        out.push((path, spans));
                    }
                }
            }
        }
    }
    out
}

/// Normalise an LSP `textDocument/codeAction` response into croft's selectable
/// [`CodeActionItem`]s. Disabled actions are dropped (VS Code hides them from
/// the lightbulb menu); inline `WorkspaceEdit`s are flattened with the same
/// [`workspace_edits`] path rename uses; an action with neither an edit nor a
/// command but with `data` is flagged for a `codeAction/resolve` round trip.
fn code_action_items(resp: &CodeActionResponse, server: &str) -> Vec<CodeActionItem> {
    let to_command = |c: &lsp_types::Command| CodeActionCommand {
        command: c.command.clone(),
        arguments: c.arguments.clone().unwrap_or_default(),
    };
    resp.iter()
        .filter_map(|entry| match entry {
            CodeActionOrCommand::Command(cmd) => Some(CodeActionItem {
                title: cmd.title.clone(),
                server: server.to_string(),
                edits: Vec::new(),
                command: Some(to_command(cmd)),
                needs_resolve: false,
                resolve_action: None,
                is_preferred: false,
            }),
            CodeActionOrCommand::CodeAction(action) => {
                if action.disabled.is_some() {
                    return None;
                }
                let edits = action
                    .edit
                    .as_ref()
                    .map(workspace_edits)
                    .unwrap_or_default();
                let command = action.command.as_ref().map(to_command);
                let needs_resolve =
                    action.edit.is_none() && command.is_none() && action.data.is_some();
                // Keep the whole action so resolve can send it back intact.
                let resolve_action = if needs_resolve {
                    serde_json::to_value(action).ok()
                } else {
                    None
                };
                Some(CodeActionItem {
                    title: action.title.clone(),
                    server: server.to_string(),
                    edits,
                    command,
                    needs_resolve,
                    resolve_action,
                    is_preferred: action.is_preferred.unwrap_or(false),
                })
            }
        })
        .collect()
}

/// Re-materialise one of croft's normalised diagnostics into the LSP wire type
/// so it can ride along as `codeAction` context. We carry range, severity,
/// message and tags (the fields croft keeps). A server's own diagnostics go
/// back as it sent them instead (`code_action_diagnostics`): its fixes key
/// on `code` and `data`, which this leaves out.
fn to_lsp_diagnostic(d: &Diagnostic) -> lsp_types::Diagnostic {
    let severity = match d.severity {
        DiagnosticSeverity::Error => lsp_types::DiagnosticSeverity::ERROR,
        DiagnosticSeverity::Warning => lsp_types::DiagnosticSeverity::WARNING,
        DiagnosticSeverity::Information => lsp_types::DiagnosticSeverity::INFORMATION,
        DiagnosticSeverity::Hint => lsp_types::DiagnosticSeverity::HINT,
    };
    lsp_types::Diagnostic {
        range: lsp_types::Range {
            start: lsp_types::Position {
                line: d.start_line,
                character: d.start_char,
            },
            end: lsp_types::Position {
                line: d.end_line,
                character: d.end_char,
            },
        },
        severity: Some(severity),
        message: d.message.clone(),
        tags: d.tags.any().then(|| {
            let mut tags = Vec::new();
            if d.tags.unnecessary {
                tags.push(lsp_types::DiagnosticTag::UNNECESSARY);
            }
            if d.tags.deprecated {
                tags.push(lsp_types::DiagnosticTag::DEPRECATED);
            }
            tags
        }),
        ..Default::default()
    }
}

/// The diagnostics `server` is asked for code actions on: its own, as it
/// published them, and the ones croft made itself, rebuilt. Another server's
/// diagnostics are not its to fix, as in VS Code (#1030).
fn code_action_diagnostics(diagnostics: &[Diagnostic], server: &str) -> Vec<lsp_types::Diagnostic> {
    diagnostics
        .iter()
        .filter_map(|d| match d.origin.as_deref() {
            Some(origin) => (origin.server == server).then(|| origin.wire.clone()),
            None => Some(to_lsp_diagnostic(d)),
        })
        .collect()
}

fn text_edit_to_span(te: &TextEdit) -> TextSpanEdit {
    TextSpanEdit {
        start: (
            te.range.start.line as usize,
            te.range.start.character as usize,
        ),
        end: (te.range.end.line as usize, te.range.end.character as usize),
        new_text: te.new_text.clone(),
        utf16: true,
    }
}

fn into_item(item: lsp_types::CompletionItem) -> CompletionItem {
    let is_snippet = item.insert_text_format == Some(lsp_types::InsertTextFormat::SNIPPET);
    let text_edit = item.text_edit.as_ref().map(|te| match te {
        lsp_types::CompletionTextEdit::Edit(e) => text_edit_to_span(e),
        lsp_types::CompletionTextEdit::InsertAndReplace(e) => text_edit_to_span(&TextEdit {
            range: e.insert,
            new_text: e.new_text.clone(),
        }),
    });
    let additional_edits = item
        .additional_text_edits
        .iter()
        .flatten()
        .map(text_edit_to_span)
        .collect();
    let documentation = item.documentation.map(|d| match d {
        lsp_types::Documentation::String(s) => s,
        lsp_types::Documentation::MarkupContent(m) => m.value,
    });
    // A server that puts the signature only in `labelDetails` (#1527)
    // still gets it shown: its `detail` (the suffix after the label, often
    // the parameter list) then its `description` (a qualifier), both kept.
    let detail = item.detail.or_else(|| {
        item.label_details.and_then(|l| {
            let parts: Vec<String> = [l.detail, l.description]
                .into_iter()
                .flatten()
                .map(|p| p.trim().to_string())
                .filter(|p| !p.is_empty())
                .collect();
            (!parts.is_empty()).then(|| parts.join(" "))
        })
    });
    CompletionItem {
        label: item.label,
        detail,
        documentation,
        insert_text: item.insert_text,
        filter_text: item.filter_text,
        kind: item.kind,
        is_snippet,
        text_edit,
        additional_edits,
        resolve: None,
    }
}

/// [`into_item`] for an item of a list, kept whole for
/// `completionItem/resolve` when its server `resolves` items and the list
/// left its imports out (#928).
fn listed_item(item: lsp_types::CompletionItem, resolves: bool) -> CompletionItem {
    let imports = item.additional_text_edits.as_ref();
    let resolve = (resolves && imports.is_none_or(Vec::is_empty)).then(|| Arc::new(item.clone()));
    CompletionItem {
        resolve,
        ..into_item(item)
    }
}

fn marked_string_text(m: &MarkedString) -> &str {
    match m {
        MarkedString::String(s) => s,
        MarkedString::LanguageString(ls) => &ls.value,
    }
}

fn hover_text(contents: &HoverContents) -> Option<String> {
    let text = match contents {
        HoverContents::Scalar(m) => marked_string_text(m).to_string(),
        HoverContents::Markup(mc) => mc.value.clone(),
        HoverContents::Array(items) => items
            .iter()
            .map(marked_string_text)
            .filter(|s| !s.trim().is_empty())
            .collect::<Vec<_>>()
            .join("\n\n"),
    };
    let text = text.trim().to_string();
    if text.is_empty() { None } else { Some(text) }
}

/// Whether the server's rename provider also validates positions via
/// `prepareRename` (#254): only an options-shaped provider can carry
/// `prepareProvider: true`.
fn prepare_rename_supported(cap: &Option<OneOf<bool, lsp_types::RenameOptions>>) -> bool {
    matches!(cap, Some(OneOf::Right(opts)) if opts.prepare_provider == Some(true))
}

/// A `Range` as the UTF-16 4-tuple the app-facing results carry.
fn range_tuple(r: &lsp_types::Range) -> (u32, u32, u32, u32) {
    (r.start.line, r.start.character, r.end.line, r.end.character)
}

/// Whether the server advertises a usable `textDocument/documentColor`
/// provider (#254). Same shape rules as `code_action_supported`.
fn color_provider_supported(cap: &Option<lsp_types::ColorProviderCapability>) -> bool {
    use lsp_types::ColorProviderCapability as C;
    match cap {
        Some(C::Simple(b)) => *b,
        Some(C::ColorProvider(_)) | Some(C::Options(_)) => true,
        None => false,
    }
}

/// Wire → internal color value (#254): 0..=1 f32 channels scaled to u8
/// for the swatch cell, the raw channels kept for the presentation
/// round trip.
fn color_item(ci: &lsp_types::ColorInformation) -> ColorItem {
    let to8 = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
    ColorItem {
        line: ci.range.start.line,
        character: ci.range.start.character,
        end_line: ci.range.end.line,
        end_character: ci.range.end.character,
        red: to8(ci.color.red),
        green: to8(ci.color.green),
        blue: to8(ci.color.blue),
        raw: (ci.color.red, ci.color.green, ci.color.blue, ci.color.alpha),
    }
}

/// Whether the server advertises a usable `textDocument/codeAction` provider.
/// `Simple(false)` and `None` are unsupported; `Simple(true)` or an options
/// object (which may also declare `resolveProvider`) is supported.
fn code_action_supported(cap: &Option<CodeActionProviderCapability>) -> bool {
    match cap {
        Some(CodeActionProviderCapability::Simple(b)) => *b,
        Some(CodeActionProviderCapability::Options(_)) => true,
        None => false,
    }
}

/// The first inline completion with any text (#607), as plain text: a
/// snippet's placeholders become their defaults, since ghost text has no
/// tab stops. Its range is kept only when it stays on one line, as the
/// protocol requires.
fn first_inline_item(answer: lsp_types::InlineCompletionResponse) -> Option<InlineItem> {
    let items = match answer {
        lsp_types::InlineCompletionResponse::Array(items) => items,
        lsp_types::InlineCompletionResponse::List(list) => list.items,
    };
    items.into_iter().find_map(|item| {
        let text = if item.insert_text_format == Some(lsp_types::InsertTextFormat::SNIPPET) {
            crate::snippets::parse_body(&item.insert_text, &|_| None).text
        } else {
            item.insert_text
        };
        let range = match item.range {
            Some(r) if r.start.line != r.end.line => return None,
            r => r.map(|r| (r.start.line, r.start.character, r.end.line, r.end.character)),
        };
        (!text.trim().is_empty()).then_some(InlineItem { text, range })
    })
}

/// Whether the server advertises a usable `textDocument/linkedEditingRange`
/// provider (#254). Same shape rules as `code_action_supported`.
fn linked_editing_supported(cap: &Option<lsp_types::LinkedEditingRangeServerCapabilities>) -> bool {
    use lsp_types::LinkedEditingRangeServerCapabilities as L;
    match cap {
        Some(L::Simple(b)) => *b,
        Some(L::Options(_)) | Some(L::RegistrationOptions(_)) => true,
        None => false,
    }
}

/// Whether the server advertises a usable `textDocument/foldingRange`
/// provider (#254). Same shape rules as `code_action_supported`.
fn folding_range_supported(cap: &Option<lsp_types::FoldingRangeProviderCapability>) -> bool {
    use lsp_types::FoldingRangeProviderCapability as F;
    match cap {
        Some(F::Simple(b)) => *b,
        Some(F::FoldingProvider(_)) | Some(F::Options(_)) => true,
        None => false,
    }
}

/// Flatten one `SelectionRange` parent chain into smallest-first UTF-16
/// spans, dropping non-growing links (some servers repeat a range).
fn flatten_selection_chain(sr: &lsp_types::SelectionRange) -> Vec<(u32, u32, u32, u32)> {
    let mut out = Vec::new();
    let mut cur = Some(sr);
    let mut last: Option<(u32, u32, u32, u32)> = None;
    while let Some(r) = cur {
        let span = (
            r.range.start.line,
            r.range.start.character,
            r.range.end.line,
            r.range.end.character,
        );
        if last != Some(span) {
            out.push(span);
            last = Some(span);
        }
        cur = r.parent.as_deref();
    }
    out
}

/// Whether the server advertises a usable `textDocument/selectionRange`
/// provider (#254). Same shape rules as `code_action_supported`.
fn selection_range_supported(cap: &Option<lsp_types::SelectionRangeProviderCapability>) -> bool {
    use lsp_types::SelectionRangeProviderCapability as S;
    match cap {
        Some(S::Simple(b)) => *b,
        Some(S::Options(_)) | Some(S::RegistrationOptions(_)) => true,
        None => false,
    }
}

/// Flatten a `workspace/symbol` response (either shape) into picker rows.
/// Nested `WorkspaceSymbol`s may carry a range-less location (a bare URI);
/// those land on line 0, which is still a useful jump target.
fn workspace_symbol_items(resp: lsp_types::WorkspaceSymbolResponse) -> Vec<WorkspaceSymbolItem> {
    use lsp_types::WorkspaceSymbolResponse;
    let item = |name: String,
                kind: SymbolKind,
                container: Option<String>,
                uri: &lsp_types::Url,
                pos: Option<Position>| {
        let path = uri.to_file_path().ok()?;
        Some(WorkspaceSymbolItem {
            name,
            kind: OutlineKind::from_lsp(kind),
            path,
            line: pos.map(|p| p.line).unwrap_or(0),
            character: pos.map(|p| p.character).unwrap_or(0),
            container,
        })
    };
    match resp {
        WorkspaceSymbolResponse::Flat(list) => list
            .into_iter()
            .filter_map(|si| {
                item(
                    si.name,
                    si.kind,
                    si.container_name,
                    &si.location.uri,
                    Some(si.location.range.start),
                )
            })
            .collect(),
        WorkspaceSymbolResponse::Nested(list) => list
            .into_iter()
            .filter_map(|ws| match ws.location {
                OneOf::Left(loc) => item(
                    ws.name,
                    ws.kind,
                    ws.container_name,
                    &loc.uri,
                    Some(loc.range.start),
                ),
                OneOf::Right(wloc) => item(ws.name, ws.kind, ws.container_name, &wloc.uri, None),
            })
            .collect(),
    }
}

/// Normalise one LSP wire inlay hint: flatten a parts label into one string,
/// fold the padding flags in as literal spaces, and strip newlines (a label
/// is spliced into a single rendered row, where a line break would corrupt
/// the cell run). The editor consumes the label verbatim after this.
fn normalise_inlay_hint(h: lsp_types::InlayHint) -> InlayHintItem {
    let mut label = match h.label {
        lsp_types::InlayHintLabel::String(s) => s,
        lsp_types::InlayHintLabel::LabelParts(parts) => {
            parts.into_iter().map(|p| p.value).collect()
        }
    };
    if label.contains(['\n', '\r']) {
        label = label.replace(['\n', '\r'], " ");
    }
    if h.padding_left == Some(true) {
        label.insert(0, ' ');
    }
    if h.padding_right == Some(true) {
        label.push(' ');
    }
    InlayHintItem {
        line: h.position.line,
        character: h.position.character,
        label,
    }
}

/// Wire → internal fold span (#254). A range whose end does not extend past
/// its start folds nothing and is dropped; `end_character` nuances are
/// deliberately ignored — croft folds whole lines, like VS Code's default.
fn normalise_folding_range(r: lsp_types::FoldingRange) -> Option<FoldingRangeItem> {
    let start = r.start_line as usize;
    let end = r.end_line as usize;
    if end <= start {
        return None;
    }
    let kind = match r.kind {
        Some(lsp_types::FoldingRangeKind::Comment) => FoldRangeKind::Comment,
        Some(lsp_types::FoldingRangeKind::Imports) => FoldRangeKind::Imports,
        Some(lsp_types::FoldingRangeKind::Region) => FoldRangeKind::Region,
        None => FoldRangeKind::Other,
    };
    Some(FoldingRangeItem {
        start_line: start,
        end_line: end,
        kind,
    })
}

fn call_hierarchy_supported(cap: &Option<lsp_types::CallHierarchyServerCapability>) -> bool {
    use lsp_types::CallHierarchyServerCapability as C;
    match cap {
        Some(C::Simple(b)) => *b,
        Some(C::Options(_)) => true,
        None => false,
    }
}

/// Whether a `boolean | <Options>`-shaped capability (definition, rename, ...)
/// is actually supported. `None` is unsupported; a bare `false` is unsupported;
/// `true` or an options object is supported. The bare-`false` case is the one
/// `Option::is_some` got wrong.
fn one_of_supported<B>(cap: &Option<OneOf<bool, B>>) -> bool {
    match cap {
        Some(OneOf::Left(b)) => *b,
        Some(OneOf::Right(_)) => true,
        None => false,
    }
}

/// Answer a formatting request that cannot reach a server. `unsupported` is
/// the honest shape for every one of these: no client in this worker can
/// format the file. The app turns it into "No formatter available for this
/// file" and, crucially, still performs the deferred save.
fn answer_unsupported(tx: &std_mpsc::Sender<FormatResult>, request_id: u64, path: PathBuf) {
    let _ = tx.send(FormatResult {
        request_id,
        path,
        edits: None,
        unsupported: true,
        server: None,
    });
}

/// Hover capability (`boolean | HoverOptions`), same bare-`false` rule.
fn hover_supported(cap: &Option<HoverProviderCapability>) -> bool {
    match cap {
        Some(HoverProviderCapability::Simple(b)) => *b,
        Some(HoverProviderCapability::Options(_)) => true,
        None => false,
    }
}

/// Whether the server advertises `signatureHelpProvider`.
fn signature_help_supported(cap: &Option<lsp_types::SignatureHelpOptions>) -> bool {
    cap.is_some()
}

/// The completion `triggerCharacters` a server lists (#929), as one string.
/// The protocol allows a longer trigger, but one key types one character,
/// so `->` is left out rather than read as `-` and `>`.
fn completion_triggers_of(caps: &ServerCapabilities) -> String {
    let options = caps.completion_provider.as_ref();
    let triggers = options.and_then(|o| o.trigger_characters.as_deref());
    let single = |t: &&String| t.chars().count() == 1;
    let triggers = triggers.unwrap_or_default().iter().filter(single);
    triggers.map(String::as_str).collect()
}

/// Whether a server asked for `textDocument/didSave`, and with the saved
/// text or without it (#854).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SaveNotify {
    /// Not asked for, so not sent: ruff advertises no `save` and warns "no
    /// handler" on every Ctrl+S that reaches it.
    Never,
    /// Sent bare; the server re-reads the file (rust-analyzer's `save: {}`).
    WithoutText,
    /// Sent carrying the text, for `save: { includeText: true }`.
    WithText,
}

/// Read [`SaveNotify`] off a server's `textDocumentSync` capability (#854).
///
/// The options form says it outright: `save` present asks for the
/// notification, absent asks for none ("if omitted the notification should
/// not be sent"), and `includeText` asks for the text. The bare
/// `TextDocumentSyncKind` number predates `save`, and VS Code, Neovim and
/// Helix all read a kind other than `None` as "saves, without the text"
/// (LSP issue #288). croft does the same, so a server that picked the old
/// form keeps hearing about saves as it does in every other editor.
///
/// Dynamic registration is not consulted because croft declares none: with
/// `synchronization.dynamicRegistration` false rust-analyzer advertises
/// `save: {}` here instead of registering it later, which is what keeps its
/// check-on-save running.
fn save_notify_of(sync: &Option<lsp_types::TextDocumentSyncCapability>) -> SaveNotify {
    use lsp_types::{TextDocumentSyncCapability as Sync, TextDocumentSyncSaveOptions as Save};
    match sync {
        Some(Sync::Options(options)) => match &options.save {
            Some(Save::SaveOptions(save)) if save.include_text == Some(true) => {
                SaveNotify::WithText
            }
            Some(Save::SaveOptions(_)) | Some(Save::Supported(true)) => SaveNotify::WithoutText,
            Some(Save::Supported(false)) | None => SaveNotify::Never,
        },
        Some(Sync::Kind(kind)) if *kind != lsp_types::TextDocumentSyncKind::NONE => {
            SaveNotify::WithoutText
        }
        Some(Sync::Kind(_)) | None => SaveNotify::Never,
    }
}

/// Result ids from the last `workspace/diagnostic` pull, per file (#533).
///
/// The incrementality contract: send back what the server last told us, and
/// it answers `Unchanged` for anything that has not moved instead of
/// resending the diagnostics. Without this every pull is a full re-report of
/// the whole workspace, which is the cost the pull path exists to avoid.
///
/// Keyed by URI string rather than `PathBuf` because that is what the server
/// echoes back, and round-tripping through a path loses the distinction on
/// any URI that is not a plain file (a server may report `untitled:` or a
/// virtual scheme). Comparing what it sent to what it sends is the whole job.
#[derive(Default)]
pub struct DiagnosticResultIds {
    by_uri: std::collections::HashMap<String, String>,
}

impl DiagnosticResultIds {
    /// What to send as `previousResultIds` on the next pull.
    pub fn previous(&self) -> Vec<lsp_types::PreviousResultId> {
        self.by_uri
            .iter()
            .filter_map(|(uri, value)| {
                Url::parse(uri).ok().map(|uri| lsp_types::PreviousResultId {
                    uri,
                    value: value.clone(),
                })
            })
            .collect()
    }

    /// Record the id a `Full` report carried, or forget the file when it
    /// carried none.
    ///
    /// A report with no `result_id` is the server declining to offer
    /// incrementality for that file. Keeping the OLD id would then send back
    /// an id the server never issued for the current content, and a server
    /// that trusts it answers `Unchanged` for a file that has in fact
    /// changed - stale diagnostics that never refresh.
    pub fn record(&mut self, uri: &str, result_id: Option<&str>) {
        match result_id {
            Some(id) => {
                self.by_uri.insert(uri.to_string(), id.to_string());
            }
            None => {
                self.by_uri.remove(uri);
            }
        }
    }

    /// How many files carry an id, so a caller can tell a cold cache from a
    /// warm one without reaching inside.
    pub fn len(&self) -> usize {
        self.by_uri.len()
    }

    /// Whether the cache is cold.
    #[cfg_attr(not(test), allow(dead_code))]
    pub fn is_empty(&self) -> bool {
        self.by_uri.is_empty()
    }
}

/// How long to wait for a `workspace/diagnostic` answer before abandoning
/// the pull (#533 regression). Generous, because a cold whole-project
/// analysis is genuinely slow — this is a stuck-server backstop, not a
/// latency budget.
const WORKSPACE_PULL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(120);

/// The most lenses resolved per document (#608): each resolve is a round
/// trip, and a generated file can carry thousands.
const MAX_CODE_LENSES: usize = 500;
/// How long a codeLens request, and then all its resolves together, may take.
const CODE_LENS_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);

/// How long a server may take to answer `textDocument/prepareRename`
/// (#1677) before F2 opens the word-under-cursor prompt instead. A
/// responsive server answers in about a millisecond; one that is busy,
/// paused or cut off must not strand "Preparing rename…" for good.
const PREPARE_RENAME_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);

/// One routed prepare-rename: the server picked for it and where the
/// caret is.
struct PrepareRenameAsk {
    request_id: u64,
    server_name: String,
    client: Arc<TokioMutex<LspClient>>,
    uri: Url,
    line: u32,
    character: u32,
    /// The client's `prepare_rename_stalled`.
    stalled: Arc<AtomicBool>,
}

/// Ask the server and always send a verdict (#254). Waiting on the lock and
/// on the reply together is bounded by `timeout` (#1677): past it the verdict
/// is `unsupported`, which opens the word-under-cursor prompt, so the rename
/// still goes through. A server that has let one expire is not asked again.
fn spawn_prepare_rename(
    ask: PrepareRenameAsk,
    timeout: std::time::Duration,
    tx: &std_mpsc::Sender<PrepareRenameResult>,
) {
    let tx = tx.clone();
    tokio::spawn(async move {
        let PrepareRenameAsk {
            request_id,
            server_name,
            client,
            uri,
            line,
            character,
            stalled,
        } = ask;
        let unsupported = |request_id| PrepareRenameResult {
            request_id,
            unsupported: true,
            error: None,
            target: None,
        };
        if stalled.load(Ordering::Relaxed) {
            let _ = tx.send(unsupported(request_id));
            return;
        }
        // Only a request that actually went out can leak, so only then does
        // the timeout retire the server; waiting on a busy lock does not.
        let sent = AtomicBool::new(false);
        let resp = tokio::time::timeout(timeout, async {
            let mut requests = client.lock().await.requests();
            sent.store(true, Ordering::Relaxed);
            requests.prepare_rename(uri, line, character).await
        })
        .await;
        let Ok(resp) = resp else {
            let retire = sent.load(Ordering::Relaxed);
            if retire {
                stalled.store(true, Ordering::Relaxed);
            }
            log_file::log(&format!(
                "lsp[{server_name}] prepareRename timed out after {timeout:?}{}",
                if retire {
                    "; renames use the word under the cursor for this session"
                } else {
                    ""
                }
            ));
            let _ = tx.send(unsupported(request_id));
            return;
        };
        let (error, target, fallback) = match resp {
            Ok(Some(lsp_types::PrepareRenameResponse::Range(r))) => {
                (None, Some((range_tuple(&r), None)), false)
            }
            Ok(Some(lsp_types::PrepareRenameResponse::RangeWithPlaceholder {
                range,
                placeholder,
            })) => (None, Some((range_tuple(&range), Some(placeholder))), false),
            // "Default behavior": the server validates the position
            // but wants the client's own word logic — route the app
            // to its word-under-cursor prompt via `unsupported`.
            Ok(Some(lsp_types::PrepareRenameResponse::DefaultBehavior { .. })) => {
                (None, None, true)
            }
            Ok(None) => (None, None, false),
            Err(e) => {
                log_file::log(&format!("lsp[{server_name}] prepareRename error: {e:#}"));
                // Surface the server's own message: the fail-fast half
                // of prepare-rename. Trim the anyhow context chain to
                // the root cause line.
                let msg = e
                    .root_cause()
                    .to_string()
                    .lines()
                    .next()
                    .unwrap_or("rename rejected")
                    .to_string();
                (Some(msg), None, false)
            }
        };
        let _ = tx.send(PrepareRenameResult {
            request_id,
            unsupported: fallback,
            error,
            target,
        });
    });
}

/// How long one server may take to answer `willRenameFiles` (#610) before
/// the Explorer move goes ahead without its edit. VS Code waits about as
/// long; a rename the user is watching must not hang on a slow server.
const WILL_RENAME_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(1500);

/// One server's share of a workspace pull (#533), gathered off the client
/// list so the request itself can run without holding the worker loop.
struct WorkspacePull {
    name: String,
    client: Arc<TokioMutex<LspClient>>,
    identifier: Option<String>,
    result_ids: Arc<TokioMutex<DiagnosticResultIds>>,
    /// Shared with the [`ManagedClient`], so a timeout recorded here is seen
    /// by every later `workspace_pull_targets` call.
    stalled: Arc<AtomicBool>,
}

/// The servers among `clients` that answer `workspace/diagnostic` (#533).
///
/// The filter is the whole "a server that does not advertise it is untouched"
/// guarantee: a server that pulls per document but not per workspace answers
/// `-32601 Unhandled method`, so it must never be asked.
fn workspace_pull_targets<'a>(
    clients: impl Iterator<Item = &'a ManagedClient>,
) -> Vec<WorkspacePull> {
    clients
        .filter(|c| c.supports_workspace_diagnostics)
        // A server that already let one pull expire is never asked again:
        // see `diagnostic_pull_stalled`.
        .filter(|c| !c.diagnostic_pull_stalled.load(Ordering::Relaxed))
        .map(|c| WorkspacePull {
            name: c.name.clone(),
            client: c.client.clone(),
            identifier: c.diagnostic_identifier.clone(),
            result_ids: c.diagnostic_result_ids.clone(),
            stalled: c.diagnostic_pull_stalled.clone(),
        })
        .collect()
}

/// Run a workspace pull against each target off the worker loop (#533).
///
/// Sequential per server, like `request_workspace_symbols`: each pull locks
/// that client, and a whole-project analysis is the kind of request a server
/// answers slowly, so the loop must not be holding the worker while it does.
fn spawn_workspace_pull(targets: Vec<WorkspacePull>, tx: std_mpsc::Sender<DiagnosticsUpdate>) {
    spawn_workspace_pull_within(targets, tx, WORKSPACE_PULL_TIMEOUT);
}

/// [`spawn_workspace_pull`] with the ceiling passed in, so a test can watch
/// the timeout path without waiting [`WORKSPACE_PULL_TIMEOUT`] for it.
fn spawn_workspace_pull_within(
    targets: Vec<WorkspacePull>,
    tx: std_mpsc::Sender<DiagnosticsUpdate>,
    ceiling: std::time::Duration,
) {
    if targets.is_empty() {
        return;
    }
    tokio::spawn(async move {
        for target in targets {
            // The RESULT-ID lock is what serialises a server's pulls, and it
            // is held end to end: snapshotting the ids without it let two
            // overlapping pulls (the spawn one and a refresh) take the SAME
            // `previous` set, so the second sent ids the first had already
            // replaced and its older report could land after the newer one
            // and win, the app's store being last-write-wins per (file,
            // server).
            //
            // The CLIENT lock is deliberately NOT held across the await. A
            // server that accepts `workspace/diagnostic` and never answers it
            // (ty 0.0.73) would otherwise own the client forever, and
            // `open_doc` — which takes the same lock ON the worker loop,
            // before it registers the document — blocked behind it, wedging
            // every later command including Go to Definition (#533
            // regression, 0.1.939). Cloning the socket keeps the request on
            // the same server while leaving the client free.
            // Lock order: result ids BEFORE the client, never the reverse.
            // The pull task is the only consumer of the ids, so nothing can
            // hold them and want the client today — but reversing this without
            // that still being true would deadlock.
            let mut ids = target.result_ids.lock().await;
            // Re-check retirement HERE, not only in `workspace_pull_targets`.
            // That filter reads the flag when the target list is built; this
            // task may then have waited the full ceiling on the ids behind an
            // earlier pull for the same server, which timed out and retired it
            // meanwhile. Acting on the stale snapshot would send exactly the
            // un-reapable request the retirement exists to prevent.
            if target.stalled.load(Ordering::Relaxed) {
                log_file::log(&format!(
                    "lsp[{}] workspace/diagnostic skipped: retired while queued",
                    target.name
                ));
                continue;
            }
            let previous = ids.previous();
            let server = {
                let client = target.client.lock().await;
                client.detached_server()
            };
            log_file::log(&format!(
                "lsp[{}] workspace/diagnostic pull, {} previous result id(s)",
                target.name,
                previous.len()
            ));
            // Bounded, because a pull can go unanswered indefinitely: `ty`
            // advertises `workspaceDiagnostics` and then never replies
            // (checked on 0.0.73 and again on 0.0.82). Without a ceiling the
            // task stays parked on a response that will not come and the
            // result ids stay locked behind it, so the NEXT pull for that
            // server never starts either. Giving up frees the task and the
            // ids — but NOT the mainloop's `outgoing` entry, which only a
            // response with that id can drain, so the abandoned request leaks
            // one entry. That is why a timeout also retires the server from
            // future pulls: one leak per client, not one per refresh.
            let resp = match tokio::time::timeout(
                ceiling,
                crate::lsp::client::LspRequests::workspace_diagnostics_on(
                    server,
                    target.identifier.clone(),
                    previous,
                ),
            )
            .await
            {
                Ok(resp) => resp,
                Err(_) => {
                    target.stalled.store(true, Ordering::Relaxed);
                    log_file::log(&format!(
                        "lsp[{}] workspace/diagnostic timed out after {}s; \
                         retiring it from workspace pulls for this session",
                        target.name,
                        ceiling.as_secs()
                    ));
                    continue;
                }
            };
            match resp {
                Ok(result) => {
                    let forwarded = apply_workspace_report(&target.name, result, &mut ids, &tx);
                    log_file::log(&format!(
                        "lsp[{}] workspace/diagnostic: {forwarded} file(s) reported, {} id(s) cached",
                        target.name,
                        ids.len()
                    ));
                }
                Err(e) => {
                    log_file::log(&format!(
                        "lsp[{}] workspace/diagnostic error: {e:#}",
                        target.name
                    ));
                }
            }
            drop(ids);
        }
    });
}

/// Fold one server's `workspace/diagnostic` answer into its result-id cache
/// and the app-facing diagnostics stream, returning how many files it
/// reported on (#533).
///
/// The reports go out on the same channel and under the same server name as
/// the PUSH path, so PROBLEMS needs no third producer: the app already stores
/// diagnostics per (file, server) and replaces a server's set wholesale. What
/// a pull adds is files no editor has open, which that store already carries
/// and `rebuild_problems` already walks.
fn apply_workspace_report(
    server: &str,
    result: lsp_types::WorkspaceDiagnosticReportResult,
    ids: &mut DiagnosticResultIds,
    tx: &std_mpsc::Sender<DiagnosticsUpdate>,
) -> usize {
    let items = match result {
        lsp_types::WorkspaceDiagnosticReportResult::Report(r) => r.items,
        lsp_types::WorkspaceDiagnosticReportResult::Partial(p) => p.items,
    };
    let mut forwarded = 0;
    for item in items {
        match item {
            // Unchanged is what `previousResultIds` bought: the server is
            // saying the id we sent still describes the file, so there is
            // nothing to re-process. Its reissued id still has to be recorded
            // - the server may rotate it on every answer.
            lsp_types::WorkspaceDocumentDiagnosticReport::Unchanged(u) => {
                ids.record(
                    u.uri.as_str(),
                    Some(u.unchanged_document_diagnostic_report.result_id.as_str()),
                );
            }
            lsp_types::WorkspaceDocumentDiagnosticReport::Full(f) => {
                let report = f.full_document_diagnostic_report;
                ids.record(f.uri.as_str(), report.result_id.as_deref());
                // A URI that is not a file (a virtual or untitled document)
                // has no row to show and no editor to paint.
                let Ok(path) = f.uri.to_file_path() else {
                    continue;
                };
                let diagnostics = report
                    .items
                    .iter()
                    .map(|d| crate::lsp::client::convert_diagnostic(server, d))
                    .collect();
                // An EMPTY list is the server saying this file is clear now,
                // which is how a fixed file loses its rows - the app's store
                // removes the server's entry on exactly that. Skipping empties
                // would leave the last report's problems on screen forever.
                let _ = tx.send(DiagnosticsUpdate {
                    path,
                    server: server.to_string(),
                    diagnostics,
                    pulled: true,
                });
                forwarded += 1;
            }
        }
    }
    forwarded
}

/// Settle time before a document pull goes out after an edit (#866): a
/// burst of keystrokes sends one pull, for its last edit, not one per key.
const DOCUMENT_PULL_DEBOUNCE: std::time::Duration = std::time::Duration::from_millis(150);

/// Ceiling on one `textDocument/diagnostic` pull (#866). A server that lets
/// one expire is retired from document pulls, for the reason
/// `ManagedClient::diagnostic_pull_stalled` gives.
const DOCUMENT_PULL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);

/// Generation numbers for document pulls (#866), unique for the whole
/// session. A per-document count would start over when a document is
/// closed and reopened, and a pull from before the close could then pass
/// for the reopened buffer's latest.
static NEXT_DOCUMENT_PULL: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);

/// One `textDocument/diagnostic` pull (#866): a server that answers it, the
/// document, and the generation this pull stands for.
struct DocumentPull {
    name: String,
    client: Arc<TokioMutex<LspClient>>,
    identifier: Option<String>,
    stalled: Arc<AtomicBool>,
    generations: Arc<StdMutex<HashMap<PathBuf, u64>>>,
    generation: u64,
    path: PathBuf,
    uri: Url,
    /// Whether the server also answers the workspace pull, which keeps its
    /// sets fresh after it is retired from document pulls.
    reports_per_workspace: bool,
    /// Where the documents the server reports on are recorded (#851).
    support: CapabilitySupport,
}

impl DocumentPull {
    /// Whether no later pull for this document has been issued since this
    /// one. Otherwise an edit overtook it, and its answer would describe text
    /// the buffer no longer holds.
    fn is_current(&self) -> bool {
        let generations = self.generations.lock().unwrap_or_else(|e| e.into_inner());
        generations.get(&self.path) == Some(&self.generation)
    }

    /// Once a pull expired and retired the server from document pulls: it
    /// reports on none of its documents any more, so it leaves their
    /// reporter lists (#851; the built-in Markdown lint comes back where it
    /// stood down for rumdl), and the sets it pulled for them are withdrawn,
    /// as nothing will refresh them after an edit. A server that also
    /// reports per workspace keeps those.
    fn retire(&self, tx: &std_mpsc::Sender<DiagnosticsUpdate>) {
        let served: Vec<PathBuf> = self
            .generations
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .keys()
            .cloned()
            .collect();
        if let Ok(mut support) = self.support.lock() {
            for path in &served {
                if let Some(names) = support.document_servers.get_mut(path) {
                    names.retain(|n| *n != self.name);
                }
            }
        }
        if self.reports_per_workspace {
            return;
        }
        for path in served {
            let _ = tx.send(DiagnosticsUpdate {
                path,
                server: self.name.clone(),
                diagnostics: Vec::new(),
                pulled: true,
            });
        }
    }
}

/// The pulls an opened or edited document calls for (#866): one per server
/// among `clients` that answers `textDocument/diagnostic` and has not been
/// retired, each stamped with a new generation so any older pull for the
/// document stands down.
fn document_pull_targets<'a>(
    clients: impl Iterator<Item = &'a ManagedClient>,
    path: &Path,
    uri: &Url,
    support: &CapabilitySupport,
) -> Vec<DocumentPull> {
    clients
        .filter(|c| c.supports_document_diagnostics)
        .filter(|c| !c.document_pull_stalled.load(Ordering::Relaxed))
        .map(|c| {
            let generation = {
                let mut generations = c
                    .document_pull_generations
                    .lock()
                    .unwrap_or_else(|e| e.into_inner());
                let next = NEXT_DOCUMENT_PULL.fetch_add(1, Ordering::Relaxed);
                generations.insert(path.to_path_buf(), next);
                next
            };
            DocumentPull {
                name: c.name.clone(),
                client: c.client.clone(),
                identifier: c.diagnostic_identifier.clone(),
                stalled: c.document_pull_stalled.clone(),
                generations: c.document_pull_generations.clone(),
                generation,
                path: path.to_path_buf(),
                uri: uri.clone(),
                reports_per_workspace: c.supports_workspace_diagnostics,
                support: support.clone(),
            }
        })
        .collect()
}

/// Run each pull off the worker loop once `debounce` has passed (#866),
/// forwarding its report under the server's name on the channel the push
/// path feeds, so the app stores it like any published set.
fn spawn_document_pulls(
    targets: Vec<DocumentPull>,
    tx: std_mpsc::Sender<DiagnosticsUpdate>,
    debounce: std::time::Duration,
) {
    spawn_document_pulls_within(targets, tx, debounce, DOCUMENT_PULL_TIMEOUT);
}

/// [`spawn_document_pulls`] with the ceiling passed in, so a test can watch
/// the timeout path without waiting [`DOCUMENT_PULL_TIMEOUT`] for it.
fn spawn_document_pulls_within(
    targets: Vec<DocumentPull>,
    tx: std_mpsc::Sender<DiagnosticsUpdate>,
    debounce: std::time::Duration,
    ceiling: std::time::Duration,
) {
    for target in targets {
        let tx = tx.clone();
        tokio::spawn(async move {
            if !debounce.is_zero() {
                tokio::time::sleep(debounce).await;
            }
            // Overtaken by a later edit while it waited, or the server was
            // retired meanwhile: nothing to ask.
            if !target.is_current() || target.stalled.load(Ordering::Relaxed) {
                return;
            }
            // As in the workspace pull, the client is not held across the
            // await: a server that never answers must not wedge `open_doc`.
            let server = {
                let client = target.client.lock().await;
                client.detached_server()
            };
            let resp = tokio::time::timeout(
                ceiling,
                crate::lsp::client::LspRequests::document_diagnostics_on(
                    server,
                    target.uri.clone(),
                    target.identifier.clone(),
                ),
            )
            .await;
            let report = match resp {
                Ok(Ok(report)) => report,
                Ok(Err(e)) => {
                    log_file::log(&format!(
                        "lsp[{}] textDocument/diagnostic error: {e:#}",
                        target.name
                    ));
                    return;
                }
                Err(_) => {
                    target.stalled.store(true, Ordering::Relaxed);
                    log_file::log(&format!(
                        "lsp[{}] textDocument/diagnostic timed out after {}s; \
                         retiring it from document pulls for this session",
                        target.name,
                        ceiling.as_secs()
                    ));
                    target.retire(&tx);
                    return;
                }
            };
            if !target.is_current() {
                return;
            }
            let Some(items) = document_report_items(report) else {
                return;
            };
            let _ = tx.send(DiagnosticsUpdate {
                path: target.path.clone(),
                server: target.name.clone(),
                diagnostics: items
                    .iter()
                    .map(|d| crate::lsp::client::convert_diagnostic(&target.name, d))
                    .collect(),
                pulled: true,
            });
        });
    }
}

/// The diagnostics a `textDocument/diagnostic` answer carries for the
/// document itself (#866). `None` for an answer with none of its own: an
/// `Unchanged` report, which croft never invites by sending a previous result
/// id, or a bare partial result.
fn document_report_items(
    result: lsp_types::DocumentDiagnosticReportResult,
) -> Option<Vec<lsp_types::Diagnostic>> {
    match result {
        lsp_types::DocumentDiagnosticReportResult::Report(
            lsp_types::DocumentDiagnosticReport::Full(full),
        ) => Some(full.full_document_diagnostic_report.items),
        _ => None,
    }
}

/// The server's `diagnosticProvider.identifier`, echoed back on every pull.
///
/// A server that registered several diagnostic sources uses it to tell which
/// source a previous result id belongs to, so sending `None` where it
/// published an identifier throws its incrementality away. Read from both
/// capability variants for the same reason
/// [`workspace_diagnostics_supported`] is.
fn diagnostic_identifier_of(cap: &Option<DiagnosticServerCapabilities>) -> Option<String> {
    match cap {
        Some(DiagnosticServerCapabilities::Options(o)) => o.identifier.clone(),
        Some(DiagnosticServerCapabilities::RegistrationOptions(r)) => {
            r.diagnostic_options.identifier.clone()
        }
        None => None,
    }
}

/// Whether the server answers `workspace/diagnostic`, the LSP 3.17 PULL of
/// whole-project diagnostics (#533).
///
/// The inner `workspace_diagnostics` flag, NOT `Option::is_some`. A server
/// that supports only per-document pulls still advertises
/// `diagnosticProvider` with that flag `false`; reading the outer `Option`
/// would send it a request it does not implement and get `-32601 Unhandled
/// method` back, which is the exact shape that made croft call
/// `textDocument/declaration` on vtsls.
///
/// Both capability variants carry the same options, so both are unwrapped
/// rather than treating `RegistrationOptions` as an unconditional yes.
fn workspace_diagnostics_supported(cap: &Option<DiagnosticServerCapabilities>) -> bool {
    match cap {
        Some(DiagnosticServerCapabilities::Options(o)) => o.workspace_diagnostics,
        Some(DiagnosticServerCapabilities::RegistrationOptions(r)) => {
            r.diagnostic_options.workspace_diagnostics
        }
        None => false,
    }
}

/// Flatten an LSP `SignatureHelp` into the widget-facing [`SignatureInfo`]
/// list, resolving each parameter label to a (start, end) char range within
/// the signature label so the popup can bold the active parameter. The active
/// parameter is taken per-signature when set, else from the help-level field.
/// ponytail: parameter label offsets are UTF-16 per the spec; treated as char
/// offsets here, which is exact for ASCII/BMP signatures (the overwhelming
/// common case) and only off for astral-plane identifiers.
fn normalise_signature_help(help: lsp_types::SignatureHelp) -> (Vec<SignatureInfo>, usize) {
    use lsp_types::ParameterLabel;
    let help_active_param = help.active_parameter;
    let signatures: Vec<SignatureInfo> = help
        .signatures
        .into_iter()
        .map(|sig| {
            let active_idx = sig.active_parameter.or(help_active_param).unwrap_or(0) as usize;
            let active_param = sig.parameters.as_ref().and_then(|params| {
                params.get(active_idx).and_then(|p| match &p.label {
                    ParameterLabel::LabelOffsets([s, e]) => Some((*s as usize, *e as usize)),
                    ParameterLabel::Simple(text) => sig.label.find(text.as_str()).map(|byte| {
                        let start = sig.label[..byte].chars().count();
                        (start, start + text.chars().count())
                    }),
                })
            });
            SignatureInfo {
                label: sig.label,
                active_param,
            }
        })
        .collect();
    let active_signature =
        (help.active_signature.unwrap_or(0) as usize).min(signatures.len().saturating_sub(1));
    (signatures, active_signature)
}

/// Declaration capability (`boolean | DeclarationOptions | DeclarationRegistrationOptions`).
/// vtsls sends `declarationProvider: false`, so the bare-`false` arm is what
/// stops croft from calling the unhandled `textDocument/declaration`.
/// Flatten the server's symbol response into a depth-tagged list in document
/// order — the shape the Outline widget renders directly. The modern `Nested`
/// hierarchy recurses (depth grows with nesting); the legacy `Flat` list has no
/// hierarchy, so every symbol sits at depth 0, sorted by position.
fn flatten_symbols(resp: DocumentSymbolResponse) -> Vec<OutlineSymbol> {
    match resp {
        DocumentSymbolResponse::Nested(syms) => {
            let mut out = Vec::new();
            push_nested(&syms, 0, &mut out);
            out
        }
        DocumentSymbolResponse::Flat(infos) => {
            let mut out: Vec<OutlineSymbol> = infos
                .into_iter()
                .map(|info| {
                    let start = info.location.range.start;
                    OutlineSymbol {
                        name: info.name,
                        detail: None,
                        kind: OutlineKind::from_lsp(info.kind),
                        depth: 0,
                        line: start.line,
                        character: start.character,
                        range_start_line: info.location.range.start.line,
                        range_end_line: info.location.range.end.line,
                        range_start_character: info.location.range.start.character,
                        range_end_character: info.location.range.end.character,
                    }
                })
                .collect();
            out.sort_by_key(|s| (s.line, s.character));
            out
        }
    }
}

/// Each level in file order (#1220): tsserver sorts its navigation tree's
/// children by name, so vtsls replies `Cart` before `sum`; VS Code orders by
/// position client-side, and so does this.
fn push_nested(syms: &[DocumentSymbol], depth: u16, out: &mut Vec<OutlineSymbol>) {
    let mut syms: Vec<&DocumentSymbol> = syms.iter().collect();
    syms.sort_by_key(|s| {
        (
            s.selection_range.start.line,
            s.selection_range.start.character,
        )
    });
    for sym in syms {
        out.push(OutlineSymbol {
            name: sym.name.clone(),
            detail: sym.detail.clone(),
            kind: OutlineKind::from_lsp(sym.kind),
            depth,
            line: sym.selection_range.start.line,
            character: sym.selection_range.start.character,
            range_start_line: sym.range.start.line,
            range_end_line: sym.range.end.line,
            range_start_character: sym.range.start.character,
            range_end_character: sym.range.end.character,
        });
        if let Some(children) = &sym.children {
            push_nested(children, depth + 1, out);
        }
    }
}

fn declaration_supported(cap: &Option<DeclarationCapability>) -> bool {
    match cap {
        Some(DeclarationCapability::Simple(b)) => *b,
        Some(DeclarationCapability::RegistrationOptions(_) | DeclarationCapability::Options(_)) => {
            true
        }
        None => false,
    }
}

/// Type-definition capability (`boolean | TypeDefinitionOptions | ...`), same
/// bare-`false` rule as hover/declaration. vtsls, basedpyright, rust-analyzer
/// and gopls all advertise it, so the row is shown for those; a server that
/// omits it (or sends `false`) gets the row hidden instead of a -32601.
fn type_definition_supported(cap: &Option<TypeDefinitionProviderCapability>) -> bool {
    match cap {
        Some(TypeDefinitionProviderCapability::Simple(b)) => *b,
        Some(TypeDefinitionProviderCapability::Options(_)) => true,
        None => false,
    }
}

/// Implementation capability (`boolean | ImplementationOptions | ...`), same
/// bare-`false` rule as hover/declaration/type-definition. rust-analyzer, gopls
/// and vtsls advertise it; a server that omits it (or sends `false`) gets the
/// "Go to Implementations" row hidden instead of a -32601.
fn implementation_supported(cap: &Option<ImplementationProviderCapability>) -> bool {
    match cap {
        Some(ImplementationProviderCapability::Simple(b)) => *b,
        Some(ImplementationProviderCapability::Options(_)) => true,
        None => false,
    }
}

fn def_location(resp: &GotoDefinitionResponse) -> Option<(PathBuf, u32, u32)> {
    let (uri, pos) = match resp {
        GotoDefinitionResponse::Scalar(loc) => (&loc.uri, loc.range.start),
        GotoDefinitionResponse::Array(locs) => {
            let loc = locs.first()?;
            (&loc.uri, loc.range.start)
        }
        GotoDefinitionResponse::Link(links) => {
            let link = links.first()?;
            (&link.target_uri, link.target_selection_range.start)
        }
    };
    let path = uri.to_file_path().ok()?;
    Some((path, pos.line, pos.character))
}

/// Every location in a goto response, not just the first. Used by Go to
/// Implementations, whose response is commonly an `Array` of every implementor
/// (a Scalar collapses to one element). Locations whose URI is not a local file
/// path are dropped.
fn def_locations(resp: &GotoDefinitionResponse) -> Vec<(PathBuf, u32, u32)> {
    let raw: Vec<(&Url, Position)> = match resp {
        GotoDefinitionResponse::Scalar(loc) => vec![(&loc.uri, loc.range.start)],
        GotoDefinitionResponse::Array(locs) => {
            locs.iter().map(|l| (&l.uri, l.range.start)).collect()
        }
        GotoDefinitionResponse::Link(links) => links
            .iter()
            .map(|l| (&l.target_uri, l.target_selection_range.start))
            .collect(),
    };
    raw.into_iter()
        .filter_map(|(uri, pos)| Some((uri.to_file_path().ok()?, pos.line, pos.character)))
        .collect()
}

/// Every reference location the server returned, as local-file targets. Unlike
/// the goto family, `textDocument/references` replies with a flat `Vec<Location>`
/// (not a `GotoDefinitionResponse`), so it gets its own mapper rather than going
/// through `def_locations`. Locations whose URI is not a local file path are
/// dropped (the same rule `def_locations` applies).
/// Normalise `callHierarchy/incomingCalls` replies: each caller becomes a
/// site at its first reported call range (the call expression) or, when the
/// server sends none, at the caller's own selection range.
fn incoming_call_sites(calls: Vec<lsp_types::CallHierarchyIncomingCall>) -> Vec<CallSite> {
    calls
        .into_iter()
        .filter_map(|c| {
            let path = c.from.uri.to_file_path().ok()?;
            let pos = c
                .from_ranges
                .first()
                .map(|r| r.start)
                .unwrap_or(c.from.selection_range.start);
            Some(CallSite {
                name: c.from.name,
                path,
                line: pos.line,
                character: pos.character,
            })
        })
        .collect()
}

/// Normalise `callHierarchy/outgoingCalls` replies: each callee becomes a
/// site at its definition (`selection_range`) — the `from_ranges` live in
/// the CALLER's document and are not jump targets here.
fn outgoing_call_sites(calls: Vec<lsp_types::CallHierarchyOutgoingCall>) -> Vec<CallSite> {
    calls
        .into_iter()
        .filter_map(|c| {
            let path = c.to.uri.to_file_path().ok()?;
            let pos = c.to.selection_range.start;
            Some(CallSite {
                name: c.to.name,
                path,
                line: pos.line,
                character: pos.character,
            })
        })
        .collect()
}

/// Type-hierarchy items (#613) as picker rows, each landing on the type's
/// name rather than the top of its range.
fn type_hierarchy_sites(items: Vec<lsp_types::TypeHierarchyItem>) -> Vec<CallSite> {
    items
        .into_iter()
        .filter_map(|t| {
            let path = t.uri.to_file_path().ok()?;
            let pos = t.selection_range.start;
            Some(CallSite {
                name: t.name,
                path,
                line: pos.line,
                character: pos.character,
            })
        })
        .collect()
}

/// Normalise `textDocument/documentHighlight` wire items into croft's own
/// UTF-16-positioned occurrence spans. A missing kind defaults to a read
/// tint, matching VS Code (Text and Read share `wordHighlightBackground`;
/// only Write gets the strong tint).
fn occurrence_items(hs: Vec<lsp_types::DocumentHighlight>) -> Vec<OccurrenceItem> {
    hs.into_iter()
        .map(|h| OccurrenceItem {
            start_line: h.range.start.line,
            start_char: h.range.start.character,
            end_line: h.range.end.line,
            end_char: h.range.end.character,
            write: h.kind == Some(lsp_types::DocumentHighlightKind::WRITE),
        })
        .collect()
}

fn reference_locations(locs: &[Location]) -> Vec<(PathBuf, u32, u32)> {
    locs.iter()
        .filter_map(|l| {
            Some((
                l.uri.to_file_path().ok()?,
                l.range.start.line,
                l.range.start.character,
            ))
        })
        .collect()
}

/// Extract a server's semantic-token legend (token-type names in index
/// order) from its advertised capabilities, but only when it supports
/// full-document requests, since that is the only variant croft issues.
fn semantic_legend_of(caps: &ServerCapabilities) -> Option<Vec<String>> {
    let opts = match caps.semantic_tokens_provider.as_ref()? {
        SemanticTokensServerCapabilities::SemanticTokensOptions(o) => o,
        SemanticTokensServerCapabilities::SemanticTokensRegistrationOptions(o) => {
            &o.semantic_tokens_options
        }
    };
    let full_ok = matches!(
        opts.full,
        Some(SemanticTokensFullOptions::Bool(true)) | Some(SemanticTokensFullOptions::Delta { .. })
    );
    if !full_ok {
        return None;
    }
    Some(
        opts.legend
            .token_types
            .iter()
            .map(|t| t.as_str().to_string())
            .collect(),
    )
}

/// Whether the server's `semanticTokensProvider` advertises range support
/// (`textDocument/semanticTokens/range`). A server that supports range is a
/// purpose-built incremental highlighter (ty), which is preferred for
/// semantic tokens over a full-only provider (basedpyright) that pays a slow
/// whole-workspace enumeration before its first response.
fn semantic_tokens_range_supported(caps: &ServerCapabilities) -> bool {
    let opts = match caps.semantic_tokens_provider.as_ref() {
        Some(SemanticTokensServerCapabilities::SemanticTokensOptions(o)) => o,
        Some(SemanticTokensServerCapabilities::SemanticTokensRegistrationOptions(o)) => {
            &o.semantic_tokens_options
        }
        None => return false,
    };
    matches!(opts.range, Some(true))
}

/// Flatten lsp-types `SemanticToken` structs back into the raw
/// relative-encoded `[deltaLine, deltaStart, length, type, modifiers]`
/// u32 array that `highlight::decode_semantic_tokens` consumes.
fn flatten_semantic_tokens(tokens: &[lsp_types::SemanticToken]) -> Vec<u32> {
    let mut out = Vec::with_capacity(tokens.len() * 5);
    for t in tokens {
        out.push(t.delta_line);
        out.push(t.delta_start);
        out.push(t.length);
        out.push(t.token_type);
        out.push(t.token_modifiers_bitset);
    }
    out
}

/// The standard LSP semantic token types croft can render. Declared so
/// servers know which types we understand; they reply with a legend that
/// is a subset of this set.
fn standard_semantic_token_types() -> Vec<SemanticTokenType> {
    vec![
        SemanticTokenType::NAMESPACE,
        SemanticTokenType::TYPE,
        SemanticTokenType::CLASS,
        SemanticTokenType::ENUM,
        SemanticTokenType::INTERFACE,
        SemanticTokenType::STRUCT,
        SemanticTokenType::TYPE_PARAMETER,
        SemanticTokenType::PARAMETER,
        SemanticTokenType::VARIABLE,
        SemanticTokenType::PROPERTY,
        SemanticTokenType::ENUM_MEMBER,
        SemanticTokenType::EVENT,
        SemanticTokenType::FUNCTION,
        SemanticTokenType::METHOD,
        SemanticTokenType::MACRO,
        SemanticTokenType::KEYWORD,
        SemanticTokenType::MODIFIER,
        SemanticTokenType::COMMENT,
        SemanticTokenType::STRING,
        SemanticTokenType::NUMBER,
        SemanticTokenType::REGEXP,
        SemanticTokenType::OPERATOR,
        SemanticTokenType::DECORATOR,
    ]
}

fn standard_semantic_token_modifiers() -> Vec<SemanticTokenModifier> {
    vec![
        SemanticTokenModifier::DECLARATION,
        SemanticTokenModifier::DEFINITION,
        SemanticTokenModifier::READONLY,
        SemanticTokenModifier::STATIC,
        SemanticTokenModifier::DEPRECATED,
        SemanticTokenModifier::ABSTRACT,
        SemanticTokenModifier::ASYNC,
        SemanticTokenModifier::MODIFICATION,
        SemanticTokenModifier::DOCUMENTATION,
        SemanticTokenModifier::DEFAULT_LIBRARY,
    ]
}

fn build_client_capabilities() -> ClientCapabilities {
    // `linkSupport` on every goto: without it a server flattens each
    // `LocationLink` into a `Location` over the whole declaration, and the
    // jump lands on its first character instead of the name, lines above it
    // in a multi-line declaration (#1284). `def_location` reads a link's
    // `targetSelectionRange`.
    let goto = || {
        Some(lsp_types::GotoCapability {
            dynamic_registration: Some(false),
            link_support: Some(true),
        })
    };
    ClientCapabilities {
        text_document: Some(TextDocumentClientCapabilities {
            definition: goto(),
            declaration: goto(),
            type_definition: goto(),
            implementation: goto(),

            // croft sends didSave, and only to a server that advertised
            // `save` (#854). No dynamic registration: croft accepts
            // `client/registerCapability` for watched files alone (#908), and
            // rust-analyzer registers didSave dynamically when told it may,
            // instead of advertising `save`.
            synchronization: Some(lsp_types::TextDocumentSyncClientCapabilities {
                dynamic_registration: Some(false),
                will_save: Some(false),
                will_save_wait_until: Some(false),
                did_save: Some(true),
            }),
            completion: Some(CompletionClientCapabilities {
                dynamic_registration: Some(false),
                context_support: Some(true),
                completion_item: Some(CompletionItemCapability {
                    snippet_support: Some(false),
                    commit_characters_support: Some(false),
                    documentation_format: Some(vec![MarkupKind::Markdown, MarkupKind::PlainText]),
                    deprecated_support: Some(true),
                    preselect_support: Some(true),
                    insert_replace_support: Some(false),
                    label_details_support: Some(true),
                    // Auto-imports may come from resolve (#928). Not docs:
                    // rust-analyzer would then leave them out of the list,
                    // which the details pane shows.
                    resolve_support: Some(lsp_types::CompletionItemCapabilityResolveSupport {
                        properties: vec![String::from("additionalTextEdits")],
                    }),
                    ..Default::default()
                }),
                completion_item_kind: Some(CompletionItemKindCapability {
                    value_set: Some(vec![
                        CompletionItemKind::TEXT,
                        CompletionItemKind::METHOD,
                        CompletionItemKind::FUNCTION,
                        CompletionItemKind::CONSTRUCTOR,
                        CompletionItemKind::FIELD,
                        CompletionItemKind::VARIABLE,
                        CompletionItemKind::CLASS,
                        CompletionItemKind::INTERFACE,
                        CompletionItemKind::MODULE,
                        CompletionItemKind::PROPERTY,
                        CompletionItemKind::UNIT,
                        CompletionItemKind::VALUE,
                        CompletionItemKind::ENUM,
                        CompletionItemKind::KEYWORD,
                        CompletionItemKind::SNIPPET,
                        CompletionItemKind::COLOR,
                        CompletionItemKind::FILE,
                        CompletionItemKind::REFERENCE,
                        CompletionItemKind::FOLDER,
                        CompletionItemKind::ENUM_MEMBER,
                        CompletionItemKind::CONSTANT,
                        CompletionItemKind::STRUCT,
                        CompletionItemKind::EVENT,
                        CompletionItemKind::OPERATOR,
                        CompletionItemKind::TYPE_PARAMETER,
                    ]),
                }),
                ..Default::default()
            }),
            signature_help: Some(lsp_types::SignatureHelpClientCapabilities {
                dynamic_registration: Some(false),
                signature_information: Some(lsp_types::SignatureInformationSettings {
                    documentation_format: Some(vec![MarkupKind::PlainText, MarkupKind::Markdown]),
                    parameter_information: Some(lsp_types::ParameterInformationSettings {
                        label_offset_support: Some(true),
                    }),
                    active_parameter_support: Some(true),
                }),
                context_support: Some(true),
            }),
            semantic_tokens: Some(SemanticTokensClientCapabilities {
                dynamic_registration: Some(false),
                requests: SemanticTokensClientCapabilitiesRequests {
                    // ty answers a viewport `semanticTokens/range` query in tens
                    // of ms even on a cold workspace, so croft fires one on open
                    // for instant first paint of on-screen code.
                    range: Some(true),
                    full: Some(SemanticTokensFullOptions::Bool(true)),
                },
                token_types: standard_semantic_token_types(),
                token_modifiers: standard_semantic_token_modifiers(),
                formats: vec![TokenFormat::RELATIVE],
                overlapping_token_support: Some(false),
                multiline_token_support: Some(false),
                // Tell the server its tokens layer over croft's tree-sitter
                // highlighting (VS Code / Zed "combined" model), so it may
                // omit tokens that already match syntax.
                augments_syntax_tokens: Some(true),
                ..Default::default()
            }),
            // Advertise hierarchical Outline support so servers return the
            // nested `DocumentSymbol` tree (rust-analyzer falls back to the
            // flat `SymbolInformation` list without this), exactly as VS Code
            // does. `flatten_symbols` handles both shapes regardless.
            document_symbol: Some(DocumentSymbolClientCapabilities {
                dynamic_registration: Some(false),
                hierarchical_document_symbol_support: Some(true),
                ..Default::default()
            }),
            // Advertise inlay-hint support so servers that gate the provider
            // on it (vtsls) publish `inlayHintProvider` and answer
            // `textDocument/inlayHint`.
            inlay_hint: Some(lsp_types::InlayHintClientCapabilities {
                dynamic_registration: Some(false),
                resolve_support: None,
            }),
            // Advertise call-hierarchy and documentHighlight support so
            // servers that gate their providers on the client declaring
            // them (vtsls does for several) publish the capability.
            call_hierarchy: Some(lsp_types::CallHierarchyClientCapabilities {
                dynamic_registration: Some(false),
            }),
            type_hierarchy: Some(lsp_types::TypeHierarchyClientCapabilities {
                dynamic_registration: Some(false),
            }),
            code_lens: Some(lsp_types::CodeLensClientCapabilities {
                dynamic_registration: Some(false),
            }),
            document_highlight: Some(lsp_types::DocumentHighlightClientCapabilities {
                dynamic_registration: Some(false),
            }),
            linked_editing_range: Some(lsp_types::LinkedEditingRangeClientCapabilities {
                dynamic_registration: Some(false),
            }),
            // LSP 3.18, still "proposed" in lsp-types (#607): a server that
            // offers ghost-text suggestions (Copilot's) answers for its files.
            inline_completion: Some(lsp_types::InlineCompletionClientCapabilities {
                dynamic_registration: Some(false),
            }),
            selection_range: Some(lsp_types::SelectionRangeClientCapabilities {
                dynamic_registration: Some(false),
            }),
            // Advertise prepare-rename support (#254 item 6). Per LSP 3.12 a
            // server publishes `RenameOptions.prepareProvider` only in answer
            // to this; without it most servers send a bare
            // `renameProvider: true`, which `prepare_rename_supported`
            // rejects — the validation would silently never engage.
            // `prepare_support_default_behavior` is what lets a server return
            // the `{ defaultBehavior: true }` shape at all.
            rename: Some(lsp_types::RenameClientCapabilities {
                dynamic_registration: Some(false),
                prepare_support: Some(true),
                prepare_support_default_behavior: Some(
                    lsp_types::PrepareSupportDefaultBehavior::IDENTIFIER,
                ),
                ..Default::default()
            }),
            // Declare push-diagnostics support. Several servers gate
            // `textDocument/publishDiagnostics` on the client advertising this
            // (ty and ruff push regardless, but vtsls stays silent without it);
            // declaring it is what every real LSP client (VS Code, Neovim) does.
            // `tagSupport` (#1522): servers that check it before tagging
            // unused or deprecated code would otherwise leave the tag out.
            publish_diagnostics: Some(PublishDiagnosticsClientCapabilities {
                related_information: Some(true),
                // Servers may leave the rule's link out otherwise (#1540).
                code_description_support: Some(true),
                tag_support: Some(lsp_types::TagSupport {
                    value_set: vec![
                        lsp_types::DiagnosticTag::UNNECESSARY,
                        lsp_types::DiagnosticTag::DEPRECATED,
                    ],
                }),
                ..Default::default()
            }),
            // Advertise rich code-action support. Without codeActionLiteralSupport
            // a server (ruff, vtsls) must answer `textDocument/codeAction` with
            // plain `Command[]` and withholds kinded source actions, so "Organize
            // Imports" / "Fix all" never surface. dataSupport + resolveSupport for
            // `edit` let servers defer the (expensive) edit to `codeAction/resolve`
            // — vtsls auto-imports and ruff fixes rely on it. This is exactly what
            // VS Code and Neovim declare.
            code_action: Some(CodeActionClientCapabilities {
                dynamic_registration: Some(false),
                code_action_literal_support: Some(CodeActionLiteralSupport {
                    code_action_kind: CodeActionKindLiteralSupport {
                        value_set: vec![
                            String::new(),
                            "quickfix".to_string(),
                            "refactor".to_string(),
                            "refactor.extract".to_string(),
                            "refactor.inline".to_string(),
                            "refactor.rewrite".to_string(),
                            "source".to_string(),
                            "source.organizeImports".to_string(),
                            "source.fixAll".to_string(),
                        ],
                    },
                }),
                is_preferred_support: Some(true),
                data_support: Some(true),
                resolve_support: Some(CodeActionCapabilityResolveSupport {
                    properties: vec!["edit".to_string()],
                }),
                ..Default::default()
            }),
            // LSP 3.17 PULL diagnostics (#533). A conforming server publishes
            // `diagnosticProvider` only when the client declares this, so
            // without it `workspace_diagnostics_supported` reads `None` on
            // every server and the pull path can never engage - a gap that
            // would read as "no server supports it" rather than "croft never
            // asked". `relatedDocumentSupport` stays false: croft pulls per
            // WORKSPACE, so it has no use for a per-document report that
            // carries other files' diagnostics alongside.
            diagnostic: Some(lsp_types::DiagnosticClientCapabilities {
                dynamic_registration: Some(false),
                related_document_support: Some(false),
            }),
            ..Default::default()
        }),
        // Advertise that croft can re-pull tokens on a server's request. ty
        // does not currently send `workspace/semanticTokens/refresh` (croft
        // covers the cold-start gap with its own empty-response retry instead),
        // but declaring support is correct and future-proofs the path for
        // servers that do.
        workspace: Some(WorkspaceClientCapabilities {
            // Same re-pull contract for hints: rust-analyzer sends
            // `workspace/inlayHint/refresh` after a config change or when its
            // analysis upgrades, and croft re-requests for the visible editors.
            inlay_hint: Some(lsp_types::InlayHintWorkspaceClientCapabilities {
                refresh_support: Some(true),
            }),
            semantic_tokens: Some(SemanticTokensWorkspaceClientCapabilities {
                refresh_support: Some(true),
            }),
            // Without this declaration a server may legally IGNORE the
            // `workspace_folders` array in initialize (LSP 3.6): the
            // capability is what tells folder-aware servers (rust-analyzer,
            // gopls, ruff, ty) the client can answer
            // `workspace/workspaceFolders` and will send
            // `didChangeWorkspaceFolders` when the set changes.
            workspace_folders: Some(true),
            // The other half of the pull contract (#533): a server sends
            // `workspace/diagnostic/refresh` only when the client says it can
            // handle one. Without it a project-wide change (a config reload, a
            // dependency resolving) never reaches the pulled set, which then
            // ages silently until something else forces a re-pull.
            diagnostic: Some(lsp_types::DiagnosticWorkspaceClientCapabilities {
                refresh_support: Some(true),
            }),
            // Explorer renames and moves ask the server for its edit first
            // (#610), so imports follow the file.
            file_operations: Some(lsp_types::WorkspaceFileOperationsClientCapabilities {
                will_rename: Some(true),
                did_rename: Some(true),
                ..Default::default()
            }),
            // Servers that leave file watching to the client (ty, gopls,
            // rust-analyzer) register the globs they want, and croft
            // forwards its watcher's events (#908). Undeclared, a file
            // changed on disk outside a tab stayed stale in the server.
            did_change_watched_files: Some(lsp_types::DidChangeWatchedFilesClientCapabilities {
                dynamic_registration: Some(true),
                relative_pattern_support: Some(true),
            }),
            ..Default::default()
        }),
        // Declare `window.workDoneProgress` so servers stream `$/progress`
        // (rust-analyzer's "Indexing…", "Building CrateGraph", "Roots
        // Scanned"). The router forwards it to the status bar, so a server
        // that is busy priming is never silently mistaken for a dead one.
        // `showMessage` and `showDocument` (#1599): croft answers a server's
        // questions from a picker and opens the documents and links it
        // points at, so gopls sends "Browse documentation" as a link to
        // open rather than a line in OUTPUT.
        window: Some(WindowClientCapabilities {
            work_done_progress: Some(true),
            show_message: Some(lsp_types::ShowMessageRequestClientCapabilities {
                message_action_item: Some(lsp_types::MessageActionItemCapabilities {
                    additional_properties_support: Some(true),
                }),
            }),
            show_document: Some(lsp_types::ShowDocumentClientCapabilities { support: true }),
        }),
        // rust-analyzer emits its Run / Debug / references lenses only for
        // client-side commands the client says it can run (#608), and these
        // are exactly the ones `crate::code_lens` maps.
        experimental: Some(serde_json::json!({
            "commands": {
                "commands": [
                    "rust-analyzer.runSingle",
                    "rust-analyzer.debugSingle",
                    "rust-analyzer.showReferences"
                ]
            }
        })),
        ..Default::default()
    }
}

/// The language server language for `path`: its `files_associations` id
/// (#1574), else what its name and extension map to (#1084). The app's
/// sync uses it to decide which tabs go to the servers at all.
pub(crate) fn path_to_language(path: &Path) -> Option<Language> {
    // `files_associations` first (#1574), so the server serves the
    // language the editor highlights: a known id with no server gets none.
    // An id croft does not know falls through to the name and extension,
    // as it does for highlighting.
    if let Some(id) = crate::highlight::associated_language_id(path) {
        let lang = crate::lsp::languages::resolve(&id);
        if lang.is_some()
            || id == "plaintext"
            || crate::highlight::lang_for_language_id(&id).is_some()
        {
            return lang;
        }
    }
    Language::from_path(path)
}

/// Project-manifest filenames whose presence marks a directory as the root of a
/// `lang` project. Used to anchor the language server at the right sub-project
/// (so basedpyright finds that project's `.venv`, rust-analyzer its `Cargo.toml`,
/// etc.). An empty slice means "no per-project rooting" → use the workspace root.
fn manifest_names(lang: Language) -> &'static [&'static str] {
    lang.root_markers()
}

/// [`project_root_within`] with the multi-root bound (#147): the walk stays
/// inside the workspace root OWNING the file (longest prefix over all
/// roots), and the fallback is that owning root — so a file under a
/// secondary root roots its servers there, never at the primary. A file
/// outside every root keeps the historical primary-root fallback.
fn project_root_for_roots(
    path: &Path,
    lang: Language,
    primary: &Path,
    extra_roots: &[PathBuf],
) -> PathBuf {
    let owner = std::iter::once(primary)
        .chain(extra_roots.iter().map(PathBuf::as_path))
        .filter(|r| path.starts_with(r))
        .max_by_key(|r| r.components().count())
        .unwrap_or(primary);
    project_root_within(path, lang, owner)
}

/// The project root a file's language server should be anchored at: the nearest
/// ancestor holding a language manifest (e.g. `pyproject.toml`, `Cargo.toml`,
/// `go.mod`, `package.json`), bounded by the workspace root `bound`. Falls back
/// to `bound` when none is found, so a plain single-project workspace behaves
/// exactly as before.
fn project_root_within(path: &Path, lang: Language, bound: &Path) -> PathBuf {
    let manifests = manifest_names(lang);
    if !manifests.is_empty() {
        let mut dir = path.parent();
        while let Some(d) = dir {
            if !d.starts_with(bound) {
                break;
            }
            if manifests.iter().any(|m| d.join(m).exists()) {
                return d.to_path_buf();
            }
            if d == bound {
                break;
            }
            dir = d.parent();
        }
    }
    bound.to_path_buf()
}

/// Walk `$PATH` looking for an executable file named `cmd`. Avoids
/// invoking the binary with `--help` or `--version` because LSP servers
/// are JSON-RPC daemons with no consistent CLI flags (basedpyright-
/// langserver exits 1 on --help and crashes on --version, rustup shims
/// pretend to exist even when their component isn't installed).
/// Resolve a server config to a spawnable command, or `None` to skip it.
/// A server carrying a `provision` is handled by croft's managed installer
/// (resolved to an absolute path under `~/.croft/servers`; a lazy background
/// install is kicked off when it's absent). Every other server is resolved
/// against PATH unchanged. `log_skip` gates the "not available" log so empty
/// re-probes don't spam the log on every request.
fn resolve_config(config: &ServerConfig, log_skip: bool) -> Option<(ServerConfig, Vec<PathBuf>)> {
    if let Some(provision) = &config.provision {
        // Native-binary servers (rust-analyzer, clangd, taplo) are toolchain
        // tools: a real copy on PATH or in a toolchain dir (~/.cargo/bin) must
        // win over a croft-downloaded one so it matches the user's compiler, and
        // for rust-analyzer `resolve_path_only` prepends that dir to the child
        // PATH so the server can find cargo/rustc under a stripped GUI launch.
        // Only when no real binary exists anywhere do we fall back to a managed
        // download / Termux `pkg` install (`resolve_for_root` also does when the
        // binary is a rustup proxy with no component behind it). npm/uv servers
        // keep their own managed-first (vtsls) or PATH-first (ty/ruff) ordering
        // inside `resolve_managed`, so this preference is scoped to the Binary
        // and Go backends (a gopls in ~/go/bin is the user's own, #930).
        if matches!(
            provision,
            crate::lsp::install::Provision::Binary { .. }
                | crate::lsp::install::Provision::Go { .. }
        ) && let Some(resolved) = resolve_path_only(
            config,
            is_on_path(&config.command),
            &toolchain_fallback_dirs(),
        ) {
            return Some(resolved);
        }
        return crate::lsp::install::resolve_managed(config, provision, log_skip);
    }
    if let Some(resolved) = resolve_path_only(
        config,
        is_on_path(&config.command),
        &toolchain_fallback_dirs(),
    ) {
        return Some(resolved);
    }
    if log_skip {
        log_file::log(&format!(
            "lsp[{}] skip: `{}` not on PATH",
            config.name, config.command
        ));
    }
    None
}

/// What to tell the user when `lang` is left with no language server (#930):
/// every server it registers is missing from PATH and croft cannot install
/// any of them, because it has no provision or `installer_missing` names
/// the tool its install needs. `None` when the language registers no server,
/// or one of them can still be installed (that install reports its own
/// progress and failures).
fn missing_servers_note(
    lang: Language,
    configs: &[ServerConfig],
    installer_missing: impl Fn(&crate::lsp::install::Provision) -> Option<&'static str>,
) -> Option<String> {
    if configs.is_empty() {
        return None;
    }
    let mut why = Vec::with_capacity(configs.len());
    for config in configs {
        match config.provision.as_ref().map(&installer_missing) {
            None => why.push(format!("{} isn't on PATH", config.command)),
            Some(Some(tool)) => why.push(format!(
                "{} isn't on PATH, and installing it needs {tool}",
                config.command
            )),
            Some(None) => return None,
        }
    }
    let label = crate::highlight::lang_for_language_id(lang.lsp_id())
        .map_or(lang.lsp_id(), |kind| {
            crate::highlight::language_label(Some(kind))
        });
    Some(format!(
        "{label}: no language server, so no diagnostics or completion ({})",
        why.join("; ")
    ))
}

/// Show `note` in the status bar and OUTPUT › Server Provisioning the first
/// time `lang` is found without a server this session; later files of that
/// language, and other project roots, stay quiet.
fn report_missing_servers_once(lang: Language, note: &str) {
    static REPORTED: StdMutex<std::collections::BTreeSet<&'static str>> =
        StdMutex::new(std::collections::BTreeSet::new());
    let first = REPORTED
        .lock()
        .map(|mut seen| seen.insert(lang.lsp_id()))
        .unwrap_or(false);
    if !first {
        return;
    }
    log_file::log(&format!("lsp[{}] {note}", lang.lsp_id()));
    crate::output::push(
        crate::output::CHANNEL_PROVISION,
        crate::output::OutputLevel::Warn,
        note,
    );
    crate::lsp::install::set_status(note);
}

pub(crate) fn is_on_path(cmd: &str) -> bool {
    let Some(path) = std::env::var_os("PATH") else {
        return false;
    };
    std::env::split_paths(&path).any(|entry| is_executable_file(&entry.join(cmd)))
}

/// True when `path` is a regular file with at least one execute bit set. On
/// non-unix any existing file counts (no mode bits to inspect).
pub(crate) fn is_executable_file(path: &Path) -> bool {
    if !path.is_file() {
        return false;
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::metadata(path)
            .map(|m| m.permissions().mode() & 0o111 != 0)
            .unwrap_or(false)
    }
    #[cfg(not(unix))]
    {
        true
    }
}

/// Toolchain `bin` dirs that a macOS GUI launch (Finder / Dock / the Croft.app
/// bundle, which `open`s Ghostty under the stripped launchd PATH) drops because
/// the login-shell profile is never sourced. rust-analyzer and gopls live here
/// but resolve by bare name, so a GUI-launched croft can't find them even
/// though a terminal launch (full PATH) can. Probed only when the command is
/// already absent from the inherited PATH, so a normal launch never reaches it,
/// which keeps local and remote behaviour identical.
fn toolchain_fallback_dirs() -> Vec<PathBuf> {
    let mut dirs = Vec::new();
    if let Some(home) = std::env::var_os("HOME") {
        let home = PathBuf::from(home);
        dirs.push(home.join(".cargo").join("bin"));
        dirs.push(home.join("go").join("bin"));
        dirs.push(home.join(".local").join("bin"));
    }
    dirs.push(PathBuf::from("/opt/homebrew/bin"));
    dirs.push(PathBuf::from("/usr/local/bin"));
    dirs
}

/// Absolute path to `cmd` in the first `dirs` entry that holds an executable
/// file of that name, or `None`.
fn find_executable_in(cmd: &str, dirs: &[PathBuf]) -> Option<PathBuf> {
    dirs.iter()
        .map(|dir| dir.join(cmd))
        .find(|candidate| is_executable_file(candidate))
}

/// Resolve a PATH-only server (no managed provision) to a spawnable
/// `(config, extra_path)` pair, or `None` to skip it. When `on_path` the
/// bare command spawns as-is; otherwise the toolchain `fallback_dirs` are
/// probed and a hit is pinned to its absolute path (with its dir prepended to
/// the child's PATH) so a stripped GUI PATH can't hide it.
fn resolve_path_only(
    config: &ServerConfig,
    on_path: bool,
    fallback_dirs: &[PathBuf],
) -> Option<(ServerConfig, Vec<PathBuf>)> {
    if on_path {
        return Some((config.clone(), Vec::new()));
    }
    let abs = find_executable_in(&config.command, fallback_dirs)?;
    let extra = abs.parent().map(Path::to_path_buf).into_iter().collect();
    let mut resolved = config.clone();
    resolved.command = abs.to_string_lossy().into_owned();
    Some((resolved, extra))
}

/// [`resolve_config`] for the servers of the project at `root` (#927). A
/// native server found on PATH or in `~/.cargo/bin` that is a rustup proxy is
/// only a server when the toolchain `root` selects has the component behind
/// it. rustup puts a `rust-analyzer` proxy there for every toolchain, but its
/// default profile installs no `rust-analyzer`, and that proxy only prints
/// "Unknown binary" and exits, so croft's managed copy serves instead.
async fn resolve_for_root(
    config: &ServerConfig,
    root: &Path,
    log_skip: bool,
) -> Option<(ServerConfig, Vec<PathBuf>)> {
    let found = resolve_config(config, log_skip)?;
    let Some(provision @ crate::lsp::install::Provision::Binary { bin, .. }) = &config.provision
    else {
        return Some(found);
    };
    let Some(rustup) = command_path(&found.0.command).and_then(|p| rustup_behind(&p)) else {
        return Some(found);
    };
    let key = (config.name, root.to_path_buf());
    let known = RUSTUP_VERDICTS
        .lock()
        .ok()
        .and_then(|verdicts| verdicts.get(&key).cloned())
        .filter(|(asked, _)| asked.elapsed() < RUSTUP_RECHECK);
    let lacks = match known {
        Some((_, lacks)) => lacks,
        None => {
            let lacks = rustup_lacks(&rustup, bin, root).await;
            if let Ok(mut verdicts) = RUSTUP_VERDICTS.lock() {
                verdicts.insert(key, (std::time::Instant::now(), lacks.clone()));
            }
            lacks
        }
    };
    let Some(RustupLack { why, fix }) = lacks else {
        return Some(found);
    };
    if log_skip {
        let msg = format!(
            "{why} (at {}); falling back to croft's managed copy",
            root.display()
        );
        log_file::log(&format!("lsp[{}] {msg}", config.name));
        crate::output::push(
            crate::output::CHANNEL_PROVISION,
            crate::output::OutputLevel::Info,
            &format!("{}: {msg}", config.name),
        );
    }
    crate::lsp::install::resolve_managed_instead(config, provision, &why, &fix)
}

/// What [`rustup_lacks`] answered per (server, project root), and when, so
/// the re-probe each request makes while croft's copy downloads does not ask
/// rustup again. Each verdict is asked again after [`RUSTUP_RECHECK`]: `None`
/// also stands for a rustup that could not say in time, and a server that
/// runs is never re-probed, so only a question still open is asked again.
static RUSTUP_VERDICTS: StdMutex<RustupVerdicts> = StdMutex::new(std::collections::BTreeMap::new());

/// [`RUSTUP_VERDICTS`]' map: (server, project root) to when rustup was
/// asked and what it said.
type RustupVerdicts =
    std::collections::BTreeMap<(&'static str, PathBuf), (std::time::Instant, Option<RustupLack>)>;

/// How long a verdict holds before rustup is asked again: the status line
/// names `rustup component add`, and once the user has run it, rustup's own
/// server takes over without a restart (#927); a rustup too slow to answer
/// once is asked again rather than trusted for good.
const RUSTUP_RECHECK: std::time::Duration = std::time::Duration::from_secs(30);

/// Why a rustup proxy cannot start its server for a project (#927), and the
/// command that mends it for the toolchain that project selects.
#[derive(Clone, Debug, PartialEq, Eq)]
struct RustupLack {
    why: String,
    fix: String,
}

/// How long rustup gets to answer before croft stops asking and keeps the
/// proxy, as it did before it asked.
const RUSTUP_DEADLINE: std::time::Duration = std::time::Duration::from_secs(3);

/// The file a resolved server `command` runs: itself when absolute, else
/// the first executable of that name on PATH.
fn command_path(command: &str) -> Option<PathBuf> {
    let path = Path::new(command);
    if path.is_absolute() {
        return Some(path.to_path_buf());
    }
    let dirs: Vec<PathBuf> = std::env::split_paths(&std::env::var_os("PATH")?).collect();
    find_executable_in(command, &dirs)
}

/// The `rustup` that `candidate` is a proxy for, or `None` when it is a
/// program of its own. rustup installs its proxies as hard links to itself,
/// or symlinks where it cannot, so a proxy is the same file as the `rustup`
/// beside it, or beside wherever its links lead.
fn rustup_behind(candidate: &Path) -> Option<PathBuf> {
    let id = file_id(candidate)?;
    let rustup = format!("rustup{}", std::env::consts::EXE_SUFFIX);
    std::iter::once(candidate.to_path_buf())
        .chain(std::fs::canonicalize(candidate).ok())
        .map(|p| p.with_file_name(&rustup))
        .find(|p| file_id(p) == Some(id))
}

/// What identifies the file `path` leads to, links followed.
#[cfg(unix)]
fn file_id(path: &Path) -> Option<(u64, u64)> {
    use std::os::unix::fs::MetadataExt;
    std::fs::metadata(path).ok().map(|m| (m.dev(), m.ino()))
}
#[cfg(not(unix))]
fn file_id(path: &Path) -> Option<PathBuf> {
    std::fs::canonicalize(path).ok()
}

/// Why the proxy `rustup` puts in front of `bin` cannot start it for the
/// project at `root`, and the `rustup component add` that mends it, named
/// with `--toolchain` so it holds from any directory; `None` when the proxy
/// can start it or rustup cannot say. Asked from
/// `root`, since that picks the toolchain (`rust-toolchain.toml`, a directory
/// override). `RUSTUP_AUTO_INSTALL=0` stops the question from installing a
/// toolchain. A toolchain that is not installed at all is left to the proxy,
/// which installs it as before, and so is a rustup too old to honour that
/// variable that is still busy at [`RUSTUP_DEADLINE`].
async fn rustup_lacks(rustup: &Path, bin: &str, root: &Path) -> Option<RustupLack> {
    if rustup_says(rustup, root, &["which", bin])
        .await?
        .status
        .success()
    {
        return None;
    }
    let active = rustup_says(rustup, root, &["show", "active-toolchain"]).await?;
    if !active.status.success() {
        return None;
    }
    let toolchain = String::from_utf8_lossy(&active.stdout)
        .split_whitespace()
        .next()?
        .to_owned();
    // Named the way users name it: `stable`, not `stable-<host triple>`.
    let triple = format!("-{}-", std::env::consts::ARCH);
    let channel = toolchain
        .split_once(&triple)
        .map_or(&*toolchain, |(c, _)| c);
    Some(RustupLack {
        why: format!("rustup's '{channel}' toolchain has no {bin}"),
        fix: format!("rustup component add {bin} --toolchain {channel}"),
    })
}

/// `rustup` run with `args` from `root`, or `None` when it could not be run
/// or did not finish within [`RUSTUP_DEADLINE`] (it is killed then).
async fn rustup_says(rustup: &Path, root: &Path, args: &[&str]) -> Option<std::process::Output> {
    let run = tokio::process::Command::new(rustup)
        .args(args)
        .current_dir(root)
        .env("RUSTUP_AUTO_INSTALL", "0")
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::null())
        .kill_on_drop(true)
        .output();
    tokio::time::timeout(RUSTUP_DEADLINE, run).await.ok()?.ok()
}

#[cfg(test)]
mod tests {
    use super::*;
    use lsp_types::{
        LanguageString, Location, LocationLink, MarkupContent, SemanticTokensLegend,
        SemanticTokensOptions,
    };
    use std::time::{Duration, Instant};

    /// #1574: the server follows `files_associations`: a `.tpl` associated
    /// with HTML gets the HTML server, and a file associated with a
    /// language that has no server gets none, not its extension's.
    #[test]
    fn an_associated_file_gets_its_associations_server() {
        let tmp = tempfile::tempdir().unwrap();
        let map = [
            ("*.tpl", "html"),
            ("*.rs", "plaintext"),
            ("*.py", "klingon"),
        ]
        .iter()
        .map(|(g, id)| (g.to_string(), id.to_string()))
        .collect();
        crate::highlight::set_file_associations(tmp.path(), &map);
        assert_eq!(
            path_to_language(&tmp.path().join("card.tpl")),
            crate::lsp::languages::resolve("html")
        );
        assert!(crate::lsp::languages::resolve("html").is_some());
        assert_eq!(path_to_language(&tmp.path().join("main.rs")), None);
        assert_eq!(
            path_to_language(&tmp.path().join("lib.py")),
            crate::lsp::languages::resolve("python"),
            "an unknown association id keeps its extension's server"
        );
        assert!(crate::lsp::languages::resolve("python").is_some());
        assert_eq!(
            path_to_language(&tmp.path().join("main.go")),
            crate::lsp::languages::resolve("go"),
            "an unassociated file keeps its extension's server"
        );
    }

    /// #1532: a `.scss` or `.less` file resolves to its own language, which
    /// the CSS server is started for; `.sass` resolves to none.
    #[test]
    fn scss_and_less_files_resolve_to_css_server_languages() {
        assert_eq!(
            path_to_language(Path::new("src/app.scss")).map(|l| l.lsp_id()),
            Some("scss")
        );
        assert_eq!(
            path_to_language(Path::new("src/theme.less")).map(|l| l.lsp_id()),
            Some("less")
        );
        assert_eq!(path_to_language(Path::new("old.sass")), None);
        assert_eq!(
            path_to_language(Path::new("plain.css")),
            Some(Language::CSS)
        );
    }

    impl LspManager {
        /// Test seam for App-level completion tests: swap the completion
        /// reply channel for one the test holds, so a reply lands in
        /// `drain_completion` at a chosen moment, as a slow server's does.
        /// The worker's own sender then goes nowhere, which a test-built App
        /// (no real servers) never uses anyway.
        pub(crate) fn completion_reply_sender_for_test(
            &mut self,
        ) -> std_mpsc::Sender<CompletionResult> {
            let (tx, rx) = std_mpsc::channel();
            self.completion_rx = rx;
            tx
        }
    }

    /// #1527: an item's documentation and its `labelDetails` signature
    /// survive the conversion; they were dropped, so nothing could show them.
    #[test]
    fn a_completion_item_keeps_its_documentation_and_label_details() {
        let item: lsp_types::CompletionItem = serde_json::from_value(serde_json::json!({
            "label": "trim",
            "detail": "fn(&self) -> &str",
            "documentation": { "kind": "markdown", "value": "Returns a string slice." }
        }))
        .unwrap();
        let ours = into_item(item);
        assert_eq!(
            ours.documentation.as_deref(),
            Some("Returns a string slice.")
        );
        assert_eq!(ours.detail.as_deref(), Some("fn(&self) -> &str"));

        let item: lsp_types::CompletionItem = serde_json::from_value(serde_json::json!({
            "label": "dumps",
            "labelDetails": { "detail": "(obj, ...)", "description": "def dumps(obj) -> str" },
            "documentation": "Serialize obj to a JSON formatted str."
        }))
        .unwrap();
        let ours = into_item(item);
        assert_eq!(
            ours.detail.as_deref(),
            Some("(obj, ...) def dumps(obj) -> str")
        );
        assert_eq!(
            ours.documentation.as_deref(),
            Some("Serialize obj to a JSON formatted str.")
        );
    }

    /// #1527: `labelDetails.detail` is the signature and `description` a
    /// separate qualifier; having both must not drop the signature.
    #[test]
    fn label_details_keep_the_signature_beside_the_description() {
        let item: lsp_types::CompletionItem = serde_json::from_value(serde_json::json!({
            "label": "dumps",
            "labelDetails": { "detail": "(obj, ...)", "description": "json" }
        }))
        .unwrap();
        assert_eq!(into_item(item).detail.as_deref(), Some("(obj, ...) json"));

        let item: lsp_types::CompletionItem = serde_json::from_value(serde_json::json!({
            "label": "dumps",
            "labelDetails": { "detail": "(obj, ...)", "description": "  " }
        }))
        .unwrap();
        assert_eq!(into_item(item).detail.as_deref(), Some("(obj, ...)"));
    }

    /// #1527 negative: an item with neither keeps neither.
    #[test]
    fn a_bare_completion_item_has_no_documentation() {
        let item: lsp_types::CompletionItem =
            serde_json::from_value(serde_json::json!({ "label": "x" })).unwrap();
        let ours = into_item(item);
        assert_eq!(ours.documentation, None);
        assert_eq!(ours.detail, None);
    }

    /// #928: an item from a server that resolves lazily is kept whole,
    /// `data` and all, to send back on accept, and croft lets servers defer
    /// imports to that resolve. An item that already carries its imports,
    /// or one from a server that does not resolve, needs no round trip.
    #[test]
    fn a_lazily_resolved_completion_item_is_kept_for_resolve() {
        let lazy = serde_json::json!({ "label": "total", "data": { "entryNames": ["total"] } });
        let item = serde_json::from_value(lazy.clone()).unwrap();
        let kept = listed_item(item, true).resolve.expect("kept for resolve");
        assert_eq!(serde_json::to_value(&*kept).unwrap(), lazy);
        let item = serde_json::from_value(lazy).unwrap();
        assert!(into_item(item).resolve.is_none());
        let at = serde_json::json!({ "line": 1, "character": 0 });
        let edit = serde_json::json!({ "range": { "start": at, "end": at }, "newText": "x" });
        let eager = serde_json::json!({ "label": "Session", "additionalTextEdits": [edit] });
        let eager = serde_json::from_value(eager).unwrap();
        assert!(listed_item(eager, true).resolve.is_none());
        let resolvable = build_client_capabilities()
            .text_document
            .and_then(|td| td.completion)
            .and_then(|c| c.completion_item)
            .and_then(|i| i.resolve_support)
            .expect("completionItem.resolveSupport is declared")
            .properties;
        assert_eq!(resolvable, ["additionalTextEdits"]);
    }

    #[test]
    fn normalise_inlay_hint_flattens_parts_and_folds_padding() {
        // vtsls sends parts labels; rust-analyzer sends plain strings with
        // padding flags. Both must land as one splice-ready string.
        let parts = lsp_types::InlayHint {
            position: Position {
                line: 3,
                character: 14,
            },
            label: lsp_types::InlayHintLabel::LabelParts(vec![
                lsp_types::InlayHintLabelPart {
                    value: ": ".into(),
                    ..Default::default()
                },
                lsp_types::InlayHintLabelPart {
                    value: "Vec<String>".into(),
                    ..Default::default()
                },
            ]),
            kind: None,
            text_edits: None,
            tooltip: None,
            padding_left: None,
            padding_right: None,
            data: None,
        };
        let item = normalise_inlay_hint(parts);
        assert_eq!(item.line, 3);
        assert_eq!(item.character, 14);
        assert_eq!(item.label, ": Vec<String>");

        let padded = lsp_types::InlayHint {
            position: Position {
                line: 0,
                character: 9,
            },
            label: lsp_types::InlayHintLabel::String("param:".into()),
            kind: None,
            text_edits: None,
            tooltip: None,
            padding_left: Some(true),
            padding_right: Some(true),
            data: None,
        };
        assert_eq!(normalise_inlay_hint(padded).label, " param: ");

        let multiline = lsp_types::InlayHint {
            position: Position {
                line: 0,
                character: 0,
            },
            label: lsp_types::InlayHintLabel::String("a\nb".into()),
            kind: None,
            text_edits: None,
            tooltip: None,
            padding_left: None,
            padding_right: None,
            data: None,
        };
        assert_eq!(
            normalise_inlay_hint(multiline).label,
            "a b",
            "a newline would corrupt the spliced row"
        );
    }

    #[test]
    fn workspace_symbol_items_maps_the_flat_response() {
        use lsp_types::{SymbolInformation, SymbolKind, Url, WorkspaceSymbolResponse};
        #[allow(deprecated)]
        let resp = WorkspaceSymbolResponse::Flat(vec![SymbolInformation {
            name: "main".into(),
            kind: SymbolKind::FUNCTION,
            tags: None,
            deprecated: None,
            location: Location {
                uri: Url::from_file_path("/w/src/main.rs").unwrap(),
                range: lsp_types::Range {
                    start: Position {
                        line: 4,
                        character: 3,
                    },
                    end: Position {
                        line: 4,
                        character: 7,
                    },
                },
            },
            container_name: Some("app".into()),
        }]);
        let items = workspace_symbol_items(resp);
        assert_eq!(
            items,
            vec![WorkspaceSymbolItem {
                name: "main".into(),
                kind: OutlineKind::Function,
                path: PathBuf::from("/w/src/main.rs"),
                line: 4,
                character: 3,
                container: Some("app".into()),
            }]
        );
    }

    #[test]
    fn workspace_symbol_items_maps_the_nested_response_and_bare_uris() {
        use lsp_types::{
            SymbolKind, Url, WorkspaceLocation, WorkspaceSymbol, WorkspaceSymbolResponse,
        };
        let resp = WorkspaceSymbolResponse::Nested(vec![
            WorkspaceSymbol {
                name: "Config".into(),
                kind: SymbolKind::STRUCT,
                tags: None,
                container_name: None,
                location: OneOf::Left(Location {
                    uri: Url::from_file_path("/w/src/config.rs").unwrap(),
                    range: lsp_types::Range {
                        start: Position {
                            line: 9,
                            character: 0,
                        },
                        end: Position {
                            line: 9,
                            character: 6,
                        },
                    },
                }),
                data: None,
            },
            WorkspaceSymbol {
                name: "helper".into(),
                kind: SymbolKind::FUNCTION,
                tags: None,
                container_name: None,
                location: OneOf::Right(WorkspaceLocation {
                    uri: Url::from_file_path("/w/src/lib.rs").unwrap(),
                }),
                data: None,
            },
        ]);
        let items = workspace_symbol_items(resp);
        assert_eq!(items.len(), 2);
        assert_eq!(items[0].kind, OutlineKind::Struct);
        assert_eq!(items[0].line, 9);
        assert_eq!(
            items[1].path,
            PathBuf::from("/w/src/lib.rs"),
            "a range-less nested location still yields a jump target"
        );
        assert_eq!(items[1].line, 0, "bare-URI locations land on line 0");
    }

    #[test]
    fn normalise_signature_help_resolves_active_param_range() {
        use lsp_types::{
            ParameterInformation, ParameterLabel, SignatureHelp, SignatureInformation,
        };
        // Two params; help-level active_parameter = 1 (the second, "b: i32").
        let help = SignatureHelp {
            signatures: vec![SignatureInformation {
                label: "foo(a: i32, b: i32)".to_string(),
                documentation: None,
                parameters: Some(vec![
                    ParameterInformation {
                        label: ParameterLabel::LabelOffsets([4, 10]),
                        documentation: None,
                    },
                    ParameterInformation {
                        label: ParameterLabel::LabelOffsets([12, 18]),
                        documentation: None,
                    },
                ]),
                active_parameter: None,
            }],
            active_signature: Some(0),
            active_parameter: Some(1),
        };
        let (sigs, active) = normalise_signature_help(help);
        assert_eq!(active, 0);
        assert_eq!(sigs.len(), 1);
        assert_eq!(sigs[0].active_param, Some((12, 18)));
    }

    #[test]
    fn normalise_signature_help_resolves_simple_label_to_range() {
        use lsp_types::{
            ParameterInformation, ParameterLabel, SignatureHelp, SignatureInformation,
        };
        let help = SignatureHelp {
            signatures: vec![SignatureInformation {
                label: "foo(a, b)".to_string(),
                documentation: None,
                parameters: Some(vec![ParameterInformation {
                    label: ParameterLabel::Simple("a".to_string()),
                    documentation: None,
                }]),
                active_parameter: None,
            }],
            active_signature: None,
            active_parameter: Some(0),
        };
        let (sigs, _) = normalise_signature_help(help);
        // "a" sits at char index 4 in "foo(a, b)".
        assert_eq!(sigs[0].active_param, Some((4, 5)));
    }

    #[test]
    fn client_capabilities_advertise_work_done_progress() {
        // Servers only emit `$/progress` (rust-analyzer's "Indexing…") when the
        // client declares `window.workDoneProgress`. Without this the status bar
        // could never show indexing state.
        let caps = build_client_capabilities();
        let window = caps.window.expect("window capabilities must be set");
        assert_eq!(window.work_done_progress, Some(true));
    }

    /// gopls only sends "Browse documentation" as a link to open, rather
    /// than as a line nobody sees, to a client that says it can show
    /// documents; servers only ask questions with actions of one that says
    /// it can answer them (#1599).
    #[test]
    fn client_capabilities_offer_show_document_and_message_actions() {
        let window = build_client_capabilities().window.expect("window");
        assert_eq!(
            window.show_document.map(|d| d.support),
            Some(true),
            "window.showDocument"
        );
        assert!(
            window
                .show_message
                .and_then(|m| m.message_action_item)
                .is_some(),
            "window.showMessage.messageActionItem"
        );
    }

    #[test]
    fn only_errors_warnings_and_links_interrupt_the_user() {
        use lsp_types::MessageType as MT;
        assert!(message_is_shown(MT::ERROR, "Failed to load workspaces."));
        assert!(message_is_shown(MT::WARNING, "cargo check failed"));
        assert!(message_is_shown(
            MT::INFO,
            "Gopls: open your browser to https://go.dev/gopls"
        ));
        assert!(!message_is_shown(MT::INFO, "Indexing done"));
        assert!(!message_is_shown(MT::LOG, "https://example.com"));
    }

    /// Without `linkSupport` a server turns each `LocationLink` into a
    /// `Location` spanning the whole declaration, so F12 lands on its first
    /// character, lines above a name in a multi-line declaration (#1284).
    #[test]
    fn client_capabilities_ask_for_location_links_on_every_goto() {
        let caps = build_client_capabilities();
        let td = caps.text_document.expect("text document capabilities");
        for (name, goto) in [
            ("definition", td.definition),
            ("declaration", td.declaration),
            ("typeDefinition", td.type_definition),
            ("implementation", td.implementation),
        ] {
            let goto = goto.unwrap_or_else(|| panic!("{name} capability must be declared"));
            assert_eq!(goto.link_support, Some(true), "{name}.linkSupport");
            assert_eq!(goto.dynamic_registration, Some(false), "{name}");
        }
    }

    /// Negative: a server that still answers with a plain `Location`
    /// jumps to its start, and a link whose declaration starts lines above
    /// its name lands on the name, not the declaration.
    #[test]
    fn a_plain_location_still_jumps_to_its_start_and_a_link_to_its_name() {
        let uri = Url::from_file_path("/tmp/config.ts").unwrap();
        let plain = GotoDefinitionResponse::Array(vec![Location {
            uri: uri.clone(),
            range: lsp_types::Range::new(Position::new(7, 0), Position::new(11, 10)),
        }]);
        assert_eq!(
            def_location(&plain),
            Some((PathBuf::from("/tmp/config.ts"), 7, 0))
        );
        let link = GotoDefinitionResponse::Link(vec![LocationLink {
            origin_selection_range: None,
            target_uri: uri,
            target_range: lsp_types::Range::new(Position::new(7, 0), Position::new(11, 10)),
            target_selection_range: lsp_types::Range::new(
                Position::new(10, 2),
                Position::new(10, 7),
            ),
        }]);
        assert_eq!(
            def_location(&link),
            Some((PathBuf::from("/tmp/config.ts"), 10, 2))
        );
        assert_eq!(
            def_locations(&link),
            vec![(PathBuf::from("/tmp/config.ts"), 10, 2)]
        );
    }

    #[test]
    fn client_capabilities_advertise_workspace_folders() {
        // Per LSP 3.6+, a server may IGNORE the `workspace_folders` array in
        // initialize unless the client declares `workspace.workspaceFolders`;
        // without it, folder-aware servers (rust-analyzer, gopls, ruff, ty)
        // legally fall back to single-root behavior.
        let caps = build_client_capabilities();
        let ws = caps.workspace.expect("workspace capabilities must be set");
        assert_eq!(
            ws.workspace_folders,
            Some(true),
            "the workspaceFolders capability gates every folder-aware server feature"
        );
    }

    /// A stub language server that completes the LSP handshake, advertises
    /// `workspaceDiagnostics`, and then NEVER answers a `workspace/diagnostic`
    /// request — exactly what `ty` 0.0.73 does, and the shape that caused the
    /// #533 regression. Everything else it answers normally.
    ///
    /// Written to a temp dir and run under the test's own Python, so the test
    /// needs no server on PATH.
    /// Returns `(script, receipt)`: the stub APPENDS one line to `receipt`
    /// for every `workspace/diagnostic` request that reaches it, so a test can
    /// assert both that a pull arrived and how many did.
    fn mute_pull_server_script(dir: &Path) -> (std::path::PathBuf, std::path::PathBuf) {
        let path = dir.join("mute_pull_server.py");
        let receipt = dir.join("pull-received");
        std::fs::write(
            &path,
            r#"
import json, sys

def read():
    length = None
    while True:
        line = sys.stdin.buffer.readline()
        if not line:
            return None
        line = line.strip()
        if not line:
            break
        if line.lower().startswith(b"content-length:"):
            length = int(line.split(b":")[1])
    if length is None:
        return None
    return json.loads(sys.stdin.buffer.read(length))

def write(msg):
    body = json.dumps(msg).encode()
    sys.stdout.buffer.write(b"Content-Length: %d\r\n\r\n" % len(body))
    sys.stdout.buffer.write(body)
    sys.stdout.buffer.flush()

while True:
    msg = read()
    if msg is None:
        break
    method = msg.get("method")
    if method == "initialize":
        write({"jsonrpc": "2.0", "id": msg["id"], "result": {"capabilities": {
            "diagnosticProvider": {
                "interFileDependencies": True,
                "workspaceDiagnostics": True,
            },
            "definitionProvider": True,
        }}})
    elif method == "workspace/diagnostic":
        # Record receipt (one line per request), so a test waits for the
        # request to ARRIVE rather than guessing with a sleep, and can count
        # how many arrived. Then never answer -- the bug.
        with open(sys.argv[1], "a") as f:
            f.write("pull\n")
    elif method == "shutdown":
        write({"jsonrpc": "2.0", "id": msg["id"], "result": None})
    elif "id" in msg:
        write({"jsonrpc": "2.0", "id": msg["id"], "result": None})
"#,
        )
        .expect("write stub server");
        (path, receipt)
    }

    /// A `ManagedClient` wrapping `client`, advertising workspace diagnostics
    /// and nothing else — the shape `workspace_pull_targets` filters over.
    fn managed_client_for_pull_test(client: LspClient) -> ManagedClient {
        ManagedClient {
            name: String::from("mute-pull"),
            client: Arc::new(TokioMutex::new(client)),
            supports_workspace_diagnostics: true,
            diagnostic_identifier: None,
            diagnostic_result_ids: Arc::new(TokioMutex::new(DiagnosticResultIds::default())),
            diagnostic_pull_stalled: Arc::new(AtomicBool::new(false)),
            save_notify: SaveNotify::Never,
            supports_document_diagnostics: false,
            document_pull_stalled: Arc::new(AtomicBool::new(false)),
            prepare_rename_stalled: Arc::new(AtomicBool::new(false)),
            document_pull_generations: Arc::new(StdMutex::new(HashMap::new())),
            supports_completion: false,
            completion_triggers: String::new(),
            supports_signature_help: false,
            supports_hover: false,
            supports_definition: false,
            supports_document_symbol: false,
            supports_declaration: false,
            supports_type_definition: false,
            supports_implementation: false,
            supports_references: false,
            supports_document_highlight: false,
            supports_linked_editing: false,
            supports_inline_completion: false,
            supports_selection_range: false,
            supports_call_hierarchy: false,
            supports_type_hierarchy: false,
            supports_workspace_symbols: false,
            supports_rename: false,
            supports_prepare_rename: false,
            supports_formatting: false,
            on_type_triggers: None,
            supports_range_formatting: false,
            supports_code_action: false,
            semantic_legend: None,
            semantic_supports_range: false,
            supports_inlay_hints: false,
            supports_document_link: false,
            supports_code_lens: false,
            code_lens_resolve: false,
            server_commands: Arc::new(Vec::new()),
            supports_folding_range: false,
            supports_document_color: false,
            will_rename: None,
            did_rename: None,
        }
    }

    /// A pull already QUEUED when the server is retired must issue nothing
    /// (#533).
    ///
    /// `workspace_pull_targets` reads the retirement flag when it builds the
    /// target list, so a second pull spawned before the first expires carries
    /// a stale snapshot. It then waits the whole ceiling on the result-id lock
    /// the first pull holds, and would wake and send exactly the un-reapable
    /// request the retirement exists to prevent. Both targets are built up
    /// front here, which is what makes the snapshot stale.
    #[test]
    fn a_pull_queued_before_retirement_issues_no_request() {
        let Some(python) = python_for_stub_server() else {
            eprintln!("SKIPPED: no python3 on PATH");
            return;
        };
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let (script, receipt) = mute_pull_server_script(&root);

        let runtime = tokio::runtime::Builder::new_multi_thread()
            .worker_threads(2)
            .enable_all()
            .build()
            .expect("a runtime");

        runtime.block_on(async {
            let config = ServerConfig {
                name: "mute-pull",
                command: python.to_string_lossy().into_owned(),
                args: vec![
                    script.to_string_lossy().into_owned(),
                    receipt.to_string_lossy().into_owned(),
                ],
                language: Language::PYTHON,
                initialization_options: None,
                provision: None,
            };
            let (diag_tx, _diag_rx) = std_mpsc::channel();
            let (prog_tx, _prog_rx) = std_mpsc::channel();
            let client = LspClient::spawn(
                &config,
                &root,
                build_client_capabilities(),
                &[],
                Arc::new(AtomicBool::new(false)),
                Arc::new(AtomicBool::new(false)),
                Arc::new(AtomicBool::new(false)),
                diag_tx,
                prog_tx,
            )
            .await
            .expect("the stub server handshakes");
            let managed = managed_client_for_pull_test(client);

            // Both target lists are built BEFORE either pull runs, so the
            // second carries a snapshot taken while the server was healthy.
            let first = workspace_pull_targets(std::iter::once(&managed));
            let second = workspace_pull_targets(std::iter::once(&managed));
            assert_eq!(second.len(), 1, "the second pull must start un-retired");

            let (tx, _rx) = std_mpsc::channel();
            spawn_workspace_pull_within(first, tx.clone(), std::time::Duration::from_millis(200));
            spawn_workspace_pull_within(second, tx, std::time::Duration::from_millis(200));

            let retired = tokio::time::timeout(std::time::Duration::from_secs(30), async {
                while !managed.diagnostic_pull_stalled.load(Ordering::Relaxed) {
                    tokio::time::sleep(std::time::Duration::from_millis(10)).await;
                }
            })
            .await;
            assert!(retired.is_ok(), "the first pull must retire the server");

            // Give the queued second pull time to wake and (wrongly) send.
            tokio::time::sleep(std::time::Duration::from_millis(600)).await;
            let pulls = std::fs::read_to_string(&receipt).unwrap_or_default();
            assert_eq!(
                pulls.lines().count(),
                1,
                "a pull queued before retirement must issue no request: each \
                 one leaves an entry in async-lsp's outgoing map that only a \
                 response can drain, and this server never answers"
            );
        });
    }

    /// A stub language server that advertises `diagnosticProvider` without
    /// workspace pulls, as rumdl and the VS Code JSON server do (#866). Each
    /// `textDocument/diagnostic` it receives appends a line to `receipt`;
    /// with `answer` it replies with one error, "stub problem", and without
    /// it never replies.
    fn document_pull_server_script(dir: &Path, answer: bool) -> (PathBuf, PathBuf) {
        let path = dir.join(format!("doc_pull_server_{answer}.py"));
        let receipt = dir.join(format!("doc-pulls-{answer}"));
        let reply = if answer {
            r#"write({"jsonrpc": "2.0", "id": msg["id"], "result": {"kind": "full", "items": [
                {"range": {"start": {"line": 0, "character": 0}, "end": {"line": 0, "character": 1}},
                 "severity": 1, "message": "stub problem"}]}})"#
        } else {
            "pass"
        };
        std::fs::write(
            &path,
            format!(
                r#"
import json, sys

def read():
    length = None
    while True:
        line = sys.stdin.buffer.readline()
        if not line:
            return None
        line = line.strip()
        if not line:
            break
        if line.lower().startswith(b"content-length:"):
            length = int(line.split(b":")[1])
    if length is None:
        return None
    return json.loads(sys.stdin.buffer.read(length))

def write(msg):
    body = json.dumps(msg).encode()
    sys.stdout.buffer.write(b"Content-Length: %d\r\n\r\n" % len(body))
    sys.stdout.buffer.write(body)
    sys.stdout.buffer.flush()

while True:
    msg = read()
    if msg is None:
        break
    method = msg.get("method")
    if method == "initialize":
        write({{"jsonrpc": "2.0", "id": msg["id"], "result": {{"capabilities": {{
            "diagnosticProvider": {{"interFileDependencies": False, "workspaceDiagnostics": False}}
        }}}}}})
    elif method == "textDocument/diagnostic":
        with open(sys.argv[1], "a") as f:
            f.write("pull\n")
        {reply}
    elif "id" in msg:
        write({{"jsonrpc": "2.0", "id": msg["id"], "result": None}})
"#
            ),
        )
        .expect("write stub server");
        (path, receipt)
    }

    /// Spawn the document-pull stub and wrap it as a client that answers
    /// `textDocument/diagnostic`, the shape `document_pull_targets` keeps.
    async fn document_pull_client(
        python: &Path,
        root: &Path,
        answer: bool,
    ) -> (ManagedClient, PathBuf) {
        let (script, receipt) = document_pull_server_script(root, answer);
        let config = ServerConfig {
            name: "doc-pull",
            command: python.to_string_lossy().into_owned(),
            args: vec![
                script.to_string_lossy().into_owned(),
                receipt.to_string_lossy().into_owned(),
            ],
            language: Language::MARKDOWN,
            initialization_options: None,
            provision: None,
        };
        let (diag_tx, _diag_rx) = std_mpsc::channel();
        let (prog_tx, _prog_rx) = std_mpsc::channel();
        let client = LspClient::spawn(
            &config,
            root,
            build_client_capabilities(),
            &[],
            Arc::new(AtomicBool::new(false)),
            Arc::new(AtomicBool::new(false)),
            Arc::new(AtomicBool::new(false)),
            diag_tx,
            prog_tx,
        )
        .await
        .expect("the stub server handshakes");
        let mut managed = managed_client_for_pull_test(client);
        managed.name = String::from("doc-pull");
        managed.supports_workspace_diagnostics = false;
        managed.supports_document_diagnostics = true;
        (managed, receipt)
    }

    fn stub_runtime() -> tokio::runtime::Runtime {
        tokio::runtime::Builder::new_multi_thread()
            .worker_threads(2)
            .enable_all()
            .build()
            .expect("a runtime")
    }

    /// #866: a server that only reports when asked has its answer forwarded
    /// under its own name, on the channel a push lands on, so the app stores
    /// it like any published set.
    #[test]
    fn a_document_pull_forwards_the_report_under_the_servers_name() {
        let Some(python) = python_for_stub_server() else {
            eprintln!("SKIPPED: no python3 on PATH");
            return;
        };
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let file = root.join("a.md");
        let uri = Url::from_file_path(&file).expect("a file uri");
        let support: CapabilitySupport = Arc::default();
        stub_runtime().block_on(async {
            let (managed, _receipt) = document_pull_client(&python, &root, true).await;
            let pulls = document_pull_targets(std::iter::once(&managed), &file, &uri, &support);
            assert_eq!(pulls.len(), 1, "a diagnosticProvider server is pulled");
            let (tx, rx) = std_mpsc::channel();
            spawn_document_pulls_within(
                pulls,
                tx,
                std::time::Duration::ZERO,
                std::time::Duration::from_secs(20),
            );
            let update = tokio::task::spawn_blocking(move || {
                rx.recv_timeout(crate::test_budget::spawn_budget(
                    std::time::Duration::from_secs(5),
                ))
            })
            .await
            .expect("the waiter")
            .expect("the pulled report arrives");
            assert_eq!(update.path, file);
            assert_eq!(update.server, "doc-pull");
            let messages: Vec<&str> = update
                .diagnostics
                .iter()
                .map(|d| d.message.as_str())
                .collect();
            assert_eq!(messages, ["stub problem"]);
        });
    }

    /// #866: while typing, only the newest pull for a document goes out. One
    /// an edit overtook is dropped before it is sent, so a slow answer about
    /// older text can never land over a newer one.
    #[test]
    fn a_document_pull_an_edit_overtook_is_never_sent() {
        let Some(python) = python_for_stub_server() else {
            eprintln!("SKIPPED: no python3 on PATH");
            return;
        };
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let file = root.join("a.md");
        let uri = Url::from_file_path(&file).expect("a file uri");
        let support: CapabilitySupport = Arc::default();
        stub_runtime().block_on(async {
            let (managed, receipt) = document_pull_client(&python, &root, true).await;
            let older = document_pull_targets(std::iter::once(&managed), &file, &uri, &support);
            let newer = document_pull_targets(std::iter::once(&managed), &file, &uri, &support);
            let (tx, rx) = std_mpsc::channel();
            let ceiling = std::time::Duration::from_secs(20);
            spawn_document_pulls_within(older, tx.clone(), std::time::Duration::ZERO, ceiling);
            spawn_document_pulls_within(newer, tx, std::time::Duration::ZERO, ceiling);
            let first = tokio::task::spawn_blocking(move || {
                let budget = crate::test_budget::spawn_budget(std::time::Duration::from_secs(5));
                let first = rx.recv_timeout(budget);
                // Room for a wrongly sent second answer to arrive too.
                let second = rx.recv_timeout(std::time::Duration::from_millis(500));
                (first, second)
            })
            .await
            .expect("the waiter");
            assert!(first.0.is_ok(), "the newest pull is answered");
            assert!(first.1.is_err(), "and only it");
            let pulls = std::fs::read_to_string(&receipt).unwrap_or_default();
            assert_eq!(
                pulls.lines().count(),
                1,
                "the overtaken pull never went out"
            );
        });
    }

    /// #866: a pull still out when its document closes is not the latest
    /// pull once the document reopens, so its late answer, about the text
    /// before the close, can never land on the reopened buffer.
    #[test]
    fn a_pull_from_before_a_close_is_stale_after_the_reopen() {
        let Some(python) = python_for_stub_server() else {
            eprintln!("SKIPPED: no python3 on PATH");
            return;
        };
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let file = root.join("a.md");
        let uri = Url::from_file_path(&file).expect("a file uri");
        let support: CapabilitySupport = Arc::default();
        stub_runtime().block_on(async {
            let (managed, _receipt) = document_pull_client(&python, &root, true).await;
            let before = document_pull_targets(std::iter::once(&managed), &file, &uri, &support);
            // What `close_doc` does to the document's generation.
            managed
                .document_pull_generations
                .lock()
                .unwrap()
                .remove(&file);
            let after = document_pull_targets(std::iter::once(&managed), &file, &uri, &support);
            assert!(after[0].is_current(), "the reopened document's pull");
            assert!(
                !before[0].is_current(),
                "the pull from before the close is stale"
            );
        });
    }

    /// #866: a server that lets a document pull go unanswered is retired
    /// from document pulls, as one that stalls a workspace pull is (#533):
    /// every unanswered request leaks an entry async-lsp can never drain. It
    /// then reports on nothing: its pulled sets are withdrawn and it leaves
    /// the file's reporters, so the built-in Markdown lint returns where it
    /// stood down for rumdl (#851).
    #[test]
    fn an_unanswered_document_pull_retires_the_server() {
        let Some(python) = python_for_stub_server() else {
            eprintln!("SKIPPED: no python3 on PATH");
            return;
        };
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let file = root.join("a.md");
        let uri = Url::from_file_path(&file).expect("a file uri");
        let support: CapabilitySupport = Arc::default();
        stub_runtime().block_on(async {
            let (managed, _receipt) = document_pull_client(&python, &root, false).await;
            // Opened with another server beside it (#851).
            support.lock().unwrap().document_servers.insert(
                file.clone(),
                vec![String::from("doc-pull"), String::from("other")],
            );
            support.lock().unwrap().document_clients.insert(
                file.clone(),
                vec![String::from("doc-pull"), String::from("other")],
            );
            let pulls = document_pull_targets(std::iter::once(&managed), &file, &uri, &support);
            let (tx, rx) = std_mpsc::channel();
            spawn_document_pulls_within(
                pulls,
                tx,
                std::time::Duration::ZERO,
                std::time::Duration::from_millis(200),
            );
            let retired = tokio::time::timeout(std::time::Duration::from_secs(30), async {
                while !managed.document_pull_stalled.load(Ordering::Relaxed) {
                    tokio::time::sleep(std::time::Duration::from_millis(10)).await;
                }
            })
            .await;
            assert!(retired.is_ok(), "the unanswered pull retires the server");
            assert!(
                document_pull_targets(std::iter::once(&managed), &file, &uri, &support).is_empty(),
                "and it is not asked again"
            );
            let withdrawn = tokio::task::spawn_blocking(move || {
                rx.recv_timeout(crate::test_budget::spawn_budget(
                    std::time::Duration::from_secs(5),
                ))
            })
            .await
            .expect("the waiter")
            .expect("its pulled set is withdrawn");
            assert_eq!(
                (withdrawn.path, withdrawn.server.as_str()),
                (file.clone(), "doc-pull")
            );
            assert!(withdrawn.diagnostics.is_empty());
            assert_eq!(
                support.lock().unwrap().document_servers[&file],
                ["other"],
                "it no longer counts as reporting on the file, and only it left"
            );
            assert_eq!(
                support.lock().unwrap().document_clients[&file],
                ["doc-pull", "other"],
                "but its client still runs, so it still serves the file (#1626)"
            );
        });
    }

    /// `workspace_pull_targets` must DROP a retired server, so the retirement
    /// actually stops the next pull rather than only recording a flag (#533).
    ///
    /// This is the end of the leak fix: `workspace/diagnostic/refresh` is
    /// server-driven and unrated, so without the filter a stalling server is
    /// re-asked on every refresh and each abandoned request leaves another
    /// entry in async-lsp's `outgoing` map that nothing can drain.
    #[test]
    fn a_retired_server_is_dropped_from_the_next_pull() {
        let Some(python) = python_for_stub_server() else {
            eprintln!("SKIPPED: no python3 on PATH");
            return;
        };
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let (script, receipt) = mute_pull_server_script(&root);

        let runtime = tokio::runtime::Builder::new_multi_thread()
            .worker_threads(2)
            .enable_all()
            .build()
            .expect("a runtime");

        runtime.block_on(async {
            let config = ServerConfig {
                name: "mute-pull",
                command: python.to_string_lossy().into_owned(),
                args: vec![
                    script.to_string_lossy().into_owned(),
                    receipt.to_string_lossy().into_owned(),
                ],
                language: Language::PYTHON,
                initialization_options: None,
                provision: None,
            };
            let (diag_tx, _diag_rx) = std_mpsc::channel();
            let (prog_tx, _prog_rx) = std_mpsc::channel();
            let client = LspClient::spawn(
                &config,
                &root,
                build_client_capabilities(),
                &[],
                Arc::new(AtomicBool::new(false)),
                Arc::new(AtomicBool::new(false)),
                Arc::new(AtomicBool::new(false)),
                diag_tx,
                prog_tx,
            )
            .await
            .expect("the stub server handshakes");

            // A `ManagedClient` as `ensure_clients` builds one, which is what
            // `workspace_pull_targets` actually filters over in production.
            let managed = managed_client_for_pull_test(client);
            assert_eq!(
                workspace_pull_targets(std::iter::once(&managed)).len(),
                1,
                "a healthy server advertising the capability must be pulled"
            );

            let (tx, _rx) = std_mpsc::channel();
            spawn_workspace_pull_within(
                workspace_pull_targets(std::iter::once(&managed)),
                tx.clone(),
                std::time::Duration::from_millis(200),
            );

            // Wait for the retirement the timeout records.
            let retired = tokio::time::timeout(std::time::Duration::from_secs(30), async {
                while !managed.diagnostic_pull_stalled.load(Ordering::Relaxed) {
                    tokio::time::sleep(std::time::Duration::from_millis(10)).await;
                }
            })
            .await;
            assert!(retired.is_ok(), "the expired pull must retire the server");

            let after_first = std::fs::read_to_string(&receipt).unwrap_or_default();
            assert_eq!(
                after_first.lines().count(),
                1,
                "the first pull must actually reach the server"
            );

            // The refresh path: a second pull for the same clients. The
            // retired server must be filtered out, so the stub sees nothing
            // more and no second un-reapable request is issued.
            assert!(
                workspace_pull_targets(std::iter::once(&managed)).is_empty(),
                "a retired server must be dropped from later pulls, or every \
                 refresh leaks another request that can never be reaped"
            );
            spawn_workspace_pull_within(
                workspace_pull_targets(std::iter::once(&managed)),
                tx,
                std::time::Duration::from_millis(200),
            );
            tokio::time::sleep(std::time::Duration::from_millis(400)).await;
            let after_second = std::fs::read_to_string(&receipt).unwrap_or_default();
            assert_eq!(
                after_second.lines().count(),
                1,
                "a retired server must receive no further pulls"
            );
        });
    }

    /// An expired pull must free the result ids, leave the cache untouched,
    /// and retire the server so it is never pulled again (#533).
    ///
    /// The retirement is what bounds the leak: a timed-out request cannot be
    /// cancelled, so its entry in async-lsp's `outgoing` map is permanent.
    /// Asking a stalled server once costs one entry; asking it on every
    /// server-driven refresh would cost one per refresh, forever.
    #[test]
    fn an_expired_pull_frees_the_ids_and_retires_the_server() {
        let Some(python) = python_for_stub_server() else {
            eprintln!("SKIPPED: no python3 on PATH");
            return;
        };
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let (script, receipt) = mute_pull_server_script(&root);

        let runtime = tokio::runtime::Builder::new_multi_thread()
            .worker_threads(2)
            .enable_all()
            .build()
            .expect("a runtime");

        runtime.block_on(async {
            let config = ServerConfig {
                name: "mute-pull",
                command: python.to_string_lossy().into_owned(),
                args: vec![
                    script.to_string_lossy().into_owned(),
                    receipt.to_string_lossy().into_owned(),
                ],
                language: Language::PYTHON,
                initialization_options: None,
                provision: None,
            };
            let (diag_tx, _diag_rx) = std_mpsc::channel();
            let (prog_tx, _prog_rx) = std_mpsc::channel();
            let client = LspClient::spawn(
                &config,
                &root,
                build_client_capabilities(),
                &[],
                Arc::new(AtomicBool::new(false)),
                Arc::new(AtomicBool::new(false)),
                Arc::new(AtomicBool::new(false)),
                diag_tx,
                prog_tx,
            )
            .await
            .expect("the stub server handshakes");

            // SEEDED, so "the cache is untouched" is a claim that can fail:
            // against an empty cache the assertion below would hold whatever
            // the timeout path did to it.
            let result_ids = Arc::new(TokioMutex::new(DiagnosticResultIds::default()));
            result_ids
                .lock()
                .await
                .record("file:///seeded.py", Some("id-seeded"));
            let stalled = Arc::new(AtomicBool::new(false));
            let (tx, _rx) = std_mpsc::channel();
            spawn_workspace_pull_within(
                vec![WorkspacePull {
                    name: String::from("mute-pull"),
                    client: Arc::new(TokioMutex::new(client)),
                    identifier: None,
                    result_ids: result_ids.clone(),
                    stalled: stalled.clone(),
                }],
                tx,
                std::time::Duration::from_millis(200),
            );

            // Wait for the retirement rather than for a fixed duration: the
            // flag is the observable the production filter reads.
            let retired = tokio::time::timeout(std::time::Duration::from_secs(30), async {
                while !stalled.load(Ordering::Relaxed) {
                    tokio::time::sleep(std::time::Duration::from_millis(10)).await;
                }
            })
            .await;
            assert!(
                retired.is_ok(),
                "an expired pull must retire the server, or every later \
                 refresh leaks another un-reapable request"
            );

            // The ids are free again, and the timeout recorded nothing: the
            // next pull re-sends the same `previous` set.
            let ids = tokio::time::timeout(std::time::Duration::from_secs(5), result_ids.lock())
                .await
                .expect("an expired pull must release the result ids");
            assert_eq!(
                ids.len(),
                1,
                "an expired pull must leave the result-id cache untouched, so \
                 the next pull re-sends the same `previous` set"
            );
        });
    }

    /// A server that accepts `workspace/diagnostic` and never answers it must
    /// not wedge every later request to that client (#533 regression).
    ///
    /// This drives the REAL [`spawn_workspace_pull`] against a real
    /// [`LspClient`]. The pull previously held the client lock across the
    /// unanswered await, and `open_doc` takes that same lock ON the worker
    /// loop, so the loop stopped and Go to Definition did nothing at all from
    /// 0.1.939 on. The assertion is that the client `Arc` is still lockable
    /// while the pull is outstanding.
    #[test]
    fn a_hung_workspace_pull_leaves_the_client_lockable() {
        let Some(python) = python_for_stub_server() else {
            eprintln!("SKIPPED: no python3 on PATH");
            return;
        };
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let (script, receipt) = mute_pull_server_script(&root);

        let runtime = tokio::runtime::Builder::new_multi_thread()
            .worker_threads(2)
            .enable_all()
            .build()
            .expect("a runtime");

        runtime.block_on(async {
            let config = ServerConfig {
                name: "mute-pull",
                command: python.to_string_lossy().into_owned(),
                args: vec![
                    script.to_string_lossy().into_owned(),
                    receipt.to_string_lossy().into_owned(),
                ],
                language: Language::PYTHON,
                initialization_options: None,
                provision: None,
            };
            let (diag_tx, _diag_rx) = std_mpsc::channel();
            let (prog_tx, _prog_rx) = std_mpsc::channel();
            let client = LspClient::spawn(
                &config,
                &root,
                build_client_capabilities(),
                &[],
                Arc::new(AtomicBool::new(false)),
                Arc::new(AtomicBool::new(false)),
                Arc::new(AtomicBool::new(false)),
                diag_tx,
                prog_tx,
            )
            .await
            .expect("the stub server handshakes");

            // Precondition: the stub really does advertise the capability, so
            // `workspace_pull_targets` would select it in production. Without
            // this the test could pass by pulling nothing at all.
            assert!(
                workspace_diagnostics_supported(&client.capabilities().diagnostic_provider),
                "the stub must advertise workspaceDiagnostics, or no pull is issued"
            );

            let client = Arc::new(TokioMutex::new(client));
            let (tx, _rx) = std_mpsc::channel();
            spawn_workspace_pull(
                vec![WorkspacePull {
                    name: String::from("mute-pull"),
                    client: client.clone(),
                    identifier: None,
                    result_ids: Arc::new(TokioMutex::new(DiagnosticResultIds::default())),
                    stalled: Arc::new(AtomicBool::new(false)),
                }],
                tx,
            );

            // Wait for the request to actually REACH the stub. A fixed sleep
            // would let the test pass for the wrong reason: `tokio::spawn`
            // need not have polled the pull future yet, and an unstarted pull
            // trivially holds no lock.
            let arrived = tokio::time::timeout(std::time::Duration::from_secs(30), async {
                while !receipt.exists() {
                    tokio::time::sleep(std::time::Duration::from_millis(10)).await;
                }
            })
            .await;
            assert!(
                arrived.is_ok(),
                "the stub never received workspace/diagnostic, so this test \
                 would not exercise the lock at all"
            );

            // What `open_doc` does on the worker loop. Before the fix this
            // never returned, and with it went every queued command.
            let opened =
                tokio::time::timeout(std::time::Duration::from_secs(5), client.lock()).await;
            assert!(
                opened.is_ok(),
                "the workspace pull held the client across its unanswered \
                 await: open_doc — and every command behind it on the worker \
                 loop, Go to Definition included — blocks forever"
            );
        });
    }

    #[test]
    fn a_workspace_pull_forwards_full_reports_and_leaves_unchanged_files_alone() {
        // The incrementality contract, end to end (#533). A Full report
        // reaches PROBLEMS and leaves its result id behind; an Unchanged one
        // is NOT re-processed but still records the id the server reissued;
        // a Full report with no id forgets the file, so the next pull cannot
        // send back an id the server never issued for this content.
        let (tx, rx) = std_mpsc::channel();
        let mut ids = DiagnosticResultIds::default();
        let uri = |p: &str| Url::from_file_path(p).expect("an absolute path");
        let wire = |message: &str| lsp_types::Diagnostic {
            range: def_range(3, 1),
            message: message.to_string(),
            ..Default::default()
        };
        let report = lsp_types::WorkspaceDiagnosticReport {
            items: vec![
                lsp_types::WorkspaceDocumentDiagnosticReport::Full(
                    lsp_types::WorkspaceFullDocumentDiagnosticReport {
                        uri: uri("/ws/broken.toml"),
                        version: None,
                        full_document_diagnostic_report: lsp_types::FullDocumentDiagnosticReport {
                            result_id: Some("id-broken".into()),
                            items: vec![wire("unexpected key")],
                        },
                    },
                ),
                lsp_types::WorkspaceDocumentDiagnosticReport::Unchanged(
                    lsp_types::WorkspaceUnchangedDocumentDiagnosticReport {
                        uri: uri("/ws/steady.toml"),
                        version: None,
                        unchanged_document_diagnostic_report:
                            lsp_types::UnchangedDocumentDiagnosticReport {
                                result_id: "id-steady".into(),
                            },
                    },
                ),
                lsp_types::WorkspaceDocumentDiagnosticReport::Full(
                    lsp_types::WorkspaceFullDocumentDiagnosticReport {
                        uri: uri("/ws/fixed.toml"),
                        version: None,
                        full_document_diagnostic_report: lsp_types::FullDocumentDiagnosticReport {
                            result_id: None,
                            items: Vec::new(),
                        },
                    },
                ),
            ],
        };
        let forwarded = apply_workspace_report("taplo", report.into(), &mut ids, &tx);
        assert_eq!(forwarded, 2, "both Full reports are the server's new word");

        let sent: Vec<DiagnosticsUpdate> = rx.try_iter().collect();
        let paths: Vec<&Path> = sent.iter().map(|u| u.path.as_path()).collect();
        assert_eq!(
            paths,
            vec![Path::new("/ws/broken.toml"), Path::new("/ws/fixed.toml")],
            "the Unchanged file must not be re-processed, and the CLEARED file must be: \
             an empty batch is how the app drops a fixed file's rows"
        );
        assert_eq!(sent[0].server, "taplo");
        assert_eq!(sent[0].diagnostics.len(), 1);
        assert!(sent[1].diagnostics.is_empty());

        let mut previous: Vec<(String, String)> = ids
            .previous()
            .into_iter()
            .map(|p| (p.uri.to_string(), p.value))
            .collect();
        previous.sort();
        assert_eq!(
            previous,
            vec![
                (
                    "file:///ws/broken.toml".to_string(),
                    "id-broken".to_string()
                ),
                (
                    "file:///ws/steady.toml".to_string(),
                    "id-steady".to_string()
                ),
            ],
            "the id-less report must leave nothing behind for /ws/fixed.toml"
        );
    }

    #[test]
    fn client_capabilities_advertise_pull_diagnostics() {
        // The gate the whole of #533 stands on. Per LSP 3.17 a server
        // publishes `diagnosticProvider` only when the client declares
        // `textDocument.diagnostic`; without it a conforming server never
        // advertises the capability, so `workspace_diagnostics_supported`
        // reads `None` on every server and the pull path can never engage.
        // The detection landed first (#536), where the gap would have looked
        // like "no server supports it" rather than "we never asked".
        let caps = build_client_capabilities();
        let td = caps
            .text_document
            .as_ref()
            .expect("text document capabilities must be set");
        assert!(
            td.diagnostic.is_some(),
            "textDocument.diagnostic gates the server advertising diagnosticProvider at all"
        );
        // And the refresh half: a server sends `workspace/diagnostic/refresh`
        // only when the client says it can handle one, so without this the
        // re-pull after a project-wide change never arrives.
        let ws = caps
            .workspace
            .as_ref()
            .expect("workspace capabilities must be set");
        assert_eq!(
            ws.diagnostic
                .as_ref()
                .expect("workspace.diagnostic must be declared")
                .refresh_support,
            Some(true),
            "refreshSupport is what lets a server ask for a re-pull"
        );
    }

    #[test]
    fn client_capabilities_offer_the_unnecessary_and_deprecated_tags() {
        let caps = build_client_capabilities();
        let publish = caps
            .text_document
            .and_then(|td| td.publish_diagnostics)
            .expect("publishDiagnostics must be declared");
        assert_eq!(
            publish.tag_support.map(|t| t.value_set),
            Some(vec![
                lsp_types::DiagnosticTag::UNNECESSARY,
                lsp_types::DiagnosticTag::DEPRECATED,
            ]),
            "a server that checks tagSupport would otherwise leave the tags out"
        );
        assert_eq!(
            publish.code_description_support,
            Some(true),
            "#1540: a server may leave a rule's link out otherwise"
        );
    }

    /// #1523: a related location takes one line of the hover, whatever
    /// line breaks its message holds.
    #[test]
    fn a_related_location_label_is_one_line() {
        let related = RelatedLocation {
            path: PathBuf::from("/w/src/a.ts"),
            line: 1,
            character: 2,
            message: "'foo'\ris\r\ndeclared\nhere.".into(),
        };
        assert_eq!(
            related.label(Path::new("/w")),
            "src/a.ts(2, 3): 'foo' is declared here."
        );
    }

    #[test]
    fn a_tagged_diagnostic_rides_back_to_code_actions_with_its_tags() {
        let d = |tags: DiagnosticTags| Diagnostic {
            start_line: 3,
            start_char: 4,
            end_line: 3,
            end_char: 7,
            severity: DiagnosticSeverity::Hint,
            message: "`tmp` is declared but its value is never read.".into(),
            tags,
            code: None,
            origin: None,
        };
        let unused = to_lsp_diagnostic(&d(DiagnosticTags {
            unnecessary: true,
            deprecated: false,
        }));
        assert_eq!(
            unused.tags,
            Some(vec![lsp_types::DiagnosticTag::UNNECESSARY]),
            "the server matches \"Remove unused declaration\" against the tag"
        );
        assert_eq!(
            to_lsp_diagnostic(&d(DiagnosticTags::default())).tags,
            None,
            "an untagged diagnostic sends no tags field"
        );
    }

    /// #1030: tsserver picks its quick fixes by the error `code`, ruff
    /// reads its fix from `data`. Each server gets back its own diagnostics
    /// exactly as it published them, and never another server's; one croft
    /// made itself still goes to every server, as before.
    #[test]
    fn a_code_action_hands_each_server_its_own_diagnostics_unchanged() {
        let wire = |source: &str, code: &str| lsp_types::Diagnostic {
            range: def_range(0, 7),
            message: format!("{source} says {code}"),
            code: Some(lsp_types::NumberOrString::String(code.into())),
            source: Some(source.into()),
            data: Some(serde_json::json!({ "fix": code })),
            ..Default::default()
        };
        let ruff = crate::lsp::client::convert_diagnostic("ruff", &wire("Ruff", "F401"));
        let ty = crate::lsp::client::convert_diagnostic("ty", &wire("ty", "unresolved-import"));
        let ours = Diagnostic {
            origin: None,
            ..ruff.clone()
        };
        let all = [ruff, ty, ours.clone()];
        assert_eq!(
            code_action_diagnostics(&all, "ruff"),
            vec![wire("Ruff", "F401"), to_lsp_diagnostic(&ours)]
        );
        assert_eq!(
            code_action_diagnostics(&all, "ty"),
            vec![wire("ty", "unresolved-import"), to_lsp_diagnostic(&ours)]
        );
        assert_eq!(
            code_action_diagnostics(&all, "basedpyright"),
            vec![to_lsp_diagnostic(&ours)]
        );
    }

    fn def_range(line: u32, ch: u32) -> lsp_types::Range {
        let p = lsp_types::Position {
            line,
            character: ch,
        };
        lsp_types::Range { start: p, end: p }
    }

    #[test]
    fn resolve_config_skips_a_server_not_on_path_and_keeps_one_that_is() {
        let absent = ServerConfig {
            name: "fake",
            command: "definitely-not-a-real-binary-zzzqqq".into(),
            args: vec![],
            language: Language::GO,
            initialization_options: None,
            provision: None,
        };
        assert!(
            resolve_config(&absent, false).is_none(),
            "a server whose command isn't on PATH must be skipped"
        );
        let present = ServerConfig {
            name: "shell",
            command: "sh".into(),
            args: vec![],
            language: Language::BASH,
            initialization_options: None,
            provision: None,
        };
        assert!(
            resolve_config(&present, false).is_some(),
            "a server whose command is on PATH must resolve"
        );
    }

    /// #930: a language whose only servers are missing says why, naming the
    /// command and, for one croft could build, the tool it would need.
    #[test]
    fn a_language_with_no_installable_server_gets_a_note_naming_the_missing_command() {
        use crate::lsp::install::Provision;
        let nothing_missing = |_: &Provision| None;
        assert_eq!(
            missing_servers_note(
                Language::LUA,
                &[ServerConfig::lua_language_server()],
                nothing_missing
            )
            .as_deref(),
            Some(
                "Lua: no language server, so no diagnostics or completion (lua-language-server isn't on PATH)"
            )
        );
        assert_eq!(
            missing_servers_note(Language::GO, &[ServerConfig::gopls()], |_: &Provision| {
                Some("go")
            })
            .as_deref(),
            Some(
                "Go: no language server, so no diagnostics or completion (gopls isn't on PATH, and installing it needs go)"
            )
        );
        // An install that can run reports its own progress, so no note: gopls
        // with `go` present, or Python's ty beside a PATH-only basedpyright.
        assert_eq!(
            missing_servers_note(Language::GO, &[ServerConfig::gopls()], nothing_missing),
            None
        );
        let python = [ServerConfig::ty(), ServerConfig::basedpyright()];
        assert_eq!(
            missing_servers_note(Language::PYTHON, &python, nothing_missing),
            None
        );
        assert_eq!(
            missing_servers_note(Language::LUA, &[], nothing_missing),
            None
        );
    }

    /// #930: opening a file whose language has no server on PATH used to be
    /// silent apart from lsp.log. It is now said once in OUTPUT › Server
    /// Provisioning, not again for another file or another project root.
    #[test]
    fn a_language_left_without_a_server_is_reported_once() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let lang = Language("issue930-no-server");
        let mut registry = ServerRegistry::new();
        registry.register(
            lang,
            ServerConfig {
                name: "issue930-server",
                command: "issue930-not-a-real-server".into(),
                args: vec![],
                language: lang,
                initialization_options: None,
                provision: None,
            },
        );
        let (diag_tx, _diag_rx) = std_mpsc::channel();
        let (prog_tx, _prog_rx) = std_mpsc::channel();
        let mut state = WorkerState {
            workspace_root: root.clone(),
            extra_roots: Vec::new(),
            registry,
            clients: HashMap::new(),
            docs: HashMap::new(),
            capability_support: Arc::new(StdMutex::new(LangCapabilitySupport::default())),
            semantic_refresh: Arc::new(AtomicBool::new(false)),
            inlay_refresh: Arc::new(AtomicBool::new(false)),
            diagnostic_refresh: Arc::new(AtomicBool::new(false)),
            diagnostics_tx: diag_tx,
            progress_tx: prog_tx,
            restarts: ServerRestarts::default(),
        };
        let runtime = LspRuntime::new().expect("runtime");
        let handle = runtime.handle().clone();
        handle.block_on(state.ensure_clients(lang, &root));
        handle.block_on(state.ensure_clients(lang, &root));
        handle.block_on(state.ensure_clients(lang, &root.join("other")));
        let notes: Vec<String> = crate::output::snapshot(crate::output::CHANNEL_PROVISION)
            .unwrap_or_default()
            .into_iter()
            .filter(|l| l.text.contains("issue930-not-a-real-server"))
            .map(|l| l.text)
            .collect();
        assert_eq!(
            notes,
            [
                "issue930-no-server: no language server, so no diagnostics or completion (issue930-not-a-real-server isn't on PATH)"
            ],
            "the missing server must be reported exactly once"
        );
    }

    #[cfg(unix)]
    #[test]
    fn resolve_path_only_pins_a_fallback_dir_binary_to_its_absolute_path() {
        use std::os::unix::fs::PermissionsExt;
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().to_path_buf();
        let bin = dir.join("rust-analyzer");
        std::fs::write(&bin, b"#!/bin/sh\n").unwrap();
        std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
        let cfg = ServerConfig {
            name: "rust-analyzer",
            command: "rust-analyzer".into(),
            args: vec![],
            language: Language::RUST,
            initialization_options: None,
            provision: None,
        };

        // Not on PATH, but present in a fallback dir: must resolve to the
        // ABSOLUTE binary path (so a GUI-launched croft with a stripped PATH
        // still spawns it) and prepend that dir to the child's PATH.
        let (resolved, extra) = resolve_path_only(&cfg, false, std::slice::from_ref(&dir))
            .expect("a binary in a fallback dir must resolve");
        assert_eq!(resolved.command, bin.to_string_lossy());
        assert_eq!(extra, vec![dir.clone()]);

        // Already on PATH: spawn the bare command, no extra PATH entries.
        let (resolved, extra) = resolve_path_only(&cfg, true, std::slice::from_ref(&dir))
            .expect("an on-PATH server must resolve");
        assert_eq!(resolved.command, "rust-analyzer");
        assert!(extra.is_empty());

        // Neither on PATH nor in any fallback dir: skip.
        assert!(
            resolve_path_only(&cfg, false, &[]).is_none(),
            "a server missing everywhere must be skipped"
        );
    }

    /// A stand-in rustup in `dir/bin` with a `rust-analyzer` proxy linked to
    /// it, returned as (rustup, proxy). Like the real one, it finds
    /// `rust-analyzer` only for a project whose `rust-toolchain.toml` pins a
    /// toolchain carrying it, names `stable` the active toolchain elsewhere,
    /// and cannot name one where the pinned toolchain is not installed.
    #[cfg(unix)]
    fn fake_rustup(dir: &Path) -> (PathBuf, PathBuf) {
        use std::os::unix::fs::PermissionsExt;
        let bin = dir.join("bin");
        std::fs::create_dir_all(&bin).unwrap();
        let rustup = bin.join("rustup");
        let script = r#"#!/bin/sh
case "$1" in
which)
  [ "$RUSTUP_AUTO_INSTALL" = 0 ] || touch installed-a-toolchain
  if [ -f rust-toolchain.toml ]; then echo "$PWD/$2"; exit 0; fi
  echo "error: not a file" >&2
  exit 1 ;;
show)
  [ -f not-installed ] && exit 1
  echo "stable-ARCH-unknown-linux-gnu (default)" ;;
esac
"#;
        std::fs::write(&rustup, script.replace("ARCH", std::env::consts::ARCH)).unwrap();
        std::fs::set_permissions(&rustup, std::fs::Permissions::from_mode(0o755)).unwrap();
        let proxy = bin.join("rust-analyzer");
        std::os::unix::fs::symlink("rustup", &proxy).unwrap();
        // Wait out "Text file busy" once: a test forking while the script
        // was open for writing holds it until that child execs.
        crate::review_ops::output_retrying_busy(std::process::Command::new(&rustup).arg("-V"))
            .expect("the stand-in rustup runs");
        (rustup, proxy)
    }

    #[cfg(unix)]
    #[test]
    fn a_rustup_proxy_is_told_apart_from_a_program_of_its_own() {
        let tmp = tempfile::tempdir().unwrap();
        let (rustup, proxy) = fake_rustup(tmp.path());
        let hard = tmp.path().join("bin/cargo-fmt");
        std::fs::hard_link(&rustup, &hard).unwrap();
        let elsewhere = tmp.path().join("rust-analyzer");
        std::os::unix::fs::symlink(&proxy, &elsewhere).unwrap();
        for (link, how) in [
            (proxy, "symlink"),
            (hard, "hard link"),
            (elsewhere, "link to a proxy"),
        ] {
            let found =
                rustup_behind(&link).unwrap_or_else(|| panic!("a {how} to rustup is a proxy"));
            assert_eq!(
                (found.file_name(), file_id(&found)),
                (rustup.file_name(), file_id(&rustup))
            );
        }
        let own = tmp.path().join("bin/clangd");
        std::fs::copy(&rustup, &own).unwrap();
        assert_eq!(
            rustup_behind(&own),
            None,
            "a binary of its own is never questioned"
        );
    }

    /// #927: rustup has a `rust-analyzer` proxy for every toolchain, so
    /// whether it can start one is a question about the toolchain the project
    /// selects, asked from its root. Where it cannot, croft must not spawn it.
    #[cfg(unix)]
    #[test]
    fn a_rustup_proxy_without_the_component_is_not_the_server_croft_starts() {
        let tmp = tempfile::tempdir().unwrap();
        let (rustup, proxy) = fake_rustup(tmp.path());
        let project = |name: &str, file: Option<&str>| {
            let dir = tmp.path().join(name);
            std::fs::create_dir(&dir).unwrap();
            if let Some(file) = file {
                std::fs::write(dir.join(file), "").unwrap();
            }
            dir
        };
        let default = project("default", None);
        let pinned = project("pinned", Some("rust-toolchain.toml"));
        let uninstalled = project("uninstalled", Some("not-installed"));
        let name = "croft-test-927-rust-analyzer";
        let config = ServerConfig {
            name,
            command: proxy.to_string_lossy().into_owned(),
            args: vec![],
            language: Language::RUST,
            initialization_options: None,
            // No download for any platform, so croft's copy never lands here.
            provision: Some(crate::lsp::install::Provision::Binary {
                targets: &[],
                bin: "rust-analyzer",
                archive: crate::lsp::install::ArchiveKind::Gz,
                bin_path: None,
                termux_pkg: None,
                sha256: &[],
            }),
        };
        let rt = stub_runtime();
        let kept = rt.block_on(resolve_for_root(&config, &pinned, false));
        assert_eq!(
            kept.map(|(c, _)| c.command),
            Some(config.command.clone()),
            "a toolchain that has rust-analyzer keeps rustup's proxy, matching the user's compiler"
        );
        assert!(
            rt.block_on(resolve_for_root(&config, &default, false))
                .is_none(),
            "a proxy that can only print 'Unknown binary' must give way to croft's copy"
        );
        assert_eq!(
            crate::lsp::install::failure_status(name, "download failed".into()),
            "download failed; run: rustup component add rust-analyzer --toolchain stable",
            "if croft's copy cannot be had either, the status line says how to get rustup's, \
             for the toolchain the project selects whatever directory it is typed in"
        );
        assert_eq!(
            rt.block_on(rustup_lacks(&rustup, "rust-analyzer", &default)),
            Some(RustupLack {
                why: String::from("rustup's 'stable' toolchain has no rust-analyzer"),
                fix: String::from("rustup component add rust-analyzer --toolchain stable"),
            }),
        );
        // Ages a verdict past its recheck, as 30 s would.
        let backdate = |dir: &Path| {
            if let Ok(mut verdicts) = RUSTUP_VERDICTS.lock()
                && let Some((asked, _)) = verdicts.get_mut(&(name, dir.to_path_buf()))
                && let Some(due) = asked.checked_sub(RUSTUP_RECHECK)
            {
                *asked = due;
            }
        };
        // The user runs that command. A fresh verdict still holds; once it is
        // due a recheck, rustup's own server is the one croft starts, with no
        // restart.
        std::fs::write(default.join("rust-toolchain.toml"), "").unwrap();
        assert!(
            rt.block_on(resolve_for_root(&config, &default, false))
                .is_none()
        );
        backdate(&default);
        assert_eq!(
            rt.block_on(resolve_for_root(&config, &default, false))
                .map(|(c, _)| c.command),
            Some(config.command.clone()),
            "the component added since is found when the verdict is asked again"
        );
        assert_eq!(
            rt.block_on(rustup_lacks(&rustup, "rust-analyzer", &uninstalled)),
            None,
            "a toolchain that is not installed yet is the proxy's to install"
        );
        // A rustup that could not say (here the toolchain was not installed
        // yet) keeps the proxy, and is asked again too: the toolchain it
        // installed has no rust-analyzer.
        assert!(
            rt.block_on(resolve_for_root(&config, &uninstalled, false))
                .is_some()
        );
        std::fs::remove_file(uninstalled.join("not-installed")).unwrap();
        backdate(&uninstalled);
        assert!(
            rt.block_on(resolve_for_root(&config, &uninstalled, false))
                .is_none(),
            "an open question is asked again, and the proxy gives way"
        );
        assert!(
            [default, pinned, uninstalled]
                .iter()
                .all(|dir| !dir.join("installed-a-toolchain").exists()),
            "asking must never install a toolchain"
        );
    }

    #[test]
    fn workspace_edits_reads_changes_map() {
        let uri = Url::from_file_path("/tmp/foo.rs").unwrap();
        let mut changes = HashMap::new();
        changes.insert(
            uri,
            vec![TextEdit {
                range: def_range(2, 4),
                new_text: "renamed".to_string(),
            }],
        );
        let we = WorkspaceEdit {
            changes: Some(changes),
            document_changes: None,
            change_annotations: None,
        };
        let out = workspace_edits(&we);
        assert_eq!(out.len(), 1);
        assert_eq!(out[0].0, PathBuf::from("/tmp/foo.rs"));
        assert_eq!(out[0].1.len(), 1);
        assert_eq!(out[0].1[0].new_text, "renamed");
        assert_eq!(out[0].1[0].start, (2, 4));
    }

    #[test]
    fn code_action_items_skips_disabled_and_normalises_edits() {
        use lsp_types::{CodeAction, CodeActionDisabled, CodeActionOrCommand, Command};
        let uri = Url::from_file_path("/tmp/foo.rs").unwrap();
        let mut changes = HashMap::new();
        changes.insert(
            uri,
            vec![TextEdit {
                range: def_range(0, 0),
                new_text: "import os\n".to_string(),
            }],
        );
        let edit = WorkspaceEdit {
            changes: Some(changes),
            document_changes: None,
            change_annotations: None,
        };
        let resp: CodeActionResponse = vec![
            // A bare command action (no inline edit; runs via executeCommand).
            CodeActionOrCommand::Command(Command {
                title: "Run fix".to_string(),
                command: "fix.run".to_string(),
                arguments: Some(vec![serde_json::json!(1)]),
            }),
            // A CodeAction carrying an inline workspace edit, marked preferred.
            CodeActionOrCommand::CodeAction(CodeAction {
                title: "Add import 'os'".to_string(),
                edit: Some(edit),
                is_preferred: Some(true),
                ..Default::default()
            }),
            // A disabled action: must be filtered out, mirroring VS Code's
            // lightbulb menu which hides disabled actions.
            CodeActionOrCommand::CodeAction(CodeAction {
                title: "Disabled thing".to_string(),
                disabled: Some(CodeActionDisabled {
                    reason: "nope".to_string(),
                }),
                ..Default::default()
            }),
        ];
        let items = code_action_items(&resp, "ruff");
        assert_eq!(items.len(), 2, "the disabled action must be filtered out");
        assert_eq!(items[0].title, "Run fix");
        assert_eq!(
            items[0].server, "ruff",
            "each item is tagged with its server"
        );
        assert!(items[0].edits.is_empty());
        assert_eq!(items[0].command.as_ref().unwrap().command, "fix.run");
        assert!(!items[0].needs_resolve);
        assert_eq!(items[1].title, "Add import 'os'");
        assert!(items[1].is_preferred);
        assert_eq!(items[1].edits.len(), 1);
        assert_eq!(items[1].edits[0].1[0].new_text, "import os\n");
        assert!(!items[1].needs_resolve);
    }

    #[test]
    fn code_action_items_flags_resolve_when_edit_absent() {
        use lsp_types::{CodeAction, CodeActionOrCommand};
        // ty / rust-analyzer style: the action arrives with `data` and no edit;
        // the edit is filled in by a later codeAction/resolve round trip.
        let resp: CodeActionResponse = vec![CodeActionOrCommand::CodeAction(CodeAction {
            title: "Import symbol".to_string(),
            data: Some(serde_json::json!({"id": 7})),
            ..Default::default()
        })];
        let items = code_action_items(&resp, "basedpyright");
        assert_eq!(items.len(), 1);
        assert_eq!(items[0].server, "basedpyright");
        assert!(items[0].edits.is_empty());
        assert!(items[0].command.is_none());
        assert!(
            items[0].needs_resolve,
            "an action with data but no edit/command must be marked for resolve"
        );
    }

    #[test]
    fn client_advertises_code_action_literal_and_resolve_support() {
        // Servers like ruff only return rich CodeAction objects (kinds such as
        // source.organizeImports / source.fixAll, plus resolvable edits) when the
        // client advertises codeActionLiteralSupport + resolveSupport. Without it
        // ty/ruff answer codeAction with nothing useful, so "Organize Imports"
        // never appears.
        let caps = build_client_capabilities();
        let ca = caps
            .text_document
            .and_then(|td| td.code_action)
            .expect("code action client capability must be declared");
        let kinds = ca
            .code_action_literal_support
            .expect("codeActionLiteralSupport must be declared")
            .code_action_kind
            .value_set;
        assert!(
            kinds.iter().any(|k| k == "source.organizeImports"),
            "the advertised kinds must include source.organizeImports"
        );
        assert!(
            kinds.iter().any(|k| k == "quickfix"),
            "the advertised kinds must include quickfix"
        );
        let resolves = ca
            .resolve_support
            .expect("resolveSupport must be declared so deferred edits resolve")
            .properties;
        assert!(resolves.iter().any(|p| p == "edit"));
        assert_eq!(ca.data_support, Some(true));
    }

    #[test]
    fn code_action_capability_detection() {
        use lsp_types::{CodeActionOptions, CodeActionProviderCapability};
        assert!(
            !code_action_supported(&None),
            "absent provider is unsupported"
        );
        assert!(
            !code_action_supported(&Some(CodeActionProviderCapability::Simple(false))),
            "a bare false is unsupported"
        );
        assert!(code_action_supported(&Some(
            CodeActionProviderCapability::Simple(true)
        )));
        assert!(
            code_action_supported(&Some(CodeActionProviderCapability::Options(
                CodeActionOptions::default()
            ))),
            "an options object means supported"
        );
    }

    /// #1084: didOpen names a JSON-with-comments file `jsonc`, so the JSON
    /// server neither flags its comments nor errors on trailing commas; plain
    /// JSON stays `json`.
    #[test]
    fn json_with_comments_files_open_as_jsonc() {
        let jsonc = Language::from_lsp_id("jsonc").expect("jsonc is a language");
        for path in [
            "/repo/tsconfig.json",
            "/repo/.vscode/launch.json",
            "/repo/.babelrc",
            "/repo/notes.jsonc",
        ] {
            let lang = path_to_language(Path::new(path));
            assert_eq!(lang, Some(jsonc), "{path}");
            assert_eq!(lang.unwrap().lsp_id(), "jsonc");
        }
        let keybindings = crate::paths::config_dir().join("keybindings.json");
        assert_eq!(path_to_language(&keybindings), Some(jsonc));
        assert_eq!(
            path_to_language(Path::new("/repo/package.json")),
            Some(Language::JSON)
        );
    }

    #[test]
    fn project_root_is_nearest_manifest_ancestor() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        // monorepo: root/app/svc is a Python sub-project with its own pyproject.
        let svc = root.join("app").join("svc");
        std::fs::create_dir_all(svc.join("src/pkg")).unwrap();
        std::fs::write(svc.join("pyproject.toml"), b"[project]\n").unwrap();
        let file = svc.join("src/pkg/mod.py");
        assert_eq!(project_root_within(&file, Language::PYTHON, root), svc);
    }

    #[test]
    fn project_root_falls_back_to_workspace_root_without_manifest() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let file = root.join("a/b/loose.py");
        std::fs::create_dir_all(file.parent().unwrap()).unwrap();
        // No pyproject anywhere up the tree → workspace root.
        assert_eq!(project_root_within(&file, Language::PYTHON, root), root);
    }

    #[test]
    fn project_root_ignores_manifest_of_other_languages() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let sub = root.join("sub");
        std::fs::create_dir_all(&sub).unwrap();
        // A Cargo.toml must not anchor a Python file; Python keeps walking to root.
        std::fs::write(sub.join("Cargo.toml"), b"[package]\n").unwrap();
        let file = sub.join("script.py");
        assert_eq!(project_root_within(&file, Language::PYTHON, root), root);
        // ...but it does anchor a Rust file.
        let rs = sub.join("src/main.rs");
        std::fs::create_dir_all(rs.parent().unwrap()).unwrap();
        assert_eq!(project_root_within(&rs, Language::RUST, root), sub);
    }

    #[test]
    fn declaration_capability_false_reads_as_unsupported() {
        // The bug: vtsls sends `declarationProvider: false`, which lsp-types
        // parses to `Some(DeclarationCapability::Simple(false))`. `Option::is_some`
        // read that as supported and croft called the unhandled method.
        assert!(!declaration_supported(&Some(
            DeclarationCapability::Simple(false)
        )));
        assert!(declaration_supported(&Some(DeclarationCapability::Simple(
            true
        ))));
        assert!(!declaration_supported(&None));
    }

    #[test]
    fn one_of_capability_false_reads_as_unsupported() {
        let off: Option<OneOf<bool, ()>> = Some(OneOf::Left(false));
        let on: Option<OneOf<bool, ()>> = Some(OneOf::Left(true));
        let opts: Option<OneOf<bool, ()>> = Some(OneOf::Right(()));
        assert!(!one_of_supported(&off));
        assert!(one_of_supported(&on));
        assert!(one_of_supported(&opts));
        assert!(!one_of_supported(&None::<OneOf<bool, ()>>));
    }

    /// A `Full` report with no `result_id` must FORGET the file, not keep
    /// the old id (#533).
    ///
    /// Keeping it sends back an id the server never issued for the current
    /// content; a server that trusts it answers `Unchanged` for a file that
    /// has changed, and the diagnostics never refresh.
    #[test]
    fn a_report_without_a_result_id_forgets_the_file() {
        let mut ids = DiagnosticResultIds::default();
        assert!(ids.is_empty(), "cold to start");

        ids.record("file:///w/a.rs", Some("v1"));
        ids.record("file:///w/b.rs", Some("v1"));
        assert_eq!(ids.len(), 2);

        // b.rs comes back with no id: the server is declining incrementality
        // for it, so the stale id must go rather than being resent.
        ids.record("file:///w/b.rs", None);
        assert_eq!(ids.len(), 1, "the file without an id is forgotten");
        let sent: Vec<String> = ids
            .previous()
            .into_iter()
            .map(|p| p.uri.to_string())
            .collect();
        assert!(
            sent.iter().any(|u| u.contains("a.rs")),
            "the file that DID carry an id is still sent: {sent:?}"
        );
        assert!(
            !sent.iter().any(|u| u.contains("b.rs")),
            "the forgotten file is not sent: {sent:?}"
        );

        // A new id for the same file replaces rather than accumulating.
        ids.record("file:///w/a.rs", Some("v2"));
        assert_eq!(ids.len(), 1, "replacing an id does not add an entry");
        assert_eq!(
            ids.previous().first().map(|p| p.value.clone()),
            Some(String::from("v2")),
            "the newest id is what goes back"
        );
    }

    /// A server that pulls per-document but NOT per-workspace advertises
    /// `diagnosticProvider` with `workspaceDiagnostics: false` (#533).
    /// Reading the outer `Option` would send it a request it does not
    /// implement; the inner flag is the only thing that separates them.
    #[test]
    fn workspace_diagnostics_reads_the_inner_flag_not_the_option() {
        let opts = |workspace: bool| lsp_types::DiagnosticOptions {
            identifier: None,
            inter_file_dependencies: false,
            workspace_diagnostics: workspace,
            work_done_progress_options: Default::default(),
        };

        // The trap: present, but per-document only.
        assert!(!workspace_diagnostics_supported(&Some(
            DiagnosticServerCapabilities::Options(opts(false))
        )));
        // Paired positive, so the assertion above cannot pass by the
        // predicate simply always saying no.
        assert!(workspace_diagnostics_supported(&Some(
            DiagnosticServerCapabilities::Options(opts(true))
        )));

        // The registration-options variant carries the same flag and must
        // not read as an unconditional yes.
        let reg = |workspace: bool| lsp_types::DiagnosticRegistrationOptions {
            text_document_registration_options: Default::default(),
            diagnostic_options: opts(workspace),
            static_registration_options: Default::default(),
        };
        assert!(!workspace_diagnostics_supported(&Some(
            DiagnosticServerCapabilities::RegistrationOptions(reg(false))
        )));
        assert!(workspace_diagnostics_supported(&Some(
            DiagnosticServerCapabilities::RegistrationOptions(reg(true))
        )));

        assert!(!workspace_diagnostics_supported(&None));
    }

    #[test]
    fn hover_capability_false_reads_as_unsupported() {
        assert!(!hover_supported(&Some(HoverProviderCapability::Simple(
            false
        ))));
        assert!(hover_supported(&Some(HoverProviderCapability::Simple(
            true
        ))));
        assert!(!hover_supported(&None));
    }

    #[test]
    fn type_definition_capability_false_reads_as_unsupported() {
        assert!(!type_definition_supported(&Some(
            TypeDefinitionProviderCapability::Simple(false)
        )));
        assert!(type_definition_supported(&Some(
            TypeDefinitionProviderCapability::Simple(true)
        )));
        assert!(!type_definition_supported(&None));
    }

    #[test]
    fn implementation_capability_false_reads_as_unsupported() {
        assert!(!implementation_supported(&Some(
            ImplementationProviderCapability::Simple(false)
        )));
        assert!(implementation_supported(&Some(
            ImplementationProviderCapability::Simple(true)
        )));
        assert!(!implementation_supported(&None));
    }

    #[test]
    fn reference_locations_maps_every_location() {
        // Go to References is 1:many: a symbol used in three places comes back
        // as a flat `Vec<Location>` (not a `GotoDefinitionResponse`), and every
        // one must survive the mapping, in order.
        let locs = vec![
            Location {
                uri: Url::from_file_path("/tmp/a.rs").unwrap(),
                range: def_range(2, 4),
            },
            Location {
                uri: Url::from_file_path("/tmp/b.rs").unwrap(),
                range: def_range(7, 1),
            },
            Location {
                uri: Url::from_file_path("/tmp/a.rs").unwrap(),
                range: def_range(11, 0),
            },
        ];
        assert_eq!(
            reference_locations(&locs),
            vec![
                (PathBuf::from("/tmp/a.rs"), 2, 4),
                (PathBuf::from("/tmp/b.rs"), 7, 1),
                (PathBuf::from("/tmp/a.rs"), 11, 0),
            ]
        );
    }

    #[test]
    fn reference_locations_empty_is_empty() {
        assert!(reference_locations(&[]).is_empty());
    }

    #[test]
    fn def_location_reads_scalar() {
        let uri = Url::from_file_path("/tmp/foo.rs").unwrap();
        let resp = GotoDefinitionResponse::Scalar(Location {
            uri,
            range: def_range(3, 5),
        });
        assert_eq!(
            def_location(&resp),
            Some((PathBuf::from("/tmp/foo.rs"), 3, 5))
        );
    }

    #[test]
    fn def_location_reads_first_of_array() {
        let resp = GotoDefinitionResponse::Array(vec![
            Location {
                uri: Url::from_file_path("/tmp/a.rs").unwrap(),
                range: def_range(1, 0),
            },
            Location {
                uri: Url::from_file_path("/tmp/b.rs").unwrap(),
                range: def_range(9, 9),
            },
        ]);
        assert_eq!(
            def_location(&resp),
            Some((PathBuf::from("/tmp/a.rs"), 1, 0))
        );
    }

    #[test]
    fn def_location_reads_link_target_selection_range() {
        let resp = GotoDefinitionResponse::Link(vec![LocationLink {
            origin_selection_range: None,
            target_uri: Url::from_file_path("/tmp/c.rs").unwrap(),
            target_range: def_range(10, 0),
            target_selection_range: def_range(12, 4),
        }]);
        assert_eq!(
            def_location(&resp),
            Some((PathBuf::from("/tmp/c.rs"), 12, 4))
        );
    }

    #[test]
    fn def_location_is_none_for_empty_array() {
        let resp = GotoDefinitionResponse::Array(vec![]);
        assert_eq!(def_location(&resp), None);
    }

    #[test]
    fn def_locations_reads_every_entry_of_array() {
        // Go to Implementations is 1:many: a trait with two implementors comes
        // back as an Array of both, and `def_locations` must keep both (whereas
        // `def_location` keeps only the first).
        let resp = GotoDefinitionResponse::Array(vec![
            Location {
                uri: Url::from_file_path("/tmp/a.rs").unwrap(),
                range: def_range(1, 0),
            },
            Location {
                uri: Url::from_file_path("/tmp/b.rs").unwrap(),
                range: def_range(9, 9),
            },
        ]);
        assert_eq!(
            def_locations(&resp),
            vec![
                (PathBuf::from("/tmp/a.rs"), 1, 0),
                (PathBuf::from("/tmp/b.rs"), 9, 9),
            ]
        );
    }

    #[test]
    fn def_locations_collapses_scalar_to_one_entry() {
        let resp = GotoDefinitionResponse::Scalar(Location {
            uri: Url::from_file_path("/tmp/foo.rs").unwrap(),
            range: def_range(3, 5),
        });
        assert_eq!(
            def_locations(&resp),
            vec![(PathBuf::from("/tmp/foo.rs"), 3, 5)]
        );
    }

    #[test]
    fn def_locations_reads_all_links() {
        let resp = GotoDefinitionResponse::Link(vec![
            LocationLink {
                origin_selection_range: None,
                target_uri: Url::from_file_path("/tmp/c.rs").unwrap(),
                target_range: def_range(10, 0),
                target_selection_range: def_range(12, 4),
            },
            LocationLink {
                origin_selection_range: None,
                target_uri: Url::from_file_path("/tmp/d.rs").unwrap(),
                target_range: def_range(20, 0),
                target_selection_range: def_range(22, 2),
            },
        ]);
        assert_eq!(
            def_locations(&resp),
            vec![
                (PathBuf::from("/tmp/c.rs"), 12, 4),
                (PathBuf::from("/tmp/d.rs"), 22, 2),
            ]
        );
    }

    #[test]
    fn hover_text_reads_plain_markup() {
        let c = HoverContents::Markup(MarkupContent {
            kind: MarkupKind::Markdown,
            value: "fn foo(x: i32) -> i32".into(),
        });
        assert_eq!(hover_text(&c).as_deref(), Some("fn foo(x: i32) -> i32"));
    }

    #[test]
    fn hover_text_reads_scalar_language_string() {
        let c = HoverContents::Scalar(MarkedString::LanguageString(LanguageString {
            language: "rust".into(),
            value: "fn foo()".into(),
        }));
        assert_eq!(hover_text(&c).as_deref(), Some("fn foo()"));
    }

    #[test]
    fn hover_text_reads_scalar_plain_string() {
        let c = HoverContents::Scalar(MarkedString::String("just text".into()));
        assert_eq!(hover_text(&c).as_deref(), Some("just text"));
    }

    #[test]
    fn hover_text_joins_array_entries_and_skips_blanks() {
        let c = HoverContents::Array(vec![
            MarkedString::String("line one".into()),
            MarkedString::String("   ".into()),
            MarkedString::LanguageString(LanguageString {
                language: "rust".into(),
                value: "line two".into(),
            }),
        ]);
        assert_eq!(hover_text(&c).as_deref(), Some("line one\n\nline two"));
    }

    #[test]
    fn hover_text_is_none_when_blank() {
        let c = HoverContents::Markup(MarkupContent {
            kind: MarkupKind::PlainText,
            value: "   ".into(),
        });
        assert_eq!(hover_text(&c), None);
    }

    #[test]
    fn hover_text_is_none_for_empty_array() {
        let c = HoverContents::Array(vec![]);
        assert_eq!(hover_text(&c), None);
    }

    fn drain_completion_blocking(
        manager: &LspManager,
        timeout: Duration,
    ) -> Option<CompletionResult> {
        let deadline = Instant::now() + timeout;
        loop {
            if let Some(r) = manager.drain_completion() {
                return Some(r);
            }
            if Instant::now() >= deadline {
                return None;
            }
            std::thread::sleep(Duration::from_millis(20));
        }
    }

    /// The `python3` the stub server runs under, if there is one.
    fn python_for_stub_server() -> Option<std::path::PathBuf> {
        let path = std::env::var_os("PATH")?;
        std::env::split_paths(&path)
            .map(|entry| entry.join("python3"))
            .find(|candidate| is_executable_file(candidate))
    }

    fn any_python_completion_server_on_path() -> bool {
        is_on_path("basedpyright-langserver")
            || is_on_path("pyright-langserver")
            || is_on_path("ty")
    }

    #[test]
    fn manager_open_change_close_pipe_via_ruff() {
        if !is_on_path("ruff") {
            eprintln!("SKIPPED: ruff not on PATH");
            return;
        }
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let file = root.join("demo.py");
        std::fs::write(&file, "x = 1\n").expect("write demo");

        let manager = LspManager::new(root).expect("manager");
        manager.open_doc(file.clone(), String::from("x = 1\n"));
        std::thread::sleep(Duration::from_millis(800));
        manager.change_doc(file.clone(), String::from("x = 2\n"));
        std::thread::sleep(Duration::from_millis(800));
        manager.close_doc(file.clone());
        std::thread::sleep(Duration::from_millis(400));
        drop(manager);
    }

    #[test]
    fn manager_completion_against_python_lsp() {
        if !any_python_completion_server_on_path() {
            eprintln!("SKIPPED: no basedpyright/pyright/ty on PATH");
            return;
        }
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let file = root.join("demo.py");
        let text = String::from("def f(input, num):\n    input_split = input.split()\n    inp\n");
        std::fs::write(&file, &text).expect("write demo");

        let mut manager = LspManager::new(root).expect("manager");
        manager.open_doc(file.clone(), text);
        std::thread::sleep(Duration::from_millis(2500));

        let id = manager.request_completion(file.clone(), 2, 7, CompletionTrigger::Invoked);
        // 30s: basedpyright is a Node.js process that initialises slowly
        // under heavy parallel `cargo test` load (the suite spawns ~900
        // tests, many of which open PTYs). 10s was reliable in isolation
        // but flaked under that load; 30s leaves plenty of headroom
        // without slowing the happy path (the loop returns the moment
        // the completion arrives).
        let result = drain_completion_blocking(&manager, Duration::from_secs(30))
            .expect("completion arrived");
        assert_eq!(result.request_id, id);
        assert_eq!(result.path, file);
        let labels: Vec<&str> = result.items.iter().map(|i| i.label.as_str()).collect();
        assert!(
            labels.iter().any(|l| l.starts_with("input")),
            "expected at least one item starting with `input`, got: {labels:?}"
        );
    }

    /// A rename for a file no server tracks (a tab opened by a relative
    /// path, #1193) is answered with no edits instead of never, which left
    /// "Renaming symbol" on the status bar forever.
    #[test]
    fn a_rename_for_an_untracked_file_is_answered_with_no_edits() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let mut manager = LspManager::new(root).expect("manager");
        let id = manager.request_rename(PathBuf::from("pkg/util.py"), 0, 4, "grand_total".into());
        let deadline = Instant::now() + Duration::from_secs(10);
        let result = loop {
            if let Some(r) = manager.drain_rename() {
                break Some(r);
            }
            if Instant::now() >= deadline {
                break None;
            }
            std::thread::sleep(Duration::from_millis(20));
        };
        let result = result.expect("the rename is answered");
        assert_eq!(result.request_id, id);
        assert!(result.edits.is_none());
    }

    fn drain_hover_blocking(manager: &LspManager, timeout: Duration) -> Option<HoverResult> {
        let deadline = Instant::now() + timeout;
        loop {
            if let Some(r) = manager.drain_hover() {
                return Some(r);
            }
            if Instant::now() >= deadline {
                return None;
            }
            std::thread::sleep(Duration::from_millis(20));
        }
    }

    #[test]
    fn manager_hover_against_python_lsp() {
        if !any_python_completion_server_on_path() {
            eprintln!("SKIPPED: no basedpyright/pyright/ty on PATH");
            return;
        }
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let file = root.join("demo.py");
        let text = String::from("def greet(name):\n    return 'hi ' + name\n\ngreet('x')\n");
        std::fs::write(&file, &text).expect("write demo");

        let mut manager = LspManager::new(root).expect("manager");
        manager.open_doc(file.clone(), text);
        std::thread::sleep(Duration::from_millis(2500));

        let id = manager.request_hover(file.clone(), 3, 0);
        let result =
            drain_hover_blocking(&manager, Duration::from_secs(30)).expect("hover arrived");
        assert_eq!(result.request_id, id);
        let hover = result.text.expect("hover text for the greet call");
        assert!(
            hover.contains("greet"),
            "hover over the greet call should name the function, got: {hover:?}"
        );
    }

    fn drain_definition_blocking(
        manager: &LspManager,
        timeout: Duration,
    ) -> Option<DefinitionResult> {
        let deadline = Instant::now() + timeout;
        loop {
            if let Some(r) = manager.drain_definition() {
                return Some(r);
            }
            if Instant::now() >= deadline {
                return None;
            }
            std::thread::sleep(Duration::from_millis(20));
        }
    }

    #[test]
    fn manager_definition_against_python_lsp() {
        if !any_python_completion_server_on_path() {
            eprintln!("SKIPPED: no basedpyright/pyright/ty on PATH");
            return;
        }
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let file = root.join("demo.py");
        let text = String::from("def greet(name):\n    return name\n\ngreet('x')\n");
        std::fs::write(&file, &text).expect("write demo");

        let mut manager = LspManager::new(root).expect("manager");
        manager.open_doc(file.clone(), text);
        std::thread::sleep(Duration::from_millis(2500));

        let id = manager.request_definition(file.clone(), 3, 0);
        let result = drain_definition_blocking(&manager, Duration::from_secs(30))
            .expect("definition arrived");
        assert_eq!(result.request_id, id);
        let (target_path, target_line, _col) = result.target.expect("definition target found");
        assert_eq!(target_path, file, "greet is defined in the same file");
        assert_eq!(target_line, 0, "greet is defined on line 0");
    }

    fn semantic_caps(range: Option<bool>) -> ServerCapabilities {
        ServerCapabilities {
            semantic_tokens_provider: Some(
                SemanticTokensServerCapabilities::SemanticTokensOptions(SemanticTokensOptions {
                    legend: SemanticTokensLegend {
                        token_types: vec![SemanticTokenType::PARAMETER],
                        token_modifiers: vec![],
                    },
                    range,
                    full: Some(SemanticTokensFullOptions::Bool(true)),
                    work_done_progress_options: Default::default(),
                }),
            ),
            ..Default::default()
        }
    }

    #[test]
    fn range_support_detected_only_when_advertised() {
        // ty advertises range; basedpyright advertises full-only.
        assert!(semantic_tokens_range_supported(&semantic_caps(Some(true))));
        assert!(!semantic_tokens_range_supported(&semantic_caps(None)));
        assert!(!semantic_tokens_range_supported(&semantic_caps(Some(
            false
        ))));
        assert!(!semantic_tokens_range_supported(
            &ServerCapabilities::default()
        ));
    }

    fn drain_semantic_blocking(
        manager: &LspManager,
        timeout: Duration,
    ) -> Option<SemanticTokensUpdate> {
        let deadline = Instant::now() + timeout;
        loop {
            if let Some(r) = manager.drain_semantic_tokens() {
                return Some(r);
            }
            if Instant::now() >= deadline {
                return None;
            }
            std::thread::sleep(Duration::from_millis(20));
        }
    }

    #[test]
    fn manager_semantic_tokens_against_python_lsp() {
        if !any_python_completion_server_on_path() {
            eprintln!("SKIPPED: no basedpyright/pyright/ty on PATH");
            return;
        }
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let file = root.join("demo.py");
        // `value` is a parameter referenced in the body; tree-sitter alone
        // cannot know the body use is the parameter, the LSP can.
        let text = String::from("def calc(value):\n    return value + 1\n");
        std::fs::write(&file, &text).expect("write demo");

        let manager = LspManager::new(root).expect("manager");
        manager.open_doc(file.clone(), text.clone());
        std::thread::sleep(Duration::from_millis(2500));
        manager.request_semantic_tokens(file.clone(), 0);

        let update = drain_semantic_blocking(&manager, Duration::from_secs(30))
            .expect("semantic tokens arrived");
        assert_eq!(update.path, file);
        assert!(
            update.legend.iter().any(|t| t == "parameter"),
            "the server legend should include the `parameter` token type, got: {:?}",
            update.legend
        );
        assert!(!update.data.is_empty(), "expected a non-empty token batch");

        // Decode and confirm the `value` reference in the body (line 1)
        // carries the parameter color, end-to-end through the real server.
        let line_starts = crate::highlight::compute_line_starts(text.as_bytes());
        let spans = crate::highlight::decode_semantic_tokens(
            &update.data,
            &update.legend,
            text.as_bytes(),
            &line_starts,
        );
        let body = "    return value + 1";
        let col = body.find("value").expect("value in body");
        let hit = spans[1]
            .iter()
            .find(|s| s.range().contains(&col))
            .expect("a semantic span should cover the body `value`");
        assert_eq!(
            hit.style.fg,
            Some(ratatui::style::Color::Rgb(0xd0, 0x87, 0x70)),
            "the parameter referenced in the body must carry the parameter color"
        );
    }

    #[test]
    fn manager_semantic_tokens_range_against_python_lsp() {
        // The viewport-range first-paint path: a `semanticTokens/range` query
        // over the opening rows must return tokens and arrive flagged
        // `is_full == false`. Requires a range-capable server (ty); when only
        // full-only basedpyright is present the request yields nothing, so the
        // assertion is gated on ty being on PATH.
        if !is_on_path("ty") {
            eprintln!("SKIPPED: ty (range-capable) not on PATH");
            return;
        }
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let file = root.join("range_demo.py");
        let text = String::from("def calc(value):\n    return value + 1\n");
        std::fs::write(&file, &text).expect("write range_demo");

        let manager = LspManager::new(root).expect("manager");
        manager.open_doc(file.clone(), text.clone());
        std::thread::sleep(Duration::from_millis(2500));
        manager.request_semantic_tokens_range(file.clone(), 0, rows_end(&text, 2), 0);

        let update = drain_semantic_blocking(&manager, Duration::from_secs(30))
            .expect("range semantic tokens arrived");
        assert_eq!(update.path, file);
        assert!(
            !update.is_full,
            "a range reply must be flagged is_full=false so it cannot clobber the full batch"
        );
        assert!(
            !update.data.is_empty(),
            "the viewport range must carry tokens for the visible function"
        );
    }

    // Reproduces the FULL real-app path for a file with a stray lone `\r`
    // (the n-gram.py bug): opened through `Editor::open`, synced the way
    // `sync_lsp` does (`lines.join("\n")`), then the batch applied via
    // `Editor::apply_semantic_tokens`. The lone `\r` is a line break for the
    // LSP but not for Rust's `str::lines`, so before the fix every token
    // below it landed one row off and the body parameter went uncolored.
    #[test]
    fn editor_overlay_aligns_with_lsp_across_a_lone_cr() {
        if !any_python_completion_server_on_path() {
            eprintln!("SKIPPED: no basedpyright/pyright/ty on PATH");
            return;
        }
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let file = root.join("mixed.py");
        // A lone `\r` (the `\n\r` after line 0) sits above the function, the
        // same shape as the real n-gram.py. Buffer lines after the fix:
        //   0:"x = 1"  1:""  2:"def calc(value):"  3:"    return value + 1"
        let disk = "x = 1\n\rdef calc(value):\n    return value + 1\n";
        std::fs::write(&file, disk).expect("write mixed");

        let mut editor = crate::widgets::editor::Editor::new();
        editor.open(&file).expect("open");
        // The lone CR must split a line so our numbering matches the server's.
        assert_eq!(
            editor.lines_for_test().len(),
            4,
            "lone CR must split a line"
        );
        let sent = editor.lines_for_test().join("\n");

        let manager = LspManager::new(root).expect("manager");
        manager.open_doc(file.clone(), sent);
        std::thread::sleep(Duration::from_millis(2500));
        manager.request_semantic_tokens(file.clone(), 0);
        let update = drain_semantic_blocking(&manager, Duration::from_secs(30))
            .expect("semantic tokens arrived");

        // When ty is installed, the range-capable preference must route the
        // request to ty (instant on any workspace), not full-only basedpyright.
        // ty's legend uniquely carries `selfParameter`; basedpyright's does not.
        if is_on_path("ty") {
            assert!(
                update.legend.iter().any(|t| t == "selfParameter"),
                "ty (range-capable) must be preferred for semantic tokens; legend={:?}",
                update.legend
            );
        }

        editor.apply_semantic_tokens(update.path, update.data, update.legend, update.is_full);
        let overlay = editor.semantic_overlay_for_test();
        // The `value` reference in the body is on buffer line 3. It must carry
        // the parameter color there, and NOT bleed onto the wrong row.
        let orange = ratatui::style::Color::Rgb(0xd0, 0x87, 0x70);
        let colored_on = |line: usize| {
            overlay
                .get(line)
                .map(|s| s.iter().any(|sp| sp.style.fg == Some(orange)))
                .unwrap_or(false)
        };
        assert!(
            colored_on(3),
            "body parameter must be colored on its real row (line 3); overlay={overlay:?}"
        );
    }

    /// A formatting request the worker cannot route MUST still answer, or the
    /// app's format-on-save latch stays armed forever: `save()` defers the
    /// write until a reply lands, so a silent bail means Cmd+S wrote nothing
    /// and said nothing. The per-LANGUAGE capability map that gates the
    /// feature is true for any file of that language, including ones this
    /// worker never tracked (outside the project root, failed didOpen).
    #[test]
    fn an_unroutable_format_request_still_answers() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let (diag_tx, _diag_rx) = std_mpsc::channel();
        let (prog_tx, _prog_rx) = std_mpsc::channel();
        let (fmt_tx, fmt_rx) = std_mpsc::channel();
        let mut state = WorkerState {
            workspace_root: root.clone(),
            extra_roots: Vec::new(),
            registry: ServerRegistry::new(),
            clients: HashMap::new(),
            docs: HashMap::new(),
            capability_support: Arc::new(StdMutex::new(LangCapabilitySupport::default())),
            semantic_refresh: Arc::new(AtomicBool::new(false)),
            inlay_refresh: Arc::new(AtomicBool::new(false)),
            diagnostic_refresh: Arc::new(AtomicBool::new(false)),
            diagnostics_tx: diag_tx,
            progress_tx: prog_tx,
            restarts: ServerRestarts::default(),
        };
        let never_opened = root.join("stray.py");

        let runtime = LspRuntime::new().expect("runtime");
        runtime.handle().clone().block_on(async {
            state
                .request_formatting(7, never_opened.clone(), 4, true, &fmt_tx)
                .await;
        });

        let reply = fmt_rx
            .try_recv()
            .expect("an untracked document must still get a reply");
        assert_eq!(reply.request_id, 7);
        assert_eq!(reply.path, never_opened);
        assert!(
            reply.unsupported,
            "the reply must tell the app no formatter is reachable"
        );
    }

    #[test]
    fn prepare_rename_capability_needs_an_options_shaped_provider() {
        assert!(!prepare_rename_supported(&None));
        assert!(!prepare_rename_supported(&Some(OneOf::Left(true))));
        assert!(!prepare_rename_supported(&Some(OneOf::Right(
            lsp_types::RenameOptions {
                prepare_provider: None,
                work_done_progress_options: Default::default(),
            }
        ))));
        assert!(prepare_rename_supported(&Some(OneOf::Right(
            lsp_types::RenameOptions {
                prepare_provider: Some(true),
                work_done_progress_options: Default::default(),
            }
        ))));
    }

    /// The rename prompt defers on this verdict, so an unroutable
    /// prepare request must still answer (#254) — with `unsupported`,
    /// which routes the app to the word-under-cursor fallback.
    #[test]
    fn an_unroutable_prepare_rename_answers_unsupported() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let (diag_tx, _diag_rx) = std_mpsc::channel();
        let (prog_tx, _prog_rx) = std_mpsc::channel();
        let (prep_tx, prep_rx) = std_mpsc::channel();
        let mut state = WorkerState {
            workspace_root: root.clone(),
            extra_roots: Vec::new(),
            registry: ServerRegistry::new(),
            clients: HashMap::new(),
            docs: HashMap::new(),
            capability_support: Arc::new(StdMutex::new(LangCapabilitySupport::default())),
            semantic_refresh: Arc::new(AtomicBool::new(false)),
            inlay_refresh: Arc::new(AtomicBool::new(false)),
            diagnostic_refresh: Arc::new(AtomicBool::new(false)),
            diagnostics_tx: diag_tx,
            progress_tx: prog_tx,
            restarts: ServerRestarts::default(),
        };
        let never_opened = root.join("stray.py");
        let runtime = LspRuntime::new().expect("runtime");
        runtime.handle().clone().block_on(async {
            state
                .request_prepare_rename(21, never_opened.clone(), 0, 0, &prep_tx)
                .await;
        });
        let reply = prep_rx.try_recv().expect("must answer");
        assert_eq!(reply.request_id, 21);
        assert!(reply.unsupported);
        assert!(reply.error.is_none() && reply.target.is_none());
    }

    /// A stub server for prepareRename (#1677). `mode` decides its answer:
    /// `mute` never answers (the bug), `range` answers a range with a
    /// placeholder, `error` refuses with a message.
    fn prepare_rename_server_script(dir: &Path) -> std::path::PathBuf {
        let path = dir.join("prepare_rename_server.py");
        std::fs::write(
            &path,
            r#"
import json, sys

mode = sys.argv[1]

def read():
    length = None
    while True:
        line = sys.stdin.buffer.readline()
        if not line:
            return None
        line = line.strip()
        if not line:
            break
        if line.lower().startswith(b"content-length:"):
            length = int(line.split(b":")[1])
    if length is None:
        return None
    return json.loads(sys.stdin.buffer.read(length))

def write(msg):
    body = json.dumps(msg).encode()
    sys.stdout.buffer.write(b"Content-Length: %d\r\n\r\n" % len(body))
    sys.stdout.buffer.write(body)
    sys.stdout.buffer.flush()

while True:
    msg = read()
    if msg is None:
        break
    method = msg.get("method")
    if method == "initialize":
        write({"jsonrpc": "2.0", "id": msg["id"], "result": {"capabilities": {
            "renameProvider": {"prepareProvider": True},
        }}})
    elif method == "textDocument/prepareRename":
        if mode == "range":
            write({"jsonrpc": "2.0", "id": msg["id"], "result": {
                "range": {"start": {"line": 0, "character": 4},
                          "end": {"line": 0, "character": 9}},
                "placeholder": "total",
            }})
        elif mode == "error":
            write({"jsonrpc": "2.0", "id": msg["id"], "error": {
                "code": -32803, "message": "cannot rename a keyword",
            }})
    elif method == "shutdown":
        write({"jsonrpc": "2.0", "id": msg["id"], "result": None})
    elif "id" in msg:
        write({"jsonrpc": "2.0", "id": msg["id"], "result": None})
"#,
        )
        .expect("write stub server");
        path
    }

    /// Run one prepareRename against the stub in `mode`, bounded by
    /// `timeout`, and return the verdict and how long it took to arrive.
    /// `None` when python3 is missing.
    fn prepare_rename_against(
        mode: &str,
        timeout: std::time::Duration,
        stalled: Arc<AtomicBool>,
    ) -> Option<(PrepareRenameResult, std::time::Duration)> {
        let python = python_for_stub_server()?;
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let script = prepare_rename_server_script(&root);
        let file = root.join("calc.py");
        std::fs::write(&file, "def total(items):\n    return sum(items)\n").unwrap();
        let runtime = tokio::runtime::Builder::new_multi_thread()
            .worker_threads(2)
            .enable_all()
            .build()
            .expect("a runtime");
        let (tx, rx) = std_mpsc::channel();
        let started = runtime.block_on(async {
            let config = ServerConfig {
                name: "prepare-rename",
                command: python.to_string_lossy().into_owned(),
                args: vec![script.to_string_lossy().into_owned(), mode.to_string()],
                language: Language::PYTHON,
                initialization_options: None,
                provision: None,
            };
            let (diag_tx, _diag_rx) = std_mpsc::channel();
            let (prog_tx, _prog_rx) = std_mpsc::channel();
            let client = LspClient::spawn(
                &config,
                &root,
                build_client_capabilities(),
                &[],
                Arc::new(AtomicBool::new(false)),
                Arc::new(AtomicBool::new(false)),
                Arc::new(AtomicBool::new(false)),
                diag_tx,
                prog_tx,
            )
            .await
            .expect("the stub server handshakes");
            assert!(
                prepare_rename_supported(&client.capabilities().rename_provider),
                "the stub must advertise prepareProvider, or F2 never asks it"
            );
            let started = std::time::Instant::now();
            spawn_prepare_rename(
                PrepareRenameAsk {
                    request_id: 7,
                    server_name: String::from("prepare-rename"),
                    client: Arc::new(TokioMutex::new(client)),
                    uri: Url::from_file_path(&file).unwrap(),
                    line: 0,
                    character: 5,
                    stalled,
                },
                timeout,
                &tx,
            );
            started
        });
        let reply = rx
            .recv_timeout(std::time::Duration::from_secs(30))
            .expect("prepareRename must always answer");
        let took = started.elapsed();
        drop(runtime);
        Some((reply, took))
    }

    /// The bug (#1677): a server that never answers prepareRename left F2 on
    /// "Preparing rename…" for good. Past the deadline the verdict is
    /// `unsupported`, which opens the word-under-cursor prompt.
    #[test]
    fn a_prepare_rename_the_server_never_answers_falls_back_after_the_deadline() {
        let deadline = std::time::Duration::from_millis(300);
        let stalled = Arc::new(AtomicBool::new(false));
        let Some((reply, took)) = prepare_rename_against("mute", deadline, stalled.clone()) else {
            eprintln!("SKIPPED: no python3 on PATH");
            return;
        };
        assert_eq!(reply.request_id, 7);
        assert!(
            reply.unsupported,
            "a timed-out prepare routes to the fallback prompt"
        );
        assert!(reply.error.is_none(), "a slow server is not a refusal");
        assert!(reply.target.is_none());
        assert!(
            took >= deadline,
            "the verdict must wait out the deadline, took {took:?}"
        );
        assert!(
            stalled.load(Ordering::Relaxed),
            "the expired request retires the server from prepareRename"
        );
    }

    /// A server retired by an earlier timeout is not asked again, so it
    /// cannot leak another abandoned request: F2 goes straight to the
    /// fallback prompt, without waiting out a deadline.
    #[test]
    fn a_retired_server_is_not_asked_to_prepare_a_rename_again() {
        let stalled = Arc::new(AtomicBool::new(true));
        let deadline = std::time::Duration::from_secs(20);
        let Some((reply, took)) = prepare_rename_against("range", deadline, stalled) else {
            eprintln!("SKIPPED: no python3 on PATH");
            return;
        };
        assert!(reply.unsupported, "a retired server routes to the fallback");
        assert!(
            reply.target.is_none(),
            "the answering server was never asked"
        );
        assert!(took < deadline, "no deadline is waited out, took {took:?}");
    }

    /// The deadline F2 runs with is short enough to feel like an answer and
    /// long enough for a busy server.
    #[test]
    fn the_prepare_rename_deadline_is_a_couple_of_seconds() {
        assert!(PREPARE_RENAME_TIMEOUT >= std::time::Duration::from_secs(1));
        assert!(PREPARE_RENAME_TIMEOUT <= std::time::Duration::from_secs(5));
    }

    /// Negative: a server that answers in time keeps its range and
    /// placeholder; the deadline only matters when no answer comes.
    #[test]
    fn a_prepare_rename_answered_in_time_keeps_the_servers_range() {
        let Some((reply, _)) = prepare_rename_against(
            "range",
            std::time::Duration::from_secs(20),
            Arc::new(AtomicBool::new(false)),
        ) else {
            eprintln!("SKIPPED: no python3 on PATH");
            return;
        };
        assert!(!reply.unsupported);
        assert!(reply.error.is_none());
        assert_eq!(
            reply.target,
            Some(((0, 4, 0, 9), Some(String::from("total"))))
        );
    }

    /// Negative: a server's refusal still fails fast with its own message,
    /// rather than being mistaken for a timeout and falling back.
    #[test]
    fn a_prepare_rename_refusal_is_not_turned_into_the_fallback() {
        let Some((reply, took)) = prepare_rename_against(
            "error",
            std::time::Duration::from_secs(20),
            Arc::new(AtomicBool::new(false)),
        ) else {
            eprintln!("SKIPPED: no python3 on PATH");
            return;
        };
        assert!(
            !reply.unsupported,
            "a refusal must not open the fallback prompt"
        );
        let error = reply.error.unwrap_or_default();
        assert!(
            error.starts_with("cannot rename a keyword"),
            "the server's own reason is shown: {error}"
        );
        assert!(
            took < std::time::Duration::from_secs(20),
            "a refusal answers at once, not at the deadline"
        );
    }

    /// Format Selection keeps whole-document formatting's always-answer
    /// contract (#254): an unroutable request still reports unsupported.
    #[test]
    fn an_unroutable_range_format_request_still_answers() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let (diag_tx, _diag_rx) = std_mpsc::channel();
        let (prog_tx, _prog_rx) = std_mpsc::channel();
        let (fmt_tx, fmt_rx) = std_mpsc::channel();
        let mut state = WorkerState {
            workspace_root: root.clone(),
            extra_roots: Vec::new(),
            registry: ServerRegistry::new(),
            clients: HashMap::new(),
            docs: HashMap::new(),
            capability_support: Arc::new(StdMutex::new(LangCapabilitySupport::default())),
            semantic_refresh: Arc::new(AtomicBool::new(false)),
            inlay_refresh: Arc::new(AtomicBool::new(false)),
            diagnostic_refresh: Arc::new(AtomicBool::new(false)),
            diagnostics_tx: diag_tx,
            progress_tx: prog_tx,
            restarts: ServerRestarts::default(),
        };
        let never_opened = root.join("stray.py");
        let runtime = LspRuntime::new().expect("runtime");
        runtime.handle().clone().block_on(async {
            state
                .request_range_formatting(
                    11,
                    never_opened.clone(),
                    (0, 0),
                    (2, 0),
                    4,
                    true,
                    &fmt_tx,
                )
                .await;
        });
        let reply = fmt_rx
            .try_recv()
            .expect("an untracked document must still get a reply");
        assert_eq!(reply.request_id, 11);
        assert!(reply.unsupported);
    }

    #[test]
    fn linked_editing_capability_shapes_gate_correctly() {
        use lsp_types::LinkedEditingRangeServerCapabilities as L;
        assert!(!linked_editing_supported(&None));
        assert!(!linked_editing_supported(&Some(L::Simple(false))));
        assert!(linked_editing_supported(&Some(L::Simple(true))));
        assert!(linked_editing_supported(&Some(L::Options(
            lsp_types::LinkedEditingRangeOptions::default()
        ))));
    }

    /// #607: the first inline completion with text is taken, a snippet as
    /// its plain text, and one whose range spans lines is skipped.
    #[test]
    fn the_first_usable_inline_completion_is_read_as_plain_text() {
        let item = |text: &str, lines: (u32, u32), snippet: bool| {
            serde_json::from_value::<lsp_types::InlineCompletionItem>(serde_json::json!({
                "insertText": text,
                "range": {
                    "start": {"line": lines.0, "character": 0},
                    "end": {"line": lines.1, "character": 3},
                },
                "insertTextFormat": if snippet { 2 } else { 1 },
            }))
            .unwrap()
        };
        let answer = lsp_types::InlineCompletionResponse::List(lsp_types::InlineCompletionList {
            items: vec![
                item("  ", (4, 4), false),
                item("two lines", (4, 5), false),
                item("foo(${1:x})$0", (4, 4), true),
            ],
        });
        assert_eq!(
            first_inline_item(answer),
            Some(InlineItem {
                text: String::from("foo(x)"),
                range: Some((4, 0, 4, 3)),
            })
        );
        let bare = serde_json::from_value(serde_json::json!([{"insertText": "bar"}])).unwrap();
        assert_eq!(
            first_inline_item(bare),
            Some(InlineItem {
                text: String::from("bar"),
                range: None,
            })
        );
    }

    #[test]
    fn folding_range_capability_shapes_gate_correctly() {
        use lsp_types::FoldingRangeProviderCapability as F;
        assert!(!folding_range_supported(&None));
        assert!(!folding_range_supported(&Some(F::Simple(false))));
        assert!(folding_range_supported(&Some(F::Simple(true))));
        assert!(folding_range_supported(&Some(F::FoldingProvider(
            lsp_types::FoldingProviderOptions {}
        ))));
        assert!(folding_range_supported(&Some(F::Options(
            lsp_types::StaticTextDocumentColorProviderOptions {
                document_selector: None,
                id: None,
            }
        ))));
    }

    #[test]
    fn normalise_folding_range_drops_empty_spans_and_maps_kinds() {
        let r = |start, end, kind| lsp_types::FoldingRange {
            start_line: start,
            start_character: None,
            end_line: end,
            end_character: None,
            kind,
            collapsed_text: None,
        };
        assert_eq!(normalise_folding_range(r(5, 5, None)), None);
        assert_eq!(normalise_folding_range(r(5, 4, None)), None);
        let got = normalise_folding_range(r(2, 9, Some(lsp_types::FoldingRangeKind::Region)))
            .expect("a real span survives");
        assert_eq!((got.start_line, got.end_line), (2, 9));
        assert_eq!(got.kind, FoldRangeKind::Region);
        assert_eq!(
            normalise_folding_range(r(0, 1, None)).map(|g| g.kind),
            Some(FoldRangeKind::Other)
        );
    }

    /// An unroutable folding-range request is SILENT — no reply at all —
    /// which is the two-phase contract: the editor keeps its
    /// indentation/region fallback unless a capable server answers.
    #[test]
    fn an_unroutable_folding_request_sends_nothing() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let (diag_tx, _diag_rx) = std_mpsc::channel();
        let (prog_tx, _prog_rx) = std_mpsc::channel();
        let (fold_tx, fold_rx) = std_mpsc::channel();
        let mut state = WorkerState {
            workspace_root: root.clone(),
            extra_roots: Vec::new(),
            registry: ServerRegistry::new(),
            clients: HashMap::new(),
            docs: HashMap::new(),
            capability_support: Arc::new(StdMutex::new(LangCapabilitySupport::default())),
            semantic_refresh: Arc::new(AtomicBool::new(false)),
            inlay_refresh: Arc::new(AtomicBool::new(false)),
            diagnostic_refresh: Arc::new(AtomicBool::new(false)),
            diagnostics_tx: diag_tx,
            progress_tx: prog_tx,
            restarts: ServerRestarts::default(),
        };
        let never_opened = root.join("stray.py");
        let runtime = LspRuntime::new().expect("runtime");
        runtime.handle().clone().block_on(async {
            state
                .request_folding_ranges(never_opened, 3, &fold_tx)
                .await;
        });
        assert!(
            fold_rx.try_recv().is_err(),
            "no reply may be sent for an untracked document"
        );
    }

    #[test]
    fn selection_range_capability_shapes_gate_correctly() {
        use lsp_types::SelectionRangeProviderCapability as S;
        assert!(!selection_range_supported(&None));
        assert!(!selection_range_supported(&Some(S::Simple(false))));
        assert!(selection_range_supported(&Some(S::Simple(true))));
        assert!(selection_range_supported(&Some(S::Options(
            lsp_types::SelectionRangeOptions {
                work_done_progress_options: Default::default(),
            }
        ))));
    }

    #[test]
    fn flatten_selection_chain_walks_parents_and_drops_repeats() {
        let range = |sl, sc, el, ec| lsp_types::Range {
            start: lsp_types::Position {
                line: sl,
                character: sc,
            },
            end: lsp_types::Position {
                line: el,
                character: ec,
            },
        };
        let chain = lsp_types::SelectionRange {
            range: range(1, 4, 1, 9),
            parent: Some(Box::new(lsp_types::SelectionRange {
                range: range(1, 4, 1, 9), // repeated link some servers emit
                parent: Some(Box::new(lsp_types::SelectionRange {
                    range: range(0, 0, 3, 0),
                    parent: None,
                })),
            })),
        };
        assert_eq!(
            flatten_selection_chain(&chain),
            vec![(1, 4, 1, 9), (0, 0, 3, 0)]
        );
    }

    /// An unroutable selectionRange request answers `unsupported` — the
    /// gesture is waiting on the reply, and the verdict is what routes it
    /// to the tree-sitter fallback instead of hanging.
    #[test]
    fn an_unroutable_selection_range_request_answers_unsupported() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let (diag_tx, _diag_rx) = std_mpsc::channel();
        let (prog_tx, _prog_rx) = std_mpsc::channel();
        let (sel_tx, sel_rx) = std_mpsc::channel();
        let mut state = WorkerState {
            workspace_root: root.clone(),
            extra_roots: Vec::new(),
            registry: ServerRegistry::new(),
            clients: HashMap::new(),
            docs: HashMap::new(),
            capability_support: Arc::new(StdMutex::new(LangCapabilitySupport::default())),
            semantic_refresh: Arc::new(AtomicBool::new(false)),
            inlay_refresh: Arc::new(AtomicBool::new(false)),
            diagnostic_refresh: Arc::new(AtomicBool::new(false)),
            diagnostics_tx: diag_tx,
            progress_tx: prog_tx,
            restarts: ServerRestarts::default(),
        };
        let never_opened = root.join("stray.py");
        let runtime = LspRuntime::new().expect("runtime");
        runtime.handle().clone().block_on(async {
            state
                .request_selection_ranges(9, never_opened.clone(), vec![(0, 0)], &sel_tx)
                .await;
        });
        let reply = sel_rx
            .try_recv()
            .expect("an untracked document must still get a verdict");
        assert_eq!(reply.request_id, 9);
        assert!(reply.unsupported);
        assert!(reply.chains.is_empty());
    }

    #[test]
    fn color_capability_shapes_and_channel_scaling() {
        use lsp_types::ColorProviderCapability as C;
        assert!(!color_provider_supported(&None));
        assert!(!color_provider_supported(&Some(C::Simple(false))));
        assert!(color_provider_supported(&Some(C::Simple(true))));
        let ci = lsp_types::ColorInformation {
            range: lsp_types::Range {
                start: lsp_types::Position {
                    line: 3,
                    character: 7,
                },
                end: lsp_types::Position {
                    line: 3,
                    character: 14,
                },
            },
            color: lsp_types::Color {
                red: 1.0,
                green: 0.5,
                blue: 0.0,
                alpha: 1.0,
            },
        };
        let item = color_item(&ci);
        assert_eq!((item.line, item.character), (3, 7));
        assert_eq!((item.red, item.green, item.blue), (255, 128, 0));
        assert_eq!(item.raw.3, 1.0);
    }

    /// The presentation picker defers on the reply, so an unroutable
    /// request must still answer — with an empty offering (#254).
    #[test]
    fn an_unroutable_color_presentation_request_answers_empty() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let (diag_tx, _diag_rx) = std_mpsc::channel();
        let (prog_tx, _prog_rx) = std_mpsc::channel();
        let (color_tx, color_rx) = std_mpsc::channel();
        let mut state = WorkerState {
            workspace_root: root.clone(),
            extra_roots: Vec::new(),
            registry: ServerRegistry::new(),
            clients: HashMap::new(),
            docs: HashMap::new(),
            capability_support: Arc::new(StdMutex::new(LangCapabilitySupport::default())),
            semantic_refresh: Arc::new(AtomicBool::new(false)),
            inlay_refresh: Arc::new(AtomicBool::new(false)),
            diagnostic_refresh: Arc::new(AtomicBool::new(false)),
            diagnostics_tx: diag_tx,
            progress_tx: prog_tx,
            restarts: ServerRestarts::default(),
        };
        let never_opened = root.join("stray.css");
        let runtime = LspRuntime::new().expect("runtime");
        runtime.handle().clone().block_on(async {
            state
                .request_color_presentations(
                    31,
                    never_opened.clone(),
                    (1.0, 0.0, 0.0, 1.0),
                    (0, 0),
                    (0, 7),
                    &color_tx,
                )
                .await;
        });
        let reply = color_rx.try_recv().expect("must answer");
        assert_eq!(reply.request_id, 31);
        assert!(reply.presentations.is_empty());
    }

    /// Minimal LSP server that answers `initialize` and appends every
    /// incoming method name to the log file given as argv[1]. Lets a test
    /// assert exactly which notifications croft put on the wire.
    ///
    /// It advertises the `CAPABILITIES` a test prepends to the script (none
    /// by default), and a `didSave` line also carries the notification's
    /// `text` as JSON, so a test can tell a bare save from one with the text.
    const FAKE_LSP_RECORDER: &str = r#"
import json, sys

log = open(sys.argv[1], "a")

def read_msg():
    length = None
    while True:
        line = sys.stdin.buffer.readline()
        if not line:
            return None
        line = line.strip()
        if not line:
            break
        if line.lower().startswith(b"content-length:"):
            length = int(line.split(b":")[1])
    if length is None:
        return None
    return json.loads(sys.stdin.buffer.read(length))

def send(msg):
    body = json.dumps(msg).encode()
    sys.stdout.buffer.write(b"Content-Length: %d\r\n\r\n" % len(body))
    sys.stdout.buffer.write(body)
    sys.stdout.buffer.flush()

while True:
    msg = read_msg()
    if msg is None:
        break
    method = msg.get("method", "")
    if method == "textDocument/didSave":
        log.write(method + " " + json.dumps(msg["params"].get("text")) + "\n")
    else:
        log.write(method + "\n")
    log.flush()
    if "id" in msg:
        if method == "initialize":
            capabilities = globals().get("CAPABILITIES", {})
            send({"jsonrpc": "2.0", "id": msg["id"], "result": {"capabilities": capabilities}})
        else:
            send({"jsonrpc": "2.0", "id": msg["id"], "result": None})
    if method == "exit":
        break
"#;

    /// #694: restarts are budgeted per (language, root), so a server that
    /// dies on every start cannot respawn on every keystroke.
    #[test]
    fn server_restarts_are_budgeted_per_window() {
        let mut restarts = ServerRestarts::default();
        let key: ClientKey = (Language::PYTHON, PathBuf::from("/w"));
        let other: ClientKey = (Language::PYTHON, PathBuf::from("/other"));
        let t0 = Instant::now();
        for i in 0..MAX_RESTARTS {
            assert!(
                restarts.try_restart(&key, t0),
                "restart {i} is within budget"
            );
        }
        assert!(!restarts.try_restart(&key, t0), "one more is refused");
        assert!(restarts.gave_up.contains(&key));
        // The budget is per key: another root is unaffected.
        assert!(restarts.try_restart(&other, t0));
        // Attempts age out of the window.
        let mut fresh = ServerRestarts::default();
        for _ in 0..MAX_RESTARTS {
            fresh.try_restart(&key, t0);
        }
        assert!(fresh.try_restart(&key, t0 + RESTART_WINDOW + Duration::from_secs(1)));
    }

    /// A stub rust-analyzer (#1626): answers `initialize`, logs each
    /// method, and answers `rust-analyzer/expandMacro` with an expansion.
    const FAKE_RUST_ANALYZER: &str = r#"
import json, sys

log = open(sys.argv[1], "a")

def read_msg():
    length = None
    while True:
        line = sys.stdin.buffer.readline()
        if not line:
            return None
        line = line.strip()
        if not line:
            break
        if line.lower().startswith(b"content-length:"):
            length = int(line.split(b":")[1])
    if length is None:
        return None
    return json.loads(sys.stdin.buffer.read(length))

def send(msg):
    body = json.dumps(msg).encode()
    sys.stdout.buffer.write(b"Content-Length: %d\r\n\r\n" % len(body))
    sys.stdout.buffer.write(body)
    sys.stdout.buffer.flush()

while True:
    msg = read_msg()
    if msg is None:
        break
    method = msg.get("method", "")
    log.write(method + " " + json.dumps(msg.get("params")) + "\n")
    log.flush()
    if "id" in msg:
        if method == "initialize":
            result = {"capabilities": {}}
        elif method == "rust-analyzer/expandMacro":
            result = {"name": "sq", "expansion": "(2 + 1) * (2 + 1)"}
        else:
            result = None
        send({"jsonrpc": "2.0", "id": msg["id"], "result": result})
    if method == "exit":
        break
"#;

    /// A worker for `root` whose only Rust server is `name`, run as the
    /// stub rust-analyzer logging to `log`.
    fn worker_with_rust_server(
        python: &Path,
        root: &Path,
        name: &'static str,
        log: &Path,
    ) -> WorkerState {
        worker_with_rust_stub(python, root, name, log, FAKE_RUST_ANALYZER)
    }

    /// [`worker_with_rust_server`] with the stub `source` as the server.
    fn worker_with_rust_stub(
        python: &Path,
        root: &Path,
        name: &'static str,
        log: &Path,
        source: &str,
    ) -> WorkerState {
        let script = root.join("fake_ra.py");
        std::fs::write(&script, source).expect("write fake server");
        let mut registry = ServerRegistry::new();
        registry.register(
            Language::RUST,
            ServerConfig {
                name,
                command: python.display().to_string(),
                args: vec![script.display().to_string(), log.display().to_string()],
                language: Language::RUST,
                initialization_options: None,
                provision: None,
            },
        );
        let (diag_tx, _diag_rx) = std_mpsc::channel();
        let (prog_tx, _prog_rx) = std_mpsc::channel();
        WorkerState {
            workspace_root: root.to_path_buf(),
            extra_roots: Vec::new(),
            registry,
            clients: HashMap::new(),
            docs: HashMap::new(),
            capability_support: Arc::new(StdMutex::new(LangCapabilitySupport::default())),
            semantic_refresh: Arc::new(AtomicBool::new(false)),
            inlay_refresh: Arc::new(AtomicBool::new(false)),
            diagnostic_refresh: Arc::new(AtomicBool::new(false)),
            diagnostics_tx: diag_tx,
            progress_tx: prog_tx,
            restarts: ServerRestarts::default(),
        }
    }

    /// #1626: Expand Macro goes to rust-analyzer as its own method, with the
    /// document and caret, and its raw answer comes back to the app.
    #[cfg(unix)]
    #[test]
    fn a_rust_analyzer_request_reaches_it_and_its_answer_comes_back() {
        use crate::lsp::rust_analyzer::RaRequest;
        let Some(python) = python_for_stub_server() else {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        };
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let file = root.join("main.rs");
        std::fs::write(&file, "fn main() {}\n").expect("write main.rs");
        let log = root.join("methods.log");
        let mut state = worker_with_rust_server(&python, &root, "rust-analyzer", &log);
        let runtime = LspRuntime::new().expect("runtime");
        let handle = runtime.handle().clone();
        handle.block_on(state.open_doc(file.clone(), String::from("fn main() {}\n")));
        let (tx, rx) = std_mpsc::channel();
        handle.block_on(state.request_rust_analyzer(
            7,
            file.clone(),
            RaRequest::ExpandMacro,
            (0, 3),
            &tx,
        ));
        let got = rx
            .recv_timeout(crate::test_budget::spawn_budget(Duration::from_secs(10)))
            .expect("an answer");
        assert_eq!(got.request_id, 7);
        assert_eq!(got.request, RaRequest::ExpandMacro);
        let value = got.outcome.expect("the stub answers");
        assert_eq!(
            crate::lsp::rust_analyzer::expansion(&value),
            Some((String::from("sq"), String::from("(2 + 1) * (2 + 1)")))
        );
        let sent = std::fs::read_to_string(&log).unwrap_or_default();
        let line = sent
            .lines()
            .find(|l| l.starts_with("rust-analyzer/expandMacro "))
            .unwrap_or_else(|| panic!("the method was sent:\n{sent}"));
        assert!(
            line.contains("\"line\": 0") && line.contains("\"character\": 3"),
            "{line}"
        );
    }

    /// #1626 negative: a Rust server that is not rust-analyzer is never sent
    /// its methods; the request answers "not running" at once.
    #[cfg(unix)]
    #[test]
    fn a_rust_analyzer_request_never_goes_to_another_server() {
        use crate::lsp::rust_analyzer::RaRequest;
        let Some(python) = python_for_stub_server() else {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        };
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let file = root.join("main.rs");
        std::fs::write(&file, "fn main() {}\n").expect("write main.rs");
        let log = root.join("methods.log");
        let mut state = worker_with_rust_server(&python, &root, "other-rust-server", &log);
        let runtime = LspRuntime::new().expect("runtime");
        let handle = runtime.handle().clone();
        handle.block_on(state.open_doc(file.clone(), String::from("fn main() {}\n")));
        let (tx, rx) = std_mpsc::channel();
        handle.block_on(state.request_rust_analyzer(
            8,
            file.clone(),
            RaRequest::ExpandMacro,
            (0, 3),
            &tx,
        ));
        let got = rx.recv_timeout(Duration::from_secs(5)).expect("an answer");
        assert_eq!(
            got.outcome,
            Err(String::from("rust-analyzer is not running for this file"))
        );
        let sent = std::fs::read_to_string(&log).unwrap_or_default();
        assert!(!sent.contains("rust-analyzer/"), "{sent}");
        // And a file that is not open answers the same way.
        handle.block_on(state.request_rust_analyzer(
            9,
            root.join("other.rs"),
            RaRequest::ExpandMacro,
            (0, 0),
            &tx,
        ));
        let got = rx.recv_timeout(Duration::from_secs(5)).expect("an answer");
        assert!(got.outcome.is_err());
    }

    /// A stub server that, once initialized, registers a `**/*.rs` watcher
    /// (#908). It logs each method with its params, and each reply croft
    /// sends it as `reply <error>`.
    const FAKE_LSP_WATCHING: &str = r#"
import json, sys

log = open(sys.argv[1], "a")

def read_msg():
    length = None
    while line := sys.stdin.buffer.readline().strip():
        if line.lower().startswith(b"content-length:"):
            length = int(line.split(b":")[1])
    return None if length is None else json.loads(sys.stdin.buffer.read(length))

def send(msg):
    body = json.dumps(msg).encode()
    sys.stdout.buffer.write(b"Content-Length: %d\r\n\r\n%s" % (len(body), body))
    sys.stdout.buffer.flush()

while (msg := read_msg()) is not None:
    method = msg.get("method")
    if method is None:
        log.write("reply " + json.dumps(msg.get("error")) + "\n")
    else:
        log.write(method + " " + json.dumps(msg.get("params")) + "\n")
    log.flush()
    if method == "initialized":
        watchers = [{"globPattern": "**/*.rs"}]
        registration = {"id": "rs", "method": "workspace/didChangeWatchedFiles",
                        "registerOptions": {"watchers": watchers}}
        send({"jsonrpc": "2.0", "id": "watch", "method": "client/registerCapability",
              "params": {"registrations": [registration]}})
    elif method and "id" in msg:
        result = {"capabilities": {}} if method == "initialize" else None
        send({"jsonrpc": "2.0", "id": msg["id"], "result": result})
    if method == "exit":
        break
"#;

    /// #908: a server that registered watchers hears about the files changed
    /// on disk that they cover, a file that is gone as deleted, and nothing
    /// about a document it has open, which reaches it through didChange.
    #[cfg(unix)]
    #[test]
    fn disk_changes_reach_the_servers_watching_them() {
        let Some(python) = python_for_stub_server() else {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        };
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let [open, lib, gone, notes] =
            ["main.rs", "lib.rs", "gone.rs", "notes.md"].map(|f| root.join(f));
        for f in [&open, &lib, &notes] {
            std::fs::write(f, "\n").expect("write file");
        }
        let log = root.join("methods.log");
        let mut state =
            worker_with_rust_stub(&python, &root, "rust-analyzer", &log, FAKE_LSP_WATCHING);
        let runtime = LspRuntime::new().expect("runtime");
        let handle = runtime.handle().clone();
        handle.block_on(state.open_doc(open.clone(), String::from("\n")));
        let sent = || std::fs::read_to_string(&log).unwrap_or_default();
        crate::test_budget::await_spawned(
            Duration::from_millis(500),
            "croft to accept the watcher registration",
            || sent().contains("reply null"),
        );
        let _in_runtime = handle.enter();
        let changed =
            [&open, &lib, &gone, &notes].map(|p| (p.clone(), lsp_types::FileChangeType::CHANGED));
        state.did_change_watched_files(changed.to_vec());
        let method = "workspace/didChangeWatchedFiles ";
        crate::test_budget::await_spawned(
            Duration::from_millis(500),
            "the watched-files notification",
            || sent().contains(method),
        );
        let log = sent();
        let line = log.lines().find_map(|l| l.strip_prefix(method));
        let uri = |p: &Path| Url::from_file_path(p).expect("uri").to_string();
        assert_eq!(
            serde_json::from_str::<serde_json::Value>(line.expect("sent")).expect("params"),
            serde_json::json!({ "changes": [
                { "uri": uri(&lib), "type": 2 },
                { "uri": uri(&gone), "type": 3 },
            ]})
        );
    }

    /// A worker whose python and go servers are fake recorders that log
    /// their pid to `<root>/<lang>.pids` (#1621).
    fn two_language_worker(root: &Path, python: &Path) -> (WorkerState, Arc<AtomicBool>) {
        let script = root.join("fake_lsp.py");
        std::fs::write(
            &script,
            format!(
                "import os, sys\nopen(sys.argv[2], 'a').write(str(os.getpid()) + '\\n')\n{FAKE_LSP_RECORDER}"
            ),
        )
        .expect("write fake server");
        let mut registry = ServerRegistry::new();
        for (lang, name, tag) in [
            (Language::PYTHON, "fake-python", "python"),
            (Language::GO, "fake-go", "go"),
        ] {
            registry.register(
                lang,
                ServerConfig {
                    name,
                    command: python.display().to_string(),
                    args: vec![
                        script.display().to_string(),
                        root.join(format!("{tag}.log")).display().to_string(),
                        root.join(format!("{tag}.pids")).display().to_string(),
                    ],
                    language: lang,
                    initialization_options: None,
                    provision: None,
                },
            );
        }
        let restarted = Arc::new(AtomicBool::new(false));
        let (diag_tx, _diag_rx) = std_mpsc::channel();
        let (prog_tx, _prog_rx) = std_mpsc::channel();
        let state = WorkerState {
            workspace_root: root.to_path_buf(),
            extra_roots: Vec::new(),
            registry,
            clients: HashMap::new(),
            docs: HashMap::new(),
            capability_support: Arc::new(StdMutex::new(LangCapabilitySupport::default())),
            semantic_refresh: Arc::new(AtomicBool::new(false)),
            inlay_refresh: Arc::new(AtomicBool::new(false)),
            diagnostic_refresh: Arc::new(AtomicBool::new(false)),
            diagnostics_tx: diag_tx,
            progress_tx: prog_tx,
            restarts: ServerRestarts::reporting_to(restarted.clone()),
        };
        (state, restarted)
    }

    /// The pids a fake server of `tag` has logged under `root`, waiting up to
    /// ten seconds for `n` of them.
    fn logged_pids(root: &Path, tag: &str, n: usize) -> Vec<i32> {
        let deadline = Instant::now() + Duration::from_secs(10);
        loop {
            let seen: Vec<i32> = std::fs::read_to_string(root.join(format!("{tag}.pids")))
                .unwrap_or_default()
                .lines()
                .filter_map(|l| l.trim().parse().ok())
                .collect();
            if seen.len() >= n || Instant::now() >= deadline {
                return seen;
            }
            std::thread::sleep(Duration::from_millis(50));
        }
    }

    /// Whether process `pid` is gone, waiting up to ten seconds for it.
    fn process_exits(pid: i32) -> bool {
        let deadline = Instant::now() + Duration::from_secs(10);
        loop {
            // SAFETY: signal 0 only asks whether the pid exists.
            if unsafe { libc::kill(pid, 0) } != 0 {
                return true;
            }
            if Instant::now() >= deadline {
                return false;
            }
            std::thread::sleep(Duration::from_millis(50));
        }
    }

    /// #1621: "Restart for This File" stops the file's server and starts a
    /// new one, even one croft had given up on, and leaves the servers of
    /// other languages running.
    #[cfg(unix)]
    #[test]
    fn restarting_a_file_s_servers_leaves_other_languages_running() {
        let Some(python) = python_for_stub_server() else {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        };
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let py = root.join("demo.py");
        let go = root.join("main.go");
        std::fs::write(&py, "x = 1\n").unwrap();
        std::fs::write(&go, "package main\n").unwrap();
        let (mut state, restarted) = two_language_worker(&root, &python);
        let (diag_tx, diag_rx) = std_mpsc::channel();
        state.diagnostics_tx = diag_tx;
        let runtime = LspRuntime::new().expect("runtime");
        let handle = runtime.handle().clone();
        handle.block_on(state.open_doc(py.clone(), String::from("x = 1\n")));
        handle.block_on(state.open_doc(go.clone(), String::from("package main\n")));
        let first_py = logged_pids(&root, "python", 1);
        let first_go = logged_pids(&root, "go", 1);
        assert_eq!((first_py.len(), first_go.len()), (1, 1));
        // A key croft gave up on after a crash loop still restarts on request.
        let py_key: ClientKey = (Language::PYTHON, root.clone());
        state.restarts.gave_up.insert(py_key.clone());

        handle.block_on(state.restart_servers_for(&py));
        let py_pids = logged_pids(&root, "python", 2);
        assert_eq!(py_pids.len(), 2, "a new python server started");
        assert!(process_exits(py_pids[0]), "the old python server exited");
        assert!(
            restarted.load(Ordering::Relaxed),
            "the app re-opens its tabs"
        );
        assert!(!state.docs.contains_key(&py), "the new server never saw it");
        let withdrawn: Vec<DiagnosticsUpdate> = diag_rx.try_iter().collect();
        assert!(
            withdrawn
                .iter()
                .any(|u| u.path == py && u.server == "fake-python" && u.diagnostics.is_empty()),
            "the old server's diagnostics are withdrawn: {withdrawn:?}"
        );
        assert!(
            !withdrawn.iter().any(|u| u.path == go),
            "go keeps its diagnostics"
        );
        assert!(
            state.clients[&py_key]
                .iter()
                .all(|m| m.client.try_lock().is_ok_and(|c| !c.has_exited()))
        );
        assert!(!state.restarts.gave_up.contains(&py_key));

        std::thread::sleep(Duration::from_millis(300));
        assert_eq!(
            logged_pids(&root, "go", 1),
            first_go,
            "go was not restarted"
        );
        // SAFETY: signal 0 only asks whether the pid exists.
        assert_eq!(unsafe { libc::kill(first_go[0], 0) }, 0, "go still runs");
        assert!(state.docs.contains_key(&go), "go keeps its document");
    }

    /// #1621: a file whose document is not open restarts only the servers
    /// of its own project root, not every root of its language.
    #[cfg(unix)]
    #[test]
    fn restarting_for_an_unopened_file_restarts_only_its_root() {
        let Some(python) = python_for_stub_server() else {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        };
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let (a, b) = (root.join("a"), root.join("b"));
        for dir in [&a, &b] {
            std::fs::create_dir_all(dir).unwrap();
            std::fs::write(dir.join("pyproject.toml"), "").unwrap();
        }
        let (in_a, in_b) = (a.join("x.py"), b.join("y.py"));
        let (mut state, _restarted) = two_language_worker(&root, &python);
        let runtime = LspRuntime::new().expect("runtime");
        let handle = runtime.handle().clone();
        handle.block_on(state.open_doc(in_a.clone(), String::from("x = 1\n")));
        let first_a = logged_pids(&root, "python", 1);
        handle.block_on(state.open_doc(in_b.clone(), String::from("y = 1\n")));
        let both = logged_pids(&root, "python", 2);
        assert_eq!((first_a.len(), both.len()), (1, 2));
        let first_b = both[1];
        // As when its open failed: the worker holds no document for it.
        state.docs.remove(&in_a);

        handle.block_on(state.restart_servers_for(&in_a));
        let pids = logged_pids(&root, "python", 3);
        assert_eq!(pids.len(), 3, "root a's server started again");
        assert!(process_exits(first_a[0]), "root a's old server exited");
        std::thread::sleep(Duration::from_millis(300));
        assert_eq!(logged_pids(&root, "python", 3).len(), 3);
        // SAFETY: signal 0 only asks whether the pid exists.
        assert_eq!(unsafe { libc::kill(first_b, 0) }, 0, "root b still runs");
        assert!(state.docs.contains_key(&in_b), "root b keeps its document");
    }

    /// Negative (#1621): a file no server serves restarts nothing.
    #[cfg(unix)]
    #[test]
    fn restarting_for_a_file_no_server_serves_restarts_nothing() {
        let Some(python) = python_for_stub_server() else {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        };
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let py = root.join("demo.py");
        std::fs::write(&py, "x = 1\n").unwrap();
        let (mut state, restarted) = two_language_worker(&root, &python);
        let runtime = LspRuntime::new().expect("runtime");
        let handle = runtime.handle().clone();
        handle.block_on(state.open_doc(py.clone(), String::from("x = 1\n")));
        let first = logged_pids(&root, "python", 1);
        handle.block_on(state.restart_servers_for(&root.join("notes.txt")));
        std::thread::sleep(Duration::from_millis(300));
        assert_eq!(logged_pids(&root, "python", 1), first);
        assert!(!restarted.load(Ordering::Relaxed));
        assert!(state.docs.contains_key(&py));
    }

    /// #1842: an extension added, removed or toggled mid-session hands the
    /// worker a new registry. The servers of a language it changes stop, and
    /// that language's next open starts what is registered now; a language
    /// it leaves alone keeps its servers running. Each time the app is told
    /// to re-open its tabs, since one the old registry served nothing for
    /// was never opened here.
    #[cfg(unix)]
    #[test]
    fn a_new_registry_restarts_only_the_languages_it_changes() {
        let Some(python) = python_for_stub_server() else {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        };
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let py = root.join("demo.py");
        let go = root.join("main.go");
        std::fs::write(&py, "x = 1\n").unwrap();
        std::fs::write(&go, "package main\n").unwrap();
        let (mut state, restarted) = two_language_worker(&root, &python);
        let (diag_tx, diag_rx) = std_mpsc::channel();
        state.diagnostics_tx = diag_tx;
        let python_server = state.registry.for_language(Language::PYTHON)[0].clone();
        let go_server = state.registry.for_language(Language::GO)[0].clone();
        let runtime = LspRuntime::new().expect("runtime");
        let handle = runtime.handle().clone();
        handle.block_on(state.open_doc(py.clone(), String::from("x = 1\n")));
        handle.block_on(state.open_doc(go.clone(), String::from("package main\n")));
        let first_py = logged_pids(&root, "python", 1);
        let first_go = logged_pids(&root, "go", 1);
        assert_eq!((first_py.len(), first_go.len()), (1, 1));

        // Python's extension turned off: only go's server is registered.
        let mut go_only = ServerRegistry::new();
        go_only.register(Language::GO, go_server.clone());
        handle.block_on(state.replace_registry(go_only));
        assert!(process_exits(first_py[0]), "python's server stopped");
        assert!(
            restarted.swap(false, Ordering::Relaxed),
            "tabs go out again"
        );
        assert!(!state.docs.contains_key(&py));
        let withdrawn: Vec<DiagnosticsUpdate> = diag_rx.try_iter().collect();
        assert!(
            withdrawn
                .iter()
                .any(|u| u.path == py && u.server == "fake-python" && u.diagnostics.is_empty()),
            "its diagnostics are withdrawn: {withdrawn:?}"
        );
        assert!(!withdrawn.iter().any(|u| u.path == go), "go keeps its own");
        handle.block_on(state.open_doc(py.clone(), String::from("x = 1\n")));
        std::thread::sleep(Duration::from_millis(300));
        assert_eq!(logged_pids(&root, "python", 1), first_py, "none starts");
        assert!(!state.docs.contains_key(&py));

        // Turned back on: the next open starts it.
        let mut both = ServerRegistry::new();
        both.register(Language::PYTHON, python_server);
        both.register(Language::GO, go_server);
        handle.block_on(state.replace_registry(both));
        assert!(restarted.load(Ordering::Relaxed), "tabs go out again");
        handle.block_on(state.open_doc(py.clone(), String::from("x = 1\n")));
        assert_eq!(logged_pids(&root, "python", 2).len(), 2, "python starts");
        assert!(state.docs.contains_key(&py));

        assert_eq!(logged_pids(&root, "go", 1), first_go, "go never restarted");
        // SAFETY: signal 0 only asks whether the pid exists.
        assert_eq!(unsafe { libc::kill(first_go[0], 0) }, 0, "go still runs");
        assert!(state.docs.contains_key(&go), "go keeps its document");
        handle.block_on(state.shutdown_all());
    }

    /// #1842: an added extension that maps an open file to a language of its
    /// own takes the file off its old language's servers, though their set
    /// did not change, so the app's re-open reaches the new language as an
    /// open rather than as a change to the old one.
    #[cfg(unix)]
    #[test]
    fn a_file_an_added_extension_claims_leaves_its_old_servers() {
        let Some(python) = python_for_stub_server() else {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        };
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let py = root.join("demo.py");
        std::fs::write(&py, "x = 1\n").unwrap();
        let (mut state, _restarted) = two_language_worker(&root, &python);
        let same = |state: &WorkerState| {
            let mut r = ServerRegistry::new();
            for lang in [Language::PYTHON, Language::GO] {
                r.register(lang, state.registry.for_language(lang)[0].clone());
            }
            r
        };
        let runtime = LspRuntime::new().expect("runtime");
        let handle = runtime.handle().clone();
        handle.block_on(state.open_doc(py.clone(), String::from("x = 1\n")));
        let first = logged_pids(&root, "python", 1);
        assert_eq!(first.len(), 1);

        // The worker runs on this thread here, so it reads this table.
        crate::lsp::languages::reload_with_user_sources(&[
            "id = \"snake\"\nname = \"Snake\"\napi_version = 1\n\n[[languages]]\nid = \"snake\"\nextensions = [\"py\"]\n",
        ]);
        let registry = same(&state);
        handle.block_on(state.replace_registry(registry));
        assert!(!state.docs.contains_key(&py), "off python's servers");
        let log = root.join("python.log");
        crate::test_budget::await_spawned(Duration::from_secs(5), "the didClose", || {
            std::fs::read_to_string(&log).is_ok_and(|l| l.contains("textDocument/didClose"))
        });
        // SAFETY: signal 0 only asks whether the pid exists.
        assert_eq!(unsafe { libc::kill(first[0], 0) }, 0, "python still runs");
        handle.block_on(state.open_doc(py.clone(), String::from("x = 1\n")));
        assert!(!state.docs.contains_key(&py), "snake has no server");
        handle.block_on(state.shutdown_all());
    }

    /// #694: a language server the kernel kills (croft makes them its first
    /// OOM victims) comes back on the next command, its documents are
    /// forgotten, and the app is told to re-open its tabs.
    #[cfg(unix)]
    #[test]
    fn a_killed_language_server_is_restarted() {
        let Some(python) = python_for_stub_server() else {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        };
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let file = root.join("demo.py");
        std::fs::write(&file, "x = 1\n").expect("write demo");
        let script = root.join("fake_lsp.py");
        let pids = root.join("pids.log");
        std::fs::write(
            &script,
            format!(
                "import os, sys\nopen(sys.argv[2], 'a').write(str(os.getpid()) + '\\n')\n{FAKE_LSP_RECORDER}"
            ),
        )
        .expect("write fake server");
        let log = root.join("methods.log");
        let mut registry = ServerRegistry::new();
        registry.register(
            Language::PYTHON,
            ServerConfig {
                name: "fake-recorder",
                command: python.display().to_string(),
                args: vec![
                    script.display().to_string(),
                    log.display().to_string(),
                    pids.display().to_string(),
                ],
                language: Language::PYTHON,
                initialization_options: None,
                provision: None,
            },
        );
        let restarted = Arc::new(AtomicBool::new(false));
        let (diag_tx, _diag_rx) = std_mpsc::channel();
        let (prog_tx, _prog_rx) = std_mpsc::channel();
        let mut state = WorkerState {
            workspace_root: root.clone(),
            extra_roots: Vec::new(),
            registry,
            clients: HashMap::new(),
            docs: HashMap::new(),
            capability_support: Arc::new(StdMutex::new(LangCapabilitySupport::default())),
            semantic_refresh: Arc::new(AtomicBool::new(false)),
            inlay_refresh: Arc::new(AtomicBool::new(false)),
            diagnostic_refresh: Arc::new(AtomicBool::new(false)),
            diagnostics_tx: diag_tx,
            progress_tx: prog_tx,
            restarts: ServerRestarts::reporting_to(restarted.clone()),
        };
        let key: ClientKey = (Language::PYTHON, root.clone());
        let started = |n: usize| {
            let deadline = Instant::now() + Duration::from_secs(10);
            loop {
                let seen: Vec<i32> = std::fs::read_to_string(&pids)
                    .unwrap_or_default()
                    .lines()
                    .filter_map(|l| l.trim().parse().ok())
                    .collect();
                if seen.len() >= n || Instant::now() >= deadline {
                    return seen;
                }
                std::thread::sleep(Duration::from_millis(50));
            }
        };

        let runtime = LspRuntime::new().expect("runtime");
        let handle = runtime.handle().clone();
        handle.block_on(state.open_doc(file.clone(), String::from("x = 1\n")));
        let first = started(1);
        assert_eq!(first.len(), 1, "the server must have started once");
        assert!(state.docs.contains_key(&file));

        // What the OOM killer does.
        // SAFETY: plain kill(2) on a pid this test's server wrote.
        unsafe {
            libc::kill(first[0], libc::SIGKILL);
        }
        let deadline = Instant::now() + Duration::from_secs(10);
        while !state.clients[&key]
            .iter()
            .all(|m| m.client.try_lock().is_ok_and(|c| c.has_exited()))
        {
            assert!(
                Instant::now() < deadline,
                "the client never noticed the kill"
            );
            std::thread::sleep(Duration::from_millis(50));
        }

        handle.block_on(state.restart_dead_servers());
        let both = started(2);
        assert_eq!(both.len(), 2, "a new server must have been started");
        assert_ne!(both[0], both[1]);
        assert!(
            restarted.load(Ordering::Relaxed),
            "the app must be told to re-open its tabs"
        );
        assert!(
            !state.docs.contains_key(&file),
            "the new server never saw the old documents"
        );
        assert!(
            state.clients[&key]
                .iter()
                .all(|m| m.client.try_lock().is_ok_and(|c| !c.has_exited())),
            "the restarted client must be alive"
        );
        // A live server is left alone: no third start.
        restarted.store(false, Ordering::Relaxed);
        handle.block_on(state.restart_dead_servers());
        std::thread::sleep(Duration::from_millis(300));
        assert_eq!(started(2).len(), 2);
        assert!(!restarted.load(Ordering::Relaxed));

        // The app re-sends every tab after a restart. The first open reaches
        // the new server as didOpen; a repeat is a change, not a second open.
        handle.block_on(state.open_doc(file.clone(), String::from("x = 1\n")));
        handle.block_on(state.open_doc(file.clone(), String::from("x = 2\n")));
        let deadline = Instant::now() + Duration::from_secs(10);
        let methods = loop {
            let text = std::fs::read_to_string(&log).unwrap_or_default();
            if text.contains("textDocument/didChange") || Instant::now() >= deadline {
                break text;
            }
            std::thread::sleep(Duration::from_millis(50));
        };
        // Both servers share the log; count only what the new one received.
        let new_server = methods.rsplit("initialize\n").next().unwrap_or_default();
        assert_eq!(
            new_server.matches("textDocument/didOpen").count(),
            1,
            "a document is opened once per server: {methods:?}"
        );
        assert!(new_server.contains("textDocument/didChange"), "{methods:?}");
        handle.block_on(state.shutdown_all());

        // A key that used up its restarts is not re-probed through an empty
        // client list either.
        state.restarts.gave_up.insert(key.clone());
        state.clients.insert(key.clone(), Vec::new());
        handle.block_on(state.ensure_clients(key.0, &key.1));
        std::thread::sleep(Duration::from_millis(300));
        assert_eq!(started(2).len(), 2, "a given-up server must stay down");

        // An empty list that comes back (a restart whose spawn failed, then a
        // later re-probe that works) must tell the app too: it already sent
        // its tabs into the empty list, so the new server never saw them.
        state.restarts.gave_up.remove(&key);
        restarted.store(false, Ordering::Relaxed);
        handle.block_on(state.ensure_clients(key.0, &key.1));
        assert_eq!(started(3).len(), 3, "the empty list must be re-probed");
        assert!(
            restarted.load(Ordering::Relaxed),
            "a recovered empty list must make the app re-open its tabs"
        );
        handle.block_on(state.shutdown_all());

        // A restart that loses a server which ran before it is tried again as
        // a set, not left short a server until croft restarts. The flaky
        // server runs until its flag file exists, then fails at launch.
        let flag = root.join("flaky.off");
        let flaky = root.join("flaky_lsp.py");
        std::fs::write(
            &flaky,
            format!(
                "import os, sys\nif os.path.exists({:?}): sys.exit(1)\n{}",
                flag.display().to_string(),
                std::fs::read_to_string(&script).expect("read fake server")
            ),
        )
        .expect("write flaky server");
        state.registry.register(
            Language::PYTHON,
            ServerConfig {
                name: "fake-flaky",
                command: python.display().to_string(),
                args: vec![
                    flaky.display().to_string(),
                    log.display().to_string(),
                    pids.display().to_string(),
                ],
                language: Language::PYTHON,
                initialization_options: None,
                provision: None,
            },
        );
        let kill_one = |state: &WorkerState, pid: i32| {
            // SAFETY: plain kill(2) on a pid this test's server wrote.
            unsafe {
                libc::kill(pid, libc::SIGKILL);
            }
            let deadline = Instant::now() + Duration::from_secs(10);
            while !state.clients[&key]
                .iter()
                .any(|m| m.client.try_lock().is_ok_and(|c| c.has_exited()))
            {
                assert!(
                    Instant::now() < deadline,
                    "the client never noticed the kill"
                );
                std::thread::sleep(Duration::from_millis(50));
            }
        };

        // A server that never came up is not one a restart lost: the others
        // are restarted once for their own crash, and then left alone.
        std::fs::write(&flag, "").expect("write flag");
        state.restarts.attempts.clear();
        state.clients.remove(&key);
        handle.block_on(state.ensure_clients(key.0, &key.1));
        let pid = *started(4).last().expect("recorder pid");
        assert_eq!(state.clients[&key].len(), 1, "only the recorder came up");
        kill_one(&state, pid);
        handle.block_on(state.restart_dead_servers());
        assert_eq!(started(5).len(), 5);
        assert!(
            !state.restarts.incomplete.contains_key(&key),
            "a server that never ran must not make the set incomplete"
        );
        handle.block_on(state.restart_dead_servers());
        std::thread::sleep(Duration::from_millis(300));
        assert_eq!(started(0).len(), 5, "a live set is not restarted again");
        handle.block_on(state.shutdown_all());

        // Both run; one crashes and the flaky one does not come back.
        std::fs::remove_file(&flag).expect("remove flag");
        state.restarts.attempts.clear();
        state.clients.remove(&key);
        handle.block_on(state.ensure_clients(key.0, &key.1));
        let pid = *started(7).last().expect("server pid");
        assert_eq!(state.clients[&key].len(), 2, "both servers came up");
        assert!(!state.restarts.incomplete.contains_key(&key));
        std::fs::write(&flag, "").expect("write flag");
        kill_one(&state, pid);
        restarted.store(false, Ordering::Relaxed);
        handle.block_on(state.restart_dead_servers());
        assert_eq!(started(8).len(), 8);
        assert_eq!(state.clients[&key].len(), 1, "only the recorder came back");
        assert!(restarted.load(Ordering::Relaxed));
        assert!(state.restarts.incomplete.contains_key(&key));
        handle.block_on(state.restart_dead_servers());
        assert_eq!(started(9).len(), 9, "a short set must be restarted");
        assert!(
            state.restarts.incomplete.contains_key(&key),
            "a restart that comes back short again must stay marked"
        );

        // A restart that brought nothing back leaves an empty list, which
        // every request re-probes. Those re-probes spend the restart budget,
        // so the servers stop being launched once it is gone.
        state.restarts.incomplete.remove(&key);
        let before = started(0).len();
        for _ in 0..MAX_RESTARTS + 2 {
            state.clients.insert(key.clone(), Vec::new());
            handle.block_on(state.ensure_clients(key.0, &key.1));
        }
        let launched = started(0).len() - before;
        assert!(
            launched < MAX_RESTARTS + 2,
            "re-probes past the budget must not launch servers ({launched})"
        );
        assert!(state.restarts.gave_up.contains(&key));
        handle.block_on(state.shutdown_all());
    }

    /// The `initialize` params a language server is sent for a workspace at
    /// `dir_name` under a temp dir, as JSON, with that workspace's path.
    fn initialize_params_for_workspace(dir_name: &str) -> (serde_json::Value, PathBuf) {
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp
            .path()
            .canonicalize()
            .expect("canonicalize")
            .join(dir_name);
        std::fs::create_dir_all(&root).expect("workspace");
        let script = tmp.path().join("fake_lsp.py");
        let params = tmp.path().join("initialize.json");
        // The recorder's message plumbing, with a loop that saves the
        // initialize params instead of logging methods.
        let head = FAKE_LSP_RECORDER
            .split("\nwhile True:")
            .next()
            .expect("recorder head");
        std::fs::write(
            &script,
            format!(
                "{head}\n\
                 while True:\n    msg = read_msg()\n    if msg is None:\n        break\n\
                 \x20   if msg.get('method') == 'exit':\n        break\n\
                 \x20   if msg.get('method') == 'initialize':\n\
                 \x20       open(sys.argv[2], 'w').write(json.dumps(msg['params']))\n\
                 \x20       send({{'jsonrpc': '2.0', 'id': msg['id'], 'result': {{'capabilities': {{}}}}}})\n\
                 \x20   elif 'id' in msg:\n\
                 \x20       send({{'jsonrpc': '2.0', 'id': msg['id'], 'result': None}})\n"
            ),
        )
        .expect("write fake server");
        let mut registry = ServerRegistry::new();
        registry.register(
            Language::PYTHON,
            ServerConfig {
                name: "fake-initialize",
                command: "python3".into(),
                args: vec![
                    script.display().to_string(),
                    tmp.path().join("methods.log").display().to_string(),
                    params.display().to_string(),
                ],
                language: Language::PYTHON,
                initialization_options: None,
                provision: None,
            },
        );
        let (diag_tx, _diag_rx) = std_mpsc::channel();
        let (prog_tx, _prog_rx) = std_mpsc::channel();
        let mut state = WorkerState {
            workspace_root: root.clone(),
            extra_roots: Vec::new(),
            registry,
            clients: HashMap::new(),
            docs: HashMap::new(),
            capability_support: Arc::new(StdMutex::new(LangCapabilitySupport::default())),
            semantic_refresh: Arc::new(AtomicBool::new(false)),
            inlay_refresh: Arc::new(AtomicBool::new(false)),
            diagnostic_refresh: Arc::new(AtomicBool::new(false)),
            diagnostics_tx: diag_tx,
            progress_tx: prog_tx,
            restarts: ServerRestarts::default(),
        };
        let runtime = LspRuntime::new().expect("runtime");
        let py = root.join("main.py");
        std::fs::write(&py, "x = 1\n").expect("write py");
        runtime
            .handle()
            .clone()
            .block_on(state.open_doc(py, String::from("x = 1\n")));
        crate::test_budget::await_spawned(
            Duration::from_secs(5),
            "the fake server to receive initialize",
            || params.is_file(),
        );
        runtime.handle().clone().block_on(state.shutdown_all());
        let json = std::fs::read_to_string(&params).expect("initialize params");
        (serde_json::from_str(&json).expect("json"), root)
    }

    /// #1517: `initialize` sent `rootUri: null` beside `workspaceFolders`.
    /// `rootUri` is deprecated but still required, and null means "no folder
    /// is open": lua-language-server then never loads the workspace and
    /// answers nothing. It now names the workspace, as VS Code and Neovim
    /// do, with `rootPath` for servers older still.
    #[test]
    fn initialize_names_the_workspace_as_root_uri_and_root_path() {
        if !is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let (params, root) = initialize_params_for_workspace("lp");
        let folder = &params["workspaceFolders"][0]["uri"];
        assert!(
            folder.is_string(),
            "workspaceFolders is still sent: {params}"
        );
        assert_eq!(
            &params["rootUri"], folder,
            "rootUri is the workspace folder"
        );
        assert_eq!(params["rootPath"], root.display().to_string());
    }

    /// Negative: a workspace path that needs escaping gives `rootUri` the
    /// same percent-encoded URI as its workspace folder, and `rootPath`
    /// the plain path, not the URI.
    #[test]
    fn root_uri_matches_the_workspace_folder_for_a_path_with_spaces() {
        if !is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let (params, root) = initialize_params_for_workspace("my lua project");
        let uri = params["rootUri"].as_str().expect("rootUri is set");
        assert!(
            uri.starts_with("file:///") && uri.ends_with("my%20lua%20project"),
            "{uri}"
        );
        assert_eq!(&params["rootUri"], &params["workspaceFolders"][0]["uri"]);
        assert_eq!(params["rootPath"], root.display().to_string());
    }

    /// Open, save and close one document against [`FAKE_LSP_RECORDER`]
    /// advertising `capabilities` (a Python literal), and return the method
    /// log once the close has arrived (#854).
    ///
    /// The close is the barrier that makes an ABSENT didSave observable: the
    /// notifications travel one ordered stream, so a server that has seen
    /// didClose has seen every didSave that was sent before it.
    fn saves_seen_by(capabilities: &str) -> String {
        saves_seen_by_each(&[capabilities]).remove(0)
    }

    /// [`saves_seen_by`] for several servers on the one document, each a
    /// [`FAKE_LSP_RECORDER`] advertising its own `capabilities`, in order;
    /// one method log per server.
    fn saves_seen_by_each(capabilities: &[&str]) -> Vec<String> {
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let file = root.join("demo.py");
        std::fs::write(&file, "x = 1\n").expect("write demo");
        let mut registry = ServerRegistry::new();
        let mut logs = Vec::new();
        for (i, caps) in capabilities.iter().enumerate() {
            let script = root.join(format!("fake_lsp_{i}.py"));
            std::fs::write(
                &script,
                format!("CAPABILITIES = {caps}\n{FAKE_LSP_RECORDER}"),
            )
            .expect("write fake server");
            let log = root.join(format!("methods_{i}.log"));
            registry.register(
                Language::PYTHON,
                ServerConfig {
                    // Named apart, so no server stands in for another.
                    name: Box::leak(format!("fake-recorder-{i}").into_boxed_str()),
                    command: "python3".into(),
                    args: vec![script.display().to_string(), log.display().to_string()],
                    language: Language::PYTHON,
                    initialization_options: None,
                    provision: None,
                },
            );
            logs.push(log);
        }
        let (diag_tx, _diag_rx) = std_mpsc::channel();
        let (prog_tx, _prog_rx) = std_mpsc::channel();
        let mut state = WorkerState {
            workspace_root: root.clone(),
            extra_roots: Vec::new(),
            registry,
            clients: HashMap::new(),
            docs: HashMap::new(),
            capability_support: Arc::new(StdMutex::new(LangCapabilitySupport::default())),
            semantic_refresh: Arc::new(AtomicBool::new(false)),
            inlay_refresh: Arc::new(AtomicBool::new(false)),
            diagnostic_refresh: Arc::new(AtomicBool::new(false)),
            diagnostics_tx: diag_tx,
            progress_tx: prog_tx,
            restarts: ServerRestarts::default(),
        };

        let runtime = LspRuntime::new().expect("runtime");
        runtime.handle().clone().block_on(async {
            state.open_doc(file.clone(), String::from("x = 1\n")).await;
            state.save_doc(file.clone(), String::from("x = 2\n")).await;
            state.close_doc(file.clone()).await;
        });

        // Up to three python3 servers start, initialize and see the document
        // open, save and close: a base as wide as the other spawn waits,
        // which costs nothing once every log shows didClose.
        crate::test_budget::await_spawned(
            Duration::from_secs(5),
            "every fake server to receive didClose",
            || {
                logs.iter().all(|log| {
                    std::fs::read_to_string(log)
                        .unwrap_or_default()
                        .contains("textDocument/didClose")
                })
            },
        );
        runtime.handle().clone().block_on(state.shutdown_all());
        logs.iter()
            .map(|log| {
                let methods = std::fs::read_to_string(log).unwrap_or_default();
                assert!(
                    methods.contains("textDocument/didOpen"),
                    "sanity: the fake server must have received didOpen; got: {methods:?}"
                );
                methods
            })
            .collect()
    }

    /// Issue #37: rust-analyzer re-runs its check-on-save (`cargo check`, the
    /// source of the Rust PROBLEMS entries) only when the client sends
    /// `textDocument/didSave`. Saving a file must therefore emit didSave, or
    /// the PROBLEMS panel goes permanently stale after the first open.
    ///
    /// The server advertises what rust-analyzer does when the client declares
    /// no dynamic registration (#854): `save: {}`, which asks for the
    /// notification without the text.
    #[test]
    fn save_doc_sends_did_save_notification_to_the_server() {
        if !is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let methods =
            saves_seen_by(r#"{"textDocumentSync": {"openClose": True, "change": 2, "save": {}}}"#);
        assert!(
            methods.lines().any(|l| l == "textDocument/didSave null"),
            "saving a document must send textDocument/didSave, without the text \
             the server did not ask for; server received: {methods:?}"
        );
    }

    /// #854: a server whose `textDocumentSync` omits `save` asked not to be
    /// told about saves ("if omitted the notification should not be sent").
    /// This is ruff 0.15's exact capability, and it logs "Received
    /// notification textDocument/didSave which does not have a handler" on
    /// every Ctrl+S it is sent anyway.
    #[test]
    fn save_doc_skips_a_server_that_did_not_ask_for_saves() {
        if !is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let methods = saves_seen_by(
            r#"{"textDocumentSync": {"change": 2, "openClose": True, "willSave": False, "willSaveWaitUntil": False}}"#,
        );
        assert!(
            !methods.contains("textDocument/didSave"),
            "a server that advertised no `save` must not be sent didSave; \
             server received: {methods:?}"
        );
    }

    /// #854: `save: { includeText: true }` asks for the saved text in the
    /// notification, and croft used to send `text: None` to everyone.
    #[test]
    fn save_doc_sends_the_text_to_a_server_that_asked_for_it() {
        if !is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let methods = saves_seen_by(
            r#"{"textDocumentSync": {"openClose": True, "change": 1, "save": {"includeText": True}}}"#,
        );
        assert!(
            methods
                .lines()
                .any(|l| l == r#"textDocument/didSave "x = 2\n""#),
            "includeText must put the saved buffer in didSave; server received: {methods:?}"
        );
    }

    /// #854 guard: servers sharing a document are each answered by their
    /// own capability, from the one save: the one that asked for the text
    /// gets it, the one that asked for a bare save gets no text, and the one
    /// that asked for nothing gets nothing.
    #[test]
    fn save_doc_answers_each_server_on_a_document_by_its_own_capability() {
        if !is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let logs = saves_seen_by_each(&[
            r#"{"textDocumentSync": {"openClose": True, "change": 1, "save": {"includeText": True}}}"#,
            r#"{"textDocumentSync": {"openClose": True, "change": 2, "save": {}}}"#,
            r#"{"textDocumentSync": {"openClose": True, "change": 2}}"#,
        ]);
        let saves = |log: &str| -> Vec<String> {
            log.lines()
                .filter(|l| l.starts_with("textDocument/didSave"))
                .map(str::to_string)
                .collect()
        };
        assert_eq!(saves(&logs[0]), vec![r#"textDocument/didSave "x = 2\n""#]);
        assert_eq!(saves(&logs[1]), vec!["textDocument/didSave null"]);
        assert!(saves(&logs[2]).is_empty(), "{:?}", logs[2]);
    }

    /// #854 review guard: the saved text reaches every server that asks for
    /// it, not just the last one, which is handed the buffer itself while
    /// the ones before it get a copy.
    #[test]
    fn every_server_that_asks_for_the_text_gets_it() {
        if !is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let logs = saves_seen_by_each(&[
            r#"{"textDocumentSync": {"openClose": True, "change": 1, "save": {"includeText": True}}}"#,
            r#"{"textDocumentSync": {"openClose": True, "change": 2, "save": {}}}"#,
            r#"{"textDocumentSync": {"openClose": True, "change": 1, "save": {"includeText": True}}}"#,
        ]);
        let saves = |log: &str| -> Vec<String> {
            log.lines()
                .filter(|l| l.starts_with("textDocument/didSave"))
                .map(str::to_string)
                .collect()
        };
        assert_eq!(saves(&logs[0]), vec![r#"textDocument/didSave "x = 2\n""#]);
        assert_eq!(saves(&logs[1]), vec!["textDocument/didSave null"]);
        assert_eq!(saves(&logs[2]), vec![r#"textDocument/didSave "x = 2\n""#]);
    }

    /// #854 guard: the fix does not reach a server that picked the older
    /// `textDocumentSync: <kind>` number. That form predates `save`, and such
    /// a server is still told about saves, without the text, as VS Code,
    /// Neovim and Helix tell it.
    #[test]
    fn save_doc_still_sends_a_bare_save_to_a_server_with_the_old_sync_kind() {
        if !is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let methods = saves_seen_by(r#"{"textDocumentSync": 2}"#);
        assert!(
            methods.lines().any(|l| l == "textDocument/didSave null"),
            "server received: {methods:?}"
        );
    }

    /// #854 guard: `includeText: false` asks for a bare save, never the text.
    #[test]
    fn save_doc_sends_no_text_when_include_text_is_false() {
        if !is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let methods = saves_seen_by(
            r#"{"textDocumentSync": {"openClose": True, "change": 2, "save": {"includeText": False}}}"#,
        );
        assert!(
            methods.lines().any(|l| l == "textDocument/didSave null"),
            "server received: {methods:?}"
        );
    }

    /// #854: every shape `textDocumentSync` can take, read the way the spec
    /// (and, for the pre-`save` kind number, VS Code) reads it.
    #[test]
    fn save_notify_reads_every_text_document_sync_shape() {
        use lsp_types::{
            SaveOptions, TextDocumentSyncCapability as Sync, TextDocumentSyncKind,
            TextDocumentSyncOptions, TextDocumentSyncSaveOptions as Save,
        };
        let options = |save: Option<Save>| {
            Some(Sync::Options(TextDocumentSyncOptions {
                open_close: Some(true),
                change: Some(TextDocumentSyncKind::INCREMENTAL),
                save,
                ..Default::default()
            }))
        };
        let with = |include_text| Some(Save::SaveOptions(SaveOptions { include_text }));
        assert_eq!(save_notify_of(&None), SaveNotify::Never);
        assert_eq!(save_notify_of(&options(None)), SaveNotify::Never);
        assert_eq!(
            save_notify_of(&options(Some(Save::Supported(false)))),
            SaveNotify::Never
        );
        assert_eq!(
            save_notify_of(&options(Some(Save::Supported(true)))),
            SaveNotify::WithoutText
        );
        assert_eq!(
            save_notify_of(&options(with(None))),
            SaveNotify::WithoutText
        );
        assert_eq!(
            save_notify_of(&options(with(Some(false)))),
            SaveNotify::WithoutText
        );
        assert_eq!(
            save_notify_of(&options(with(Some(true)))),
            SaveNotify::WithText
        );
        assert_eq!(
            save_notify_of(&Some(Sync::Kind(TextDocumentSyncKind::FULL))),
            SaveNotify::WithoutText
        );
        assert_eq!(
            save_notify_of(&Some(Sync::Kind(TextDocumentSyncKind::NONE))),
            SaveNotify::Never
        );
    }

    /// #908: servers such as ty register the files they want to hear about
    /// only when the client declares it can take the registration.
    #[test]
    fn client_capabilities_declare_watched_files_registration() {
        let watched = build_client_capabilities()
            .workspace
            .and_then(|w| w.did_change_watched_files)
            .expect("workspace.didChangeWatchedFiles must be declared");
        assert_eq!(watched.dynamic_registration, Some(true));
        assert_eq!(watched.relative_pattern_support, Some(true));
    }

    /// #854: rust-analyzer advertises `save` only while the client declares
    /// no dynamic registration for document sync; told it may register, it
    /// drops `save` and sends `client/registerCapability`, which croft
    /// declines, and check-on-save would stop. Pin the declaration.
    #[test]
    fn client_capabilities_declare_did_save_without_dynamic_registration() {
        let caps = build_client_capabilities();
        let sync = caps
            .text_document
            .and_then(|td| td.synchronization)
            .expect("textDocument.synchronization must be declared");
        assert_eq!(sync.did_save, Some(true));
        assert_eq!(
            sync.dynamic_registration,
            Some(false),
            "dynamic registration would move rust-analyzer's didSave to a \
             registerCapability croft does not handle"
        );
    }

    /// A fake server that advertises `inlayHintProvider` and answers
    /// `textDocument/inlayHint` with one plain-string hint (with padding) and
    /// one label-parts hint, covering both wire shapes end to end.
    const FAKE_LSP_INLAY: &str = r#"
import json, sys

def read_msg():
    length = None
    while True:
        line = sys.stdin.buffer.readline()
        if not line:
            return None
        line = line.strip()
        if not line:
            break
        if line.lower().startswith(b"content-length:"):
            length = int(line.split(b":")[1])
    if length is None:
        return None
    return json.loads(sys.stdin.buffer.read(length))

def send(msg):
    body = json.dumps(msg).encode()
    sys.stdout.buffer.write(b"Content-Length: %d\r\n\r\n" % len(body))
    sys.stdout.buffer.write(body)
    sys.stdout.buffer.flush()

while True:
    msg = read_msg()
    if msg is None:
        break
    method = msg.get("method", "")
    if "id" in msg:
        if method == "initialize":
            send({"jsonrpc": "2.0", "id": msg["id"],
                  "result": {"capabilities": {"inlayHintProvider": True}}})
        elif method == "textDocument/inlayHint":
            send({"jsonrpc": "2.0", "id": msg["id"], "result": [
                {"position": {"line": 0, "character": 5}, "label": ": int"},
                {"position": {"line": 0, "character": 9},
                 "label": [{"value": "n"}, {"value": ":"}],
                 "paddingRight": True},
            ]})
        else:
            send({"jsonrpc": "2.0", "id": msg["id"], "result": None})
    if method == "exit":
        break
"#;

    /// A server as strict as rust-analyzer about positions (#1490): it
    /// remembers each opened document and answers an inlay-hint request whose
    /// range ends past the document with `-32603 Invalid offset`.
    const FAKE_LSP_STRICT_INLAY: &str = r#"
import json, sys

def read_msg():
    length = None
    while True:
        line = sys.stdin.buffer.readline()
        if not line:
            return None
        line = line.strip()
        if not line:
            break
        if line.lower().startswith(b"content-length:"):
            length = int(line.split(b":")[1])
    if length is None:
        return None
    return json.loads(sys.stdin.buffer.read(length))

def send(msg):
    body = json.dumps(msg).encode()
    sys.stdout.buffer.write(b"Content-Length: %d\r\n\r\n" % len(body))
    sys.stdout.buffer.write(body)
    sys.stdout.buffer.flush()

docs = {}
while True:
    msg = read_msg()
    if msg is None:
        break
    method = msg.get("method", "")
    params = msg.get("params") or {}
    if method == "textDocument/didOpen":
        doc = params["textDocument"]
        docs[doc["uri"]] = doc["text"]
    if "id" in msg:
        if method == "initialize":
            send({"jsonrpc": "2.0", "id": msg["id"],
                  "result": {"capabilities": {"inlayHintProvider": True}}})
        elif method == "textDocument/inlayHint":
            lines = docs.get(params["textDocument"]["uri"], "").split("\n")
            end = params["range"]["end"]
            line, col = end["line"], end["character"]
            in_range = line < len(lines) and col <= len(lines[line].encode("utf-16-le")) // 2
            if in_range:
                send({"jsonrpc": "2.0", "id": msg["id"], "result": [
                    {"position": {"line": 1, "character": 9}, "label": ": u32"},
                ]})
            else:
                send({"jsonrpc": "2.0", "id": msg["id"], "error": {
                    "code": -32603,
                    "message": "Invalid offset LineCol { line: %d, col: %d }" % (line, col)}})
        else:
            send({"jsonrpc": "2.0", "id": msg["id"], "result": None})
    if method == "exit":
        break
"#;

    /// Opens `text` on the strict server and asks for inlay hints ending at
    /// `end`; returns the hints that reach the drain channel.
    fn strict_inlay_hints(text: &str, end: Position) -> Vec<InlayHintItem> {
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let file = root.join("main.py");
        std::fs::write(&file, text).expect("write demo");
        let script = root.join("fake_strict_lsp.py");
        std::fs::write(&script, FAKE_LSP_STRICT_INLAY).expect("write fake server");
        let mut registry = ServerRegistry::new();
        registry.register(
            Language::PYTHON,
            ServerConfig {
                name: "fake-strict",
                command: "python3".into(),
                args: vec![script.display().to_string()],
                language: Language::PYTHON,
                initialization_options: None,
                provision: None,
            },
        );
        let (diag_tx, _diag_rx) = std_mpsc::channel();
        let (prog_tx, _prog_rx) = std_mpsc::channel();
        let mut state = WorkerState {
            workspace_root: root.clone(),
            extra_roots: Vec::new(),
            registry,
            clients: HashMap::new(),
            docs: HashMap::new(),
            capability_support: Arc::new(StdMutex::new(LangCapabilitySupport::default())),
            semantic_refresh: Arc::new(AtomicBool::new(false)),
            inlay_refresh: Arc::new(AtomicBool::new(false)),
            diagnostic_refresh: Arc::new(AtomicBool::new(false)),
            diagnostics_tx: diag_tx,
            progress_tx: prog_tx,
            restarts: ServerRestarts::default(),
        };
        let (tx, rx) = std_mpsc::channel();
        let runtime = LspRuntime::new().expect("runtime");
        runtime.handle().clone().block_on(async {
            state.open_doc(file.clone(), text.to_string()).await;
            state.request_inlay_hints(file.clone(), end, 7, &tx).await;
        });
        let update = rx
            .recv_timeout(Duration::from_secs(30))
            .expect("an inlay-hint reply must reach the drain channel");
        runtime.handle().clone().block_on(state.shutdown_all());
        update.hints
    }

    #[test]
    fn a_strict_server_answers_inlay_hints_for_the_whole_document() {
        if !is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let text = "def main():\n    v = 40 + 2\n    print(v)\n";
        let hints = strict_inlay_hints(text, document_end(text));
        assert_eq!(
            hints,
            vec![InlayHintItem {
                line: 1,
                character: 9,
                label: String::from(": u32"),
            }],
            "a range ending at the document's end must not be rejected"
        );
    }

    #[test]
    fn a_strict_server_answers_inlay_hints_without_a_final_newline() {
        if !is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let text = "def main():\n    v = 40 + 2\n    print(v)";
        assert_eq!(strict_inlay_hints(text, document_end(text)).len(), 1);
    }

    /// Negative: the fake server really is strict, so the tests above would
    /// catch a range one line past the end (what croft used to send).
    #[test]
    fn a_strict_server_rejects_a_range_one_line_past_the_end() {
        if !is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let text = "def main():\n    v = 40 + 2\n    print(v)\n";
        let end = document_end(text);
        assert!(strict_inlay_hints(text, Position::new(end.line + 1, 0)).is_empty());
    }

    #[test]
    fn document_end_is_the_last_line_and_its_utf16_length() {
        assert_eq!(document_end(""), Position::new(0, 0));
        assert_eq!(document_end("x = 1\n"), Position::new(1, 0));
        assert_eq!(document_end("a\nbc"), Position::new(1, 2));
        assert_eq!(document_end("a\n\n"), Position::new(2, 0));
        // UTF-16 units, not bytes or chars: `é` is one, `😀` is two.
        assert_eq!(document_end("x\né😀"), Position::new(1, 3));
    }

    #[test]
    fn rows_end_stops_at_the_document_end() {
        let text = "a\nb\nc\n";
        // Within the document: the start of the row after the range.
        assert_eq!(rows_end(text, 0), Position::new(0, 0));
        assert_eq!(rows_end(text, 2), Position::new(2, 0));
        assert_eq!(rows_end(text, 3), Position::new(3, 0));
        // A viewport taller than the file ends where the file does.
        assert_eq!(rows_end(text, 19), Position::new(3, 0));
        assert_eq!(rows_end("a\nbc", 19), Position::new(1, 2));
    }

    /// The full worker wire path: capability gate, `textDocument/inlayHint`
    /// request, label normalisation, and the seq-tagged reply on the drain
    /// channel.
    #[test]
    fn request_inlay_hints_round_trips_through_a_hinting_server() {
        if !is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let file = root.join("demo.py");
        std::fs::write(&file, "x = f(1)\n").expect("write demo");
        let script = root.join("fake_inlay_lsp.py");
        std::fs::write(&script, FAKE_LSP_INLAY).expect("write fake server");

        let mut registry = ServerRegistry::new();
        registry.register(
            Language::PYTHON,
            ServerConfig {
                name: "fake-inlay",
                command: "python3".into(),
                args: vec![script.display().to_string()],
                language: Language::PYTHON,
                initialization_options: None,
                provision: None,
            },
        );
        let (diag_tx, _diag_rx) = std_mpsc::channel();
        let (prog_tx, _prog_rx) = std_mpsc::channel();
        let mut state = WorkerState {
            workspace_root: root.clone(),
            extra_roots: Vec::new(),
            registry,
            clients: HashMap::new(),
            docs: HashMap::new(),
            capability_support: Arc::new(StdMutex::new(LangCapabilitySupport::default())),
            semantic_refresh: Arc::new(AtomicBool::new(false)),
            inlay_refresh: Arc::new(AtomicBool::new(false)),
            diagnostic_refresh: Arc::new(AtomicBool::new(false)),
            diagnostics_tx: diag_tx,
            progress_tx: prog_tx,
            restarts: ServerRestarts::default(),
        };

        let (tx, rx) = std_mpsc::channel();
        let runtime = LspRuntime::new().expect("runtime");
        runtime.handle().clone().block_on(async {
            state
                .open_doc(file.clone(), String::from("x = f(1)\n"))
                .await;
            state
                .request_inlay_hints(file.clone(), document_end("x = f(1)\n"), 42, &tx)
                .await;
        });

        let update = rx
            .recv_timeout(Duration::from_secs(30))
            .expect("an inlay-hint reply must reach the drain channel");
        assert_eq!(update.path, file);
        assert_eq!(update.seq, 42, "the reply must echo the request's seq");
        assert_eq!(
            update.hints,
            vec![
                InlayHintItem {
                    line: 0,
                    character: 5,
                    label: String::from(": int"),
                },
                InlayHintItem {
                    line: 0,
                    character: 9,
                    label: String::from("n: "),
                },
            ],
            "both label shapes must normalise, padding folded in"
        );
        runtime.handle().clone().block_on(state.shutdown_all());
    }

    #[test]
    fn occurrence_items_map_ranges_and_the_write_kind() {
        use lsp_types::{DocumentHighlight, DocumentHighlightKind, Position, Range};
        let hs = vec![
            DocumentHighlight {
                range: Range {
                    start: Position {
                        line: 2,
                        character: 4,
                    },
                    end: Position {
                        line: 2,
                        character: 9,
                    },
                },
                kind: Some(DocumentHighlightKind::WRITE),
            },
            DocumentHighlight {
                range: Range {
                    start: Position {
                        line: 5,
                        character: 0,
                    },
                    end: Position {
                        line: 5,
                        character: 5,
                    },
                },
                kind: None,
            },
        ];
        assert_eq!(
            occurrence_items(hs),
            vec![
                OccurrenceItem {
                    start_line: 2,
                    start_char: 4,
                    end_line: 2,
                    end_char: 9,
                    write: true,
                },
                OccurrenceItem {
                    start_line: 5,
                    start_char: 0,
                    end_line: 5,
                    end_char: 5,
                    write: false,
                },
            ],
            "WRITE maps to write=true; an absent kind defaults to a read tint"
        );
    }

    /// A fake server whose completion list is marked `isIncomplete` and
    /// names the `triggerKind` it was asked with (#1529).
    const FAKE_LSP_INCOMPLETE: &str = r#"
import json, sys

def read_msg():
    length = None
    while True:
        line = sys.stdin.buffer.readline()
        if not line:
            return None
        line = line.strip()
        if not line:
            break
        if line.lower().startswith(b"content-length:"):
            length = int(line.split(b":")[1])
    if length is None:
        return None
    return json.loads(sys.stdin.buffer.read(length))

def send(msg):
    body = json.dumps(msg).encode()
    sys.stdout.buffer.write(b"Content-Length: %d\r\n\r\n" % len(body))
    sys.stdout.buffer.write(body)
    sys.stdout.buffer.flush()

while True:
    msg = read_msg()
    if msg is None:
        break
    method = msg.get("method", "")
    if "id" in msg:
        if method == "initialize":
            send({"jsonrpc": "2.0", "id": msg["id"], "result": {"capabilities": {
                "completionProvider": {"triggerCharacters": ["/", "->", "@"]}}}})
        elif method == "textDocument/completion":
            context = msg["params"].get("context", {})
            kind = context.get("triggerKind")
            typed = context.get("triggerCharacter") or ""
            send({"jsonrpc": "2.0", "id": msg["id"], "result": {
                "isIncomplete": True,
                "items": [{"label": "kind%s%s" % (kind, typed)}]}})
        else:
            send({"jsonrpc": "2.0", "id": msg["id"], "result": None})
    if method == "exit":
        break
"#;

    /// #1529: an `isIncomplete` list reaches the app as such, and the
    /// re-ask goes out as `TriggerForIncompleteCompletions` (3); a first
    /// ask stays `Invoked` (1). #929: a trigger character goes as one (2),
    /// and the server's one-character `triggerCharacters` are recorded for
    /// its own project root, which another root's probe does not touch.
    #[test]
    fn an_incomplete_completion_list_is_reported_and_re_asked_with_kind_3() {
        if !is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let file = root.join("demo.py");
        std::fs::write(&file, "lo\n").expect("write demo");
        let script = root.join("fake_incomplete_lsp.py");
        std::fs::write(&script, FAKE_LSP_INCOMPLETE).expect("write fake server");
        let mut registry = ServerRegistry::new();
        registry.register(
            Language::PYTHON,
            ServerConfig {
                name: "fake-incomplete",
                command: "python3".into(),
                args: vec![script.display().to_string()],
                language: Language::PYTHON,
                initialization_options: None,
                provision: None,
            },
        );
        let (diag_tx, _diag_rx) = std_mpsc::channel();
        let (prog_tx, _prog_rx) = std_mpsc::channel();
        let mut state = WorkerState {
            workspace_root: root.clone(),
            extra_roots: Vec::new(),
            registry,
            clients: HashMap::new(),
            docs: HashMap::new(),
            capability_support: Arc::new(StdMutex::new(LangCapabilitySupport::default())),
            semantic_refresh: Arc::new(AtomicBool::new(false)),
            inlay_refresh: Arc::new(AtomicBool::new(false)),
            diagnostic_refresh: Arc::new(AtomicBool::new(false)),
            diagnostics_tx: diag_tx,
            progress_tx: prog_tx,
            restarts: ServerRestarts::default(),
        };
        let (tx, rx) = std_mpsc::channel();
        let runtime = LspRuntime::new().expect("runtime");
        runtime.handle().clone().block_on(async {
            state.open_doc(file.clone(), String::from("lo\n")).await;
            state
                .request_completion(1, file.clone(), 0, 2, CompletionTrigger::Invoked, &tx)
                .await;
        });
        let first = rx
            .recv_timeout(Duration::from_secs(30))
            .expect("first reply");
        runtime.handle().clone().block_on(async {
            state
                .request_completion(2, file.clone(), 0, 2, CompletionTrigger::Incomplete, &tx)
                .await;
        });
        let again = rx
            .recv_timeout(Duration::from_secs(30))
            .expect("second reply");
        runtime.handle().clone().block_on(async {
            let typed = CompletionTrigger::Character('/');
            state
                .request_completion(3, file.clone(), 0, 2, typed, &tx)
                .await;
        });
        let typed = rx.recv_timeout(Duration::from_secs(30)).expect("reply");
        assert_eq!(typed.items[0].label, "kind2/", "a trigger character");
        let support = state.capability_support.lock().unwrap();
        let doc_root = support.document_roots[&file].clone();
        let triggers = support
            .completion_triggers
            .get(&(Language::PYTHON, doc_root.clone()));
        assert_eq!(triggers.map(String::as_str), Some("/@"), "not `->`");
        drop(support);
        assert!(first.is_incomplete, "isIncomplete reaches the app");
        assert_eq!(first.items[0].label, "kind1", "a first ask is Invoked");
        assert_eq!(again.request_id, 2);
        assert_eq!(
            again.items[0].label, "kind3",
            "the re-ask is TriggerForIncompleteCompletions"
        );
        // Another project root of the language, whose probe finds no server
        // that completes, leaves this root's triggers as they were.
        state.registry = ServerRegistry::new();
        let other = root.join("other");
        runtime
            .handle()
            .clone()
            .block_on(state.ensure_clients(Language::PYTHON, &other));
        let support = state.capability_support.lock().unwrap();
        let kept = support
            .completion_triggers
            .get(&(Language::PYTHON, doc_root));
        assert_eq!(
            kept.map(String::as_str),
            Some("/@"),
            "kept for its own root"
        );
        drop(support);
        runtime.handle().clone().block_on(state.shutdown_all());
    }

    /// A fake server that advertises `documentHighlightProvider` and answers
    /// `textDocument/documentHighlight` with one write and one kindless
    /// occurrence, covering the wire shapes end to end.
    const FAKE_LSP_HIGHLIGHT: &str = r#"
import json, sys

def read_msg():
    length = None
    while True:
        line = sys.stdin.buffer.readline()
        if not line:
            return None
        line = line.strip()
        if not line:
            break
        if line.lower().startswith(b"content-length:"):
            length = int(line.split(b":")[1])
    if length is None:
        return None
    return json.loads(sys.stdin.buffer.read(length))

def send(msg):
    body = json.dumps(msg).encode()
    sys.stdout.buffer.write(b"Content-Length: %d\r\n\r\n" % len(body))
    sys.stdout.buffer.write(body)
    sys.stdout.buffer.flush()

while True:
    msg = read_msg()
    if msg is None:
        break
    method = msg.get("method", "")
    if "id" in msg:
        if method == "initialize":
            send({"jsonrpc": "2.0", "id": msg["id"],
                  "result": {"capabilities": {"documentHighlightProvider": True}}})
        elif method == "textDocument/documentHighlight":
            send({"jsonrpc": "2.0", "id": msg["id"], "result": [
                {"range": {"start": {"line": 0, "character": 0},
                           "end": {"line": 0, "character": 1}},
                 "kind": 3},
                {"range": {"start": {"line": 0, "character": 4},
                           "end": {"line": 0, "character": 5}}},
            ]})
        else:
            send({"jsonrpc": "2.0", "id": msg["id"], "result": None})
    if method == "exit":
        break
"#;

    /// The full worker wire path for occurrences: capability gate,
    /// `textDocument/documentHighlight` request, kind normalisation, and the
    /// request-id-tagged reply on the drain channel.
    #[test]
    fn request_document_highlights_round_trips_through_a_highlighting_server() {
        if !is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let file = root.join("demo.py");
        std::fs::write(&file, "x = 1; x\n").expect("write demo");
        let script = root.join("fake_highlight_lsp.py");
        std::fs::write(&script, FAKE_LSP_HIGHLIGHT).expect("write fake server");

        let mut registry = ServerRegistry::new();
        registry.register(
            Language::PYTHON,
            ServerConfig {
                name: "fake-highlight",
                command: "python3".into(),
                args: vec![script.display().to_string()],
                language: Language::PYTHON,
                initialization_options: None,
                provision: None,
            },
        );
        let (diag_tx, _diag_rx) = std_mpsc::channel();
        let (prog_tx, _prog_rx) = std_mpsc::channel();
        let mut state = WorkerState {
            workspace_root: root.clone(),
            extra_roots: Vec::new(),
            registry,
            clients: HashMap::new(),
            docs: HashMap::new(),
            capability_support: Arc::new(StdMutex::new(LangCapabilitySupport::default())),
            semantic_refresh: Arc::new(AtomicBool::new(false)),
            inlay_refresh: Arc::new(AtomicBool::new(false)),
            diagnostic_refresh: Arc::new(AtomicBool::new(false)),
            diagnostics_tx: diag_tx,
            progress_tx: prog_tx,
            restarts: ServerRestarts::default(),
        };

        let (tx, rx) = std_mpsc::channel();
        let runtime = LspRuntime::new().expect("runtime");
        runtime.handle().clone().block_on(async {
            state
                .open_doc(file.clone(), String::from("x = 1; x\n"))
                .await;
            state
                .request_document_highlights(7, file.clone(), 0, 0, &tx)
                .await;
        });

        let result = rx
            .recv_timeout(Duration::from_secs(30))
            .expect("a document-highlight reply must reach the drain channel");
        assert_eq!(result.request_id, 7, "the reply must echo the request id");
        assert_eq!(
            result.items,
            vec![
                OccurrenceItem {
                    start_line: 0,
                    start_char: 0,
                    end_line: 0,
                    end_char: 1,
                    write: true,
                },
                OccurrenceItem {
                    start_line: 0,
                    start_char: 4,
                    end_line: 0,
                    end_char: 5,
                    write: false,
                },
            ]
        );
        runtime.handle().clone().block_on(state.shutdown_all());
    }

    #[test]
    fn incoming_call_sites_prefer_the_call_range_over_the_definition() {
        use lsp_types::{
            CallHierarchyIncomingCall, CallHierarchyItem, Position, Range, SymbolKind,
        };
        let item = |name: &str, line: u32| CallHierarchyItem {
            name: name.to_string(),
            kind: SymbolKind::FUNCTION,
            tags: None,
            detail: None,
            uri: Url::from_file_path("/proj/src/lib.rs").unwrap(),
            range: Range {
                start: Position { line, character: 0 },
                end: Position {
                    line: line + 5,
                    character: 0,
                },
            },
            selection_range: Range {
                start: Position { line, character: 3 },
                end: Position { line, character: 8 },
            },
            data: None,
        };
        let calls = vec![
            CallHierarchyIncomingCall {
                from: item("caller_a", 10),
                from_ranges: vec![Range {
                    start: Position {
                        line: 12,
                        character: 8,
                    },
                    end: Position {
                        line: 12,
                        character: 14,
                    },
                }],
            },
            CallHierarchyIncomingCall {
                from: item("caller_b", 30),
                from_ranges: Vec::new(),
            },
        ];
        let sites = incoming_call_sites(calls);
        assert_eq!(sites.len(), 2);
        assert_eq!(sites[0].name, "caller_a");
        assert_eq!(
            (sites[0].line, sites[0].character),
            (12, 8),
            "jump to the CALL expression when the server reports it"
        );
        assert_eq!(
            (sites[1].line, sites[1].character),
            (30, 3),
            "fall back to the caller's own selection range"
        );
    }

    #[test]
    fn outgoing_call_sites_target_the_callee_definition() {
        use lsp_types::{
            CallHierarchyItem, CallHierarchyOutgoingCall, Position, Range, SymbolKind,
        };
        let callee = CallHierarchyItem {
            name: String::from("helper"),
            kind: SymbolKind::FUNCTION,
            tags: None,
            detail: None,
            uri: Url::from_file_path("/proj/src/util.rs").unwrap(),
            range: Range {
                start: Position {
                    line: 4,
                    character: 0,
                },
                end: Position {
                    line: 9,
                    character: 0,
                },
            },
            selection_range: Range {
                start: Position {
                    line: 4,
                    character: 7,
                },
                end: Position {
                    line: 4,
                    character: 13,
                },
            },
            data: None,
        };
        let sites = outgoing_call_sites(vec![CallHierarchyOutgoingCall {
            to: callee,
            from_ranges: Vec::new(),
        }]);
        assert_eq!(sites[0].name, "helper");
        assert!(sites[0].path.ends_with("src/util.rs"));
        assert_eq!(
            (sites[0].line, sites[0].character),
            (4, 7),
            "outgoing jumps land on the callee's definition"
        );
    }

    /// A fake server that advertises `callHierarchyProvider`, answers
    /// `textDocument/prepareCallHierarchy` with one item and
    /// `callHierarchy/incomingCalls` with one caller.
    const FAKE_LSP_CALLS: &str = r#"
import json, sys

def read_msg():
    length = None
    while True:
        line = sys.stdin.buffer.readline()
        if not line:
            return None
        line = line.strip()
        if not line:
            break
        if line.lower().startswith(b"content-length:"):
            length = int(line.split(b":")[1])
    if length is None:
        return None
    return json.loads(sys.stdin.buffer.read(length))

def send(msg):
    body = json.dumps(msg).encode()
    sys.stdout.buffer.write(b"Content-Length: %d\r\n\r\n" % len(body))
    sys.stdout.buffer.write(body)
    sys.stdout.buffer.flush()

ITEM = None
while True:
    msg = read_msg()
    if msg is None:
        break
    method = msg.get("method", "")
    if "id" in msg:
        if method == "initialize":
            send({"jsonrpc": "2.0", "id": msg["id"],
                  "result": {"capabilities": {"callHierarchyProvider": True}}})
        elif method == "textDocument/prepareCallHierarchy":
            uri = msg["params"]["textDocument"]["uri"]
            ITEM = {"name": "target_fn", "kind": 12, "uri": uri,
                    "range": {"start": {"line": 0, "character": 0},
                              "end": {"line": 2, "character": 0}},
                    "selectionRange": {"start": {"line": 0, "character": 4},
                                       "end": {"line": 0, "character": 12}}}
            send({"jsonrpc": "2.0", "id": msg["id"], "result": [ITEM]})
        elif method == "callHierarchy/incomingCalls":
            caller = dict(ITEM)
            caller["name"] = "the_caller"
            send({"jsonrpc": "2.0", "id": msg["id"], "result": [
                {"from": caller,
                 "fromRanges": [{"start": {"line": 7, "character": 4},
                                 "end": {"line": 7, "character": 12}}]},
            ]})
        else:
            send({"jsonrpc": "2.0", "id": msg["id"], "result": None})
    if method == "exit":
        break
"#;

    /// The full worker wire path for call hierarchy: capability gate, the
    /// prepare + incomingCalls two-step, and the request-id-tagged reply.
    #[test]
    fn request_call_hierarchy_round_trips_through_a_supporting_server() {
        if !is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let file = root.join("demo.py");
        std::fs::write(&file, "def target_fn():\n    pass\n").expect("write demo");
        let script = root.join("fake_calls_lsp.py");
        std::fs::write(&script, FAKE_LSP_CALLS).expect("write fake server");

        let mut registry = ServerRegistry::new();
        registry.register(
            Language::PYTHON,
            ServerConfig {
                name: "fake-calls",
                command: "python3".into(),
                args: vec![script.display().to_string()],
                language: Language::PYTHON,
                initialization_options: None,
                provision: None,
            },
        );
        let (diag_tx, _diag_rx) = std_mpsc::channel();
        let (prog_tx, _prog_rx) = std_mpsc::channel();
        let mut state = WorkerState {
            workspace_root: root.clone(),
            extra_roots: Vec::new(),
            registry,
            clients: HashMap::new(),
            docs: HashMap::new(),
            capability_support: Arc::new(StdMutex::new(LangCapabilitySupport::default())),
            semantic_refresh: Arc::new(AtomicBool::new(false)),
            inlay_refresh: Arc::new(AtomicBool::new(false)),
            diagnostic_refresh: Arc::new(AtomicBool::new(false)),
            diagnostics_tx: diag_tx,
            progress_tx: prog_tx,
            restarts: ServerRestarts::default(),
        };

        let (tx, rx) = std_mpsc::channel();
        let runtime = LspRuntime::new().expect("runtime");
        runtime.handle().clone().block_on(async {
            state
                .open_doc(file.clone(), String::from("def target_fn():\n    pass\n"))
                .await;
            state
                .request_call_hierarchy(9, file.clone(), 0, 4, true, &tx)
                .await;
        });

        let result = rx
            .recv_timeout(Duration::from_secs(30))
            .expect("a call-hierarchy reply must reach the drain channel");
        assert_eq!(result.request_id, 9);
        assert_eq!(result.kind, HierarchyKind::IncomingCalls);
        assert!(!result.unsupported);
        assert_eq!(result.sites.len(), 1);
        assert_eq!(result.sites[0].name, "the_caller");
        assert_eq!(
            (result.sites[0].line, result.sites[0].character),
            (7, 4),
            "the site is the call expression from fromRanges"
        );
        runtime.handle().clone().block_on(state.shutdown_all());
    }

    /// A fake server that advertises `typeHierarchyProvider` (a key
    /// `lsp-types` 0.95 drops), answering prepare with one item and
    /// `typeHierarchy/supertypes` with one parent.
    const FAKE_LSP_TYPES: &str = r#"
import json, sys

def read_msg():
    length = None
    while True:
        line = sys.stdin.buffer.readline()
        if not line:
            return None
        line = line.strip()
        if not line:
            break
        if line.lower().startswith(b"content-length:"):
            length = int(line.split(b":")[1])
    if length is None:
        return None
    return json.loads(sys.stdin.buffer.read(length))

def send(msg):
    body = json.dumps(msg).encode()
    sys.stdout.buffer.write(b"Content-Length: %d\r\n\r\n" % len(body))
    sys.stdout.buffer.write(body)
    sys.stdout.buffer.flush()

def item(name, uri, line):
    r = {"start": {"line": line, "character": 6}, "end": {"line": line, "character": 6 + len(name)}}
    return {"name": name, "kind": 5, "uri": uri, "range": r, "selectionRange": r}

while True:
    msg = read_msg()
    if msg is None:
        break
    method = msg.get("method", "")
    if "id" in msg:
        if method == "initialize":
            send({"jsonrpc": "2.0", "id": msg["id"],
                  "result": {"capabilities": {"typeHierarchyProvider": True}}})
        elif method == "textDocument/prepareTypeHierarchy":
            uri = msg["params"]["textDocument"]["uri"]
            send({"jsonrpc": "2.0", "id": msg["id"], "result": [item("Child", uri, 0)]})
        elif method == "typeHierarchy/supertypes":
            uri = msg["params"]["item"]["uri"]
            send({"jsonrpc": "2.0", "id": msg["id"], "result": [item("Base", uri, 3)]})
        else:
            send({"jsonrpc": "2.0", "id": msg["id"], "result": None})
    if method == "exit":
        break
"#;

    /// The worker wire path for type hierarchy (#613): the capability read
    /// from the raw initialize result, prepare + supertypes, and the reply.
    #[test]
    fn request_type_hierarchy_round_trips_through_a_supporting_server() {
        if !is_on_path("python3") {
            eprintln!("SKIPPED: python3 not on PATH");
            return;
        }
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path().canonicalize().expect("canonicalize");
        let file = root.join("demo.py");
        std::fs::write(&file, "class Child(Base):\n    pass\n").expect("write demo");
        let script = root.join("fake_types_lsp.py");
        std::fs::write(&script, FAKE_LSP_TYPES).expect("write fake server");

        let mut registry = ServerRegistry::new();
        registry.register(
            Language::PYTHON,
            ServerConfig {
                name: "fake-types",
                command: "python3".into(),
                args: vec![script.display().to_string()],
                language: Language::PYTHON,
                initialization_options: None,
                provision: None,
            },
        );
        let (diag_tx, _diag_rx) = std_mpsc::channel();
        let (prog_tx, _prog_rx) = std_mpsc::channel();
        let mut state = WorkerState {
            workspace_root: root.clone(),
            extra_roots: Vec::new(),
            registry,
            clients: HashMap::new(),
            docs: HashMap::new(),
            capability_support: Arc::new(StdMutex::new(LangCapabilitySupport::default())),
            semantic_refresh: Arc::new(AtomicBool::new(false)),
            inlay_refresh: Arc::new(AtomicBool::new(false)),
            diagnostic_refresh: Arc::new(AtomicBool::new(false)),
            diagnostics_tx: diag_tx,
            progress_tx: prog_tx,
            restarts: ServerRestarts::default(),
        };

        let (tx, rx) = std_mpsc::channel();
        let runtime = LspRuntime::new().expect("runtime");
        runtime.handle().clone().block_on(async {
            state
                .open_doc(file.clone(), String::from("class Child(Base):\n    pass\n"))
                .await;
            state
                .request_type_hierarchy(9, file.clone(), 0, 6, true, &tx)
                .await;
        });

        let result = rx
            .recv_timeout(Duration::from_secs(30))
            .expect("a type-hierarchy reply must reach the drain channel");
        assert_eq!(result.request_id, 9);
        assert_eq!(result.kind, HierarchyKind::Supertypes);
        assert!(!result.unsupported);
        assert_eq!(result.sites.len(), 1);
        assert_eq!(result.sites[0].name, "Base");
        assert_eq!(
            (result.sites[0].line, result.sites[0].character),
            (3, 6),
            "the site is the supertype's name, from selectionRange"
        );
        runtime.handle().clone().block_on(state.shutdown_all());
    }

    /// A nested `documentSymbol` reply from JSON.
    fn nested_reply(json: serde_json::Value) -> DocumentSymbolResponse {
        DocumentSymbolResponse::Nested(serde_json::from_value(json).unwrap())
    }

    fn doc_symbol(name: &str, line: u32, children: serde_json::Value) -> serde_json::Value {
        let pos = serde_json::json!({"line": line, "character": 2});
        let range = serde_json::json!({"start": pos, "end": pos});
        serde_json::json!({
            "name": name, "kind": 5, "range": range, "selectionRange": range,
            "children": children,
        })
    }

    /// #1220: tsserver sorts each level of its navigation tree by name, so
    /// OUTLINE and Go to Symbol listed `Cart` before `sum` and `cents`
    /// before `id`. Every level comes out in file order, as in VS Code.
    #[test]
    fn nested_symbols_list_in_file_order_at_every_level() {
        let reply = nested_reply(serde_json::json!([
            doc_symbol(
                "Cart",
                11,
                serde_json::json!([
                    doc_symbol("add", 13, serde_json::json!([])),
                    doc_symbol("items", 12, serde_json::json!([])),
                    doc_symbol("total", 16, serde_json::json!([])),
                ])
            ),
            doc_symbol("handler", 6, serde_json::json!([])),
            doc_symbol(
                "Item",
                0,
                serde_json::json!([
                    doc_symbol("cents", 0, serde_json::json!([])),
                    doc_symbol("id", 0, serde_json::json!([])),
                ])
            ),
            doc_symbol("sum", 2, serde_json::json!([])),
        ]));
        let mut reply = reply;
        // `cents` is declared after `id` on the same line.
        if let DocumentSymbolResponse::Nested(syms) = &mut reply {
            let item = syms.iter_mut().find(|s| s.name == "Item").unwrap();
            let fields = item.children.as_mut().unwrap();
            fields[0].selection_range.start.character = 30;
            fields[1].selection_range.start.character = 17;
        }
        let names: Vec<(String, u16)> = flatten_symbols(reply)
            .into_iter()
            .map(|s| (s.name, s.depth))
            .collect();
        let expected = [
            ("Item", 0),
            ("id", 1),
            ("cents", 1),
            ("sum", 0),
            ("handler", 0),
            ("Cart", 0),
            ("items", 1),
            ("add", 1),
            ("total", 1),
        ];
        let expected: Vec<(String, u16)> =
            expected.iter().map(|(n, d)| (n.to_string(), *d)).collect();
        assert_eq!(names, expected);
    }

    /// Negative (#1220): a reply already in file order (Python, Rust) comes
    /// out unchanged, children stay under their own parent, and the flat
    /// `SymbolInformation` shape still sorts by position.
    #[test]
    fn symbols_already_in_file_order_and_flat_replies_are_unchanged() {
        let reply = nested_reply(serde_json::json!([
            doc_symbol(
                "first",
                1,
                serde_json::json!([doc_symbol("late_child", 9, serde_json::json!([])),])
            ),
            doc_symbol("second", 4, serde_json::json!([])),
        ]));
        let names: Vec<(String, u16)> = flatten_symbols(reply)
            .into_iter()
            .map(|s| (s.name, s.depth))
            .collect();
        assert_eq!(
            names,
            vec![
                ("first".to_string(), 0),
                ("late_child".to_string(), 1),
                ("second".to_string(), 0)
            ],
            "a child declared after the next sibling's line stays under its parent"
        );
        let pos = |line: u32| {
            serde_json::json!({"start": {"line": line, "character": 0},
                                                 "end": {"line": line, "character": 1}})
        };
        let flat: Vec<lsp_types::SymbolInformation> = serde_json::from_value(serde_json::json!([
            {"name": "b", "kind": 12, "location": {"uri": "file:///x.py", "range": pos(5)}},
            {"name": "a", "kind": 12, "location": {"uri": "file:///x.py", "range": pos(2)}},
        ]))
        .unwrap();
        let names: Vec<String> = flatten_symbols(DocumentSymbolResponse::Flat(flat))
            .into_iter()
            .map(|s| s.name)
            .collect();
        assert_eq!(names, ["a", "b"]);
    }
}